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 case Builtin::BIstrlcat:
1455 case Builtin::BI__builtin_strlcat:
1456 case Builtin::BIstrlcpy:
1457 case Builtin::BI__builtin_strlcpy: {
1458 // Whether these functions overflow depends on the runtime strlen of the
1459 // string, not just the buffer size, so emitting the "always overflow"
1460 // diagnostic isn't quite right. We should still diagnose passing a buffer
1461 // size larger than the destination buffer though; this is a runtime abort
1462 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1463 DiagID = diag::warn_fortify_source_size_mismatch;
1464 SourceSize =
1465 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1466 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1467 break;
1468 }
1469
1470 case Builtin::BIbzero:
1471 case Builtin::BI__builtin_bzero:
1472 case Builtin::BImemcpy:
1473 case Builtin::BI__builtin_memcpy:
1474 case Builtin::BImemmove:
1475 case Builtin::BI__builtin_memmove:
1476 case Builtin::BImemset:
1477 case Builtin::BI__builtin_memset:
1478 case Builtin::BImempcpy:
1479 case Builtin::BI__builtin_mempcpy: {
1480 DiagID = diag::warn_fortify_source_overflow;
1481 SourceSize =
1482 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1483 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1484
1485 // Buffer overread doesn't make sense for memset/bzero.
1486 if (BuiltinID != Builtin::BImemset &&
1487 BuiltinID != Builtin::BI__builtin_memset &&
1488 BuiltinID != Builtin::BIbzero &&
1489 BuiltinID != Builtin::BI__builtin_bzero) {
1490 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1491 }
1492 break;
1493 }
1494 case Builtin::BIbcopy:
1495 case Builtin::BI__builtin_bcopy: {
1496 DiagID = diag::warn_fortify_source_overflow;
1497 SourceSize =
1498 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1499 DestinationSize = Checker.ComputeSizeArgument(Index: 1);
1500 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1501 break;
1502 }
1503
1504 // memchr(buf, val, size)
1505 case Builtin::BImemchr:
1506 case Builtin::BI__builtin_memchr: {
1507 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1508 return;
1509 }
1510
1511 // memcmp/bcmp(buf0, buf1, size)
1512 // Two checks since each buffer is read
1513 case Builtin::BImemcmp:
1514 case Builtin::BI__builtin_memcmp:
1515 case Builtin::BIbcmp:
1516 case Builtin::BI__builtin_bcmp: {
1517 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1518 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1519 return;
1520 }
1521 case Builtin::BIsnprintf:
1522 case Builtin::BI__builtin_snprintf:
1523 case Builtin::BIvsnprintf:
1524 case Builtin::BI__builtin_vsnprintf: {
1525 DiagID = diag::warn_fortify_source_size_mismatch;
1526 SourceSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1527 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1528 StringRef FormatStrRef;
1529 size_t StrLen;
1530 if (SourceSize &&
1531 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1532 EstimateSizeFormatHandler H(FormatStrRef);
1533 const char *FormatBytes = FormatStrRef.data();
1534 if (!analyze_format_string::ParsePrintfString(
1535 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1536 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1537 llvm::APSInt FormatSize =
1538 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1539 .extOrTrunc(width: SizeTypeWidth);
1540 if (FormatSize > *SourceSize && *SourceSize != 0) {
1541 unsigned TruncationDiagID =
1542 H.isKernelCompatible() ? diag::warn_format_truncation
1543 : diag::warn_format_truncation_non_kprintf;
1544 SmallString<16> SpecifiedSizeStr;
1545 SmallString<16> FormatSizeStr;
1546 SourceSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1547 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1548 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1549 PD: PDiag(DiagID: TruncationDiagID)
1550 << Checker.getFunctionName()
1551 << SpecifiedSizeStr << FormatSizeStr);
1552 }
1553 }
1554 }
1555 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1556 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1557 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1558 IdentifierInfo *FnInfo = FD->getIdentifier();
1559 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1560 }
1561 }
1562
1563 if (!SourceSize || !DestinationSize ||
1564 llvm::APSInt::compareValues(I1: *SourceSize, I2: *DestinationSize) <= 0)
1565 return;
1566
1567 std::string FunctionName = Checker.getFunctionName();
1568
1569 SmallString<16> DestinationStr;
1570 SmallString<16> SourceStr;
1571 DestinationSize->toString(Str&: DestinationStr, /*Radix=*/10);
1572 SourceSize->toString(Str&: SourceStr, /*Radix=*/10);
1573 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1574 PD: PDiag(DiagID)
1575 << FunctionName << DestinationStr << SourceStr);
1576}
1577
1578void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1579 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1580 return;
1581
1582 // Recognize the libc function by builtin identity rather than by name and
1583 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1584 // builtin id is attached to any file-scope, C-linkage declaration of umask
1585 // regardless of the libc's mode_t spelling -- including a hand-written
1586 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1587 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1588 if (FD->getBuiltinID() != Builtin::BIumask)
1589 return;
1590
1591 // umask(mode_t): warn when the constant-evaluated argument has bits set
1592 // outside the file-permission mask (0777). Those bits are ignored.
1593 if (TheCall->getNumArgs() != 1)
1594 return;
1595 Expr *Arg = TheCall->getArg(Arg: 0);
1596 if (!Arg->getType()->isIntegerType())
1597 return;
1598 Expr::EvalResult R;
1599 if (!Arg->EvaluateAsInt(Result&: R, Ctx: getASTContext()))
1600 return;
1601 // Operate on the raw two's-complement bit pattern so that negative literals
1602 // (which convert to large unsigned mode_t values) are caught.
1603 llvm::APInt RawValue = R.Val.getInt();
1604 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1605 llvm::APInt Extra = RawValue & ~Mask;
1606 if (Extra == 0)
1607 return;
1608 SmallString<16> ExtraStr;
1609 Extra.toString(Str&: ExtraStr, /*Radix=*/8, /*Signed=*/false);
1610 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fortify_umask_unused_bits)
1611 << ExtraStr;
1612}
1613
1614static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1615 Scope::ScopeFlags NeededScopeFlags,
1616 unsigned DiagID) {
1617 // Scopes aren't available during instantiation. Fortunately, builtin
1618 // functions cannot be template args so they cannot be formed through template
1619 // instantiation. Therefore checking once during the parse is sufficient.
1620 if (SemaRef.inTemplateInstantiation())
1621 return false;
1622
1623 Scope *S = SemaRef.getCurScope();
1624 while (S && !S->isSEHExceptScope())
1625 S = S->getParent();
1626 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1627 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1628 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1629 << DRE->getDecl()->getIdentifier();
1630 return true;
1631 }
1632
1633 return false;
1634}
1635
1636// In OpenCL, __builtin_alloca_* should return a pointer to address space
1637// that corresponds to the stack address space i.e private address space.
1638static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1639 QualType RT = TheCall->getType();
1640 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1641 "__builtin_alloca has invalid address space");
1642
1643 RT = RT->getPointeeType();
1644 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1645 TheCall->setType(S.Context.getPointerType(T: RT));
1646}
1647
1648static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1649 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1650 return true;
1651
1652 for (Expr *Arg : TheCall->arguments()) {
1653 // If argument is dependent on a template parameter, we can't resolve now.
1654 if (Arg->isTypeDependent() || Arg->isValueDependent())
1655 continue;
1656 // Reject void types.
1657 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1658 if (ArgTy->isVoidType())
1659 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1660 }
1661
1662 TheCall->setType(S.Context.getSizeType());
1663 return false;
1664}
1665
1666namespace {
1667enum PointerAuthOpKind {
1668 PAO_Strip,
1669 PAO_Sign,
1670 PAO_Auth,
1671 PAO_SignGeneric,
1672 PAO_Discriminator,
1673 PAO_BlendPointer,
1674 PAO_BlendInteger,
1675 PAO_BlendPC
1676};
1677}
1678
1679bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1680 if (getLangOpts().PointerAuthIntrinsics)
1681 return false;
1682
1683 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1684 return true;
1685}
1686
1687static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1688 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1689}
1690
1691static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1692 // Convert it to type 'int'.
1693 if (convertArgumentToType(S, Value&: Arg, Ty: S.Context.IntTy))
1694 return true;
1695
1696 // Value-dependent expressions are okay; wait for template instantiation.
1697 if (Arg->isValueDependent())
1698 return false;
1699
1700 unsigned KeyValue;
1701 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1702}
1703
1704bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1705 // Attempt to constant-evaluate the expression.
1706 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1707 if (!KeyValue) {
1708 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1709 << 0 << Arg->getSourceRange();
1710 return true;
1711 }
1712
1713 // Ask the target to validate the key parameter.
1714 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1715 llvm::SmallString<32> Value;
1716 {
1717 llvm::raw_svector_ostream Str(Value);
1718 Str << *KeyValue;
1719 }
1720
1721 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1722 << Value << Arg->getSourceRange();
1723 return true;
1724 }
1725
1726 Result = KeyValue->getZExtValue();
1727 return false;
1728}
1729
1730bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1731 PointerAuthDiscArgKind Kind,
1732 unsigned &IntVal) {
1733 if (!Arg) {
1734 IntVal = 0;
1735 return true;
1736 }
1737
1738 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1739 if (!Result) {
1740 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1741 return false;
1742 }
1743
1744 unsigned Max;
1745 bool IsAddrDiscArg = false;
1746
1747 switch (Kind) {
1748 case PointerAuthDiscArgKind::Addr:
1749 Max = 1;
1750 IsAddrDiscArg = true;
1751 break;
1752 case PointerAuthDiscArgKind::Extra:
1753 Max = PointerAuthQualifier::MaxDiscriminator;
1754 break;
1755 };
1756
1757 if (*Result < 0 || *Result > Max) {
1758 if (IsAddrDiscArg)
1759 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1760 << Result->getExtValue();
1761 else
1762 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1763 << Result->getExtValue() << Max;
1764
1765 return false;
1766 };
1767
1768 IntVal = Result->getZExtValue();
1769 return true;
1770}
1771
1772static std::pair<const ValueDecl *, CharUnits>
1773findConstantBaseAndOffset(Sema &S, Expr *E) {
1774 // Must evaluate as a pointer.
1775 Expr::EvalResult Result;
1776 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1777 return {nullptr, CharUnits()};
1778
1779 const auto *BaseDecl =
1780 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1781 if (!BaseDecl)
1782 return {nullptr, CharUnits()};
1783
1784 return {BaseDecl, Result.Val.getLValueOffset()};
1785}
1786
1787static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1788 bool RequireConstant = false) {
1789 if (Arg->hasPlaceholderType()) {
1790 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1791 if (R.isInvalid())
1792 return true;
1793 Arg = R.get();
1794 }
1795
1796 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1797 return OpKind != PAO_BlendInteger;
1798 };
1799 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1800 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1801 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1802 };
1803
1804 // Require the value to have the right range of type.
1805 QualType ExpectedTy;
1806 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1807 ExpectedTy = Arg->getType().getUnqualifiedType();
1808 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1809 ExpectedTy = S.Context.VoidPtrTy;
1810 } else if (AllowsInteger(OpKind) &&
1811 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1812 ExpectedTy = S.Context.getUIntPtrType();
1813
1814 } else {
1815 // Diagnose the failures.
1816 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1817 << unsigned(OpKind == PAO_Discriminator ? 1
1818 : OpKind == PAO_BlendPointer ? 2
1819 : OpKind == PAO_BlendInteger ? 3
1820 : OpKind == PAO_BlendPC ? 4
1821 : 0)
1822 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1823 << Arg->getType() << Arg->getSourceRange();
1824 return true;
1825 }
1826
1827 // Convert to that type. This should just be an lvalue-to-rvalue
1828 // conversion.
1829 if (convertArgumentToType(S, Value&: Arg, Ty: ExpectedTy))
1830 return true;
1831
1832 if (!RequireConstant) {
1833 // Warn about null pointers for non-generic sign and auth operations.
1834 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1835 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1836 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1837 ? diag::warn_ptrauth_sign_null_pointer
1838 : diag::warn_ptrauth_auth_null_pointer)
1839 << Arg->getSourceRange();
1840 }
1841
1842 return false;
1843 }
1844
1845 // Perform special checking on the arguments to ptrauth_sign_constant.
1846
1847 // The main argument.
1848 if (OpKind == PAO_Sign) {
1849 // Require the value we're signing to have a special form.
1850 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1851 bool Invalid;
1852
1853 // Must be rooted in a declaration reference.
1854 if (!BaseDecl)
1855 Invalid = true;
1856
1857 // If it's a function declaration, we can't have an offset.
1858 else if (isa<FunctionDecl>(Val: BaseDecl))
1859 Invalid = !Offset.isZero();
1860
1861 // Otherwise we're fine.
1862 else
1863 Invalid = false;
1864
1865 if (Invalid)
1866 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1867 return Invalid;
1868 }
1869
1870 // The discriminator argument.
1871 assert(OpKind == PAO_Discriminator);
1872
1873 // Must be a pointer or integer or blend thereof.
1874 Expr *Pointer = nullptr;
1875 Expr *Integer = nullptr;
1876 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1877 if (Call->getBuiltinCallee() ==
1878 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1879 Pointer = Call->getArg(Arg: 0);
1880 Integer = Call->getArg(Arg: 1);
1881 }
1882 }
1883 if (!Pointer && !Integer) {
1884 if (Arg->getType()->isPointerType())
1885 Pointer = Arg;
1886 else
1887 Integer = Arg;
1888 }
1889
1890 // Check the pointer.
1891 bool Invalid = false;
1892 if (Pointer) {
1893 assert(Pointer->getType()->isPointerType());
1894
1895 // TODO: if we're initializing a global, check that the address is
1896 // somehow related to what we're initializing. This probably will
1897 // never really be feasible and we'll have to catch it at link-time.
1898 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1899 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
1900 Invalid = true;
1901 }
1902
1903 // Check the integer.
1904 if (Integer) {
1905 assert(Integer->getType()->isIntegerType());
1906 if (!Integer->isEvaluatable(Ctx: S.Context))
1907 Invalid = true;
1908 }
1909
1910 if (Invalid)
1911 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
1912 return Invalid;
1913}
1914
1915static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
1916 if (S.checkArgCount(Call, DesiredArgCount: 2))
1917 return ExprError();
1918 if (checkPointerAuthEnabled(S, E: Call))
1919 return ExprError();
1920 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
1921 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
1922 return ExprError();
1923
1924 Call->setType(Call->getArgs()[0]->getType());
1925 return Call;
1926}
1927
1928static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
1929 if (S.checkArgCount(Call, DesiredArgCount: 2))
1930 return ExprError();
1931 if (checkPointerAuthEnabled(S, E: Call))
1932 return ExprError();
1933 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
1934 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
1935 return ExprError();
1936
1937 Call->setType(S.Context.getUIntPtrType());
1938 return Call;
1939}
1940
1941static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
1942 if (S.checkArgCount(Call, DesiredArgCount: 2))
1943 return ExprError();
1944 if (checkPointerAuthEnabled(S, E: Call))
1945 return ExprError();
1946 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
1947 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
1948 return ExprError();
1949
1950 Call->setType(S.Context.getUIntPtrType());
1951 return Call;
1952}
1953
1954static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
1955 PointerAuthOpKind OpKind,
1956 bool RequireConstant) {
1957 if (S.checkArgCount(Call, DesiredArgCount: 3))
1958 return ExprError();
1959 if (checkPointerAuthEnabled(S, E: Call))
1960 return ExprError();
1961 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
1962 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1963 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
1964 RequireConstant))
1965 return ExprError();
1966
1967 Call->setType(Call->getArgs()[0]->getType());
1968 return Call;
1969}
1970
1971static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
1972 if (S.checkArgCount(Call, DesiredArgCount: 5))
1973 return ExprError();
1974 if (checkPointerAuthEnabled(S, E: Call))
1975 return ExprError();
1976 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1977 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1978 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1979 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1980 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
1981 return ExprError();
1982
1983 Call->setType(Call->getArgs()[0]->getType());
1984 return Call;
1985}
1986
1987static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call) {
1988 if (S.checkArgCount(Call, DesiredArgCount: 6))
1989 return ExprError();
1990 if (checkPointerAuthEnabled(S, E: Call))
1991 return ExprError();
1992 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1993 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1994 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1995 checkPointerAuthValue(S, Arg&: Call->getArgs()[3], OpKind: PAO_BlendPC) ||
1996 checkPointerAuthKey(S, Arg&: Call->getArgs()[4]) ||
1997 checkPointerAuthValue(S, Arg&: Call->getArgs()[5], OpKind: PAO_Discriminator))
1998 return ExprError();
1999
2000 // Validate that the oldKey is IA or IB, not DA or DB.
2001 // This enforces the constraint that auth_with_pc_and_resign only supports
2002 // IA/IB keys for authentication, as only those keys support the PC-based
2003 // signing instructions (paciasppc/pacibsppc).
2004 unsigned OldKey = 0;
2005 if (!S.checkConstantPointerAuthKey(Arg: Call->getArgs()[1], Result&: OldKey)) {
2006 using AK = PointerAuthSchema::ARM8_3Key;
2007 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2008 OldKey != static_cast<unsigned>(AK::ASIB)) {
2009 S.Diag(Loc: Call->getArgs()[1]->getExprLoc(),
2010 DiagID: diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2011 << OldKey << Call->getArgs()[1]->getSourceRange();
2012 return ExprError();
2013 }
2014 }
2015
2016 Call->setType(Call->getArgs()[0]->getType());
2017 return Call;
2018}
2019
2020static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
2021 if (S.checkArgCount(Call, DesiredArgCount: 6))
2022 return ExprError();
2023 if (checkPointerAuthEnabled(S, E: Call))
2024 return ExprError();
2025 const Expr *AddendExpr = Call->getArg(Arg: 5);
2026 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
2027 if (!AddendIsConstInt) {
2028 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
2029 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
2030 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
2031 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
2032 << FDecl->getDeclName() << Arg->getSourceRange();
2033 }
2034 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2035 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2036 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2037 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2038 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
2039 !AddendIsConstInt)
2040 return ExprError();
2041
2042 Call->setType(Call->getArgs()[0]->getType());
2043 return Call;
2044}
2045
2046static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
2047 if (checkPointerAuthEnabled(S, E: Call))
2048 return ExprError();
2049
2050 // We've already performed normal call type-checking.
2051 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
2052
2053 // Operand must be an ordinary or UTF-8 string literal.
2054 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
2055 if (!Literal || Literal->getCharByteWidth() != 1) {
2056 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
2057 << (Literal ? 1 : 0) << Arg->getSourceRange();
2058 return ExprError();
2059 }
2060
2061 return Call;
2062}
2063
2064static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
2065 if (S.checkArgCount(Call, DesiredArgCount: 1))
2066 return ExprError();
2067 Expr *FirstArg = Call->getArg(Arg: 0);
2068 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
2069 if (FirstValue.isInvalid())
2070 return ExprError();
2071 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
2072 QualType FirstArgType = FirstArg->getType();
2073 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2074 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
2075
2076 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2077 if (!FirstArgRecord) {
2078 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2079 << /*isPolymorphic=*/0 << FirstArgType;
2080 return ExprError();
2081 }
2082 if (S.RequireCompleteType(
2083 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
2084 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
2085 return ExprError();
2086 }
2087
2088 if (!FirstArgRecord->isPolymorphic()) {
2089 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2090 << /*isPolymorphic=*/1 << FirstArgRecord;
2091 return ExprError();
2092 }
2093 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
2094 Call->setType(ReturnType);
2095 return Call;
2096}
2097
2098static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2099 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2100 return ExprError();
2101
2102 // Compute __builtin_launder's parameter type from the argument.
2103 // The parameter type is:
2104 // * The type of the argument if it's not an array or function type,
2105 // Otherwise,
2106 // * The decayed argument type.
2107 QualType ParamTy = [&]() {
2108 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
2109 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2110 return S.Context.getPointerType(T: Ty->getElementType());
2111 if (ArgTy->isFunctionType()) {
2112 return S.Context.getPointerType(T: ArgTy);
2113 }
2114 return ArgTy;
2115 }();
2116
2117 TheCall->setType(ParamTy);
2118
2119 auto DiagSelect = [&]() -> std::optional<unsigned> {
2120 if (!ParamTy->isPointerType())
2121 return 0;
2122 if (ParamTy->isFunctionPointerType())
2123 return 1;
2124 if (ParamTy->isVoidPointerType())
2125 return 2;
2126 return std::optional<unsigned>{};
2127 }();
2128 if (DiagSelect) {
2129 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
2130 << *DiagSelect << TheCall->getSourceRange();
2131 return ExprError();
2132 }
2133
2134 // We either have an incomplete class type, or we have a class template
2135 // whose instantiation has not been forced. Example:
2136 //
2137 // template <class T> struct Foo { T value; };
2138 // Foo<int> *p = nullptr;
2139 // auto *d = __builtin_launder(p);
2140 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
2141 DiagID: diag::err_incomplete_type))
2142 return ExprError();
2143
2144 assert(ParamTy->getPointeeType()->isObjectType() &&
2145 "Unhandled non-object pointer case");
2146
2147 InitializedEntity Entity =
2148 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
2149 ExprResult Arg =
2150 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
2151 if (Arg.isInvalid())
2152 return ExprError();
2153 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2154
2155 return TheCall;
2156}
2157
2158static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
2159 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2160 return ExprError();
2161
2162 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
2163 if (Arg.isInvalid())
2164 return ExprError();
2165 QualType ParamTy = Arg.get()->getType();
2166 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2167 TheCall->setType(S.Context.BoolTy);
2168
2169 // Only accept pointers to objects as arguments, which should have object
2170 // pointer or void pointer types.
2171 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2172 // LWG4138: Function pointer types not allowed
2173 if (PT->getPointeeType()->isFunctionType()) {
2174 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2175 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2176 << 1;
2177 return ExprError();
2178 }
2179 // Disallow VLAs too since those shouldn't be able to
2180 // be a template parameter for `std::is_within_lifetime`
2181 if (PT->getPointeeType()->isVariableArrayType()) {
2182 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2183 << 1 << "__builtin_is_within_lifetime";
2184 return ExprError();
2185 }
2186 } else {
2187 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2188 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2189 << 0;
2190 return ExprError();
2191 }
2192 return TheCall;
2193}
2194
2195static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2196 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2197 return ExprError();
2198
2199 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2200 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2201 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2202 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2203 << /*a pointer*/ 0;
2204 return ExprError();
2205 }
2206
2207 QualType T = Dest->getPointeeType();
2208 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2209 DiagID: diag::err_incomplete_type))
2210 return ExprError();
2211
2212 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2213 T->isIncompleteArrayType()) {
2214 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2215 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2216 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2217 return ExprError();
2218 }
2219
2220 TheCall->setType(Dest);
2221
2222 QualType Src = TheCall->getArg(Arg: 1)->getType();
2223 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2224 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2225 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2226 << /*the same*/ 3;
2227 return ExprError();
2228 }
2229
2230 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2231 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2232 if (Size.isInvalid())
2233 return ExprError();
2234
2235 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2236 if (Size.isInvalid())
2237 return ExprError();
2238 SizeExpr = Size.get();
2239 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2240
2241 return TheCall;
2242}
2243
2244// Emit an error and return true if the current object format type is in the
2245// list of unsupported types.
2246static bool CheckBuiltinTargetNotInUnsupported(
2247 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2248 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2249 llvm::Triple::ObjectFormatType CurObjFormat =
2250 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2251 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2252 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2253 << TheCall->getSourceRange();
2254 return true;
2255 }
2256 return false;
2257}
2258
2259// Emit an error and return true if the current architecture is not in the list
2260// of supported architectures.
2261static bool
2262CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2263 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2264 llvm::Triple::ArchType CurArch =
2265 S.getASTContext().getTargetInfo().getTriple().getArch();
2266 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2267 return false;
2268 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2269 << TheCall->getSourceRange();
2270 return true;
2271}
2272
2273static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2274 SourceLocation CallSiteLoc);
2275
2276bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2277 CallExpr *TheCall) {
2278 switch (TI.getTriple().getArch()) {
2279 default:
2280 // Some builtins don't require additional checking, so just consider these
2281 // acceptable.
2282 return false;
2283 case llvm::Triple::arm:
2284 case llvm::Triple::armeb:
2285 case llvm::Triple::thumb:
2286 case llvm::Triple::thumbeb:
2287 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2288 case llvm::Triple::aarch64:
2289 case llvm::Triple::aarch64_32:
2290 case llvm::Triple::aarch64_be:
2291 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2292 case llvm::Triple::bpfeb:
2293 case llvm::Triple::bpfel:
2294 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2295 case llvm::Triple::dxil:
2296 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2297 case llvm::Triple::hexagon:
2298 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2299 case llvm::Triple::mips:
2300 case llvm::Triple::mipsel:
2301 case llvm::Triple::mips64:
2302 case llvm::Triple::mips64el:
2303 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2304 case llvm::Triple::spirv:
2305 case llvm::Triple::spirv32:
2306 case llvm::Triple::spirv64:
2307 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2308 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2309 return false;
2310 case llvm::Triple::systemz:
2311 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2312 case llvm::Triple::x86:
2313 case llvm::Triple::x86_64:
2314 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2315 case llvm::Triple::ppc:
2316 case llvm::Triple::ppcle:
2317 case llvm::Triple::ppc64:
2318 case llvm::Triple::ppc64le:
2319 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2320 case llvm::Triple::amdgpu:
2321 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2322 case llvm::Triple::riscv32:
2323 case llvm::Triple::riscv64:
2324 case llvm::Triple::riscv32be:
2325 case llvm::Triple::riscv64be:
2326 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2327 case llvm::Triple::loongarch32:
2328 case llvm::Triple::loongarch64:
2329 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2330 TheCall);
2331 case llvm::Triple::wasm32:
2332 case llvm::Triple::wasm64:
2333 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2334 case llvm::Triple::nvptx:
2335 case llvm::Triple::nvptx64:
2336 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2337 }
2338}
2339
2340static bool isValidMathElementType(QualType T) {
2341 return T->isDependentType() ||
2342 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2343}
2344
2345// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2346// not a valid type, emit an error message and return true. Otherwise return
2347// false.
2348static bool
2349checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2350 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2351 int ArgOrdinal) {
2352 clang::QualType EltTy =
2353 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2354 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2355 : ArgTy;
2356
2357 switch (ArgTyRestr) {
2358 case Sema::EltwiseBuiltinArgTyRestriction::None:
2359 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2360 !isValidMathElementType(T: ArgTy)) {
2361 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2362 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2363 << ArgTy;
2364 }
2365 break;
2366 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2367 if (!EltTy->isRealFloatingType()) {
2368 // FIXME: make diagnostic's wording correct for matrices
2369 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2370 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2371 << /* floating-point */ 1 << ArgTy;
2372 }
2373 break;
2374 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2375 if (!EltTy->isIntegerType()) {
2376 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2377 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2378 << /* no fp */ 0 << ArgTy;
2379 }
2380 break;
2381 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2382 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2383 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2384 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2385 << /* or fp */ 1 << ArgTy;
2386 }
2387 break;
2388 }
2389
2390 return false;
2391}
2392
2393/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2394/// This checks that the target supports the builtin and that the string
2395/// argument is constant and valid.
2396static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2397 const TargetInfo *AuxTI, unsigned BuiltinID) {
2398 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2399 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2400 "Expecting __builtin_cpu_...");
2401
2402 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2403 const TargetInfo *TheTI = &TI;
2404 auto SupportsBI = [=](const TargetInfo *TInfo) {
2405 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2406 (!IsCPUSupports && TInfo->supportsCpuIs()));
2407 };
2408 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2409 TheTI = AuxTI;
2410
2411 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2412 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2413 return S.Diag(Loc: TheCall->getBeginLoc(),
2414 DiagID: TI.getTriple().isOSAIX()
2415 ? diag::err_builtin_aix_os_unsupported
2416 : diag::err_builtin_target_unsupported)
2417 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2418
2419 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2420 // Check if the argument is a string literal.
2421 if (!isa<StringLiteral>(Val: Arg))
2422 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2423 << Arg->getSourceRange();
2424
2425 // Check the contents of the string.
2426 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2427 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2428 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2429 << Arg->getSourceRange();
2430 return false;
2431 }
2432 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2433 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2434 << Arg->getSourceRange();
2435 return false;
2436}
2437
2438/// Checks that __builtin_bswapg was called with a single argument, which is an
2439/// unsigned integer, and overrides the return value type to the integer type.
2440static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2441 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2442 return true;
2443 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2444 if (ArgRes.isInvalid())
2445 return true;
2446
2447 Expr *Arg = ArgRes.get();
2448 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2449 if (Arg->isTypeDependent())
2450 return false;
2451
2452 QualType ArgTy = Arg->getType();
2453
2454 if (!ArgTy->isIntegerType()) {
2455 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2456 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2457 << ArgTy;
2458 return true;
2459 }
2460 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2461 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2462 BT->getNumBits() != 1) {
2463 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2464 << ArgTy << BT->getNumBits();
2465 return true;
2466 }
2467 }
2468 TheCall->setType(ArgTy);
2469 return false;
2470}
2471
2472/// Checks that __builtin_bitreverseg was called with a single argument, which
2473/// is an integer
2474static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2475 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2476 return true;
2477 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2478 if (ArgRes.isInvalid())
2479 return true;
2480
2481 Expr *Arg = ArgRes.get();
2482 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2483 if (Arg->isTypeDependent())
2484 return false;
2485
2486 QualType ArgTy = Arg->getType();
2487
2488 if (!ArgTy->isIntegerType()) {
2489 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2490 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2491 << ArgTy;
2492 return true;
2493 }
2494 TheCall->setType(ArgTy);
2495 return false;
2496}
2497
2498/// Checks that __builtin_popcountg was called with a single argument, which is
2499/// an unsigned integer.
2500static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2501 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2502 return true;
2503
2504 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2505 if (ArgRes.isInvalid())
2506 return true;
2507
2508 Expr *Arg = ArgRes.get();
2509 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2510
2511 QualType ArgTy = Arg->getType();
2512
2513 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2514 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2515 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2516 << ArgTy;
2517 return true;
2518 }
2519 return false;
2520}
2521
2522/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2523/// argument and return either int, bool, or the argument type.
2524static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2525 QualType ReturnType) {
2526 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2527 return true;
2528
2529 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2530 if (ArgRes.isInvalid())
2531 return true;
2532
2533 Expr *Arg = ArgRes.get();
2534 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2535
2536 QualType ArgTy = Arg->getType();
2537 // C23 stdbit.h functions do not permit bool or enumeration types.
2538 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2539 return S.Diag(Loc: Arg->getBeginLoc(),
2540 DiagID: diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2541 << 1 /*1st argument*/ << ArgTy;
2542 if (!ArgTy->isUnsignedIntegerType())
2543 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_invalid_arg_type)
2544 << 1 /*1st argument*/ << ArgTy;
2545
2546 // For builtins returning unsigned int, verify the argument's bit width fits.
2547 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2548 // produce a count that overflows the return type.
2549 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2550 uint64_t ArgWidth = S.Context.getIntWidth(T: ArgTy);
2551 uint64_t ReturnTypeWidth = S.Context.getIntWidth(T: S.Context.UnsignedIntTy);
2552 if (!llvm::isUIntN(N: ReturnTypeWidth, x: ArgWidth))
2553 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_result_overflow)
2554 << ArgTy;
2555 }
2556
2557 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2558 return false;
2559}
2560
2561/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2562/// an unsigned integer, and an optional second argument, which is promoted to
2563/// an 'int'.
2564static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2565 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2566 return true;
2567
2568 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2569 if (Arg0Res.isInvalid())
2570 return true;
2571
2572 Expr *Arg0 = Arg0Res.get();
2573 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2574
2575 QualType Arg0Ty = Arg0->getType();
2576
2577 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2578 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2579 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2580 << Arg0Ty;
2581 return true;
2582 }
2583
2584 if (TheCall->getNumArgs() > 1) {
2585 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2586 if (Arg1Res.isInvalid())
2587 return true;
2588
2589 Expr *Arg1 = Arg1Res.get();
2590 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2591
2592 QualType Arg1Ty = Arg1->getType();
2593
2594 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2595 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2596 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2597 return true;
2598 }
2599 }
2600
2601 return false;
2602}
2603
2604class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2605 unsigned ArgIndex;
2606 bool OnlyUnsigned;
2607
2608 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2609 QualType T) {
2610 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2611 << ArgIndex << /*scalar*/ 1
2612 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2613 << /*no fp*/ 0 << T;
2614 }
2615
2616public:
2617 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2618 : ContextualImplicitConverter(/*Suppress=*/false,
2619 /*SuppressConversion=*/true),
2620 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2621
2622 bool match(QualType T) override {
2623 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2624 }
2625
2626 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2627 QualType T) override {
2628 return emitError(S, Loc, T);
2629 }
2630
2631 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2632 QualType T) override {
2633 return emitError(S, Loc, T);
2634 }
2635
2636 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2637 QualType T,
2638 QualType ConvTy) override {
2639 return emitError(S, Loc, T);
2640 }
2641
2642 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2643 QualType ConvTy) override {
2644 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2645 }
2646
2647 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2648 QualType T) override {
2649 return emitError(S, Loc, T);
2650 }
2651
2652 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2653 QualType ConvTy) override {
2654 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2655 }
2656
2657 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2658 QualType T,
2659 QualType ConvTy) override {
2660 llvm_unreachable("conversion functions are permitted");
2661 }
2662};
2663
2664/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2665/// arguments, that the first argument is an unsigned integer type, and that
2666/// the second argument is an integer type.
2667static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2668 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2669 return true;
2670
2671 // First argument (value to rotate) must be unsigned integer type.
2672 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2673 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2674 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2675 if (Arg0Res.isInvalid())
2676 return true;
2677
2678 Expr *Arg0 = Arg0Res.get();
2679 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2680
2681 QualType Arg0Ty = Arg0->getType();
2682 if (!Arg0Ty->isUnsignedIntegerType())
2683 return true;
2684
2685 // Second argument (rotation count) must be integer type.
2686 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2687 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2688 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2689 if (Arg1Res.isInvalid())
2690 return true;
2691
2692 Expr *Arg1 = Arg1Res.get();
2693 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2694
2695 QualType Arg1Ty = Arg1->getType();
2696 if (!Arg1Ty->isIntegerType())
2697 return true;
2698
2699 TheCall->setType(Arg0Ty);
2700 return false;
2701}
2702
2703static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2704 unsigned Pos, bool AllowConst,
2705 bool AllowAS) {
2706 QualType MaskTy = MaskArg->getType();
2707 if (!MaskTy->isExtVectorBoolType())
2708 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2709 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2710 << MaskTy;
2711
2712 QualType PtrTy = PtrArg->getType();
2713 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2714 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2715 << Pos << "scalar pointer";
2716
2717 QualType PointeeTy = PtrTy->getPointeeType();
2718 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2719 (!AllowConst && PointeeTy.isConstQualified()) ||
2720 (!AllowAS && PointeeTy.hasAddressSpace())) {
2721 QualType Target =
2722 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2723 return S.Diag(Loc: PtrArg->getExprLoc(),
2724 DiagID: diag::err_typecheck_convert_incompatible)
2725 << PtrTy << Target << /*different qualifiers=*/5
2726 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2727 << PtrTy << Target;
2728 }
2729 return false;
2730}
2731
2732static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2733 bool TypeDependent = false;
2734 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2735 ExprResult Converted =
2736 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2737 if (Converted.isInvalid())
2738 return true;
2739 TheCall->setArg(Arg, ArgExpr: Converted.get());
2740 TypeDependent |= Converted.get()->isTypeDependent();
2741 }
2742
2743 if (TypeDependent)
2744 TheCall->setType(S.Context.DependentTy);
2745 return false;
2746}
2747
2748static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2749 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2750 return ExprError();
2751
2752 if (ConvertMaskedBuiltinArgs(S, TheCall))
2753 return ExprError();
2754
2755 Expr *MaskArg = TheCall->getArg(Arg: 0);
2756 Expr *PtrArg = TheCall->getArg(Arg: 1);
2757 if (TheCall->isTypeDependent())
2758 return TheCall;
2759
2760 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2761 AllowAS: TheCall->getBuiltinCallee() ==
2762 Builtin::BI__builtin_masked_load))
2763 return ExprError();
2764
2765 QualType MaskTy = MaskArg->getType();
2766 QualType PtrTy = PtrArg->getType();
2767 QualType PointeeTy = PtrTy->getPointeeType();
2768 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2769
2770 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2771 NumElts: MaskVecTy->getNumElements());
2772 if (TheCall->getNumArgs() == 3) {
2773 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2774 QualType PassThruTy = PassThruArg->getType();
2775 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2776 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2777 << /* third argument */ 3 << RetTy;
2778 }
2779
2780 TheCall->setType(RetTy);
2781 return TheCall;
2782}
2783
2784static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2785 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2786 return ExprError();
2787
2788 if (ConvertMaskedBuiltinArgs(S, TheCall))
2789 return ExprError();
2790
2791 Expr *MaskArg = TheCall->getArg(Arg: 0);
2792 Expr *ValArg = TheCall->getArg(Arg: 1);
2793 Expr *PtrArg = TheCall->getArg(Arg: 2);
2794 if (TheCall->isTypeDependent())
2795 return TheCall;
2796
2797 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2798 AllowAS: TheCall->getBuiltinCallee() ==
2799 Builtin::BI__builtin_masked_store))
2800 return ExprError();
2801
2802 QualType MaskTy = MaskArg->getType();
2803 QualType PtrTy = PtrArg->getType();
2804 QualType ValTy = ValArg->getType();
2805 if (!ValTy->isVectorType())
2806 return ExprError(
2807 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2808 << 2 << "vector");
2809
2810 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2811 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2812
2813 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2814 return ExprError(
2815 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2816 << S.getASTContext().BuiltinInfo.getQuotedName(
2817 ID: TheCall->getBuiltinCallee())
2818 << MaskTy << ValTy);
2819 }
2820
2821 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2822 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2823 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2824 DiagID: diag::err_vec_builtin_incompatible_vector)
2825 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2826 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2827 TheCall->getArg(Arg: 1)->getEndLoc()));
2828
2829 TheCall->setType(S.Context.VoidTy);
2830 return TheCall;
2831}
2832
2833static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2834 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2835 return ExprError();
2836
2837 if (ConvertMaskedBuiltinArgs(S, TheCall))
2838 return ExprError();
2839
2840 Expr *MaskArg = TheCall->getArg(Arg: 0);
2841 Expr *IdxArg = TheCall->getArg(Arg: 1);
2842 Expr *PtrArg = TheCall->getArg(Arg: 2);
2843 if (TheCall->isTypeDependent())
2844 return TheCall;
2845
2846 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2847 /*AllowAS=*/true))
2848 return ExprError();
2849
2850 QualType IdxTy = IdxArg->getType();
2851 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2852 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2853 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2854 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2855 << IdxTy;
2856
2857 QualType MaskTy = MaskArg->getType();
2858 QualType PtrTy = PtrArg->getType();
2859 QualType PointeeTy = PtrTy->getPointeeType();
2860 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2861 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2862 return ExprError(
2863 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2864 << S.getASTContext().BuiltinInfo.getQuotedName(
2865 ID: TheCall->getBuiltinCallee())
2866 << MaskTy << IdxTy);
2867
2868 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2869 NumElts: MaskVecTy->getNumElements());
2870 if (TheCall->getNumArgs() == 4) {
2871 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2872 QualType PassThruTy = PassThruArg->getType();
2873 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2874 return S.Diag(Loc: PassThruArg->getExprLoc(),
2875 DiagID: diag::err_vec_masked_load_store_ptr)
2876 << /* fourth argument */ 4 << RetTy;
2877 }
2878
2879 TheCall->setType(RetTy);
2880 return TheCall;
2881}
2882
2883static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2884 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2885 return ExprError();
2886
2887 if (ConvertMaskedBuiltinArgs(S, TheCall))
2888 return ExprError();
2889
2890 Expr *MaskArg = TheCall->getArg(Arg: 0);
2891 Expr *IdxArg = TheCall->getArg(Arg: 1);
2892 Expr *ValArg = TheCall->getArg(Arg: 2);
2893 Expr *PtrArg = TheCall->getArg(Arg: 3);
2894 if (TheCall->isTypeDependent())
2895 return TheCall;
2896
2897 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2898 /*AllowAS=*/true))
2899 return ExprError();
2900
2901 QualType IdxTy = IdxArg->getType();
2902 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2903 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2904 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2905 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2906 << IdxTy;
2907
2908 QualType ValTy = ValArg->getType();
2909 QualType MaskTy = MaskArg->getType();
2910 QualType PtrTy = PtrArg->getType();
2911
2912 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2913 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2914 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2915 return ExprError(
2916 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2917 << S.getASTContext().BuiltinInfo.getQuotedName(
2918 ID: TheCall->getBuiltinCallee())
2919 << MaskTy << IdxTy);
2920 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2921 return ExprError(
2922 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2923 << S.getASTContext().BuiltinInfo.getQuotedName(
2924 ID: TheCall->getBuiltinCallee())
2925 << MaskTy << ValTy);
2926
2927 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2928 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2929 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2930 DiagID: diag::err_vec_builtin_incompatible_vector)
2931 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2932 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2933 TheCall->getArg(Arg: 1)->getEndLoc()));
2934
2935 TheCall->setType(S.Context.VoidTy);
2936 return TheCall;
2937}
2938
2939static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
2940 SourceLocation Loc = TheCall->getBeginLoc();
2941 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2942 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2943
2944 if (Args.size() == 0) {
2945 S.Diag(Loc: TheCall->getBeginLoc(),
2946 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2947 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2948 << /*is_non_object=*/0 << TheCall->getSourceRange();
2949 return ExprError();
2950 }
2951
2952 QualType FuncT = Args[0]->getType();
2953
2954 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2955 if (Args.size() < 2) {
2956 S.Diag(Loc: TheCall->getBeginLoc(),
2957 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2958 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2959 << /*is_non_object=*/0 << TheCall->getSourceRange();
2960 return ExprError();
2961 }
2962
2963 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2964 QualType ObjectT = Args[1]->getType();
2965
2966 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2967 return ExprError();
2968
2969 ExprResult ObjectArg = [&]() -> ExprResult {
2970 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2971 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2972 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2973 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2974 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2975 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2976 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
2977 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
2978 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
2979 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
2980 return Args[1];
2981 }
2982
2983 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2984 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2985 // reference_wrapper;
2986 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2987 if (RD->isInStdNamespace() &&
2988 RD->getDeclName().getAsString() == "reference_wrapper") {
2989 CXXScopeSpec SS;
2990 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
2991 UnqualifiedId GetID;
2992 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
2993
2994 ExprResult MemExpr = S.ActOnMemberAccessExpr(
2995 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
2996 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
2997
2998 if (MemExpr.isInvalid())
2999 return ExprError();
3000
3001 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
3002 }
3003 }
3004
3005 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3006 // class T and t1 does not satisfy the previous two items;
3007
3008 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
3009 }();
3010
3011 if (ObjectArg.isInvalid())
3012 return ExprError();
3013
3014 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
3015 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
3016 if (BinOp.isInvalid())
3017 return ExprError();
3018
3019 if (MPT->isMemberDataPointer())
3020 return BinOp;
3021
3022 // Give the synthesized expression a valid source range for diagnostics.
3023 auto *MemCall = new (S.Context)
3024 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3025
3026 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
3027 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
3028 }
3029 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
3030 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
3031}
3032
3033// Performs a similar job to Sema::UsualUnaryConversions, but without any
3034// implicit promotion of integral/enumeration types.
3035static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
3036 // First, convert to an r-value.
3037 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
3038 if (Res.isInvalid())
3039 return ExprError();
3040
3041 // Promote floating-point types.
3042 return S.UsualUnaryFPConversions(E: Res.get());
3043}
3044
3045static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
3046 if (const auto *TyA = VecTy->getAs<VectorType>())
3047 return TyA->getElementType();
3048 if (VecTy->isSizelessVectorType())
3049 return VecTy->getSizelessVectorEltType(Ctx: Context);
3050 return QualType();
3051}
3052
3053ExprResult
3054Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3055 CallExpr *TheCall) {
3056 ExprResult TheCallResult(TheCall);
3057
3058 // Find out if any arguments are required to be integer constant expressions.
3059 unsigned ICEArguments = 0;
3060 ASTContext::GetBuiltinTypeError Error;
3061 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
3062 if (Error != ASTContext::GE_None)
3063 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3064
3065 // If any arguments are required to be ICE's, check and diagnose.
3066 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3067 // Skip arguments not required to be ICE's.
3068 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3069
3070 llvm::APSInt Result;
3071 // If we don't have enough arguments, continue so we can issue better
3072 // diagnostic in checkArgCount(...)
3073 if (ArgNo < TheCall->getNumArgs() &&
3074 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
3075 return true;
3076 ICEArguments &= ~(1 << ArgNo);
3077 }
3078
3079 FPOptions FPO;
3080 switch (BuiltinID) {
3081 case Builtin::BI__builtin___get_unsafe_stack_start:
3082 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3083 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3084 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3085 << "__safestack_get_unsafe_stack_bottom";
3086 break;
3087 case Builtin::BI__builtin___get_unsafe_stack_top:
3088 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3089 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3090 << "__safestack_get_unsafe_stack_top";
3091 break;
3092 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3093 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3094 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3095 << "__safestack_get_unsafe_stack_ptr";
3096 break;
3097 case Builtin::BI__builtin_cpu_supports:
3098 case Builtin::BI__builtin_cpu_is:
3099 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
3100 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
3101 return ExprError();
3102 break;
3103 case Builtin::BI__builtin_cpu_init:
3104 if (!Context.getTargetInfo().supportsCpuInit()) {
3105 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3106 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3107 return ExprError();
3108 }
3109 break;
3110 case Builtin::BI__builtin___CFStringMakeConstantString:
3111 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3112 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3113 if (CheckBuiltinTargetNotInUnsupported(
3114 S&: *this, BuiltinID, TheCall,
3115 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3116 return ExprError();
3117 assert(TheCall->getNumArgs() == 1 &&
3118 "Wrong # arguments to builtin CFStringMakeConstantString");
3119 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
3120 return ExprError();
3121 break;
3122 case Builtin::BI__builtin_ms_va_start:
3123 case Builtin::BI__builtin_zos_va_start:
3124 case Builtin::BI__builtin_stdarg_start:
3125 case Builtin::BI__builtin_va_start:
3126 case Builtin::BI__builtin_c23_va_start:
3127 if (BuiltinVAStart(BuiltinID, TheCall))
3128 return ExprError();
3129 break;
3130 case Builtin::BI__va_start: {
3131 switch (Context.getTargetInfo().getTriple().getArch()) {
3132 case llvm::Triple::aarch64:
3133 case llvm::Triple::arm:
3134 case llvm::Triple::thumb:
3135 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
3136 return ExprError();
3137 break;
3138 default:
3139 if (BuiltinVAStart(BuiltinID, TheCall))
3140 return ExprError();
3141 break;
3142 }
3143 break;
3144 }
3145
3146 // The acquire, release, and no fence variants are ARM and AArch64 only.
3147 case Builtin::BI_interlockedbittestandset_acq:
3148 case Builtin::BI_interlockedbittestandset_rel:
3149 case Builtin::BI_interlockedbittestandset_nf:
3150 case Builtin::BI_interlockedbittestandreset_acq:
3151 case Builtin::BI_interlockedbittestandreset_rel:
3152 case Builtin::BI_interlockedbittestandreset_nf:
3153 if (CheckBuiltinTargetInSupported(
3154 S&: *this, TheCall,
3155 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3156 return ExprError();
3157 break;
3158
3159 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3160 case Builtin::BI_bittest64:
3161 case Builtin::BI_bittestandcomplement64:
3162 case Builtin::BI_bittestandreset64:
3163 case Builtin::BI_bittestandset64:
3164 case Builtin::BI_interlockedbittestandreset64:
3165 case Builtin::BI_interlockedbittestandset64:
3166 if (CheckBuiltinTargetInSupported(
3167 S&: *this, TheCall,
3168 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3169 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3170 return ExprError();
3171 break;
3172
3173 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3174 case Builtin::BI_interlockedbittestandreset64_acq:
3175 case Builtin::BI_interlockedbittestandreset64_rel:
3176 case Builtin::BI_interlockedbittestandreset64_nf:
3177 case Builtin::BI_interlockedbittestandset64_acq:
3178 case Builtin::BI_interlockedbittestandset64_rel:
3179 case Builtin::BI_interlockedbittestandset64_nf:
3180 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
3181 return ExprError();
3182 break;
3183
3184 case Builtin::BI__builtin_set_flt_rounds:
3185 if (CheckBuiltinTargetInSupported(
3186 S&: *this, TheCall,
3187 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3188 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3189 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3190 llvm::Triple::ppc64le}))
3191 return ExprError();
3192 break;
3193
3194 case Builtin::BI__builtin_isgreater:
3195 case Builtin::BI__builtin_isgreaterequal:
3196 case Builtin::BI__builtin_isless:
3197 case Builtin::BI__builtin_islessequal:
3198 case Builtin::BI__builtin_islessgreater:
3199 case Builtin::BI__builtin_isunordered:
3200 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3201 return ExprError();
3202 break;
3203 case Builtin::BI__builtin_fpclassify:
3204 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
3205 return ExprError();
3206 break;
3207 case Builtin::BI__builtin_isfpclass:
3208 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
3209 return ExprError();
3210 break;
3211 case Builtin::BI__builtin_isfinite:
3212 case Builtin::BI__builtin_isinf:
3213 case Builtin::BI__builtin_isinf_sign:
3214 case Builtin::BI__builtin_isnan:
3215 case Builtin::BI__builtin_issignaling:
3216 case Builtin::BI__builtin_isnormal:
3217 case Builtin::BI__builtin_issubnormal:
3218 case Builtin::BI__builtin_iszero:
3219 case Builtin::BI__builtin_signbit:
3220 case Builtin::BI__builtin_signbitf:
3221 case Builtin::BI__builtin_signbitl:
3222 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
3223 return ExprError();
3224 break;
3225 case Builtin::BI__builtin_shufflevector:
3226 return BuiltinShuffleVector(TheCall);
3227 // TheCall will be freed by the smart pointer here, but that's fine, since
3228 // BuiltinShuffleVector guts it, but then doesn't release it.
3229 case Builtin::BI__builtin_masked_load:
3230 case Builtin::BI__builtin_masked_expand_load:
3231 return BuiltinMaskedLoad(S&: *this, TheCall);
3232 case Builtin::BI__builtin_masked_store:
3233 case Builtin::BI__builtin_masked_compress_store:
3234 return BuiltinMaskedStore(S&: *this, TheCall);
3235 case Builtin::BI__builtin_masked_gather:
3236 return BuiltinMaskedGather(S&: *this, TheCall);
3237 case Builtin::BI__builtin_masked_scatter:
3238 return BuiltinMaskedScatter(S&: *this, TheCall);
3239 case Builtin::BI__builtin_invoke:
3240 return BuiltinInvoke(S&: *this, TheCall);
3241 case Builtin::BI__builtin_prefetch:
3242 if (BuiltinPrefetch(TheCall))
3243 return ExprError();
3244 break;
3245 case Builtin::BI__builtin_alloca_with_align:
3246 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3247 if (BuiltinAllocaWithAlign(TheCall))
3248 return ExprError();
3249 [[fallthrough]];
3250 case Builtin::BI__builtin_alloca:
3251 case Builtin::BI__builtin_alloca_uninitialized:
3252 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3253 << TheCall->getDirectCallee();
3254 if (getLangOpts().OpenCL) {
3255 builtinAllocaAddrSpace(S&: *this, TheCall);
3256 }
3257 break;
3258 case Builtin::BI__builtin_infer_alloc_token:
3259 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3260 return ExprError();
3261 break;
3262 case Builtin::BI__arithmetic_fence:
3263 if (BuiltinArithmeticFence(TheCall))
3264 return ExprError();
3265 break;
3266 case Builtin::BI__assume:
3267 case Builtin::BI__builtin_assume:
3268 if (BuiltinAssume(TheCall))
3269 return ExprError();
3270 break;
3271 case Builtin::BI__builtin_assume_aligned:
3272 if (BuiltinAssumeAligned(TheCall))
3273 return ExprError();
3274 break;
3275 case Builtin::BI__builtin_dynamic_object_size:
3276 case Builtin::BI__builtin_object_size:
3277 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3278 return ExprError();
3279 break;
3280 case Builtin::BI__builtin_longjmp:
3281 if (BuiltinLongjmp(TheCall))
3282 return ExprError();
3283 break;
3284 case Builtin::BI__builtin_setjmp:
3285 if (BuiltinSetjmp(TheCall))
3286 return ExprError();
3287 break;
3288 case Builtin::BI__builtin_complex:
3289 if (BuiltinComplex(TheCall))
3290 return ExprError();
3291 break;
3292 case Builtin::BI__builtin_classify_type:
3293 case Builtin::BI__builtin_constant_p: {
3294 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3295 return true;
3296 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3297 if (Arg.isInvalid()) return true;
3298 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3299 TheCall->setType(Context.IntTy);
3300 break;
3301 }
3302 case Builtin::BI__builtin_launder:
3303 return BuiltinLaunder(S&: *this, TheCall);
3304 case Builtin::BI__builtin_is_within_lifetime:
3305 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3306 case Builtin::BI__builtin_trivially_relocate:
3307 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3308 case Builtin::BI__builtin_clear_padding: {
3309 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3310 return ExprError();
3311
3312 const Expr *PtrArg = TheCall->getArg(Arg: 0);
3313 const QualType PtrArgType = PtrArg->getType();
3314 if (!PtrArgType->isPointerType()) {
3315 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3316 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3317 << "pointer";
3318 return ExprError();
3319 }
3320 QualType PointeeType = PtrArgType->getPointeeType();
3321 if (PointeeType.isConstQualified()) {
3322 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_assign_const)
3323 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3324 return ExprError();
3325 }
3326 if (RequireCompleteType(Loc: PtrArg->getBeginLoc(), T: PointeeType,
3327 DiagID: diag::err_typecheck_decl_incomplete_type))
3328 return ExprError();
3329
3330 // For non trivially copyable types, we try to match gcc's behaviour.
3331 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3332 // object, either a local variable or a function parameter passed by value
3333 auto IsAddrOfDeclExpr = [&]() {
3334 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Ctx: Context);
3335 const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: Inner);
3336 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3337 return false;
3338
3339 const Expr *Operand =
3340 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Ctx: Context);
3341 const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Operand);
3342 if (!DeclRef)
3343 return false;
3344
3345 const auto *VarDecl = dyn_cast<::clang::VarDecl>(Val: DeclRef->getDecl());
3346 if (!VarDecl || VarDecl->getType()->isReferenceType())
3347 return false;
3348
3349 // matching GCC behaviour
3350 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3351 QualType VarQType = VarDecl->getType();
3352 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3353 Context.hasSameUnqualifiedType(T1: PointeeType, T2: VarQType);
3354 };
3355
3356 if (!PointeeType.isTriviallyCopyableType(Context) &&
3357 !PointeeType->isAtomicType() // _Atomic is not copyable
3358 && !IsAddrOfDeclExpr()) {
3359 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_needs_trivial_copy)
3360 << PtrArg->getType() << PtrArg->getSourceRange();
3361 return ExprError();
3362 }
3363
3364 if (auto *Record = PointeeType->getAsRecordDecl();
3365 Record && Record->hasFlexibleArrayMember()) {
3366 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_no_flexible_array)
3367 << PointeeType << PtrArg->getSourceRange();
3368 return ExprError();
3369 }
3370
3371 break;
3372 }
3373 case Builtin::BI__sync_fetch_and_add:
3374 case Builtin::BI__sync_fetch_and_add_1:
3375 case Builtin::BI__sync_fetch_and_add_2:
3376 case Builtin::BI__sync_fetch_and_add_4:
3377 case Builtin::BI__sync_fetch_and_add_8:
3378 case Builtin::BI__sync_fetch_and_add_16:
3379 case Builtin::BI__sync_fetch_and_sub:
3380 case Builtin::BI__sync_fetch_and_sub_1:
3381 case Builtin::BI__sync_fetch_and_sub_2:
3382 case Builtin::BI__sync_fetch_and_sub_4:
3383 case Builtin::BI__sync_fetch_and_sub_8:
3384 case Builtin::BI__sync_fetch_and_sub_16:
3385 case Builtin::BI__sync_fetch_and_or:
3386 case Builtin::BI__sync_fetch_and_or_1:
3387 case Builtin::BI__sync_fetch_and_or_2:
3388 case Builtin::BI__sync_fetch_and_or_4:
3389 case Builtin::BI__sync_fetch_and_or_8:
3390 case Builtin::BI__sync_fetch_and_or_16:
3391 case Builtin::BI__sync_fetch_and_and:
3392 case Builtin::BI__sync_fetch_and_and_1:
3393 case Builtin::BI__sync_fetch_and_and_2:
3394 case Builtin::BI__sync_fetch_and_and_4:
3395 case Builtin::BI__sync_fetch_and_and_8:
3396 case Builtin::BI__sync_fetch_and_and_16:
3397 case Builtin::BI__sync_fetch_and_xor:
3398 case Builtin::BI__sync_fetch_and_xor_1:
3399 case Builtin::BI__sync_fetch_and_xor_2:
3400 case Builtin::BI__sync_fetch_and_xor_4:
3401 case Builtin::BI__sync_fetch_and_xor_8:
3402 case Builtin::BI__sync_fetch_and_xor_16:
3403 case Builtin::BI__sync_fetch_and_nand:
3404 case Builtin::BI__sync_fetch_and_nand_1:
3405 case Builtin::BI__sync_fetch_and_nand_2:
3406 case Builtin::BI__sync_fetch_and_nand_4:
3407 case Builtin::BI__sync_fetch_and_nand_8:
3408 case Builtin::BI__sync_fetch_and_nand_16:
3409 case Builtin::BI__sync_add_and_fetch:
3410 case Builtin::BI__sync_add_and_fetch_1:
3411 case Builtin::BI__sync_add_and_fetch_2:
3412 case Builtin::BI__sync_add_and_fetch_4:
3413 case Builtin::BI__sync_add_and_fetch_8:
3414 case Builtin::BI__sync_add_and_fetch_16:
3415 case Builtin::BI__sync_sub_and_fetch:
3416 case Builtin::BI__sync_sub_and_fetch_1:
3417 case Builtin::BI__sync_sub_and_fetch_2:
3418 case Builtin::BI__sync_sub_and_fetch_4:
3419 case Builtin::BI__sync_sub_and_fetch_8:
3420 case Builtin::BI__sync_sub_and_fetch_16:
3421 case Builtin::BI__sync_and_and_fetch:
3422 case Builtin::BI__sync_and_and_fetch_1:
3423 case Builtin::BI__sync_and_and_fetch_2:
3424 case Builtin::BI__sync_and_and_fetch_4:
3425 case Builtin::BI__sync_and_and_fetch_8:
3426 case Builtin::BI__sync_and_and_fetch_16:
3427 case Builtin::BI__sync_or_and_fetch:
3428 case Builtin::BI__sync_or_and_fetch_1:
3429 case Builtin::BI__sync_or_and_fetch_2:
3430 case Builtin::BI__sync_or_and_fetch_4:
3431 case Builtin::BI__sync_or_and_fetch_8:
3432 case Builtin::BI__sync_or_and_fetch_16:
3433 case Builtin::BI__sync_xor_and_fetch:
3434 case Builtin::BI__sync_xor_and_fetch_1:
3435 case Builtin::BI__sync_xor_and_fetch_2:
3436 case Builtin::BI__sync_xor_and_fetch_4:
3437 case Builtin::BI__sync_xor_and_fetch_8:
3438 case Builtin::BI__sync_xor_and_fetch_16:
3439 case Builtin::BI__sync_nand_and_fetch:
3440 case Builtin::BI__sync_nand_and_fetch_1:
3441 case Builtin::BI__sync_nand_and_fetch_2:
3442 case Builtin::BI__sync_nand_and_fetch_4:
3443 case Builtin::BI__sync_nand_and_fetch_8:
3444 case Builtin::BI__sync_nand_and_fetch_16:
3445 case Builtin::BI__sync_val_compare_and_swap:
3446 case Builtin::BI__sync_val_compare_and_swap_1:
3447 case Builtin::BI__sync_val_compare_and_swap_2:
3448 case Builtin::BI__sync_val_compare_and_swap_4:
3449 case Builtin::BI__sync_val_compare_and_swap_8:
3450 case Builtin::BI__sync_val_compare_and_swap_16:
3451 case Builtin::BI__sync_bool_compare_and_swap:
3452 case Builtin::BI__sync_bool_compare_and_swap_1:
3453 case Builtin::BI__sync_bool_compare_and_swap_2:
3454 case Builtin::BI__sync_bool_compare_and_swap_4:
3455 case Builtin::BI__sync_bool_compare_and_swap_8:
3456 case Builtin::BI__sync_bool_compare_and_swap_16:
3457 case Builtin::BI__sync_lock_test_and_set:
3458 case Builtin::BI__sync_lock_test_and_set_1:
3459 case Builtin::BI__sync_lock_test_and_set_2:
3460 case Builtin::BI__sync_lock_test_and_set_4:
3461 case Builtin::BI__sync_lock_test_and_set_8:
3462 case Builtin::BI__sync_lock_test_and_set_16:
3463 case Builtin::BI__sync_lock_release:
3464 case Builtin::BI__sync_lock_release_1:
3465 case Builtin::BI__sync_lock_release_2:
3466 case Builtin::BI__sync_lock_release_4:
3467 case Builtin::BI__sync_lock_release_8:
3468 case Builtin::BI__sync_lock_release_16:
3469 case Builtin::BI__sync_swap:
3470 case Builtin::BI__sync_swap_1:
3471 case Builtin::BI__sync_swap_2:
3472 case Builtin::BI__sync_swap_4:
3473 case Builtin::BI__sync_swap_8:
3474 case Builtin::BI__sync_swap_16:
3475 return BuiltinAtomicOverloaded(TheCallResult);
3476 case Builtin::BI__sync_synchronize:
3477 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3478 << TheCall->getCallee()->getSourceRange();
3479 break;
3480 case Builtin::BI__builtin_nontemporal_load:
3481 case Builtin::BI__builtin_nontemporal_store:
3482 return BuiltinNontemporalOverloaded(TheCallResult);
3483 case Builtin::BI__builtin_memcpy_inline: {
3484 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3485 // We warn about copying to or from `nullptr` pointers when `size` is
3486 // greater than 0. When `size` is value dependent we cannot evaluate its
3487 // value so we bail out.
3488 if (SizeOp->isValueDependent())
3489 break;
3490 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3491 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3492 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3493 }
3494 break;
3495 }
3496 case Builtin::BI__builtin_memset_inline: {
3497 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3498 // We warn about filling to `nullptr` pointers when `size` is greater than
3499 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3500 // out.
3501 if (SizeOp->isValueDependent())
3502 break;
3503 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3504 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3505 break;
3506 }
3507#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3508 case Builtin::BI##ID: \
3509 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3510#include "clang/Basic/Builtins.inc"
3511 case Builtin::BI__annotation: {
3512 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3513 if (!TT.isOSWindows() && !TT.isUEFI()) {
3514 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3515 << TheCall->getSourceRange();
3516 return ExprError();
3517 }
3518 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3519 return ExprError();
3520 break;
3521 }
3522 case Builtin::BI__builtin_annotation:
3523 if (BuiltinAnnotation(S&: *this, TheCall))
3524 return ExprError();
3525 break;
3526 case Builtin::BI__builtin_addressof:
3527 if (BuiltinAddressof(S&: *this, TheCall))
3528 return ExprError();
3529 break;
3530 case Builtin::BI__builtin_function_start:
3531 if (BuiltinFunctionStart(S&: *this, TheCall))
3532 return ExprError();
3533 break;
3534 case Builtin::BI__builtin_is_aligned:
3535 case Builtin::BI__builtin_align_up:
3536 case Builtin::BI__builtin_align_down:
3537 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3538 return ExprError();
3539 break;
3540 case Builtin::BI__builtin_add_overflow:
3541 case Builtin::BI__builtin_sub_overflow:
3542 case Builtin::BI__builtin_mul_overflow:
3543 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3544 return ExprError();
3545 break;
3546 case Builtin::BI__builtin_operator_new:
3547 case Builtin::BI__builtin_operator_delete: {
3548 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3549 ExprResult Res =
3550 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3551 return Res;
3552 }
3553 case Builtin::BI__builtin_dump_struct:
3554 return BuiltinDumpStruct(S&: *this, TheCall);
3555 case Builtin::BI__builtin_expect_with_probability: {
3556 // We first want to ensure we are called with 3 arguments
3557 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3558 return ExprError();
3559 // then check probability is constant float in range [0.0, 1.0]
3560 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3561 SmallVector<PartialDiagnosticAt, 8> Notes;
3562 Expr::EvalResult Eval;
3563 Eval.Diag = &Notes;
3564 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3565 !Eval.Val.isFloat()) {
3566 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3567 << ProbArg->getSourceRange();
3568 for (const PartialDiagnosticAt &PDiag : Notes)
3569 Diag(Loc: PDiag.first, PD: PDiag.second);
3570 return ExprError();
3571 }
3572 llvm::APFloat Probability = Eval.Val.getFloat();
3573 bool LoseInfo = false;
3574 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3575 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3576 if (!(Probability >= llvm::APFloat(0.0) &&
3577 Probability <= llvm::APFloat(1.0))) {
3578 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3579 << ProbArg->getSourceRange();
3580 return ExprError();
3581 }
3582 break;
3583 }
3584 case Builtin::BI__builtin_preserve_access_index:
3585 if (BuiltinPreserveAI(S&: *this, TheCall))
3586 return ExprError();
3587 break;
3588 case Builtin::BI__builtin_call_with_static_chain:
3589 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3590 return ExprError();
3591 break;
3592 case Builtin::BI__exception_code:
3593 case Builtin::BI_exception_code:
3594 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3595 DiagID: diag::err_seh___except_block))
3596 return ExprError();
3597 break;
3598 case Builtin::BI__exception_info:
3599 case Builtin::BI_exception_info:
3600 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3601 DiagID: diag::err_seh___except_filter))
3602 return ExprError();
3603 break;
3604 case Builtin::BI__GetExceptionInfo:
3605 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3606 return ExprError();
3607
3608 if (CheckCXXThrowOperand(
3609 ThrowLoc: TheCall->getBeginLoc(),
3610 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3611 E: TheCall))
3612 return ExprError();
3613
3614 TheCall->setType(Context.VoidPtrTy);
3615 break;
3616 case Builtin::BIaddressof:
3617 case Builtin::BI__addressof:
3618 case Builtin::BIforward:
3619 case Builtin::BIforward_like:
3620 case Builtin::BImove:
3621 case Builtin::BImove_if_noexcept:
3622 case Builtin::BIas_const: {
3623 // These are all expected to be of the form
3624 // T &/&&/* f(U &/&&)
3625 // where T and U only differ in qualification.
3626 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3627 return ExprError();
3628 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3629 QualType Result = FDecl->getReturnType();
3630 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3631 BuiltinID == Builtin::BI__addressof;
3632 if (!(Param->isReferenceType() &&
3633 (ReturnsPointer ? Result->isAnyPointerType()
3634 : Result->isReferenceType()) &&
3635 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3636 T2: Result->getPointeeType()))) {
3637 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3638 << FDecl;
3639 return ExprError();
3640 }
3641 break;
3642 }
3643 case Builtin::BI__builtin_ptrauth_strip:
3644 return PointerAuthStrip(S&: *this, Call: TheCall);
3645 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3646 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3647 case Builtin::BI__builtin_ptrauth_sign_constant:
3648 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3649 /*RequireConstant=*/true);
3650 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3651 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3652 /*RequireConstant=*/false);
3653 case Builtin::BI__builtin_ptrauth_auth:
3654 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3655 /*RequireConstant=*/false);
3656 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3657 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3658 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3659 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3660 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3661 return PointerAuthAuthWithPCAndResign(S&: *this, Call: TheCall);
3662 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3663 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3664 case Builtin::BI__builtin_ptrauth_string_discriminator:
3665 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3666
3667 case Builtin::BI__builtin_get_vtable_pointer:
3668 return GetVTablePointer(S&: *this, Call: TheCall);
3669
3670 // OpenCL v2.0, s6.13.16 - Pipe functions
3671 case Builtin::BIread_pipe:
3672 case Builtin::BIwrite_pipe:
3673 // Since those two functions are declared with var args, we need a semantic
3674 // check for the argument.
3675 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3676 return ExprError();
3677 break;
3678 case Builtin::BIreserve_read_pipe:
3679 case Builtin::BIreserve_write_pipe:
3680 case Builtin::BIwork_group_reserve_read_pipe:
3681 case Builtin::BIwork_group_reserve_write_pipe:
3682 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3683 return ExprError();
3684 break;
3685 case Builtin::BIsub_group_reserve_read_pipe:
3686 case Builtin::BIsub_group_reserve_write_pipe:
3687 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3688 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3689 return ExprError();
3690 break;
3691 case Builtin::BIcommit_read_pipe:
3692 case Builtin::BIcommit_write_pipe:
3693 case Builtin::BIwork_group_commit_read_pipe:
3694 case Builtin::BIwork_group_commit_write_pipe:
3695 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3696 return ExprError();
3697 break;
3698 case Builtin::BIsub_group_commit_read_pipe:
3699 case Builtin::BIsub_group_commit_write_pipe:
3700 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3701 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3702 return ExprError();
3703 break;
3704 case Builtin::BIget_pipe_num_packets:
3705 case Builtin::BIget_pipe_max_packets:
3706 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3707 return ExprError();
3708 break;
3709 case Builtin::BIto_global:
3710 case Builtin::BIto_local:
3711 case Builtin::BIto_private:
3712 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3713 return ExprError();
3714 break;
3715 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3716 case Builtin::BIenqueue_kernel:
3717 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3718 return ExprError();
3719 break;
3720 case Builtin::BIget_kernel_work_group_size:
3721 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3722 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3723 return ExprError();
3724 break;
3725 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3726 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3727 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3728 return ExprError();
3729 break;
3730 case Builtin::BI__builtin_os_log_format:
3731 Cleanup.setExprNeedsCleanups(true);
3732 [[fallthrough]];
3733 case Builtin::BI__builtin_os_log_format_buffer_size:
3734 if (BuiltinOSLogFormat(TheCall))
3735 return ExprError();
3736 break;
3737 case Builtin::BI__builtin_frame_address:
3738 case Builtin::BI__builtin_return_address: {
3739 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3740 return ExprError();
3741
3742 // -Wframe-address warning if non-zero passed to builtin
3743 // return/frame address.
3744 Expr::EvalResult Result;
3745 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3746 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3747 Result.Val.getInt() != 0)
3748 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3749 << ((BuiltinID == Builtin::BI__builtin_return_address)
3750 ? "__builtin_return_address"
3751 : "__builtin_frame_address")
3752 << TheCall->getSourceRange();
3753 break;
3754 }
3755
3756 case Builtin::BI__builtin_nondeterministic_value: {
3757 if (BuiltinNonDeterministicValue(TheCall))
3758 return ExprError();
3759 break;
3760 }
3761
3762 // __builtin_elementwise_abs restricts the element type to signed integers or
3763 // floating point types only.
3764 case Builtin::BI__builtin_elementwise_abs:
3765 if (PrepareBuiltinElementwiseMathOneArgCall(
3766 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3767 return ExprError();
3768 break;
3769
3770 // These builtins restrict the element type to floating point
3771 // types only.
3772 case Builtin::BI__builtin_elementwise_acos:
3773 case Builtin::BI__builtin_elementwise_asin:
3774 case Builtin::BI__builtin_elementwise_atan:
3775 case Builtin::BI__builtin_elementwise_ceil:
3776 case Builtin::BI__builtin_elementwise_cos:
3777 case Builtin::BI__builtin_elementwise_cosh:
3778 case Builtin::BI__builtin_elementwise_exp:
3779 case Builtin::BI__builtin_elementwise_exp2:
3780 case Builtin::BI__builtin_elementwise_exp10:
3781 case Builtin::BI__builtin_elementwise_floor:
3782 case Builtin::BI__builtin_elementwise_log:
3783 case Builtin::BI__builtin_elementwise_log2:
3784 case Builtin::BI__builtin_elementwise_log10:
3785 case Builtin::BI__builtin_elementwise_roundeven:
3786 case Builtin::BI__builtin_elementwise_round:
3787 case Builtin::BI__builtin_elementwise_rint:
3788 case Builtin::BI__builtin_elementwise_nearbyint:
3789 case Builtin::BI__builtin_elementwise_sin:
3790 case Builtin::BI__builtin_elementwise_sinh:
3791 case Builtin::BI__builtin_elementwise_sqrt:
3792 case Builtin::BI__builtin_elementwise_tan:
3793 case Builtin::BI__builtin_elementwise_tanh:
3794 case Builtin::BI__builtin_elementwise_trunc:
3795 case Builtin::BI__builtin_elementwise_canonicalize:
3796 if (PrepareBuiltinElementwiseMathOneArgCall(
3797 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3798 return ExprError();
3799 break;
3800 case Builtin::BI__builtin_elementwise_fma:
3801 if (BuiltinElementwiseTernaryMath(TheCall))
3802 return ExprError();
3803 break;
3804
3805 case Builtin::BI__builtin_elementwise_ldexp: {
3806 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3807 return ExprError();
3808
3809 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3810 if (A.isInvalid())
3811 return ExprError();
3812 QualType TyA = A.get()->getType();
3813 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3814 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3815 return ExprError();
3816
3817 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3818 if (Exp.isInvalid())
3819 return ExprError();
3820 QualType TyExp = Exp.get()->getType();
3821 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3822 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3823 ArgOrdinal: 2))
3824 return ExprError();
3825
3826 // Check the two arguments are either scalars or vectors of equal length.
3827 const auto *Vec0 = TyA->getAs<VectorType>();
3828 const auto *Vec1 = TyExp->getAs<VectorType>();
3829 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3830 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3831 if (Arg0Length != Arg1Length) {
3832 Diag(Loc: Exp.get()->getBeginLoc(),
3833 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3834 << TyA << TyExp << A.get()->getSourceRange()
3835 << Exp.get()->getSourceRange();
3836 return ExprError();
3837 }
3838
3839 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3840 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3841 TheCall->setType(TyA);
3842 break;
3843 }
3844
3845 // These builtins restrict the element type to floating point
3846 // types only, and take in two arguments.
3847 case Builtin::BI__builtin_elementwise_minnum:
3848 case Builtin::BI__builtin_elementwise_maxnum:
3849 case Builtin::BI__builtin_elementwise_minimum:
3850 case Builtin::BI__builtin_elementwise_maximum:
3851 case Builtin::BI__builtin_elementwise_minimumnum:
3852 case Builtin::BI__builtin_elementwise_maximumnum:
3853 case Builtin::BI__builtin_elementwise_atan2:
3854 case Builtin::BI__builtin_elementwise_fmod:
3855 case Builtin::BI__builtin_elementwise_pow:
3856 if (BuiltinElementwiseMath(TheCall,
3857 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3858 return ExprError();
3859 break;
3860 // These builtins restrict the element type to integer
3861 // types only.
3862 case Builtin::BI__builtin_elementwise_add_sat:
3863 case Builtin::BI__builtin_elementwise_sub_sat:
3864 case Builtin::BI__builtin_elementwise_clmul:
3865 case Builtin::BI__builtin_elementwise_pext:
3866 case Builtin::BI__builtin_elementwise_pdep:
3867 if (BuiltinElementwiseMath(TheCall,
3868 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3869 return ExprError();
3870 break;
3871 case Builtin::BI__builtin_elementwise_fshl:
3872 case Builtin::BI__builtin_elementwise_fshr:
3873 if (BuiltinElementwiseTernaryMath(
3874 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3875 return ExprError();
3876 break;
3877 case Builtin::BI__builtin_elementwise_min:
3878 case Builtin::BI__builtin_elementwise_max: {
3879 if (BuiltinElementwiseMath(TheCall))
3880 return ExprError();
3881 Expr *Arg0 = TheCall->getArg(Arg: 0);
3882 Expr *Arg1 = TheCall->getArg(Arg: 1);
3883 QualType Ty0 = Arg0->getType();
3884 QualType Ty1 = Arg1->getType();
3885 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3886 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3887 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3888 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3889 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3890 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
3891 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
3892 break;
3893 }
3894 case Builtin::BI__builtin_elementwise_popcount:
3895 case Builtin::BI__builtin_elementwise_bitreverse:
3896 if (PrepareBuiltinElementwiseMathOneArgCall(
3897 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3898 return ExprError();
3899 break;
3900 case Builtin::BI__builtin_elementwise_copysign: {
3901 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3902 return ExprError();
3903
3904 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3905 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3906 if (Magnitude.isInvalid() || Sign.isInvalid())
3907 return ExprError();
3908
3909 QualType MagnitudeTy = Magnitude.get()->getType();
3910 QualType SignTy = Sign.get()->getType();
3911 if (checkMathBuiltinElementType(
3912 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3913 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3914 checkMathBuiltinElementType(
3915 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3916 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3917 return ExprError();
3918 }
3919
3920 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3921 return Diag(Loc: Sign.get()->getBeginLoc(),
3922 DiagID: diag::err_typecheck_call_different_arg_types)
3923 << MagnitudeTy << SignTy;
3924 }
3925
3926 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3927 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3928 TheCall->setType(Magnitude.get()->getType());
3929 break;
3930 }
3931 case Builtin::BI__builtin_elementwise_clzg:
3932 case Builtin::BI__builtin_elementwise_ctzg:
3933 // These builtins can be unary or binary. Note for empty calls we call the
3934 // unary checker in order to not emit an error that says the function
3935 // expects 2 arguments, which would be misleading.
3936 if (TheCall->getNumArgs() <= 1) {
3937 if (PrepareBuiltinElementwiseMathOneArgCall(
3938 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3939 return ExprError();
3940 } else if (BuiltinElementwiseMath(
3941 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3942 return ExprError();
3943 break;
3944 case Builtin::BI__builtin_reduce_max:
3945 case Builtin::BI__builtin_reduce_min: {
3946 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3947 return ExprError();
3948
3949 const Expr *Arg = TheCall->getArg(Arg: 0);
3950 const auto *TyA = Arg->getType()->getAs<VectorType>();
3951
3952 QualType ElTy;
3953 if (TyA)
3954 ElTy = TyA->getElementType();
3955 else if (Arg->getType()->isSizelessVectorType())
3956 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3957
3958 if (ElTy.isNull()) {
3959 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3960 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3961 << Arg->getType();
3962 return ExprError();
3963 }
3964
3965 TheCall->setType(ElTy);
3966 break;
3967 }
3968 case Builtin::BI__builtin_reduce_maximum:
3969 case Builtin::BI__builtin_reduce_minimum: {
3970 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3971 return ExprError();
3972
3973 const Expr *Arg = TheCall->getArg(Arg: 0);
3974 const auto *TyA = Arg->getType()->getAs<VectorType>();
3975
3976 QualType ElTy;
3977 if (TyA)
3978 ElTy = TyA->getElementType();
3979 else if (Arg->getType()->isSizelessVectorType())
3980 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3981
3982 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3983 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3984 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3985 << Arg->getType();
3986 return ExprError();
3987 }
3988
3989 TheCall->setType(ElTy);
3990 break;
3991 }
3992
3993 // These builtins support vectors of integers only.
3994 // TODO: ADD/MUL should support floating-point types.
3995 case Builtin::BI__builtin_reduce_add:
3996 case Builtin::BI__builtin_reduce_mul:
3997 case Builtin::BI__builtin_reduce_xor:
3998 case Builtin::BI__builtin_reduce_or:
3999 case Builtin::BI__builtin_reduce_and: {
4000 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4001 return ExprError();
4002
4003 const Expr *Arg = TheCall->getArg(Arg: 0);
4004
4005 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
4006 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4007 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4008 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4009 << Arg->getType();
4010 return ExprError();
4011 }
4012
4013 TheCall->setType(ElTy);
4014 break;
4015 }
4016
4017 case Builtin::BI__builtin_reduce_assoc_fadd:
4018 case Builtin::BI__builtin_reduce_in_order_fadd: {
4019 // For in-order reductions require the user to specify the start value.
4020 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4021 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
4022 return ExprError();
4023
4024 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4025 if (Vec.isInvalid())
4026 return ExprError();
4027
4028 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
4029
4030 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
4031 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4032 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4033 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4034 << Vec.get()->getType();
4035 return ExprError();
4036 }
4037
4038 if (TheCall->getNumArgs() == 2) {
4039 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4040 if (StartValue.isInvalid())
4041 return ExprError();
4042
4043 if (!StartValue.get()->getType()->isRealFloatingType()) {
4044 Diag(Loc: StartValue.get()->getBeginLoc(),
4045 DiagID: diag::err_builtin_invalid_arg_type)
4046 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4047 << StartValue.get()->getType();
4048 return ExprError();
4049 }
4050 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
4051 }
4052
4053 TheCall->setType(ElTy);
4054 break;
4055 }
4056
4057 case Builtin::BI__builtin_matrix_transpose:
4058 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
4059
4060 case Builtin::BI__builtin_matrix_column_major_load:
4061 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
4062
4063 case Builtin::BI__builtin_matrix_column_major_store:
4064 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
4065
4066 case Builtin::BI__builtin_verbose_trap:
4067 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
4068 return ExprError();
4069 break;
4070
4071 case Builtin::BI__builtin_get_device_side_mangled_name: {
4072 auto Check = [](CallExpr *TheCall) {
4073 if (TheCall->getNumArgs() != 1)
4074 return false;
4075 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
4076 if (!DRE)
4077 return false;
4078 auto *D = DRE->getDecl();
4079 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
4080 return false;
4081 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4082 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4083 };
4084 if (!Check(TheCall)) {
4085 Diag(Loc: TheCall->getBeginLoc(),
4086 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
4087 return ExprError();
4088 }
4089 break;
4090 }
4091 case Builtin::BI__builtin_bswapg:
4092 if (BuiltinBswapg(S&: *this, TheCall))
4093 return ExprError();
4094 break;
4095 case Builtin::BI__builtin_bitreverseg:
4096 if (BuiltinBitreverseg(S&: *this, TheCall))
4097 return ExprError();
4098 break;
4099 case Builtin::BI__builtin_popcountg:
4100 if (BuiltinPopcountg(S&: *this, TheCall))
4101 return ExprError();
4102 break;
4103 case Builtin::BI__builtin_clzg:
4104 case Builtin::BI__builtin_ctzg:
4105 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
4106 return ExprError();
4107 break;
4108
4109 case Builtin::BI__builtin_stdc_rotate_left:
4110 case Builtin::BI__builtin_stdc_rotate_right:
4111 if (BuiltinRotateGeneric(S&: *this, TheCall))
4112 return ExprError();
4113 break;
4114
4115 case Builtin::BI__builtin_stdc_memreverse8:
4116 case Builtin::BIstdc_memreverse8:
4117 case Builtin::BIstdc_memreverse8u8:
4118 case Builtin::BIstdc_memreverse8u16:
4119 case Builtin::BIstdc_memreverse8u32:
4120 case Builtin::BIstdc_memreverse8u64:
4121 if (Context.getTargetInfo().getCharWidth() != 8) {
4122 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_requires_char_bit_8)
4123 << TheCall->getDirectCallee()->getName();
4124 return ExprError();
4125 }
4126 break;
4127
4128 case Builtin::BI__builtin_stdc_bit_floor:
4129 case Builtin::BI__builtin_stdc_bit_ceil:
4130 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: QualType()))
4131 return ExprError();
4132 break;
4133 case Builtin::BI__builtin_stdc_has_single_bit:
4134 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.BoolTy))
4135 return ExprError();
4136 break;
4137 case Builtin::BI__builtin_stdc_leading_zeros:
4138 case Builtin::BI__builtin_stdc_leading_ones:
4139 case Builtin::BI__builtin_stdc_trailing_zeros:
4140 case Builtin::BI__builtin_stdc_trailing_ones:
4141 case Builtin::BI__builtin_stdc_first_leading_zero:
4142 case Builtin::BI__builtin_stdc_first_leading_one:
4143 case Builtin::BI__builtin_stdc_first_trailing_zero:
4144 case Builtin::BI__builtin_stdc_first_trailing_one:
4145 case Builtin::BI__builtin_stdc_count_zeros:
4146 case Builtin::BI__builtin_stdc_count_ones:
4147 case Builtin::BI__builtin_stdc_bit_width:
4148 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.UnsignedIntTy))
4149 return ExprError();
4150 break;
4151
4152 case Builtin::BI__builtin_allow_runtime_check: {
4153 Expr *Arg = TheCall->getArg(Arg: 0);
4154 // Check if the argument is a string literal.
4155 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
4156 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4157 << Arg->getSourceRange();
4158 return ExprError();
4159 }
4160 break;
4161 }
4162
4163 case Builtin::BI__builtin_allow_sanitize_check: {
4164 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
4165 return ExprError();
4166
4167 Expr *Arg = TheCall->getArg(Arg: 0);
4168 // Check if the argument is a string literal.
4169 const StringLiteral *SanitizerName =
4170 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
4171 if (!SanitizerName) {
4172 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4173 << Arg->getSourceRange();
4174 return ExprError();
4175 }
4176 // Validate the sanitizer name.
4177 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4178 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
4179 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4180 Value: true)
4181 .Default(Value: false)) {
4182 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
4183 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4184 << Arg->getSourceRange();
4185 return ExprError();
4186 }
4187 break;
4188 }
4189 case Builtin::BI__builtin_counted_by_ref:
4190 if (BuiltinCountedByRef(TheCall))
4191 return ExprError();
4192 break;
4193 }
4194
4195 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4196 return ExprError();
4197
4198 // Since the target specific builtins for each arch overlap, only check those
4199 // of the arch we are compiling for.
4200 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
4201 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
4202 assert(Context.getAuxTargetInfo() &&
4203 "Aux Target Builtin, but not an aux target?");
4204
4205 if (CheckTSBuiltinFunctionCall(
4206 TI: *Context.getAuxTargetInfo(),
4207 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
4208 return ExprError();
4209 } else {
4210 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
4211 TheCall))
4212 return ExprError();
4213 }
4214 }
4215
4216 return TheCallResult;
4217}
4218
4219bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4220 llvm::APSInt Result;
4221 // We can't check the value of a dependent argument.
4222 Expr *Arg = TheCall->getArg(Arg: ArgNum);
4223 if (Arg->isTypeDependent() || Arg->isValueDependent())
4224 return false;
4225
4226 // Check constant-ness first.
4227 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4228 return true;
4229
4230 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4231 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4232 return false;
4233
4234 return Diag(Loc: TheCall->getBeginLoc(),
4235 DiagID: diag::err_argument_not_contiguous_bit_field)
4236 << ArgNum << Arg->getSourceRange();
4237}
4238
4239bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4240 unsigned FirstArg, FormatStringInfo *FSI) {
4241 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4242 bool IsVariadic = false;
4243 if (const FunctionType *FnTy = D->getFunctionType())
4244 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
4245 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
4246 IsVariadic = BD->isVariadic();
4247 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
4248 IsVariadic = OMD->isVariadic();
4249
4250 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4251 IsVariadic, FSI);
4252}
4253
4254bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4255 bool HasImplicitThisParam, bool IsVariadic,
4256 FormatStringInfo *FSI) {
4257 if (FirstArg == 0)
4258 FSI->ArgPassingKind = FAPK_VAList;
4259 else if (IsVariadic)
4260 FSI->ArgPassingKind = FAPK_Variadic;
4261 else
4262 FSI->ArgPassingKind = FAPK_Fixed;
4263 FSI->FormatIdx = FormatIdx - 1;
4264 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4265
4266 // The way the format attribute works in GCC, the implicit this argument
4267 // of member functions is counted. However, it doesn't appear in our own
4268 // lists, so decrement format_idx in that case.
4269 if (HasImplicitThisParam) {
4270 if(FSI->FormatIdx == 0)
4271 return false;
4272 --FSI->FormatIdx;
4273 if (FSI->FirstDataArg != 0)
4274 --FSI->FirstDataArg;
4275 }
4276 return true;
4277}
4278
4279/// Checks if a the given expression evaluates to null.
4280///
4281/// Returns true if the value evaluates to null.
4282static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4283 // Treat (smart) pointers constructed from nullptr as null, whether we can
4284 // const-evaluate them or not.
4285 // This must happen first: the smart pointer expr might have _Nonnull type!
4286 if (isa<CXXNullPtrLiteralExpr>(
4287 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
4288 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
4289 return true;
4290
4291 // If the expression has non-null type, it doesn't evaluate to null.
4292 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4293 if (*nullability == NullabilityKind::NonNull)
4294 return false;
4295 }
4296
4297 // As a special case, transparent unions initialized with zero are
4298 // considered null for the purposes of the nonnull attribute.
4299 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4300 UT &&
4301 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4302 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
4303 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
4304 Expr = ILE->getInit(Init: 0);
4305 }
4306
4307 bool Result;
4308 return (!Expr->isValueDependent() &&
4309 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
4310 !Result);
4311}
4312
4313static void CheckNonNullArgument(Sema &S,
4314 const Expr *ArgExpr,
4315 SourceLocation CallSiteLoc) {
4316 if (CheckNonNullExpr(S, Expr: ArgExpr))
4317 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
4318 PD: S.PDiag(DiagID: diag::warn_null_arg)
4319 << ArgExpr->getSourceRange());
4320}
4321
4322/// Determine whether the given type has a non-null nullability annotation.
4323static bool isNonNullType(QualType type) {
4324 if (auto nullability = type->getNullability())
4325 return *nullability == NullabilityKind::NonNull;
4326
4327 return false;
4328}
4329
4330static void CheckNonNullArguments(Sema &S,
4331 const NamedDecl *FDecl,
4332 const FunctionProtoType *Proto,
4333 ArrayRef<const Expr *> Args,
4334 SourceLocation CallSiteLoc) {
4335 assert((FDecl || Proto) && "Need a function declaration or prototype");
4336
4337 // Already checked by constant evaluator.
4338 if (S.isConstantEvaluatedContext())
4339 return;
4340 // Check the attributes attached to the method/function itself.
4341 llvm::SmallBitVector NonNullArgs;
4342 if (FDecl) {
4343 // Handle the nonnull attribute on the function/method declaration itself.
4344 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4345 if (!NonNull->args_size()) {
4346 // Easy case: all pointer arguments are nonnull.
4347 for (const auto *Arg : Args)
4348 if (S.isValidPointerAttrType(T: Arg->getType()))
4349 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4350 return;
4351 }
4352
4353 for (const ParamIdx &Idx : NonNull->args()) {
4354 unsigned IdxAST = Idx.getASTIndex();
4355 if (IdxAST >= Args.size())
4356 continue;
4357 if (NonNullArgs.empty())
4358 NonNullArgs.resize(N: Args.size());
4359 NonNullArgs.set(IdxAST);
4360 }
4361 }
4362 }
4363
4364 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4365 // Handle the nonnull attribute on the parameters of the
4366 // function/method.
4367 ArrayRef<ParmVarDecl*> parms;
4368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4369 parms = FD->parameters();
4370 else
4371 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4372
4373 unsigned ParamIndex = 0;
4374 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4375 I != E; ++I, ++ParamIndex) {
4376 const ParmVarDecl *PVD = *I;
4377 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4378 if (NonNullArgs.empty())
4379 NonNullArgs.resize(N: Args.size());
4380
4381 NonNullArgs.set(ParamIndex);
4382 }
4383 }
4384 } else {
4385 // If we have a non-function, non-method declaration but no
4386 // function prototype, try to dig out the function prototype.
4387 if (!Proto) {
4388 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4389 QualType type = VD->getType().getNonReferenceType();
4390 if (auto pointerType = type->getAs<PointerType>())
4391 type = pointerType->getPointeeType();
4392 else if (auto blockType = type->getAs<BlockPointerType>())
4393 type = blockType->getPointeeType();
4394 // FIXME: data member pointers?
4395
4396 // Dig out the function prototype, if there is one.
4397 Proto = type->getAs<FunctionProtoType>();
4398 }
4399 }
4400
4401 // Fill in non-null argument information from the nullability
4402 // information on the parameter types (if we have them).
4403 if (Proto) {
4404 unsigned Index = 0;
4405 for (auto paramType : Proto->getParamTypes()) {
4406 if (isNonNullType(type: paramType)) {
4407 if (NonNullArgs.empty())
4408 NonNullArgs.resize(N: Args.size());
4409
4410 NonNullArgs.set(Index);
4411 }
4412
4413 ++Index;
4414 }
4415 }
4416 }
4417
4418 // Check for non-null arguments.
4419 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4420 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4421 if (NonNullArgs[ArgIndex])
4422 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4423 }
4424}
4425
4426void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4427 StringRef ParamName, QualType ArgTy,
4428 QualType ParamTy) {
4429
4430 // If a function accepts a pointer or reference type
4431 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4432 return;
4433
4434 // If the parameter is a pointer type, get the pointee type for the
4435 // argument too. If the parameter is a reference type, don't try to get
4436 // the pointee type for the argument.
4437 if (ParamTy->isPointerType())
4438 ArgTy = ArgTy->getPointeeType();
4439
4440 // Remove reference or pointer
4441 ParamTy = ParamTy->getPointeeType();
4442
4443 // Find expected alignment, and the actual alignment of the passed object.
4444 // getTypeAlignInChars requires complete types
4445 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4446 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4447 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4448 return;
4449
4450 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4451 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4452
4453 // If the argument is less aligned than the parameter, there is a
4454 // potential alignment issue.
4455 if (ArgAlign < ParamAlign)
4456 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4457 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4458 << ParamName << (FDecl != nullptr) << FDecl;
4459}
4460
4461void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4462 const Expr *ThisArg,
4463 ArrayRef<const Expr *> Args) {
4464 if (!FD || Args.empty())
4465 return;
4466 auto GetArgAt = [&](int Idx) -> const Expr * {
4467 if (Idx == LifetimeCaptureByAttr::Global ||
4468 Idx == LifetimeCaptureByAttr::Unknown)
4469 return nullptr;
4470 if (IsMemberFunction && Idx == 0)
4471 return ThisArg;
4472 return Args[Idx - IsMemberFunction];
4473 };
4474 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4475 unsigned ArgIdx) {
4476 if (!Attr)
4477 return;
4478
4479 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4480 for (int CapturingParamIdx : Attr->params()) {
4481 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4482 continue;
4483 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4484 // initialization codepath.
4485 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4486 isa<CXXConstructorDecl>(Val: FD))
4487 continue;
4488 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4489 CapturingEntity CE{.Entity: Capturing};
4490 // Ensure that 'Captured' outlives the 'Capturing' entity.
4491 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4492 }
4493 };
4494 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4495 for (const auto *A :
4496 FD->getParamDecl(i: I)->specific_attrs<LifetimeCaptureByAttr>())
4497 HandleCaptureByAttr(A, I + IsMemberFunction);
4498 // Check when the implicit object param is captured.
4499 if (IsMemberFunction) {
4500 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4501 if (!TSI)
4502 return;
4503 AttributedTypeLoc ATL;
4504 for (TypeLoc TL = TSI->getTypeLoc();
4505 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4506 TL = ATL.getModifiedLoc())
4507 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4508 }
4509}
4510
4511void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4512 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4513 bool IsMemberFunction, SourceLocation Loc,
4514 SourceRange Range, VariadicCallType CallType) {
4515
4516 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4517 llvm::any_of(Range&: Args, P: [](const Expr *E) {
4518 return E && E->isInstantiationDependent();
4519 }))
4520 return;
4521
4522 // Printf and scanf checking.
4523 llvm::SmallBitVector CheckedVarArgs;
4524 if (FDecl) {
4525 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4526 // Only create vector if there are format attributes.
4527 CheckedVarArgs.resize(N: Args.size());
4528 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4529 CheckedVarArgs);
4530 }
4531
4532 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4533 CheckedVarArgs.resize(N: Args.size());
4534 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4535 CheckedVarArgs);
4536 }
4537 }
4538
4539 // Refuse POD arguments that weren't caught by the format string
4540 // checks above.
4541 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4542 if (CallType != VariadicCallType::DoesNotApply &&
4543 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4544 unsigned NumParams = Proto ? Proto->getNumParams()
4545 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4546 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4547 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4548 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4549 : 0;
4550
4551 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4552 // Args[ArgIdx] can be null in malformed code.
4553 if (const Expr *Arg = Args[ArgIdx]) {
4554 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4555 checkVariadicArgument(E: Arg, CT: CallType);
4556 }
4557 }
4558 }
4559 if (FD)
4560 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4561 if (FDecl || Proto) {
4562 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4563
4564 // Type safety checking.
4565 if (FDecl) {
4566 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4567 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4568 }
4569 }
4570
4571 // Check that passed arguments match the alignment of original arguments.
4572 // Try to get the missing prototype from the declaration.
4573 if (!Proto && FDecl) {
4574 const auto *FT = FDecl->getFunctionType();
4575 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4576 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4577 }
4578 if (Proto) {
4579 // For variadic functions, we may have more args than parameters.
4580 // For some K&R functions, we may have less args than parameters.
4581 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4582 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4583 bool IsScalableArg = false;
4584 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4585 // Args[ArgIdx] can be null in malformed code.
4586 if (const Expr *Arg = Args[ArgIdx]) {
4587 if (Arg->containsErrors())
4588 continue;
4589
4590 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4591 FDecl->hasLinkage() &&
4592 FDecl->getFormalLinkage() != Linkage::Internal &&
4593 CallType == VariadicCallType::DoesNotApply)
4594 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4595
4596 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4597 if (ParamTy->isSizelessVectorType())
4598 IsScalableArg = true;
4599 QualType ArgTy = Arg->getType();
4600 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4601 ArgTy, ParamTy);
4602 }
4603 }
4604
4605 // If the callee has an AArch64 SME attribute to indicate that it is an
4606 // __arm_streaming function, then the caller requires SME to be available.
4607 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4608 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4609 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4610 llvm::StringMap<bool> CallerFeatureMap;
4611 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4612 if (!CallerFeatureMap.contains(Key: "sme"))
4613 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4614 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4615 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4616 }
4617 }
4618
4619 // If the call requires a streaming-mode change and has scalable vector
4620 // arguments or return values, then warn the user that the streaming and
4621 // non-streaming vector lengths may be different.
4622 // When both streaming and non-streaming vector lengths are defined and
4623 // mismatched, produce an error.
4624 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4625 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4626 (IsScalableArg || IsScalableRet)) {
4627 bool IsCalleeStreaming =
4628 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4629 bool IsCalleeStreamingCompatible =
4630 ExtInfo.AArch64SMEAttributes &
4631 FunctionType::SME_PStateSMCompatibleMask;
4632 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4633 if (!IsCalleeStreamingCompatible &&
4634 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4635 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4636 const LangOptions &LO = getLangOpts();
4637 unsigned VL = LO.VScaleMin * 128;
4638 unsigned SVL = LO.VScaleStreamingMin * 128;
4639 bool IsVLMismatch = VL && SVL && VL != SVL;
4640
4641 auto EmitDiag = [&](bool IsArg) {
4642 if (IsVLMismatch) {
4643 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4644 // Emit warning for streaming-compatible callers
4645 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4646 << IsArg << IsCalleeStreaming << SVL << VL;
4647 else
4648 // Emit error otherwise
4649 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4650 << IsArg << SVL << VL;
4651 } else
4652 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4653 << IsArg;
4654 };
4655
4656 if (IsScalableArg)
4657 EmitDiag(true);
4658 if (IsScalableRet)
4659 EmitDiag(false);
4660 }
4661 }
4662
4663 FunctionType::ArmStateValue CalleeArmZAState =
4664 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4665 FunctionType::ArmStateValue CalleeArmZT0State =
4666 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4667 if (CalleeArmZAState != FunctionType::ARM_None ||
4668 CalleeArmZT0State != FunctionType::ARM_None) {
4669 bool CallerHasZAState = false;
4670 bool CallerHasZT0State = false;
4671 if (CallerFD) {
4672 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4673 if (Attr && Attr->isNewZA())
4674 CallerHasZAState = true;
4675 if (Attr && Attr->isNewZT0())
4676 CallerHasZT0State = true;
4677 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4678 CallerHasZAState |=
4679 FunctionType::getArmZAState(
4680 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4681 FunctionType::ARM_None;
4682 CallerHasZT0State |=
4683 FunctionType::getArmZT0State(
4684 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4685 FunctionType::ARM_None;
4686 }
4687 }
4688
4689 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4690 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4691
4692 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4693 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4694
4695 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4696 CalleeArmZT0State != FunctionType::ARM_None) {
4697 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4698 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4699 }
4700 }
4701 }
4702
4703 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4704 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4705 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4706 if (!Arg->isValueDependent()) {
4707 Expr::EvalResult Align;
4708 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4709 const llvm::APSInt &I = Align.Val.getInt();
4710 if (!I.isPowerOf2())
4711 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4712 << Arg->getSourceRange();
4713
4714 if (I > Sema::MaximumAlignment)
4715 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4716 << Arg->getSourceRange() << Sema::MaximumAlignment;
4717 }
4718 }
4719 }
4720
4721 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4722 !isUnevaluatedContext())
4723 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::err_variadic_device_fn)
4724 << diag::OffloadLang::SYCL;
4725
4726 if (FD)
4727 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4728}
4729
4730void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4731 if (TemplateDecl *Decl =
4732 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4733 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4734 }
4735}
4736
4737void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4738 ArrayRef<const Expr *> Args,
4739 const FunctionProtoType *Proto,
4740 SourceLocation Loc) {
4741 VariadicCallType CallType = Proto->isVariadic()
4742 ? VariadicCallType::Constructor
4743 : VariadicCallType::DoesNotApply;
4744
4745 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4746 CheckArgAlignment(
4747 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4748 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4749
4750 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4751 Loc, Range: SourceRange(), CallType);
4752}
4753
4754bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4755 const FunctionProtoType *Proto) {
4756 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4757 isa<CXXMethodDecl>(Val: FDecl);
4758 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4759 IsMemberOperatorCall;
4760 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4761 Fn: TheCall->getCallee());
4762 Expr** Args = TheCall->getArgs();
4763 unsigned NumArgs = TheCall->getNumArgs();
4764
4765 Expr *ImplicitThis = nullptr;
4766 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4767 // If this is a call to a member operator, hide the first
4768 // argument from checkCall.
4769 // FIXME: Our choice of AST representation here is less than ideal.
4770 ImplicitThis = Args[0];
4771 ++Args;
4772 --NumArgs;
4773 } else if (IsMemberFunction && !FDecl->isStatic() &&
4774 !FDecl->hasCXXExplicitFunctionObjectParameter())
4775 ImplicitThis =
4776 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4777
4778 if (ImplicitThis) {
4779 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4780 // used.
4781 QualType ThisType = ImplicitThis->getType();
4782 if (!ThisType->isPointerType()) {
4783 assert(!ThisType->isReferenceType());
4784 ThisType = Context.getPointerType(T: ThisType);
4785 }
4786
4787 QualType ThisTypeFromDecl = Context.getPointerType(
4788 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4789
4790 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4791 ParamTy: ThisTypeFromDecl);
4792 }
4793
4794 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4795 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4796 Range: TheCall->getCallee()->getSourceRange(), CallType);
4797
4798 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4799 // None of the checks below are needed for functions that don't have
4800 // simple names (e.g., C++ conversion functions).
4801 if (!FnInfo)
4802 return false;
4803
4804 // Enforce TCB except for builtin calls, which are always allowed.
4805 if (FDecl->getBuiltinID() == 0)
4806 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4807
4808 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4809 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4810 CheckInfNaNFunction(Call: TheCall, FDecl);
4811
4812 if (getLangOpts().ObjC)
4813 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4814
4815 unsigned CMId = FDecl->getMemoryFunctionKind();
4816
4817 // Handle memory setting and copying functions.
4818 switch (CMId) {
4819 case 0:
4820 return false;
4821 case Builtin::BIstrlcpy: // fallthrough
4822 case Builtin::BIstrlcat:
4823 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4824 break;
4825 case Builtin::BIstrncat:
4826 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4827 break;
4828 case Builtin::BIfree:
4829 CheckFreeArguments(E: TheCall);
4830 break;
4831 default:
4832 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4833 }
4834
4835 return false;
4836}
4837
4838bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4839 const FunctionProtoType *Proto) {
4840 QualType Ty;
4841 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4842 Ty = V->getType().getNonReferenceType();
4843 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4844 Ty = F->getType().getNonReferenceType();
4845 else
4846 return false;
4847
4848 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4849 !Ty->isFunctionProtoType())
4850 return false;
4851
4852 VariadicCallType CallType;
4853 if (!Proto || !Proto->isVariadic()) {
4854 CallType = VariadicCallType::DoesNotApply;
4855 } else if (Ty->isBlockPointerType()) {
4856 CallType = VariadicCallType::Block;
4857 } else { // Ty->isFunctionPointerType()
4858 CallType = VariadicCallType::Function;
4859 }
4860
4861 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4862 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4863 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4864 Range: TheCall->getCallee()->getSourceRange(), CallType);
4865
4866 return false;
4867}
4868
4869bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4870 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4871 Fn: TheCall->getCallee());
4872 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4873 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4874 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4875 Range: TheCall->getCallee()->getSourceRange(), CallType);
4876
4877 return false;
4878}
4879
4880static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4881 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4882 return false;
4883
4884 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4885 switch (Op) {
4886 case AtomicExpr::AO__c11_atomic_init:
4887 case AtomicExpr::AO__opencl_atomic_init:
4888 llvm_unreachable("There is no ordering argument for an init");
4889
4890 case AtomicExpr::AO__c11_atomic_load:
4891 case AtomicExpr::AO__opencl_atomic_load:
4892 case AtomicExpr::AO__hip_atomic_load:
4893 case AtomicExpr::AO__atomic_load_n:
4894 case AtomicExpr::AO__atomic_load:
4895 case AtomicExpr::AO__scoped_atomic_load_n:
4896 case AtomicExpr::AO__scoped_atomic_load:
4897 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4898 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4899
4900 case AtomicExpr::AO__c11_atomic_store:
4901 case AtomicExpr::AO__opencl_atomic_store:
4902 case AtomicExpr::AO__hip_atomic_store:
4903 case AtomicExpr::AO__atomic_store:
4904 case AtomicExpr::AO__atomic_store_n:
4905 case AtomicExpr::AO__scoped_atomic_store:
4906 case AtomicExpr::AO__scoped_atomic_store_n:
4907 case AtomicExpr::AO__atomic_clear:
4908 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4909 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4910 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4911
4912 default:
4913 return true;
4914 }
4915}
4916
4917ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4918 AtomicExpr::AtomicOp Op) {
4919 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4920 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4921 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4922 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4923 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4924 Op);
4925}
4926
4927/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4928/// equivalents. Provide a fixit when the scope is a compile-time constant and
4929/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4930/// compare_exchange builtins differ in how they accept the desired value, so
4931/// only a warning (without a fixit) is emitted for those.
4932static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange,
4933 MultiExprArg Args,
4934 AtomicExpr::AtomicOp Op) {
4935 StringRef OldName;
4936 StringRef NewName;
4937 bool CanFixIt;
4938
4939 switch (Op) {
4940#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4941 case AtomicExpr::AO__hip_atomic_##hip: \
4942 OldName = "__hip_atomic_" #hip; \
4943 NewName = "__scoped_atomic_" #scoped; \
4944 CanFixIt = true; \
4945 break;
4946 HIP_ATOMIC_FIXABLE(load, load_n)
4947 HIP_ATOMIC_FIXABLE(store, store_n)
4948 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4949 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4950 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4951 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4952 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4953 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4954 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4955 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4956#undef HIP_ATOMIC_FIXABLE
4957 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4958 OldName = "__hip_atomic_compare_exchange_weak";
4959 NewName = "__scoped_atomic_compare_exchange";
4960 CanFixIt = false;
4961 break;
4962 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4963 OldName = "__hip_atomic_compare_exchange_strong";
4964 NewName = "__scoped_atomic_compare_exchange";
4965 CanFixIt = false;
4966 break;
4967 default:
4968 llvm_unreachable("unhandled HIP atomic op");
4969 }
4970
4971 auto DB = S.Diag(Loc: ExprRange.getBegin(), DiagID: diag::warn_hip_deprecated_builtin)
4972 << OldName << NewName;
4973 if (!CanFixIt)
4974 return;
4975
4976 DB << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: NewName);
4977
4978 Expr *Scope = Args[Args.size() - 1];
4979 std::optional<llvm::APSInt> ScopeVal =
4980 Scope->getIntegerConstantExpr(Ctx: S.Context);
4981 if (!ScopeVal)
4982 return;
4983
4984 StringRef ScopeName;
4985 switch (ScopeVal->getZExtValue()) {
4986 case AtomicScopeHIPModel::SingleThread:
4987 ScopeName = "__MEMORY_SCOPE_SINGLE";
4988 break;
4989 case AtomicScopeHIPModel::Wavefront:
4990 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4991 break;
4992 case AtomicScopeHIPModel::Workgroup:
4993 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4994 break;
4995 case AtomicScopeHIPModel::Agent:
4996 ScopeName = "__MEMORY_SCOPE_DEVICE";
4997 break;
4998 case AtomicScopeHIPModel::System:
4999 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5000 break;
5001 case AtomicScopeHIPModel::Cluster:
5002 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5003 break;
5004 default:
5005 return;
5006 }
5007
5008 DB << FixItHint::CreateReplacement(
5009 RemoveRange: CharSourceRange::getTokenRange(R: Scope->getSourceRange()), Code: ScopeName);
5010}
5011
5012ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5013 SourceLocation RParenLoc, MultiExprArg Args,
5014 AtomicExpr::AtomicOp Op,
5015 AtomicArgumentOrder ArgOrder) {
5016 // All the non-OpenCL operations take one of the following forms.
5017 // The OpenCL operations take the __c11 forms with one extra argument for
5018 // synchronization scope.
5019 enum {
5020 // C __c11_atomic_init(A *, C)
5021 Init,
5022
5023 // C __c11_atomic_load(A *, int)
5024 Load,
5025
5026 // void __atomic_load(A *, CP, int)
5027 LoadCopy,
5028
5029 // void __atomic_store(A *, CP, int)
5030 Copy,
5031
5032 // C __c11_atomic_add(A *, M, int)
5033 Arithmetic,
5034
5035 // C __atomic_exchange_n(A *, CP, int)
5036 Xchg,
5037
5038 // void __atomic_exchange(A *, C *, CP, int)
5039 GNUXchg,
5040
5041 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5042 C11CmpXchg,
5043
5044 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5045 GNUCmpXchg,
5046
5047 // bool __atomic_test_and_set(A *, int)
5048 TestAndSetByte,
5049
5050 // void __atomic_clear(A *, int)
5051 ClearByte,
5052 } Form = Init;
5053
5054 const unsigned NumForm = ClearByte + 1;
5055 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5056 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5057 // where:
5058 // C is an appropriate type,
5059 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5060 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5061 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5062 // the int parameters are for orderings.
5063
5064 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5065 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5066 "need to update code for modified forms");
5067 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5068 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5069 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5070 "need to update code for modified C11 atomics");
5071 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5072 Op <= AtomicExpr::AO__opencl_atomic_store;
5073 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5074 Op <= AtomicExpr::AO__hip_atomic_store;
5075 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5076 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5077 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5078 Op <= AtomicExpr::AO__c11_atomic_store) ||
5079 IsOpenCL;
5080 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5081 Op == AtomicExpr::AO__atomic_store_n ||
5082 Op == AtomicExpr::AO__atomic_exchange_n ||
5083 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5084 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5085 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5086 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5087 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5088 // Bit mask for extra allowed value types other than integers for atomic
5089 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5090 // allow floating point.
5091 enum ArithOpExtraValueType {
5092 AOEVT_None = 0,
5093 AOEVT_Pointer = 1,
5094 AOEVT_FP = 2,
5095 AOEVT_Int = 4,
5096 };
5097 unsigned ArithAllows = AOEVT_None;
5098
5099 switch (Op) {
5100 case AtomicExpr::AO__c11_atomic_init:
5101 case AtomicExpr::AO__opencl_atomic_init:
5102 Form = Init;
5103 break;
5104
5105 case AtomicExpr::AO__c11_atomic_load:
5106 case AtomicExpr::AO__opencl_atomic_load:
5107 case AtomicExpr::AO__hip_atomic_load:
5108 case AtomicExpr::AO__atomic_load_n:
5109 case AtomicExpr::AO__scoped_atomic_load_n:
5110 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5111 Form = Load;
5112 break;
5113
5114 case AtomicExpr::AO__atomic_load:
5115 case AtomicExpr::AO__scoped_atomic_load:
5116 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5117 Form = LoadCopy;
5118 break;
5119
5120 case AtomicExpr::AO__c11_atomic_store:
5121 case AtomicExpr::AO__opencl_atomic_store:
5122 case AtomicExpr::AO__hip_atomic_store:
5123 case AtomicExpr::AO__atomic_store:
5124 case AtomicExpr::AO__atomic_store_n:
5125 case AtomicExpr::AO__scoped_atomic_store:
5126 case AtomicExpr::AO__scoped_atomic_store_n:
5127 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5128 Form = Copy;
5129 break;
5130 case AtomicExpr::AO__atomic_fetch_add:
5131 case AtomicExpr::AO__atomic_fetch_sub:
5132 case AtomicExpr::AO__atomic_add_fetch:
5133 case AtomicExpr::AO__atomic_sub_fetch:
5134 case AtomicExpr::AO__scoped_atomic_fetch_add:
5135 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5136 case AtomicExpr::AO__scoped_atomic_add_fetch:
5137 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5138 case AtomicExpr::AO__c11_atomic_fetch_add:
5139 case AtomicExpr::AO__c11_atomic_fetch_sub:
5140 case AtomicExpr::AO__opencl_atomic_fetch_add:
5141 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5142 case AtomicExpr::AO__hip_atomic_fetch_add:
5143 case AtomicExpr::AO__hip_atomic_fetch_sub:
5144 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5145 Form = Arithmetic;
5146 break;
5147 case AtomicExpr::AO__atomic_fetch_fminimum:
5148 case AtomicExpr::AO__atomic_fetch_fmaximum:
5149 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5150 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5151 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5152 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5153 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5154 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5155 ArithAllows = AOEVT_FP;
5156 Form = Arithmetic;
5157 break;
5158 case AtomicExpr::AO__atomic_fetch_max:
5159 case AtomicExpr::AO__atomic_fetch_min:
5160 case AtomicExpr::AO__atomic_max_fetch:
5161 case AtomicExpr::AO__atomic_min_fetch:
5162 case AtomicExpr::AO__scoped_atomic_fetch_max:
5163 case AtomicExpr::AO__scoped_atomic_fetch_min:
5164 case AtomicExpr::AO__scoped_atomic_max_fetch:
5165 case AtomicExpr::AO__scoped_atomic_min_fetch:
5166 case AtomicExpr::AO__c11_atomic_fetch_max:
5167 case AtomicExpr::AO__c11_atomic_fetch_min:
5168 case AtomicExpr::AO__opencl_atomic_fetch_max:
5169 case AtomicExpr::AO__opencl_atomic_fetch_min:
5170 case AtomicExpr::AO__hip_atomic_fetch_max:
5171 case AtomicExpr::AO__hip_atomic_fetch_min:
5172 ArithAllows = AOEVT_Int | AOEVT_FP;
5173 Form = Arithmetic;
5174 break;
5175 case AtomicExpr::AO__c11_atomic_fetch_and:
5176 case AtomicExpr::AO__c11_atomic_fetch_or:
5177 case AtomicExpr::AO__c11_atomic_fetch_xor:
5178 case AtomicExpr::AO__hip_atomic_fetch_and:
5179 case AtomicExpr::AO__hip_atomic_fetch_or:
5180 case AtomicExpr::AO__hip_atomic_fetch_xor:
5181 case AtomicExpr::AO__c11_atomic_fetch_nand:
5182 case AtomicExpr::AO__opencl_atomic_fetch_and:
5183 case AtomicExpr::AO__opencl_atomic_fetch_or:
5184 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5185 case AtomicExpr::AO__atomic_fetch_and:
5186 case AtomicExpr::AO__atomic_fetch_or:
5187 case AtomicExpr::AO__atomic_fetch_xor:
5188 case AtomicExpr::AO__atomic_fetch_nand:
5189 case AtomicExpr::AO__atomic_and_fetch:
5190 case AtomicExpr::AO__atomic_or_fetch:
5191 case AtomicExpr::AO__atomic_xor_fetch:
5192 case AtomicExpr::AO__atomic_nand_fetch:
5193 case AtomicExpr::AO__atomic_fetch_uinc:
5194 case AtomicExpr::AO__atomic_fetch_udec:
5195 case AtomicExpr::AO__scoped_atomic_fetch_and:
5196 case AtomicExpr::AO__scoped_atomic_fetch_or:
5197 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5198 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5199 case AtomicExpr::AO__scoped_atomic_and_fetch:
5200 case AtomicExpr::AO__scoped_atomic_or_fetch:
5201 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5202 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5203 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5204 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5205 Form = Arithmetic;
5206 break;
5207
5208 case AtomicExpr::AO__c11_atomic_exchange:
5209 case AtomicExpr::AO__hip_atomic_exchange:
5210 case AtomicExpr::AO__opencl_atomic_exchange:
5211 case AtomicExpr::AO__atomic_exchange_n:
5212 case AtomicExpr::AO__scoped_atomic_exchange_n:
5213 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5214 Form = Xchg;
5215 break;
5216
5217 case AtomicExpr::AO__atomic_exchange:
5218 case AtomicExpr::AO__scoped_atomic_exchange:
5219 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5220 Form = GNUXchg;
5221 break;
5222
5223 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5224 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5225 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5226 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5227 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5228 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5229 Form = C11CmpXchg;
5230 break;
5231
5232 case AtomicExpr::AO__atomic_compare_exchange:
5233 case AtomicExpr::AO__atomic_compare_exchange_n:
5234 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5235 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5236 ArithAllows = AOEVT_Pointer;
5237 Form = GNUCmpXchg;
5238 break;
5239
5240 case AtomicExpr::AO__atomic_test_and_set:
5241 Form = TestAndSetByte;
5242 break;
5243
5244 case AtomicExpr::AO__atomic_clear:
5245 Form = ClearByte;
5246 break;
5247 }
5248
5249 unsigned AdjustedNumArgs = NumArgs[Form];
5250 if ((IsOpenCL || IsHIP || IsScoped) &&
5251 Op != AtomicExpr::AO__opencl_atomic_init)
5252 ++AdjustedNumArgs;
5253 // Check we have the right number of arguments.
5254 if (Args.size() < AdjustedNumArgs) {
5255 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
5256 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5257 << /*is non object*/ 0 << ExprRange;
5258 return ExprError();
5259 } else if (Args.size() > AdjustedNumArgs) {
5260 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
5261 DiagID: diag::err_typecheck_call_too_many_args)
5262 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5263 << /*is non object*/ 0 << ExprRange;
5264 return ExprError();
5265 }
5266
5267 // Inspect the first argument of the atomic operation.
5268 Expr *Ptr = Args[0];
5269 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
5270 if (ConvertedPtr.isInvalid())
5271 return ExprError();
5272
5273 Ptr = ConvertedPtr.get();
5274 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5275 if (!pointerType) {
5276 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5277 << Ptr->getType() << 0 << Ptr->getSourceRange();
5278 return ExprError();
5279 }
5280
5281 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5282 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5283 QualType ValType = AtomTy; // 'C'
5284 if (IsC11) {
5285 if (!AtomTy->isAtomicType()) {
5286 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
5287 << Ptr->getType() << Ptr->getSourceRange();
5288 return ExprError();
5289 }
5290 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5291 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5292 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
5293 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5294 << Ptr->getSourceRange();
5295 return ExprError();
5296 }
5297 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5298 } else if (Form != Load && Form != LoadCopy) {
5299 if (ValType.isConstQualified()) {
5300 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
5301 << Ptr->getType() << Ptr->getSourceRange();
5302 return ExprError();
5303 }
5304 }
5305
5306 if (Form != TestAndSetByte && Form != ClearByte) {
5307 // Pointer to object of size zero is not allowed.
5308 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
5309 DiagID: diag::err_incomplete_type))
5310 return ExprError();
5311
5312 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
5313 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5314 << Ptr->getType() << 1 << Ptr->getSourceRange();
5315 return ExprError();
5316 }
5317 } else {
5318 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5319 // non-const pointer type, including void* and pointers to incomplete
5320 // structs, but only access the first byte.
5321 AtomTy = Context.CharTy;
5322 AtomTy = AtomTy.withCVRQualifiers(
5323 CVR: pointerType->getPointeeType().getCVRQualifiers());
5324 QualType PointerQT = Context.getPointerType(T: AtomTy);
5325 pointerType = PointerQT->getAs<PointerType>();
5326 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
5327 ValType = AtomTy;
5328 }
5329
5330 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5331 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5332 Diag(Loc: ExprRange.getBegin(),
5333 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5334 << 0 << Ptr->getType() << Ptr->getSourceRange();
5335 return ExprError();
5336 }
5337
5338 // For an arithmetic operation, the implied arithmetic must be well-formed.
5339 // For _n operations, the value type must also be a valid atomic type.
5340 if (Form == Arithmetic || IsN) {
5341 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5342 // trivial type errors.
5343 auto IsAllowedValueType = [&](QualType ValType,
5344 unsigned AllowedType) -> bool {
5345 bool IsX87LongDouble =
5346 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
5347 &Context.getTargetInfo().getLongDoubleFormat() ==
5348 &llvm::APFloat::x87DoubleExtended();
5349 if (ValType->isIntegerType())
5350 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5351 // integers. Explicit AOEVT_Int or other combinations allow integers.
5352 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5353 if (ValType->isPointerType())
5354 return AllowedType & AOEVT_Pointer;
5355 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5356 return false;
5357 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5358 if (IsX87LongDouble)
5359 return false;
5360 return true;
5361 };
5362 if (!IsAllowedValueType(ValType, ArithAllows)) {
5363 auto DID =
5364 ArithAllows == AOEVT_FP
5365 ? diag::err_atomic_op_needs_atomic_fp
5366 : (ArithAllows & AOEVT_FP
5367 ? (ArithAllows & AOEVT_Pointer
5368 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5369 : diag::err_atomic_op_needs_atomic_int_or_fp)
5370 : (ArithAllows & AOEVT_Pointer
5371 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5372 : diag::err_atomic_op_needs_atomic_int));
5373 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
5374 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5375 return ExprError();
5376 }
5377 if (IsC11 && ValType->isPointerType() &&
5378 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
5379 DiagID: diag::err_incomplete_type)) {
5380 return ExprError();
5381 }
5382 }
5383
5384 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5385 !AtomTy->isScalarType()) {
5386 // For GNU atomics, require a trivially-copyable type. This is not part of
5387 // the GNU atomics specification but we enforce it for consistency with
5388 // other atomics which generally all require a trivially-copyable type. This
5389 // is because atomics just copy bits.
5390 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
5391 << Ptr->getType() << Ptr->getSourceRange();
5392 return ExprError();
5393 }
5394
5395 switch (ValType.getObjCLifetime()) {
5396 case Qualifiers::OCL_None:
5397 case Qualifiers::OCL_ExplicitNone:
5398 // okay
5399 break;
5400
5401 case Qualifiers::OCL_Weak:
5402 case Qualifiers::OCL_Strong:
5403 case Qualifiers::OCL_Autoreleasing:
5404 // FIXME: Can this happen? By this point, ValType should be known
5405 // to be trivially copyable.
5406 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
5407 << ValType << Ptr->getSourceRange();
5408 return ExprError();
5409 }
5410
5411 // All atomic operations have an overload which takes a pointer to a volatile
5412 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5413 // into the result or the other operands. Similarly atomic_load takes a
5414 // pointer to a const 'A'.
5415 ValType.removeLocalVolatile();
5416 ValType.removeLocalConst();
5417 QualType ResultType = ValType;
5418 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5419 Form == ClearByte)
5420 ResultType = Context.VoidTy;
5421 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5422 ResultType = Context.BoolTy;
5423
5424 // The type of a parameter passed 'by value'. In the GNU atomics, such
5425 // arguments are actually passed as pointers.
5426 QualType ByValType = ValType; // 'CP'
5427 bool IsPassedByAddress = false;
5428 if (!IsC11 && !IsHIP && !IsN) {
5429 ByValType = Ptr->getType();
5430 IsPassedByAddress = true;
5431 }
5432
5433 SmallVector<Expr *, 5> APIOrderedArgs;
5434 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5435 APIOrderedArgs.push_back(Elt: Args[0]);
5436 switch (Form) {
5437 case Init:
5438 case Load:
5439 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
5440 break;
5441 case LoadCopy:
5442 case Copy:
5443 case Arithmetic:
5444 case Xchg:
5445 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5446 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5447 break;
5448 case GNUXchg:
5449 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5450 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
5451 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5452 break;
5453 case C11CmpXchg:
5454 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5455 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5456 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5457 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5458 break;
5459 case GNUCmpXchg:
5460 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5461 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5462 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5463 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5464 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5465 break;
5466 case TestAndSetByte:
5467 case ClearByte:
5468 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5469 break;
5470 }
5471 } else
5472 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5473
5474 // The first argument's non-CV pointer type is used to deduce the type of
5475 // subsequent arguments, except for:
5476 // - weak flag (always converted to bool)
5477 // - memory order (always converted to int)
5478 // - scope (always converted to int)
5479 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5480 QualType Ty;
5481 if (i < NumVals[Form] + 1) {
5482 switch (i) {
5483 case 0:
5484 // The first argument is always a pointer. It has a fixed type.
5485 // It is always dereferenced, a nullptr is undefined.
5486 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5487 // Nothing else to do: we already know all we want about this pointer.
5488 continue;
5489 case 1:
5490 // The second argument is the non-atomic operand. For arithmetic, this
5491 // is always passed by value, and for a compare_exchange it is always
5492 // passed by address. For the rest, GNU uses by-address and C11 uses
5493 // by-value.
5494 assert(Form != Load);
5495 if (Form == Arithmetic && ValType->isPointerType())
5496 Ty = Context.getPointerDiffType();
5497 else if (Form == Init || Form == Arithmetic)
5498 Ty = ValType;
5499 else if (Form == Copy || Form == Xchg) {
5500 if (IsPassedByAddress) {
5501 // The value pointer is always dereferenced, a nullptr is undefined.
5502 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5503 CallSiteLoc: ExprRange.getBegin());
5504 }
5505 Ty = ByValType;
5506 } else {
5507 Expr *ValArg = APIOrderedArgs[i];
5508 // The value pointer is always dereferenced, a nullptr is undefined.
5509 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5510 LangAS AS = LangAS::Default;
5511 // Keep address space of non-atomic pointer type.
5512 if (const PointerType *PtrTy =
5513 ValArg->getType()->getAs<PointerType>()) {
5514 AS = PtrTy->getPointeeType().getAddressSpace();
5515 }
5516 Ty = Context.getPointerType(
5517 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5518 }
5519 break;
5520 case 2:
5521 // The third argument to compare_exchange / GNU exchange is the desired
5522 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5523 if (IsPassedByAddress)
5524 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5525 Ty = ByValType;
5526 break;
5527 case 3:
5528 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5529 Ty = Context.BoolTy;
5530 break;
5531 }
5532 } else {
5533 // The order(s) and scope are always converted to int.
5534 Ty = Context.IntTy;
5535 }
5536
5537 InitializedEntity Entity =
5538 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5539 ExprResult Arg = APIOrderedArgs[i];
5540 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5541 if (Arg.isInvalid())
5542 return true;
5543 APIOrderedArgs[i] = Arg.get();
5544 }
5545
5546 // Permute the arguments into a 'consistent' order.
5547 SmallVector<Expr*, 5> SubExprs;
5548 SubExprs.push_back(Elt: Ptr);
5549 switch (Form) {
5550 case Init:
5551 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5552 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5553 break;
5554 case Load:
5555 case TestAndSetByte:
5556 case ClearByte:
5557 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5558 break;
5559 case LoadCopy:
5560 case Copy:
5561 case Arithmetic:
5562 case Xchg:
5563 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5564 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5565 break;
5566 case GNUXchg:
5567 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5568 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5569 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5570 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5571 break;
5572 case C11CmpXchg:
5573 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5574 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5575 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5576 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5577 break;
5578 case GNUCmpXchg:
5579 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5580 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5581 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5582 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5583 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5584 break;
5585 }
5586
5587 // If the memory orders are constants, check they are valid.
5588 if (SubExprs.size() >= 2 && Form != Init) {
5589 std::optional<llvm::APSInt> Success =
5590 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5591 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5592 Diag(Loc: SubExprs[1]->getBeginLoc(),
5593 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5594 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5595 << SubExprs[1]->getSourceRange();
5596 }
5597 if (SubExprs.size() >= 5) {
5598 if (std::optional<llvm::APSInt> Failure =
5599 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5600 if (!llvm::is_contained(
5601 Set: {llvm::AtomicOrderingCABI::relaxed,
5602 llvm::AtomicOrderingCABI::consume,
5603 llvm::AtomicOrderingCABI::acquire,
5604 llvm::AtomicOrderingCABI::seq_cst},
5605 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5606 Diag(Loc: SubExprs[3]->getBeginLoc(),
5607 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5608 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5609 }
5610 }
5611 }
5612 }
5613
5614 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5615 auto *Scope = Args[Args.size() - 1];
5616 if (std::optional<llvm::APSInt> Result =
5617 Scope->getIntegerConstantExpr(Ctx: Context)) {
5618 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5619 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5620 << Scope->getSourceRange();
5621 }
5622 SubExprs.push_back(Elt: Scope);
5623 }
5624
5625 if (IsHIP)
5626 DiagnoseDeprecatedHIPAtomic(S&: *this, ExprRange, Args, Op);
5627
5628 AtomicExpr *AE = new (Context)
5629 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5630
5631 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5632 Op == AtomicExpr::AO__c11_atomic_store ||
5633 Op == AtomicExpr::AO__opencl_atomic_load ||
5634 Op == AtomicExpr::AO__hip_atomic_load ||
5635 Op == AtomicExpr::AO__opencl_atomic_store ||
5636 Op == AtomicExpr::AO__hip_atomic_store) &&
5637 Context.AtomicUsesUnsupportedLibcall(E: AE))
5638 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5639 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5640 Op == AtomicExpr::AO__opencl_atomic_load ||
5641 Op == AtomicExpr::AO__hip_atomic_load)
5642 ? 0
5643 : 1);
5644
5645 if (ValType->isBitIntType()) {
5646 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5647 return ExprError();
5648 }
5649
5650 return AE;
5651}
5652
5653/// checkBuiltinArgument - Given a call to a builtin function, perform
5654/// normal type-checking on the given argument, updating the call in
5655/// place. This is useful when a builtin function requires custom
5656/// type-checking for some of its arguments but not necessarily all of
5657/// them.
5658///
5659/// Returns true on error.
5660static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5661 FunctionDecl *Fn = E->getDirectCallee();
5662 assert(Fn && "builtin call without direct callee!");
5663
5664 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5665 InitializedEntity Entity =
5666 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5667
5668 ExprResult Arg = E->getArg(Arg: ArgIndex);
5669 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5670 if (Arg.isInvalid())
5671 return true;
5672
5673 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5674 return false;
5675}
5676
5677ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5678 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5679 Expr *Callee = TheCall->getCallee();
5680 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5681 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5682
5683 // Ensure that we have at least one argument to do type inference from.
5684 if (TheCall->getNumArgs() < 1) {
5685 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5686 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5687 << Callee->getSourceRange();
5688 return ExprError();
5689 }
5690
5691 // Inspect the first argument of the atomic builtin. This should always be
5692 // a pointer type, whose element is an integral scalar or pointer type.
5693 // Because it is a pointer type, we don't have to worry about any implicit
5694 // casts here.
5695 // FIXME: We don't allow floating point scalars as input.
5696 Expr *FirstArg = TheCall->getArg(Arg: 0);
5697 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5698 if (FirstArgResult.isInvalid())
5699 return ExprError();
5700 FirstArg = FirstArgResult.get();
5701 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5702
5703 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5704 if (!pointerType) {
5705 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5706 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5707 return ExprError();
5708 }
5709
5710 QualType ValType = pointerType->getPointeeType();
5711 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5712 !ValType->isBlockPointerType()) {
5713 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5714 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5715 return ExprError();
5716 }
5717 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5718 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5719 Diag(Loc: FirstArg->getBeginLoc(),
5720 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5721 << 1 << ValType << FirstArg->getSourceRange();
5722 return ExprError();
5723 }
5724
5725 if (ValType.isConstQualified()) {
5726 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5727 << FirstArg->getType() << FirstArg->getSourceRange();
5728 return ExprError();
5729 }
5730
5731 switch (ValType.getObjCLifetime()) {
5732 case Qualifiers::OCL_None:
5733 case Qualifiers::OCL_ExplicitNone:
5734 // okay
5735 break;
5736
5737 case Qualifiers::OCL_Weak:
5738 case Qualifiers::OCL_Strong:
5739 case Qualifiers::OCL_Autoreleasing:
5740 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5741 << ValType << FirstArg->getSourceRange();
5742 return ExprError();
5743 }
5744
5745 // Strip any qualifiers off ValType.
5746 ValType = ValType.getUnqualifiedType();
5747
5748 // The majority of builtins return a value, but a few have special return
5749 // types, so allow them to override appropriately below.
5750 QualType ResultType = ValType;
5751
5752 // We need to figure out which concrete builtin this maps onto. For example,
5753 // __sync_fetch_and_add with a 2 byte object turns into
5754 // __sync_fetch_and_add_2.
5755#define BUILTIN_ROW(x) \
5756 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5757 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5758
5759 static const unsigned BuiltinIndices[][5] = {
5760 BUILTIN_ROW(__sync_fetch_and_add),
5761 BUILTIN_ROW(__sync_fetch_and_sub),
5762 BUILTIN_ROW(__sync_fetch_and_or),
5763 BUILTIN_ROW(__sync_fetch_and_and),
5764 BUILTIN_ROW(__sync_fetch_and_xor),
5765 BUILTIN_ROW(__sync_fetch_and_nand),
5766
5767 BUILTIN_ROW(__sync_add_and_fetch),
5768 BUILTIN_ROW(__sync_sub_and_fetch),
5769 BUILTIN_ROW(__sync_and_and_fetch),
5770 BUILTIN_ROW(__sync_or_and_fetch),
5771 BUILTIN_ROW(__sync_xor_and_fetch),
5772 BUILTIN_ROW(__sync_nand_and_fetch),
5773
5774 BUILTIN_ROW(__sync_val_compare_and_swap),
5775 BUILTIN_ROW(__sync_bool_compare_and_swap),
5776 BUILTIN_ROW(__sync_lock_test_and_set),
5777 BUILTIN_ROW(__sync_lock_release),
5778 BUILTIN_ROW(__sync_swap)
5779 };
5780#undef BUILTIN_ROW
5781
5782 // Determine the index of the size.
5783 unsigned SizeIndex;
5784 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5785 case 1: SizeIndex = 0; break;
5786 case 2: SizeIndex = 1; break;
5787 case 4: SizeIndex = 2; break;
5788 case 8: SizeIndex = 3; break;
5789 case 16: SizeIndex = 4; break;
5790 default:
5791 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5792 << FirstArg->getType() << FirstArg->getSourceRange();
5793 return ExprError();
5794 }
5795
5796 // Each of these builtins has one pointer argument, followed by some number of
5797 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5798 // that we ignore. Find out which row of BuiltinIndices to read from as well
5799 // as the number of fixed args.
5800 unsigned BuiltinID = FDecl->getBuiltinID();
5801 unsigned BuiltinIndex, NumFixed = 1;
5802 bool WarnAboutSemanticsChange = false;
5803 switch (BuiltinID) {
5804 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5805 case Builtin::BI__sync_fetch_and_add:
5806 case Builtin::BI__sync_fetch_and_add_1:
5807 case Builtin::BI__sync_fetch_and_add_2:
5808 case Builtin::BI__sync_fetch_and_add_4:
5809 case Builtin::BI__sync_fetch_and_add_8:
5810 case Builtin::BI__sync_fetch_and_add_16:
5811 BuiltinIndex = 0;
5812 break;
5813
5814 case Builtin::BI__sync_fetch_and_sub:
5815 case Builtin::BI__sync_fetch_and_sub_1:
5816 case Builtin::BI__sync_fetch_and_sub_2:
5817 case Builtin::BI__sync_fetch_and_sub_4:
5818 case Builtin::BI__sync_fetch_and_sub_8:
5819 case Builtin::BI__sync_fetch_and_sub_16:
5820 BuiltinIndex = 1;
5821 break;
5822
5823 case Builtin::BI__sync_fetch_and_or:
5824 case Builtin::BI__sync_fetch_and_or_1:
5825 case Builtin::BI__sync_fetch_and_or_2:
5826 case Builtin::BI__sync_fetch_and_or_4:
5827 case Builtin::BI__sync_fetch_and_or_8:
5828 case Builtin::BI__sync_fetch_and_or_16:
5829 BuiltinIndex = 2;
5830 break;
5831
5832 case Builtin::BI__sync_fetch_and_and:
5833 case Builtin::BI__sync_fetch_and_and_1:
5834 case Builtin::BI__sync_fetch_and_and_2:
5835 case Builtin::BI__sync_fetch_and_and_4:
5836 case Builtin::BI__sync_fetch_and_and_8:
5837 case Builtin::BI__sync_fetch_and_and_16:
5838 BuiltinIndex = 3;
5839 break;
5840
5841 case Builtin::BI__sync_fetch_and_xor:
5842 case Builtin::BI__sync_fetch_and_xor_1:
5843 case Builtin::BI__sync_fetch_and_xor_2:
5844 case Builtin::BI__sync_fetch_and_xor_4:
5845 case Builtin::BI__sync_fetch_and_xor_8:
5846 case Builtin::BI__sync_fetch_and_xor_16:
5847 BuiltinIndex = 4;
5848 break;
5849
5850 case Builtin::BI__sync_fetch_and_nand:
5851 case Builtin::BI__sync_fetch_and_nand_1:
5852 case Builtin::BI__sync_fetch_and_nand_2:
5853 case Builtin::BI__sync_fetch_and_nand_4:
5854 case Builtin::BI__sync_fetch_and_nand_8:
5855 case Builtin::BI__sync_fetch_and_nand_16:
5856 BuiltinIndex = 5;
5857 WarnAboutSemanticsChange = true;
5858 break;
5859
5860 case Builtin::BI__sync_add_and_fetch:
5861 case Builtin::BI__sync_add_and_fetch_1:
5862 case Builtin::BI__sync_add_and_fetch_2:
5863 case Builtin::BI__sync_add_and_fetch_4:
5864 case Builtin::BI__sync_add_and_fetch_8:
5865 case Builtin::BI__sync_add_and_fetch_16:
5866 BuiltinIndex = 6;
5867 break;
5868
5869 case Builtin::BI__sync_sub_and_fetch:
5870 case Builtin::BI__sync_sub_and_fetch_1:
5871 case Builtin::BI__sync_sub_and_fetch_2:
5872 case Builtin::BI__sync_sub_and_fetch_4:
5873 case Builtin::BI__sync_sub_and_fetch_8:
5874 case Builtin::BI__sync_sub_and_fetch_16:
5875 BuiltinIndex = 7;
5876 break;
5877
5878 case Builtin::BI__sync_and_and_fetch:
5879 case Builtin::BI__sync_and_and_fetch_1:
5880 case Builtin::BI__sync_and_and_fetch_2:
5881 case Builtin::BI__sync_and_and_fetch_4:
5882 case Builtin::BI__sync_and_and_fetch_8:
5883 case Builtin::BI__sync_and_and_fetch_16:
5884 BuiltinIndex = 8;
5885 break;
5886
5887 case Builtin::BI__sync_or_and_fetch:
5888 case Builtin::BI__sync_or_and_fetch_1:
5889 case Builtin::BI__sync_or_and_fetch_2:
5890 case Builtin::BI__sync_or_and_fetch_4:
5891 case Builtin::BI__sync_or_and_fetch_8:
5892 case Builtin::BI__sync_or_and_fetch_16:
5893 BuiltinIndex = 9;
5894 break;
5895
5896 case Builtin::BI__sync_xor_and_fetch:
5897 case Builtin::BI__sync_xor_and_fetch_1:
5898 case Builtin::BI__sync_xor_and_fetch_2:
5899 case Builtin::BI__sync_xor_and_fetch_4:
5900 case Builtin::BI__sync_xor_and_fetch_8:
5901 case Builtin::BI__sync_xor_and_fetch_16:
5902 BuiltinIndex = 10;
5903 break;
5904
5905 case Builtin::BI__sync_nand_and_fetch:
5906 case Builtin::BI__sync_nand_and_fetch_1:
5907 case Builtin::BI__sync_nand_and_fetch_2:
5908 case Builtin::BI__sync_nand_and_fetch_4:
5909 case Builtin::BI__sync_nand_and_fetch_8:
5910 case Builtin::BI__sync_nand_and_fetch_16:
5911 BuiltinIndex = 11;
5912 WarnAboutSemanticsChange = true;
5913 break;
5914
5915 case Builtin::BI__sync_val_compare_and_swap:
5916 case Builtin::BI__sync_val_compare_and_swap_1:
5917 case Builtin::BI__sync_val_compare_and_swap_2:
5918 case Builtin::BI__sync_val_compare_and_swap_4:
5919 case Builtin::BI__sync_val_compare_and_swap_8:
5920 case Builtin::BI__sync_val_compare_and_swap_16:
5921 BuiltinIndex = 12;
5922 NumFixed = 2;
5923 break;
5924
5925 case Builtin::BI__sync_bool_compare_and_swap:
5926 case Builtin::BI__sync_bool_compare_and_swap_1:
5927 case Builtin::BI__sync_bool_compare_and_swap_2:
5928 case Builtin::BI__sync_bool_compare_and_swap_4:
5929 case Builtin::BI__sync_bool_compare_and_swap_8:
5930 case Builtin::BI__sync_bool_compare_and_swap_16:
5931 BuiltinIndex = 13;
5932 NumFixed = 2;
5933 ResultType = Context.BoolTy;
5934 break;
5935
5936 case Builtin::BI__sync_lock_test_and_set:
5937 case Builtin::BI__sync_lock_test_and_set_1:
5938 case Builtin::BI__sync_lock_test_and_set_2:
5939 case Builtin::BI__sync_lock_test_and_set_4:
5940 case Builtin::BI__sync_lock_test_and_set_8:
5941 case Builtin::BI__sync_lock_test_and_set_16:
5942 BuiltinIndex = 14;
5943 break;
5944
5945 case Builtin::BI__sync_lock_release:
5946 case Builtin::BI__sync_lock_release_1:
5947 case Builtin::BI__sync_lock_release_2:
5948 case Builtin::BI__sync_lock_release_4:
5949 case Builtin::BI__sync_lock_release_8:
5950 case Builtin::BI__sync_lock_release_16:
5951 BuiltinIndex = 15;
5952 NumFixed = 0;
5953 ResultType = Context.VoidTy;
5954 break;
5955
5956 case Builtin::BI__sync_swap:
5957 case Builtin::BI__sync_swap_1:
5958 case Builtin::BI__sync_swap_2:
5959 case Builtin::BI__sync_swap_4:
5960 case Builtin::BI__sync_swap_8:
5961 case Builtin::BI__sync_swap_16:
5962 BuiltinIndex = 16;
5963 break;
5964 }
5965
5966 // Now that we know how many fixed arguments we expect, first check that we
5967 // have at least that many.
5968 if (TheCall->getNumArgs() < 1+NumFixed) {
5969 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5970 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5971 << Callee->getSourceRange();
5972 return ExprError();
5973 }
5974
5975 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5976 << Callee->getSourceRange();
5977
5978 if (WarnAboutSemanticsChange) {
5979 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5980 << Callee->getSourceRange();
5981 }
5982
5983 // Get the decl for the concrete builtin from this, we can tell what the
5984 // concrete integer type we should convert to is.
5985 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5986 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5987 FunctionDecl *NewBuiltinDecl;
5988 if (NewBuiltinID == BuiltinID)
5989 NewBuiltinDecl = FDecl;
5990 else {
5991 // Perform builtin lookup to avoid redeclaring it.
5992 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5993 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5994 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5995 assert(Res.getFoundDecl());
5996 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5997 if (!NewBuiltinDecl)
5998 return ExprError();
5999 }
6000
6001 // The first argument --- the pointer --- has a fixed type; we
6002 // deduce the types of the rest of the arguments accordingly. Walk
6003 // the remaining arguments, converting them to the deduced value type.
6004 for (unsigned i = 0; i != NumFixed; ++i) {
6005 ExprResult Arg = TheCall->getArg(Arg: i+1);
6006
6007 // GCC does an implicit conversion to the pointer or integer ValType. This
6008 // can fail in some cases (1i -> int**), check for this error case now.
6009 // Initialize the argument.
6010 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6011 Type: ValType, /*consume*/ Consumed: false);
6012 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6013 if (Arg.isInvalid())
6014 return ExprError();
6015
6016 // Okay, we have something that *can* be converted to the right type. Check
6017 // to see if there is a potentially weird extension going on here. This can
6018 // happen when you do an atomic operation on something like an char* and
6019 // pass in 42. The 42 gets converted to char. This is even more strange
6020 // for things like 45.123 -> char, etc.
6021 // FIXME: Do this check.
6022 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
6023 }
6024
6025 // Create a new DeclRefExpr to refer to the new decl.
6026 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6027 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
6028 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
6029 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6030
6031 // Set the callee in the CallExpr.
6032 // FIXME: This loses syntactic information.
6033 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
6034 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
6035 CK: CK_BuiltinFnToFnPtr);
6036 TheCall->setCallee(PromotedCall.get());
6037
6038 // Change the result type of the call to match the original value type. This
6039 // is arbitrary, but the codegen for these builtins ins design to handle it
6040 // gracefully.
6041 TheCall->setType(ResultType);
6042
6043 // Prohibit problematic uses of bit-precise integer types with atomic
6044 // builtins. The arguments would have already been converted to the first
6045 // argument's type, so only need to check the first argument.
6046 const auto *BitIntValType = ValType->getAs<BitIntType>();
6047 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
6048 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
6049 return ExprError();
6050 }
6051
6052 return TheCallResult;
6053}
6054
6055ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6056 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6057 DeclRefExpr *DRE =
6058 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6059 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6060 unsigned BuiltinID = FDecl->getBuiltinID();
6061 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6062 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6063 "Unexpected nontemporal load/store builtin!");
6064 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6065 unsigned numArgs = isStore ? 2 : 1;
6066
6067 // Ensure that we have the proper number of arguments.
6068 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
6069 return ExprError();
6070
6071 // Inspect the last argument of the nontemporal builtin. This should always
6072 // be a pointer type, from which we imply the type of the memory access.
6073 // Because it is a pointer type, we don't have to worry about any implicit
6074 // casts here.
6075 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
6076 ExprResult PointerArgResult =
6077 DefaultFunctionArrayLvalueConversion(E: PointerArg);
6078
6079 if (PointerArgResult.isInvalid())
6080 return ExprError();
6081 PointerArg = PointerArgResult.get();
6082 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
6083
6084 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6085 if (!pointerType) {
6086 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
6087 << PointerArg->getType() << PointerArg->getSourceRange();
6088 return ExprError();
6089 }
6090
6091 QualType ValType = pointerType->getPointeeType();
6092
6093 // Strip any qualifiers off ValType.
6094 ValType = ValType.getUnqualifiedType();
6095 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6096 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6097 !ValType->isVectorType()) {
6098 Diag(Loc: DRE->getBeginLoc(),
6099 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6100 << PointerArg->getType() << PointerArg->getSourceRange();
6101 return ExprError();
6102 }
6103
6104 if (!isStore) {
6105 TheCall->setType(ValType);
6106 return TheCallResult;
6107 }
6108
6109 ExprResult ValArg = TheCall->getArg(Arg: 0);
6110 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6111 Context, Type: ValType, /*consume*/ Consumed: false);
6112 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
6113 if (ValArg.isInvalid())
6114 return ExprError();
6115
6116 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
6117 TheCall->setType(Context.VoidTy);
6118 return TheCallResult;
6119}
6120
6121/// CheckObjCString - Checks that the format string argument to the os_log()
6122/// and os_trace() functions is correct, and converts it to const char *.
6123ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6124 Arg = Arg->IgnoreParenCasts();
6125 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
6126 if (!Literal) {
6127 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
6128 Literal = ObjcLiteral->getString();
6129 }
6130 }
6131
6132 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6133 return ExprError(
6134 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
6135 << Arg->getSourceRange());
6136 }
6137
6138 ExprResult Result(Literal);
6139 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
6140 InitializedEntity Entity =
6141 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
6142 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
6143 return Result;
6144}
6145
6146/// Check that the user is calling the appropriate va_start builtin for the
6147/// target and calling convention.
6148static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6149 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6150 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6151 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6152 TT.getArch() == llvm::Triple::aarch64_32);
6153 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6154 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6155 if (IsX64 || IsAArch64) {
6156 CallingConv CC = CC_C;
6157 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6158 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6159 if (IsMSVAStart) {
6160 // Don't allow this in System V ABI functions.
6161 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6162 return S.Diag(Loc: Fn->getBeginLoc(),
6163 DiagID: diag::err_ms_va_start_used_in_sysv_function);
6164 } else {
6165 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6166 // On x64 Windows, don't allow this in System V ABI functions.
6167 // (Yes, that means there's no corresponding way to support variadic
6168 // System V ABI functions on Windows.)
6169 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6170 (!IsWindowsOrUEFI && CC == CC_Win64))
6171 return S.Diag(Loc: Fn->getBeginLoc(),
6172 DiagID: diag::err_va_start_used_in_wrong_abi_function)
6173 << !IsWindowsOrUEFI;
6174 }
6175 return false;
6176 }
6177
6178 if (IsMSVAStart)
6179 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
6180 return false;
6181}
6182
6183static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6184 ParmVarDecl **LastParam = nullptr) {
6185 // Determine whether the current function, block, or obj-c method is variadic
6186 // and get its parameter list.
6187 bool IsVariadic = false;
6188 ArrayRef<ParmVarDecl *> Params;
6189 DeclContext *Caller =
6190 S.CurContext->getEnclosingNonExpansionStatementContext();
6191 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
6192 IsVariadic = Block->isVariadic();
6193 Params = Block->parameters();
6194 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
6195 IsVariadic = FD->isVariadic();
6196 Params = FD->parameters();
6197 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
6198 IsVariadic = MD->isVariadic();
6199 // FIXME: This isn't correct for methods (results in bogus warning).
6200 Params = MD->parameters();
6201 } else if (isa<CapturedDecl>(Val: Caller)) {
6202 // We don't support va_start in a CapturedDecl.
6203 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
6204 return true;
6205 } else {
6206 // This must be some other declcontext that parses exprs.
6207 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
6208 return true;
6209 }
6210
6211 if (!IsVariadic) {
6212 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
6213 return true;
6214 }
6215
6216 if (LastParam)
6217 *LastParam = Params.empty() ? nullptr : Params.back();
6218
6219 return false;
6220}
6221
6222bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6223 Expr *Fn = TheCall->getCallee();
6224 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
6225 return true;
6226
6227 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6228 // This builtin requires one argument (the va_list), allows two arguments,
6229 // but diagnoses more than two arguments. e.g.,
6230 // __builtin_c23_va_start(); // error
6231 // __builtin_c23_va_start(list); // ok
6232 // __builtin_c23_va_start(list, param); // ok
6233 // __builtin_c23_va_start(list, anything, anything); // error
6234 // This differs from the GCC behavior in that they accept the last case
6235 // with a warning, but it doesn't seem like a useful behavior to allow.
6236 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
6237 return true;
6238 } else {
6239 // In C23 mode, va_start only needs one argument. However, the builtin still
6240 // requires two arguments (which matches the behavior of the GCC builtin),
6241 // <stdarg.h> passes `0` as the second argument in C23 mode.
6242 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6243 return true;
6244 }
6245
6246 // Type-check the first argument normally.
6247 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
6248 return true;
6249
6250 // Check that the current function is variadic, and get its last parameter.
6251 ParmVarDecl *LastParam;
6252 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
6253 return true;
6254
6255 // Verify that the second argument to the builtin is the last non-variadic
6256 // argument of the current function or method. In C23 mode, if the call is
6257 // not to __builtin_c23_va_start, and the second argument is an integer
6258 // constant expression with value 0, then we don't bother with this check.
6259 // For __builtin_c23_va_start, we only perform the check for the second
6260 // argument being the last argument to the current function if there is a
6261 // second argument present.
6262 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6263 TheCall->getNumArgs() < 2) {
6264 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6265 return false;
6266 }
6267
6268 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
6269 if (std::optional<llvm::APSInt> Val =
6270 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
6271 Val && LangOpts.C23 && *Val == 0 &&
6272 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6273 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6274 return false;
6275 }
6276
6277 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6278 // next block.
6279 QualType Type;
6280 SourceLocation ParamLoc;
6281 bool IsCRegister = false;
6282 bool SecondArgIsLastNonVariadicArgument = false;
6283 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
6284 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
6285 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6286
6287 Type = PV->getType();
6288 ParamLoc = PV->getLocation();
6289 IsCRegister =
6290 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6291 }
6292 }
6293
6294 if (!SecondArgIsLastNonVariadicArgument)
6295 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
6296 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6297 else if (IsCRegister || Type->isReferenceType() ||
6298 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
6299 // Promotable integers are UB, but enumerations need a bit of
6300 // extra checking to see what their promotable type actually is.
6301 if (!Context.isPromotableIntegerType(T: Type))
6302 return false;
6303 const auto *ED = Type->getAsEnumDecl();
6304 if (!ED)
6305 return true;
6306 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
6307 }()) {
6308 unsigned Reason = 0;
6309 if (Type->isReferenceType()) Reason = 1;
6310 else if (IsCRegister) Reason = 2;
6311 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
6312 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
6313 }
6314
6315 return false;
6316}
6317
6318bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6319 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6320 const LangOptions &LO = getLangOpts();
6321
6322 if (LO.CPlusPlus)
6323 return Arg->getType()
6324 .getCanonicalType()
6325 .getTypePtr()
6326 ->getPointeeType()
6327 .withoutLocalFastQualifiers() == Context.CharTy;
6328
6329 // In C, allow aliasing through `char *`, this is required for AArch64 at
6330 // least.
6331 return true;
6332 };
6333
6334 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6335 // const char *named_addr);
6336
6337 Expr *Func = Call->getCallee();
6338
6339 if (Call->getNumArgs() < 3)
6340 return Diag(Loc: Call->getEndLoc(),
6341 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6342 << 0 /*function call*/ << 3 << Call->getNumArgs()
6343 << /*is non object*/ 0;
6344
6345 // Type-check the first argument normally.
6346 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
6347 return true;
6348
6349 // Check that the current function is variadic.
6350 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
6351 return true;
6352
6353 // __va_start on Windows does not validate the parameter qualifiers
6354
6355 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
6356 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6357
6358 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
6359 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6360
6361 const QualType &ConstCharPtrTy =
6362 Context.getPointerType(T: Context.CharTy.withConst());
6363 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6364 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6365 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6366 << 0 /* qualifier difference */
6367 << 3 /* parameter mismatch */
6368 << 2 << Arg1->getType() << ConstCharPtrTy;
6369
6370 const QualType SizeTy = Context.getSizeType();
6371 if (!Context.hasSameType(
6372 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
6373 T2: SizeTy))
6374 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6375 << Arg2->getType() << SizeTy << 1 /* different class */
6376 << 0 /* qualifier difference */
6377 << 3 /* parameter mismatch */
6378 << 3 << Arg2->getType() << SizeTy;
6379
6380 return false;
6381}
6382
6383bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6384 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6385 return true;
6386
6387 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6388 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
6389 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6390 << 1 << 0 << TheCall->getSourceRange();
6391
6392 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
6393 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
6394
6395 // Do standard promotions between the two arguments, returning their common
6396 // type.
6397 QualType Res = UsualArithmeticConversions(
6398 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
6399 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6400 return true;
6401
6402 // Make sure any conversions are pushed back into the call; this is
6403 // type safe since unordered compare builtins are declared as "_Bool
6404 // foo(...)".
6405 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
6406 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
6407
6408 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6409 return false;
6410
6411 // If the common type isn't a real floating type, then the arguments were
6412 // invalid for this operation.
6413 if (Res.isNull() || !Res->isRealFloatingType())
6414 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
6415 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
6416 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6417 << SourceRange(OrigArg0.get()->getBeginLoc(),
6418 OrigArg1.get()->getEndLoc());
6419
6420 return false;
6421}
6422
6423bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6424 unsigned BuiltinID) {
6425 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
6426 return true;
6427
6428 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
6429 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6430 BuiltinID == Builtin::BI__builtin_isinf ||
6431 BuiltinID == Builtin::BI__builtin_isinf_sign))
6432 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6433 << 0 << 0 << TheCall->getSourceRange();
6434
6435 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6436 BuiltinID == Builtin::BI__builtin_isunordered))
6437 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6438 << 1 << 0 << TheCall->getSourceRange();
6439
6440 bool IsFPClass = NumArgs == 2;
6441
6442 // Find out position of floating-point argument.
6443 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6444
6445 // We can count on all parameters preceding the floating-point just being int.
6446 // Try all of those.
6447 for (unsigned i = 0; i < FPArgNo; ++i) {
6448 Expr *Arg = TheCall->getArg(Arg: i);
6449
6450 if (Arg->isTypeDependent())
6451 return false;
6452
6453 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
6454 Action: AssignmentAction::Passing);
6455
6456 if (Res.isInvalid())
6457 return true;
6458 TheCall->setArg(Arg: i, ArgExpr: Res.get());
6459 }
6460
6461 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
6462
6463 if (OrigArg->isTypeDependent())
6464 return false;
6465
6466 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6467 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6468 if (!Res.isUsable())
6469 return true;
6470 OrigArg = Res.get();
6471
6472 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6473
6474 QualType VectorResultTy;
6475 QualType ElementTy = OrigArg->getType();
6476 // TODO: When all classification function are implemented with is_fpclass,
6477 // vector argument can be supported in all of them.
6478 if (ElementTy->isVectorType() && IsFPClass) {
6479 VectorResultTy = GetSignedVectorType(V: ElementTy);
6480 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6481 }
6482
6483 // This operation requires a non-_Complex floating-point number.
6484 if (!ElementTy->isRealFloatingType())
6485 return Diag(Loc: OrigArg->getBeginLoc(),
6486 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6487 << OrigArg->getType() << OrigArg->getSourceRange();
6488
6489 // __builtin_isfpclass has integer parameter that specify test mask. It is
6490 // passed in (...), so it should be analyzed completely here.
6491 if (IsFPClass) {
6492 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6493 return true;
6494
6495 ExprResult MaskRes = PerformImplicitConversion(
6496 From: TheCall->getArg(Arg: NumArgs - 1), ToType: Context.IntTy, Action: AssignmentAction::Passing);
6497 if (!MaskRes.isUsable())
6498 return true;
6499 TheCall->setArg(Arg: NumArgs - 1, ArgExpr: MaskRes.get());
6500 }
6501
6502 // TODO: enable this code to all classification functions.
6503 if (IsFPClass) {
6504 QualType ResultTy;
6505 if (!VectorResultTy.isNull())
6506 ResultTy = VectorResultTy;
6507 else
6508 ResultTy = Context.IntTy;
6509 TheCall->setType(ResultTy);
6510 }
6511
6512 return false;
6513}
6514
6515bool Sema::BuiltinComplex(CallExpr *TheCall) {
6516 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6517 return true;
6518
6519 bool Dependent = false;
6520 for (unsigned I = 0; I != 2; ++I) {
6521 Expr *Arg = TheCall->getArg(Arg: I);
6522 QualType T = Arg->getType();
6523 if (T->isDependentType()) {
6524 Dependent = true;
6525 continue;
6526 }
6527
6528 // Despite supporting _Complex int, GCC requires a real floating point type
6529 // for the operands of __builtin_complex.
6530 if (!T->isRealFloatingType()) {
6531 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6532 << Arg->getType() << Arg->getSourceRange();
6533 }
6534
6535 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6536 if (Converted.isInvalid())
6537 return true;
6538 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6539 }
6540
6541 if (Dependent) {
6542 TheCall->setType(Context.DependentTy);
6543 return false;
6544 }
6545
6546 Expr *Real = TheCall->getArg(Arg: 0);
6547 Expr *Imag = TheCall->getArg(Arg: 1);
6548 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6549 return Diag(Loc: Real->getBeginLoc(),
6550 DiagID: diag::err_typecheck_call_different_arg_types)
6551 << Real->getType() << Imag->getType()
6552 << Real->getSourceRange() << Imag->getSourceRange();
6553 }
6554
6555 TheCall->setType(Context.getComplexType(T: Real->getType()));
6556 return false;
6557}
6558
6559/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6560// This is declared to take (...), so we have to check everything.
6561ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6562 unsigned NumArgs = TheCall->getNumArgs();
6563 if (NumArgs < 2)
6564 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6565 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6566 << 0 /*function call*/ << 2 << NumArgs
6567 << /*is non object*/ 0 << TheCall->getSourceRange());
6568
6569 // Determine which of the following types of shufflevector we're checking:
6570 // 1) unary, vector mask: (lhs, mask)
6571 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6572 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6573 unsigned NumElements = 0;
6574
6575 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6576 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6577 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6578 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6579
6580 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6581 return ExprError(
6582 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6583 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6584 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6585 TheCall->getArg(Arg: 1)->getEndLoc()));
6586
6587 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6588 unsigned NumResElements = NumArgs - 2;
6589
6590 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6591 // with mask. If so, verify that RHS is an integer vector type with the
6592 // same number of elts as lhs.
6593 if (NumArgs == 2) {
6594 auto *RHSVecType = RHSType->castAs<VectorType>();
6595 if (RHSVecType->getElementType()->isBooleanType() ||
6596 !RHSVecType->getElementType()->isIntegerType()) {
6597 return ExprError(
6598 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
6599 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6600 << /*no fp*/ 0 << RHSType
6601 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6602 TheCall->getArg(Arg: 1)->getEndLoc()));
6603 }
6604
6605 if (RHSVecType->getNumElements() != NumElements)
6606 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6607 DiagID: diag::err_typecheck_vector_lengths_not_equal)
6608 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6609 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6610 TheCall->getArg(Arg: 1)->getEndLoc()));
6611 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6612 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6613 DiagID: diag::err_vec_builtin_incompatible_vector)
6614 << TheCall->getDirectCallee()
6615 << /*isMoreThanTwoArgs*/ false
6616 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6617 TheCall->getArg(Arg: 1)->getEndLoc()));
6618 } else if (NumElements != NumResElements) {
6619 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6620 ResType = ResType->isExtVectorType()
6621 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6622 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6623 VecKind: VectorKind::Generic);
6624 }
6625 }
6626
6627 for (unsigned I = 2; I != NumArgs; ++I) {
6628 Expr *Arg = TheCall->getArg(Arg: I);
6629 if (Arg->isTypeDependent() || Arg->isValueDependent())
6630 continue;
6631
6632 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6633 if (!Result)
6634 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6635 DiagID: diag::err_shufflevector_nonconstant_argument)
6636 << Arg->getSourceRange());
6637
6638 // Allow -1 which will be translated to undef in the IR.
6639 if (Result->isSigned() && Result->isAllOnes())
6640 ;
6641 else if (Result->getActiveBits() > 64 ||
6642 Result->getZExtValue() >= NumElements * 2)
6643 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6644 DiagID: diag::err_shufflevector_argument_too_large)
6645 << Arg->getSourceRange());
6646
6647 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6648 }
6649
6650 auto *Result = new (Context) ShuffleVectorExpr(
6651 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6652 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6653
6654 // All moved to Result.
6655 TheCall->shrinkNumArgs(NewNumArgs: 0);
6656 return Result;
6657}
6658
6659ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6660 SourceLocation BuiltinLoc,
6661 SourceLocation RParenLoc) {
6662 ExprValueKind VK = VK_PRValue;
6663 ExprObjectKind OK = OK_Ordinary;
6664 QualType DstTy = TInfo->getType();
6665 QualType SrcTy = E->getType();
6666
6667 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6668 return ExprError(Diag(Loc: BuiltinLoc,
6669 DiagID: diag::err_convertvector_non_vector)
6670 << E->getSourceRange());
6671 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6672 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6673 << "second"
6674 << "__builtin_convertvector");
6675
6676 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6677 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6678 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6679 if (SrcElts != DstElts)
6680 return ExprError(Diag(Loc: BuiltinLoc,
6681 DiagID: diag::err_convertvector_incompatible_vector)
6682 << E->getSourceRange());
6683 }
6684
6685 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6686 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6687}
6688
6689bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6690 unsigned NumArgs = TheCall->getNumArgs();
6691
6692 if (NumArgs > 3)
6693 return Diag(Loc: TheCall->getEndLoc(),
6694 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6695 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6696 << TheCall->getSourceRange();
6697
6698 // Argument 0 is checked for us and the remaining arguments must be
6699 // constant integers.
6700 for (unsigned i = 1; i != NumArgs; ++i) {
6701 if (convertArgumentToType(S&: *this, Value&: TheCall->getArgs()[i], Ty: Context.IntTy))
6702 return true;
6703 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6704 return true;
6705 }
6706
6707 return false;
6708}
6709
6710bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6711 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6712 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6713 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6714 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6715 return true;
6716 Expr *Arg = TheCall->getArg(Arg: 0);
6717 if (Arg->isInstantiationDependent())
6718 return false;
6719
6720 QualType ArgTy = Arg->getType();
6721 if (!ArgTy->hasFloatingRepresentation())
6722 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6723 << ArgTy;
6724 if (Arg->isLValue()) {
6725 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6726 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6727 }
6728 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6729 return false;
6730}
6731
6732bool Sema::BuiltinAssume(CallExpr *TheCall) {
6733 Expr *Arg = TheCall->getArg(Arg: 0);
6734 if (Arg->isInstantiationDependent()) return false;
6735
6736 if (Arg->HasSideEffects(Ctx: Context))
6737 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6738 << Arg->getSourceRange()
6739 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6740
6741 return false;
6742}
6743
6744bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6745 // The alignment must be a constant integer.
6746 Expr *Arg = TheCall->getArg(Arg: 1);
6747
6748 // We can't check the value of a dependent argument.
6749 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6750 if (const auto *UE =
6751 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6752 if (UE->getKind() == UETT_AlignOf ||
6753 UE->getKind() == UETT_PreferredAlignOf)
6754 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6755 << Arg->getSourceRange();
6756
6757 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6758
6759 if (!Result.isPowerOf2())
6760 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6761 << Arg->getSourceRange();
6762
6763 if (Result < Context.getCharWidth())
6764 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6765 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6766
6767 if (Result > std::numeric_limits<int32_t>::max())
6768 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6769 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6770 }
6771
6772 return false;
6773}
6774
6775bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6776 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6777 return true;
6778
6779 unsigned NumArgs = TheCall->getNumArgs();
6780 Expr *FirstArg = TheCall->getArg(Arg: 0);
6781
6782 {
6783 ExprResult FirstArgResult =
6784 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6785 if (!FirstArgResult.get()->getType()->isPointerType()) {
6786 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6787 << TheCall->getSourceRange();
6788 return true;
6789 }
6790 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6791 }
6792
6793 // The alignment must be a constant integer.
6794 Expr *SecondArg = TheCall->getArg(Arg: 1);
6795
6796 // We can't check the value of a dependent argument.
6797 if (!SecondArg->isValueDependent()) {
6798 llvm::APSInt Result;
6799 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6800 return true;
6801
6802 if (!Result.isPowerOf2())
6803 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6804 << SecondArg->getSourceRange();
6805
6806 if (Result > Sema::MaximumAlignment)
6807 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6808 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6809
6810 TheCall->setArg(Arg: 1,
6811 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6812 }
6813
6814 if (NumArgs > 2) {
6815 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6816 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6817 return true;
6818 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6819 }
6820
6821 return false;
6822}
6823
6824bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6825 unsigned BuiltinID =
6826 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6827 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6828
6829 unsigned NumArgs = TheCall->getNumArgs();
6830 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6831 if (NumArgs < NumRequiredArgs) {
6832 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6833 << 0 /* function call */ << NumRequiredArgs << NumArgs
6834 << /*is non object*/ 0 << TheCall->getSourceRange();
6835 }
6836 if (NumArgs >= NumRequiredArgs + 0x100) {
6837 return Diag(Loc: TheCall->getEndLoc(),
6838 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6839 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6840 << /*is non object*/ 0 << TheCall->getSourceRange();
6841 }
6842 unsigned i = 0;
6843
6844 // For formatting call, check buffer arg.
6845 if (!IsSizeCall) {
6846 ExprResult Arg(TheCall->getArg(Arg: i));
6847 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6848 Context, Type: Context.VoidPtrTy, Consumed: false);
6849 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6850 if (Arg.isInvalid())
6851 return true;
6852 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6853 i++;
6854 }
6855
6856 // Check string literal arg.
6857 unsigned FormatIdx = i;
6858 {
6859 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6860 if (Arg.isInvalid())
6861 return true;
6862 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6863 i++;
6864 }
6865
6866 // Make sure variadic args are scalar.
6867 unsigned FirstDataArg = i;
6868 while (i < NumArgs) {
6869 ExprResult Arg = DefaultVariadicArgumentPromotion(
6870 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6871 if (Arg.isInvalid())
6872 return true;
6873 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6874 if (ArgSize.getQuantity() >= 0x100) {
6875 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6876 << i << (int)ArgSize.getQuantity() << 0xff
6877 << TheCall->getSourceRange();
6878 }
6879 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6880 i++;
6881 }
6882
6883 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6884 // call to avoid duplicate diagnostics.
6885 if (!IsSizeCall) {
6886 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6887 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6888 bool Success = CheckFormatArguments(
6889 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6890 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6891 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6892 if (!Success)
6893 return true;
6894 }
6895
6896 if (IsSizeCall) {
6897 TheCall->setType(Context.getSizeType());
6898 } else {
6899 TheCall->setType(Context.VoidPtrTy);
6900 }
6901 return false;
6902}
6903
6904bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6905 llvm::APSInt &Result) {
6906 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6907
6908 if (Arg->isTypeDependent() || Arg->isValueDependent())
6909 return false;
6910
6911 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6912 if (!R) {
6913 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6914 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6915 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6916 << FDecl->getDeclName() << Arg->getSourceRange();
6917 }
6918 Result = *R;
6919
6920 return false;
6921}
6922
6923bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6924 int High, bool RangeIsError) {
6925 if (isConstantEvaluatedContext())
6926 return false;
6927 llvm::APSInt Result;
6928
6929 // We can't check the value of a dependent argument.
6930 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6931 if (Arg->isTypeDependent() || Arg->isValueDependent())
6932 return false;
6933
6934 // Check constant-ness first.
6935 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6936 return true;
6937
6938 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6939 if (RangeIsError)
6940 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6941 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6942 else
6943 // Defer the warning until we know if the code will be emitted so that
6944 // dead code can ignore this.
6945 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6946 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6947 << toString(I: Result, Radix: 10) << Low << High
6948 << Arg->getSourceRange());
6949 }
6950
6951 return false;
6952}
6953
6954bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6955 unsigned Num) {
6956 llvm::APSInt Result;
6957
6958 // We can't check the value of a dependent argument.
6959 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6960 if (Arg->isTypeDependent() || Arg->isValueDependent())
6961 return false;
6962
6963 // Check constant-ness first.
6964 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6965 return true;
6966
6967 if (Result.getSExtValue() % Num != 0)
6968 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6969 << Num << Arg->getSourceRange();
6970
6971 return false;
6972}
6973
6974bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6975 llvm::APSInt Result;
6976
6977 // We can't check the value of a dependent argument.
6978 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6979 if (Arg->isTypeDependent() || Arg->isValueDependent())
6980 return false;
6981
6982 // Check constant-ness first.
6983 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6984 return true;
6985
6986 if (Result.isPowerOf2())
6987 return false;
6988
6989 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6990 << Arg->getSourceRange();
6991}
6992
6993static bool IsShiftedByte(llvm::APSInt Value) {
6994 if (Value.isNegative())
6995 return false;
6996
6997 // Check if it's a shifted byte, by shifting it down
6998 while (true) {
6999 // If the value fits in the bottom byte, the check passes.
7000 if (Value < 0x100)
7001 return true;
7002
7003 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7004 // fails.
7005 if ((Value & 0xFF) != 0)
7006 return false;
7007
7008 // If the bottom 8 bits are all 0, but something above that is nonzero,
7009 // then shifting the value right by 8 bits won't affect whether it's a
7010 // shifted byte or not. So do that, and go round again.
7011 Value >>= 8;
7012 }
7013}
7014
7015bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7016 unsigned ArgBits) {
7017 llvm::APSInt Result;
7018
7019 // We can't check the value of a dependent argument.
7020 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7021 if (Arg->isTypeDependent() || Arg->isValueDependent())
7022 return false;
7023
7024 // Check constant-ness first.
7025 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7026 return true;
7027
7028 // Truncate to the given size.
7029 Result = Result.getLoBits(numBits: ArgBits);
7030 Result.setIsUnsigned(true);
7031
7032 if (IsShiftedByte(Value: Result))
7033 return false;
7034
7035 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
7036 << Arg->getSourceRange();
7037}
7038
7039bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7040 unsigned ArgNum,
7041 unsigned ArgBits) {
7042 llvm::APSInt Result;
7043
7044 // We can't check the value of a dependent argument.
7045 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7046 if (Arg->isTypeDependent() || Arg->isValueDependent())
7047 return false;
7048
7049 // Check constant-ness first.
7050 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7051 return true;
7052
7053 // Truncate to the given size.
7054 Result = Result.getLoBits(numBits: ArgBits);
7055 Result.setIsUnsigned(true);
7056
7057 // Check to see if it's in either of the required forms.
7058 if (IsShiftedByte(Value: Result) ||
7059 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7060 return false;
7061
7062 return Diag(Loc: TheCall->getBeginLoc(),
7063 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
7064 << Arg->getSourceRange();
7065}
7066
7067bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7068 if (!Context.getTargetInfo().hasSjLjLowering())
7069 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
7070 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7071
7072 Expr *Arg = TheCall->getArg(Arg: 1);
7073 llvm::APSInt Result;
7074
7075 // TODO: This is less than ideal. Overload this to take a value.
7076 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
7077 return true;
7078
7079 if (Result != 1)
7080 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
7081 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7082
7083 return false;
7084}
7085
7086bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7087 if (!Context.getTargetInfo().hasSjLjLowering())
7088 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
7089 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7090 return false;
7091}
7092
7093bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7094 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
7095 return true;
7096
7097 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
7098 if (ArgRes.isInvalid())
7099 return true;
7100
7101 // For simplicity, we support only limited expressions for the argument.
7102 // Specifically a flexible array member or a pointer with counted_by:
7103 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7104 // complex casting, which really shouldn't be a huge problem.
7105 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7106 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7107 return Diag(Loc: Arg->getBeginLoc(),
7108 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7109 << Arg->getSourceRange();
7110
7111 if (Arg->HasSideEffects(Ctx: Context))
7112 return Diag(Loc: Arg->getBeginLoc(),
7113 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
7114 << Arg->getSourceRange();
7115
7116 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
7117 const auto *CATy =
7118 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7119
7120 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7121 // Member has counted_by attribute - return pointer to count field
7122 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
7123 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7124 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
7125 return false;
7126 }
7127 }
7128
7129 // FAMs and pointers without counted_by return void*
7130 QualType MemberTy = ME->getMemberDecl()->getType();
7131 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7132 return Diag(Loc: Arg->getBeginLoc(),
7133 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7134 << Arg->getSourceRange();
7135 } else {
7136 return Diag(Loc: Arg->getBeginLoc(),
7137 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7138 << Arg->getSourceRange();
7139 }
7140
7141 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
7142 return false;
7143}
7144
7145/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7146/// It allows leaking and modification of bounds safety information.
7147bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7148 BuiltinCountedByRefKind K) {
7149 const CallExpr *CE =
7150 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
7151 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7152 return false;
7153
7154 switch (K) {
7155 case BuiltinCountedByRefKind::Assignment:
7156 case BuiltinCountedByRefKind::Initializer:
7157 Diag(Loc: E->getExprLoc(),
7158 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7159 << 0 << E->getSourceRange();
7160 break;
7161 case BuiltinCountedByRefKind::FunctionArg:
7162 Diag(Loc: E->getExprLoc(),
7163 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7164 << 1 << E->getSourceRange();
7165 break;
7166 case BuiltinCountedByRefKind::ReturnArg:
7167 Diag(Loc: E->getExprLoc(),
7168 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7169 << 2 << E->getSourceRange();
7170 break;
7171 case BuiltinCountedByRefKind::ArraySubscript:
7172 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7173 << 0 << E->getSourceRange();
7174 break;
7175 case BuiltinCountedByRefKind::BinaryExpr:
7176 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7177 << 1 << E->getSourceRange();
7178 break;
7179 }
7180
7181 return true;
7182}
7183
7184namespace {
7185
7186class UncoveredArgHandler {
7187 enum { Unknown = -1, AllCovered = -2 };
7188
7189 signed FirstUncoveredArg = Unknown;
7190 SmallVector<const Expr *, 4> DiagnosticExprs;
7191
7192public:
7193 UncoveredArgHandler() = default;
7194
7195 bool hasUncoveredArg() const {
7196 return (FirstUncoveredArg >= 0);
7197 }
7198
7199 unsigned getUncoveredArg() const {
7200 assert(hasUncoveredArg() && "no uncovered argument");
7201 return FirstUncoveredArg;
7202 }
7203
7204 void setAllCovered() {
7205 // A string has been found with all arguments covered, so clear out
7206 // the diagnostics.
7207 DiagnosticExprs.clear();
7208 FirstUncoveredArg = AllCovered;
7209 }
7210
7211 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7212 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7213
7214 // Don't update if a previous string covers all arguments.
7215 if (FirstUncoveredArg == AllCovered)
7216 return;
7217
7218 // UncoveredArgHandler tracks the highest uncovered argument index
7219 // and with it all the strings that match this index.
7220 if (NewFirstUncoveredArg == FirstUncoveredArg)
7221 DiagnosticExprs.push_back(Elt: StrExpr);
7222 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7223 DiagnosticExprs.clear();
7224 DiagnosticExprs.push_back(Elt: StrExpr);
7225 FirstUncoveredArg = NewFirstUncoveredArg;
7226 }
7227 }
7228
7229 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7230};
7231
7232enum StringLiteralCheckType {
7233 SLCT_NotALiteral,
7234 SLCT_UncheckedLiteral,
7235 SLCT_CheckedLiteral
7236};
7237
7238} // namespace
7239
7240static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7241 BinaryOperatorKind BinOpKind,
7242 bool AddendIsRight) {
7243 unsigned BitWidth = Offset.getBitWidth();
7244 unsigned AddendBitWidth = Addend.getBitWidth();
7245 // There might be negative interim results.
7246 if (Addend.isUnsigned()) {
7247 Addend = Addend.zext(width: ++AddendBitWidth);
7248 Addend.setIsSigned(true);
7249 }
7250 // Adjust the bit width of the APSInts.
7251 if (AddendBitWidth > BitWidth) {
7252 Offset = Offset.sext(width: AddendBitWidth);
7253 BitWidth = AddendBitWidth;
7254 } else if (BitWidth > AddendBitWidth) {
7255 Addend = Addend.sext(width: BitWidth);
7256 }
7257
7258 bool Ov = false;
7259 llvm::APSInt ResOffset = Offset;
7260 if (BinOpKind == BO_Add)
7261 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
7262 else {
7263 assert(AddendIsRight && BinOpKind == BO_Sub &&
7264 "operator must be add or sub with addend on the right");
7265 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
7266 }
7267
7268 // We add an offset to a pointer here so we should support an offset as big as
7269 // possible.
7270 if (Ov) {
7271 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7272 "index (intermediate) result too big");
7273 Offset = Offset.sext(width: 2 * BitWidth);
7274 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7275 return;
7276 }
7277
7278 Offset = std::move(ResOffset);
7279}
7280
7281namespace {
7282
7283// This is a wrapper class around StringLiteral to support offsetted string
7284// literals as format strings. It takes the offset into account when returning
7285// the string and its length or the source locations to display notes correctly.
7286class FormatStringLiteral {
7287 const StringLiteral *FExpr;
7288 int64_t Offset;
7289
7290public:
7291 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7292 : FExpr(fexpr), Offset(Offset) {}
7293
7294 const StringLiteral *getFormatString() const { return FExpr; }
7295
7296 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
7297
7298 unsigned getByteLength() const {
7299 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7300 }
7301
7302 unsigned getLength() const { return FExpr->getLength() - Offset; }
7303 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7304
7305 StringLiteralKind getKind() const { return FExpr->getKind(); }
7306
7307 QualType getType() const { return FExpr->getType(); }
7308
7309 bool isAscii() const { return FExpr->isOrdinary(); }
7310 bool isWide() const { return FExpr->isWide(); }
7311 bool isUTF8() const { return FExpr->isUTF8(); }
7312 bool isUTF16() const { return FExpr->isUTF16(); }
7313 bool isUTF32() const { return FExpr->isUTF32(); }
7314 bool isPascal() const { return FExpr->isPascal(); }
7315
7316 SourceLocation getLocationOfByte(
7317 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7318 const TargetInfo &Target, unsigned *StartToken = nullptr,
7319 unsigned *StartTokenByteOffset = nullptr) const {
7320 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
7321 StartToken, StartTokenByteOffset);
7322 }
7323
7324 SourceLocation getBeginLoc() const LLVM_READONLY {
7325 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7326 }
7327
7328 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7329};
7330
7331} // namespace
7332
7333static void CheckFormatString(
7334 Sema &S, const FormatStringLiteral *FExpr,
7335 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7336 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7337 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7338 bool inFunctionCall, VariadicCallType CallType,
7339 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7340 bool IgnoreStringsWithoutSpecifiers);
7341
7342static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7343 const Expr *E);
7344
7345// Determine if an expression is a string literal or constant string.
7346// If this function returns false on the arguments to a function expecting a
7347// format string, we will usually need to emit a warning.
7348// True string literals are then checked by CheckFormatString.
7349static StringLiteralCheckType
7350checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7351 const Expr *E, ArrayRef<const Expr *> Args,
7352 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7353 unsigned firstDataArg, FormatStringType Type,
7354 VariadicCallType CallType, bool InFunctionCall,
7355 llvm::SmallBitVector &CheckedVarArgs,
7356 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7357 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7358 bool IgnoreStringsWithoutSpecifiers = false) {
7359 if (S.isConstantEvaluatedContext())
7360 return SLCT_NotALiteral;
7361tryAgain:
7362 assert(Offset.isSigned() && "invalid offset");
7363
7364 if (E->isTypeDependent() || E->isValueDependent())
7365 return SLCT_NotALiteral;
7366
7367 E = E->IgnoreParenCasts();
7368
7369 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
7370 // Technically -Wformat-nonliteral does not warn about this case.
7371 // The behavior of printf and friends in this case is implementation
7372 // dependent. Ideally if the format string cannot be null then
7373 // it should have a 'nonnull' attribute in the function prototype.
7374 return SLCT_UncheckedLiteral;
7375
7376 switch (E->getStmtClass()) {
7377 case Stmt::InitListExprClass:
7378 // Handle expressions like {"foobar"}.
7379 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
7380 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7381 format_idx, firstDataArg, Type, CallType,
7382 /*InFunctionCall*/ false, CheckedVarArgs,
7383 UncoveredArg, Offset, CallerFormatParamIdx,
7384 IgnoreStringsWithoutSpecifiers);
7385 }
7386 return SLCT_NotALiteral;
7387 case Stmt::BinaryConditionalOperatorClass:
7388 case Stmt::ConditionalOperatorClass: {
7389 // The expression is a literal if both sub-expressions were, and it was
7390 // completely checked only if both sub-expressions were checked.
7391 const AbstractConditionalOperator *C =
7392 cast<AbstractConditionalOperator>(Val: E);
7393
7394 // Determine whether it is necessary to check both sub-expressions, for
7395 // example, because the condition expression is a constant that can be
7396 // evaluated at compile time.
7397 bool CheckLeft = true, CheckRight = true;
7398
7399 bool Cond;
7400 if (C->getCond()->EvaluateAsBooleanCondition(
7401 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
7402 if (Cond)
7403 CheckRight = false;
7404 else
7405 CheckLeft = false;
7406 }
7407
7408 // We need to maintain the offsets for the right and the left hand side
7409 // separately to check if every possible indexed expression is a valid
7410 // string literal. They might have different offsets for different string
7411 // literals in the end.
7412 StringLiteralCheckType Left;
7413 if (!CheckLeft)
7414 Left = SLCT_UncheckedLiteral;
7415 else {
7416 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
7417 Args, APK, format_idx, firstDataArg, Type,
7418 CallType, InFunctionCall, CheckedVarArgs,
7419 UncoveredArg, Offset, CallerFormatParamIdx,
7420 IgnoreStringsWithoutSpecifiers);
7421 if (Left == SLCT_NotALiteral || !CheckRight) {
7422 return Left;
7423 }
7424 }
7425
7426 StringLiteralCheckType Right = checkFormatStringExpr(
7427 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
7428 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7429 UncoveredArg, Offset, CallerFormatParamIdx,
7430 IgnoreStringsWithoutSpecifiers);
7431
7432 return (CheckLeft && Left < Right) ? Left : Right;
7433 }
7434
7435 case Stmt::ImplicitCastExprClass:
7436 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
7437 goto tryAgain;
7438
7439 case Stmt::OpaqueValueExprClass:
7440 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
7441 E = src;
7442 goto tryAgain;
7443 }
7444 return SLCT_NotALiteral;
7445
7446 case Stmt::PredefinedExprClass:
7447 // While __func__, etc., are technically not string literals, they
7448 // cannot contain format specifiers and thus are not a security
7449 // liability.
7450 return SLCT_UncheckedLiteral;
7451
7452 case Stmt::DeclRefExprClass: {
7453 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
7454
7455 // As an exception, do not flag errors for variables binding to
7456 // const string literals.
7457 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
7458 bool isConstant = false;
7459 QualType T = DR->getType();
7460
7461 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7462 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
7463 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7464 isConstant = T.isConstant(Ctx: S.Context) &&
7465 PT->getPointeeType().isConstant(Ctx: S.Context);
7466 } else if (T->isObjCObjectPointerType()) {
7467 // In ObjC, there is usually no "const ObjectPointer" type,
7468 // so don't check if the pointee type is constant.
7469 isConstant = T.isConstant(Ctx: S.Context);
7470 }
7471
7472 if (isConstant) {
7473 if (const Expr *Init = VD->getAnyInitializer()) {
7474 // Look through initializers like const char c[] = { "foo" }
7475 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7476 if (InitList->isStringLiteralInit())
7477 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7478 }
7479 return checkFormatStringExpr(
7480 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7481 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7482 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7483 }
7484 }
7485
7486 // When the format argument is an argument of this function, and this
7487 // function also has the format attribute, there are several interactions
7488 // for which there shouldn't be a warning. For instance, when calling
7489 // v*printf from a function that has the printf format attribute, we
7490 // should not emit a warning about using `fmt`, even though it's not
7491 // constant, because the arguments have already been checked for the
7492 // caller of `logmessage`:
7493 //
7494 // __attribute__((format(printf, 1, 2)))
7495 // void logmessage(char const *fmt, ...) {
7496 // va_list ap;
7497 // va_start(ap, fmt);
7498 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7499 // ...
7500 // }
7501 //
7502 // Another interaction that we need to support is using a format string
7503 // specified by the format_matches attribute:
7504 //
7505 // __attribute__((format_matches(printf, 1, "%s %d")))
7506 // void logmessage(char const *fmt, const char *a, int b) {
7507 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7508 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7509 // ...
7510 // }
7511 //
7512 // Yet another interaction that we need to support is calling a variadic
7513 // format function from a format function that has fixed arguments. For
7514 // instance:
7515 //
7516 // __attribute__((format(printf, 1, 2)))
7517 // void logstring(char const *fmt, char const *str) {
7518 // printf(fmt, str); /* do not emit a warning about "fmt" */
7519 // }
7520 //
7521 // Same (and perhaps more relatably) for the variadic template case:
7522 //
7523 // template<typename... Args>
7524 // __attribute__((format(printf, 1, 2)))
7525 // void log(const char *fmt, Args&&... args) {
7526 // printf(fmt, forward<Args>(args)...);
7527 // /* do not emit a warning about "fmt" */
7528 // }
7529 //
7530 // Due to implementation difficulty, we only check the format, not the
7531 // format arguments, in all cases.
7532 //
7533 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7534 if (CallerFormatParamIdx)
7535 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7536 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7537 for (const auto *PVFormatMatches :
7538 D->specific_attrs<FormatMatchesAttr>()) {
7539 Sema::FormatStringInfo CalleeFSI;
7540 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7541 FirstArg: 0, FSI: &CalleeFSI))
7542 continue;
7543 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7544 // If using the wrong type of format string, emit a diagnostic
7545 // here and stop checking to avoid irrelevant diagnostics.
7546 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7547 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7548 DiagID: diag::warn_format_string_type_incompatible)
7549 << PVFormatMatches->getType()->getName()
7550 << S.GetFormatStringTypeName(FST: Type);
7551 if (!InFunctionCall) {
7552 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7553 DiagID: diag::note_format_string_defined);
7554 }
7555 return SLCT_UncheckedLiteral;
7556 }
7557 return checkFormatStringExpr(
7558 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7559 Args, APK, format_idx, firstDataArg, Type, CallType,
7560 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7561 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7562 }
7563 }
7564
7565 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7566 Sema::FormatStringInfo CallerFSI;
7567 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7568 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7569 continue;
7570 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7571 // We also check if the formats are compatible.
7572 // We can't pass a 'scanf' string to a 'printf' function.
7573 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7574 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7575 DiagID: diag::warn_format_string_type_incompatible)
7576 << PVFormat->getType()->getName()
7577 << S.GetFormatStringTypeName(FST: Type);
7578 if (!InFunctionCall) {
7579 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7580 }
7581 return SLCT_UncheckedLiteral;
7582 }
7583 // Lastly, check that argument passing kinds transition in a
7584 // way that makes sense:
7585 // from a caller with FAPK_VAList, allow FAPK_VAList
7586 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7587 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7588 // from a caller with FAPK_Variadic, allow FAPK_VAList
7589 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7590 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7591 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7592 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7593 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7594 return SLCT_UncheckedLiteral;
7595 }
7596 }
7597 }
7598 }
7599 }
7600 }
7601
7602 return SLCT_NotALiteral;
7603 }
7604
7605 case Stmt::CallExprClass:
7606 case Stmt::CXXMemberCallExprClass: {
7607 const CallExpr *CE = cast<CallExpr>(Val: E);
7608 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7609 bool IsFirst = true;
7610 StringLiteralCheckType CommonResult;
7611 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7612 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7613 StringLiteralCheckType Result = checkFormatStringExpr(
7614 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7615 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7616 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7617 if (IsFirst) {
7618 CommonResult = Result;
7619 IsFirst = false;
7620 }
7621 }
7622 if (!IsFirst)
7623 return CommonResult;
7624
7625 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7626 unsigned BuiltinID = FD->getBuiltinID();
7627 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7628 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7629 const Expr *Arg = CE->getArg(Arg: 0);
7630 return checkFormatStringExpr(
7631 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7632 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7633 UncoveredArg, Offset, CallerFormatParamIdx,
7634 IgnoreStringsWithoutSpecifiers);
7635 }
7636 }
7637 }
7638 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7639 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7640 format_idx, firstDataArg, Type, CallType,
7641 /*InFunctionCall*/ false, CheckedVarArgs,
7642 UncoveredArg, Offset, CallerFormatParamIdx,
7643 IgnoreStringsWithoutSpecifiers);
7644 return SLCT_NotALiteral;
7645 }
7646 case Stmt::ObjCMessageExprClass: {
7647 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7648 if (const auto *MD = ME->getMethodDecl()) {
7649 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7650 // As a special case heuristic, if we're using the method -[NSBundle
7651 // localizedStringForKey:value:table:], ignore any key strings that lack
7652 // format specifiers. The idea is that if the key doesn't have any
7653 // format specifiers then its probably just a key to map to the
7654 // localized strings. If it does have format specifiers though, then its
7655 // likely that the text of the key is the format string in the
7656 // programmer's language, and should be checked.
7657 const ObjCInterfaceDecl *IFace;
7658 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7659 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7660 MD->getSelector().isKeywordSelector(
7661 Names: {"localizedStringForKey", "value", "table"})) {
7662 IgnoreStringsWithoutSpecifiers = true;
7663 }
7664
7665 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7666 return checkFormatStringExpr(
7667 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7668 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7669 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7670 }
7671 }
7672
7673 return SLCT_NotALiteral;
7674 }
7675 case Stmt::ObjCStringLiteralClass:
7676 case Stmt::StringLiteralClass: {
7677 const StringLiteral *StrE = nullptr;
7678
7679 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7680 StrE = ObjCFExpr->getString();
7681 else
7682 StrE = cast<StringLiteral>(Val: E);
7683
7684 if (StrE) {
7685 if (Offset.isNegative() || Offset > StrE->getLength()) {
7686 // TODO: It would be better to have an explicit warning for out of
7687 // bounds literals.
7688 return SLCT_NotALiteral;
7689 }
7690 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7691 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7692 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7693 CallType, CheckedVarArgs, UncoveredArg,
7694 IgnoreStringsWithoutSpecifiers);
7695 return SLCT_CheckedLiteral;
7696 }
7697
7698 return SLCT_NotALiteral;
7699 }
7700 case Stmt::BinaryOperatorClass: {
7701 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7702
7703 // A string literal + an int offset is still a string literal.
7704 if (BinOp->isAdditiveOp()) {
7705 Expr::EvalResult LResult, RResult;
7706
7707 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7708 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7709 InConstantContext: S.isConstantEvaluatedContext());
7710 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7711 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7712 InConstantContext: S.isConstantEvaluatedContext());
7713
7714 if (LIsInt != RIsInt) {
7715 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7716
7717 if (LIsInt) {
7718 if (BinOpKind == BO_Add) {
7719 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7720 E = BinOp->getRHS();
7721 goto tryAgain;
7722 }
7723 } else {
7724 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7725 E = BinOp->getLHS();
7726 goto tryAgain;
7727 }
7728 }
7729 }
7730
7731 return SLCT_NotALiteral;
7732 }
7733 case Stmt::UnaryOperatorClass: {
7734 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7735 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7736 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7737 Expr::EvalResult IndexResult;
7738 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7739 AllowSideEffects: Expr::SE_NoSideEffects,
7740 InConstantContext: S.isConstantEvaluatedContext())) {
7741 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7742 /*RHS is int*/ AddendIsRight: true);
7743 E = ASE->getBase();
7744 goto tryAgain;
7745 }
7746 }
7747
7748 return SLCT_NotALiteral;
7749 }
7750
7751 default:
7752 return SLCT_NotALiteral;
7753 }
7754}
7755
7756// If this expression can be evaluated at compile-time,
7757// check if the result is a StringLiteral and return it
7758// otherwise return nullptr
7759static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7760 const Expr *E) {
7761 Expr::EvalResult Result;
7762 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7763 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7764 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7765 return LVE;
7766 }
7767 return nullptr;
7768}
7769
7770StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7771 switch (FST) {
7772 case FormatStringType::Scanf:
7773 return "scanf";
7774 case FormatStringType::Printf:
7775 return "printf";
7776 case FormatStringType::NSString:
7777 return "NSString";
7778 case FormatStringType::Strftime:
7779 return "strftime";
7780 case FormatStringType::Strfmon:
7781 return "strfmon";
7782 case FormatStringType::Kprintf:
7783 return "kprintf";
7784 case FormatStringType::FreeBSDKPrintf:
7785 return "freebsd_kprintf";
7786 case FormatStringType::OSLog:
7787 return "os_log";
7788 default:
7789 return "<unknown>";
7790 }
7791}
7792
7793FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7794 return llvm::StringSwitch<FormatStringType>(Flavor)
7795 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7796 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7797 Value: FormatStringType::Printf)
7798 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7799 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7800 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7801 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7802 Value: FormatStringType::Kprintf)
7803 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7804 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7805 .Case(S: "os_log", Value: FormatStringType::OSLog)
7806 .Default(Value: FormatStringType::Unknown);
7807}
7808
7809FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7810 return GetFormatStringType(Flavor: Format->getType()->getName());
7811}
7812
7813FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7814 return GetFormatStringType(Flavor: Format->getType()->getName());
7815}
7816
7817bool Sema::CheckFormatArguments(const FormatAttr *Format,
7818 ArrayRef<const Expr *> Args, bool IsCXXMember,
7819 VariadicCallType CallType, SourceLocation Loc,
7820 SourceRange Range,
7821 llvm::SmallBitVector &CheckedVarArgs) {
7822 FormatStringInfo FSI;
7823 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7824 HasImplicitThisParam: IsCXXMember,
7825 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7826 return CheckFormatArguments(
7827 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7828 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7829 return false;
7830}
7831
7832bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7833 ArrayRef<const Expr *> Args, bool IsCXXMember,
7834 VariadicCallType CallType, SourceLocation Loc,
7835 SourceRange Range,
7836 llvm::SmallBitVector &CheckedVarArgs) {
7837 FormatStringInfo FSI;
7838 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7839 FSI: &FSI)) {
7840 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7841 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7842 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7843 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7844 CallType, Loc, range: Range, CheckedVarArgs);
7845 }
7846 return false;
7847}
7848
7849static bool CheckMissingFormatAttribute(
7850 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7851 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7852 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7853 SourceLocation Loc) {
7854 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7855 return false;
7856
7857 DeclContext *DC = S->CurContext->getEnclosingNonExpansionStatementContext();
7858 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7859 return false;
7860 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7861
7862 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7863
7864 // Find the offset to convert between attribute and parameter indexes.
7865 unsigned CallerArgumentIndexOffset =
7866 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7867
7868 unsigned FirstArgumentIndex = -1;
7869 switch (APK) {
7870 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7871 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7872 // As an extension, clang allows the format attribute on non-variadic
7873 // functions.
7874 // Caller must have fixed arguments to pass them to a fixed or variadic
7875 // function. Try to match caller and callee arguments. If successful, then
7876 // emit a diag with the caller idx, otherwise we can't determine the callee
7877 // arguments.
7878 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7879 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7880 // There aren't enough arguments in the caller to pass to callee.
7881 return false;
7882 }
7883 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7884 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7885 const auto *Arg =
7886 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7887 if (!Arg)
7888 return false;
7889 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7890 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7891 return false;
7892 }
7893 FirstArgumentIndex =
7894 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7895 break;
7896 }
7897 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7898 // Caller arguments are either variadic or a va_list.
7899 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7900 ? (NumCallerParams + CallerArgumentIndexOffset)
7901 : 0;
7902 break;
7903 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7904 // The callee has a format_matches attribute. We will emit that instead.
7905 if (!ReferenceFormatString)
7906 return false;
7907 break;
7908 }
7909
7910 // Emit the diagnostic and fixit.
7911 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7912 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7913 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7914 do {
7915 std::string Attr, Fixit;
7916 llvm::raw_string_ostream AttrOS(Attr);
7917 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7918 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7919 << FirstArgumentIndex << ")";
7920 } else {
7921 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7922 << ", \"";
7923 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7924 AttrOS << "\")";
7925 }
7926 AttrOS.flush();
7927 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7928 if (ND)
7929 DB << ND;
7930 else
7931 DB << "block";
7932
7933 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7934 if (isa<BlockDecl>(Val: Caller))
7935 break;
7936
7937 SourceLocation SL;
7938 llvm::raw_string_ostream IS(Fixit);
7939 // The attribute goes at the start of the declaration in C/C++ functions
7940 // and methods, but after the declaration for Objective-C methods.
7941 if (isa<ObjCMethodDecl>(Val: Caller)) {
7942 IS << ' ';
7943 SL = Caller->getEndLoc();
7944 }
7945 const LangOptions &LO = S->getLangOpts();
7946 if (LO.C23 || LO.CPlusPlus11)
7947 IS << "[[gnu::" << Attr << "]]";
7948 else if (LO.ObjC || LO.GNUMode)
7949 IS << "__attribute__((" << Attr << "))";
7950 else
7951 break;
7952 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7953 IS << ' ';
7954 SL = Caller->getBeginLoc();
7955 }
7956 IS.flush();
7957
7958 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7959 } while (false);
7960
7961 // Add implicit format or format_matches attribute.
7962 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7963 Caller->addAttr(A: FormatAttr::CreateImplicit(
7964 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7965 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7966 } else {
7967 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7968 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7969 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7970 }
7971
7972 {
7973 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7974 if (ND)
7975 DB << ND;
7976 else
7977 DB << "block";
7978 }
7979 return true;
7980}
7981
7982bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7983 Sema::FormatArgumentPassingKind APK,
7984 StringLiteral *ReferenceFormatString,
7985 unsigned format_idx, unsigned firstDataArg,
7986 FormatStringType Type,
7987 VariadicCallType CallType, SourceLocation Loc,
7988 SourceRange Range,
7989 llvm::SmallBitVector &CheckedVarArgs) {
7990 // CHECK: printf/scanf-like function is called with no format string.
7991 if (format_idx >= Args.size()) {
7992 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7993 return false;
7994 }
7995
7996 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7997
7998 // CHECK: format string is not a string literal.
7999 //
8000 // Dynamically generated format strings are difficult to
8001 // automatically vet at compile time. Requiring that format strings
8002 // are string literals: (1) permits the checking of format strings by
8003 // the compiler and thereby (2) can practically remove the source of
8004 // many format string exploits.
8005
8006 // Format string can be either ObjC string (e.g. @"%d") or
8007 // C string (e.g. "%d")
8008 // ObjC string uses the same format specifiers as C string, so we can use
8009 // the same format string checking logic for both ObjC and C strings.
8010 UncoveredArgHandler UncoveredArg;
8011 std::optional<unsigned> CallerParamIdx;
8012 StringLiteralCheckType CT = checkFormatStringExpr(
8013 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
8014 firstDataArg, Type, CallType,
8015 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
8016 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
8017
8018 // Generate a diagnostic where an uncovered argument is detected.
8019 if (UncoveredArg.hasUncoveredArg()) {
8020 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8021 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8022 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
8023 }
8024
8025 if (CT != SLCT_NotALiteral)
8026 // Literal format string found, check done!
8027 return CT == SLCT_CheckedLiteral;
8028
8029 // Do not emit diag when the string param is a macro expansion and the
8030 // format is either NSString or CFString. This is a hack to prevent
8031 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8032 // which are usually used in place of NS and CF string literals.
8033 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8034 if (Type == FormatStringType::NSString &&
8035 SourceMgr.isInSystemMacro(loc: FormatLoc))
8036 return false;
8037
8038 if (CallerParamIdx && CheckMissingFormatAttribute(
8039 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
8040 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
8041 return false;
8042
8043 // Strftime is particular as it always uses a single 'time' argument,
8044 // so it is safe to pass a non-literal string.
8045 if (Type == FormatStringType::Strftime)
8046 return false;
8047
8048 // If there are no arguments specified, warn with -Wformat-security, otherwise
8049 // warn only with -Wformat-nonliteral.
8050 if (Args.size() == firstDataArg) {
8051 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
8052 << OrigFormatExpr->getSourceRange();
8053 switch (Type) {
8054 default:
8055 break;
8056 case FormatStringType::Kprintf:
8057 case FormatStringType::FreeBSDKPrintf:
8058 case FormatStringType::Printf:
8059 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8060 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
8061 break;
8062 case FormatStringType::NSString:
8063 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8064 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
8065 break;
8066 }
8067 } else {
8068 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
8069 << OrigFormatExpr->getSourceRange();
8070 }
8071 return false;
8072}
8073
8074namespace {
8075
8076class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8077protected:
8078 Sema &S;
8079 const FormatStringLiteral *FExpr;
8080 const Expr *OrigFormatExpr;
8081 const FormatStringType FSType;
8082 const unsigned FirstDataArg;
8083 const unsigned NumDataArgs;
8084 const char *Beg; // Start of format string.
8085 const Sema::FormatArgumentPassingKind ArgPassingKind;
8086 ArrayRef<const Expr *> Args;
8087 unsigned FormatIdx;
8088 llvm::SmallBitVector CoveredArgs;
8089 bool usesPositionalArgs = false;
8090 bool atFirstArg = true;
8091 bool inFunctionCall;
8092 VariadicCallType CallType;
8093 llvm::SmallBitVector &CheckedVarArgs;
8094 UncoveredArgHandler &UncoveredArg;
8095
8096public:
8097 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8098 const Expr *origFormatExpr, const FormatStringType type,
8099 unsigned firstDataArg, unsigned numDataArgs,
8100 const char *beg, Sema::FormatArgumentPassingKind APK,
8101 ArrayRef<const Expr *> Args, unsigned formatIdx,
8102 bool inFunctionCall, VariadicCallType callType,
8103 llvm::SmallBitVector &CheckedVarArgs,
8104 UncoveredArgHandler &UncoveredArg)
8105 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8106 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8107 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8108 inFunctionCall(inFunctionCall), CallType(callType),
8109 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8110 CoveredArgs.resize(N: numDataArgs);
8111 CoveredArgs.reset();
8112 }
8113
8114 bool HasFormatArguments() const {
8115 return ArgPassingKind == Sema::FAPK_Fixed ||
8116 ArgPassingKind == Sema::FAPK_Variadic;
8117 }
8118
8119 void DoneProcessing();
8120
8121 void HandleIncompleteSpecifier(const char *startSpecifier,
8122 unsigned specifierLen) override;
8123
8124 void HandleInvalidLengthModifier(
8125 const analyze_format_string::FormatSpecifier &FS,
8126 const analyze_format_string::ConversionSpecifier &CS,
8127 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8128
8129 void HandleNonStandardLengthModifier(
8130 const analyze_format_string::FormatSpecifier &FS,
8131 const char *startSpecifier, unsigned specifierLen);
8132
8133 void HandleNonStandardConversionSpecifier(
8134 const analyze_format_string::ConversionSpecifier &CS,
8135 const char *startSpecifier, unsigned specifierLen);
8136
8137 void HandlePosition(const char *startPos, unsigned posLen) override;
8138
8139 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8140 analyze_format_string::PositionContext p) override;
8141
8142 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8143
8144 void HandleNullChar(const char *nullCharacter) override;
8145
8146 template <typename Range>
8147 static void
8148 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8149 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8150 bool IsStringLocation, Range StringRange,
8151 ArrayRef<FixItHint> Fixit = {});
8152
8153protected:
8154 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8155 const char *startSpec,
8156 unsigned specifierLen,
8157 const char *csStart, unsigned csLen);
8158
8159 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8160 const char *startSpec,
8161 unsigned specifierLen);
8162
8163 SourceRange getFormatStringRange();
8164 CharSourceRange getSpecifierRange(const char *startSpecifier,
8165 unsigned specifierLen);
8166 SourceLocation getLocationOfByte(const char *x);
8167
8168 const Expr *getDataArg(unsigned i) const;
8169
8170 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8171 const analyze_format_string::ConversionSpecifier &CS,
8172 const char *startSpecifier, unsigned specifierLen,
8173 unsigned argIndex);
8174
8175 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8176 const Expr *E, const char *startSpecifier,
8177 unsigned specifierLen);
8178
8179 template <typename Range>
8180 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8181 bool IsStringLocation, Range StringRange,
8182 ArrayRef<FixItHint> Fixit = {});
8183};
8184
8185} // namespace
8186
8187SourceRange CheckFormatHandler::getFormatStringRange() {
8188 return OrigFormatExpr->getSourceRange();
8189}
8190
8191CharSourceRange
8192CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8193 unsigned specifierLen) {
8194 SourceLocation Start = getLocationOfByte(x: startSpecifier);
8195 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
8196
8197 // Advance the end SourceLocation by one due to half-open ranges.
8198 End = End.getLocWithOffset(Offset: 1);
8199
8200 return CharSourceRange::getCharRange(B: Start, E: End);
8201}
8202
8203SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8204 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
8205 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
8206}
8207
8208void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8209 unsigned specifierLen) {
8210 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
8211 Loc: getLocationOfByte(x: startSpecifier),
8212 /*IsStringLocation*/ true,
8213 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8214}
8215
8216bool CheckFormatHandler::CheckUnsupportedType(
8217 const analyze_format_string::ArgType &AT, const Expr *E,
8218 const char *StartSpecifier, unsigned SpecifierLen) {
8219 if (!AT.isUnsupported())
8220 return false;
8221
8222 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_unsupported_type)
8223 << AT.getRepresentativeTypeName(C&: S.Context),
8224 Loc: E->getExprLoc(), /*IsStringLocation=*/false,
8225 StringRange: getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen));
8226 return true;
8227}
8228
8229void CheckFormatHandler::HandleInvalidLengthModifier(
8230 const analyze_format_string::FormatSpecifier &FS,
8231 const analyze_format_string::ConversionSpecifier &CS,
8232 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8233 using namespace analyze_format_string;
8234
8235 const LengthModifier &LM = FS.getLengthModifier();
8236 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8237
8238 // See if we know how to fix this length modifier.
8239 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8240 if (FixedLM) {
8241 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8242 Loc: getLocationOfByte(x: LM.getStart()),
8243 /*IsStringLocation*/ true,
8244 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8245
8246 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8247 << FixedLM->toString()
8248 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8249
8250 } else {
8251 FixItHint Hint;
8252 if (DiagID == diag::warn_format_nonsensical_length)
8253 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
8254
8255 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8256 Loc: getLocationOfByte(x: LM.getStart()),
8257 /*IsStringLocation*/ true,
8258 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: Hint);
8259 }
8260}
8261
8262void CheckFormatHandler::HandleNonStandardLengthModifier(
8263 const analyze_format_string::FormatSpecifier &FS,
8264 const char *startSpecifier, unsigned specifierLen) {
8265 using namespace analyze_format_string;
8266
8267 const LengthModifier &LM = FS.getLengthModifier();
8268 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8269
8270 // See if we know how to fix this length modifier.
8271 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8272 if (FixedLM) {
8273 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8274 << LM.toString() << 0,
8275 Loc: getLocationOfByte(x: LM.getStart()),
8276 /*IsStringLocation*/ true,
8277 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8278
8279 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8280 << FixedLM->toString()
8281 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8282
8283 } else {
8284 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8285 << LM.toString() << 0,
8286 Loc: getLocationOfByte(x: LM.getStart()),
8287 /*IsStringLocation*/ true,
8288 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8289 }
8290}
8291
8292void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8293 const analyze_format_string::ConversionSpecifier &CS,
8294 const char *startSpecifier, unsigned specifierLen) {
8295 using namespace analyze_format_string;
8296
8297 // See if we know how to fix this conversion specifier.
8298 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8299 if (FixedCS) {
8300 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8301 << CS.toString() << /*conversion specifier*/ 1,
8302 Loc: getLocationOfByte(x: CS.getStart()),
8303 /*IsStringLocation*/ true,
8304 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8305
8306 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
8307 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
8308 << FixedCS->toString()
8309 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
8310 } else {
8311 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8312 << CS.toString() << /*conversion specifier*/ 1,
8313 Loc: getLocationOfByte(x: CS.getStart()),
8314 /*IsStringLocation*/ true,
8315 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8316 }
8317}
8318
8319void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8320 if (!S.getDiagnostics().isIgnored(
8321 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
8322 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
8323 Loc: getLocationOfByte(x: startPos),
8324 /*IsStringLocation*/ true,
8325 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8326}
8327
8328void CheckFormatHandler::HandleInvalidPosition(
8329 const char *startSpecifier, unsigned specifierLen,
8330 analyze_format_string::PositionContext p) {
8331 if (!S.getDiagnostics().isIgnored(
8332 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
8333 EmitFormatDiagnostic(
8334 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8335 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
8336 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8337}
8338
8339void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8340 unsigned posLen) {
8341 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
8342 Loc: SourceLocation()))
8343 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
8344 Loc: getLocationOfByte(x: startPos),
8345 /*IsStringLocation*/ true,
8346 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8347}
8348
8349void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8350 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
8351 // The presence of a null character is likely an error.
8352 EmitFormatDiagnostic(
8353 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
8354 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/ true,
8355 StringRange: getFormatStringRange());
8356 }
8357}
8358
8359// Note that this may return NULL if there was an error parsing or building
8360// one of the argument expressions.
8361const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8362 return Args[FirstDataArg + i];
8363}
8364
8365void CheckFormatHandler::DoneProcessing() {
8366 // Does the number of data arguments exceed the number of
8367 // format conversions in the format string?
8368 if (HasFormatArguments()) {
8369 // Find any arguments that weren't covered.
8370 CoveredArgs.flip();
8371 signed notCoveredArg = CoveredArgs.find_first();
8372 if (notCoveredArg >= 0) {
8373 assert((unsigned)notCoveredArg < NumDataArgs);
8374 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
8375 } else {
8376 UncoveredArg.setAllCovered();
8377 }
8378 }
8379}
8380
8381void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8382 const Expr *ArgExpr) {
8383 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8384
8385 if (!ArgExpr)
8386 return;
8387
8388 SourceLocation Loc = ArgExpr->getBeginLoc();
8389
8390 if (S.getSourceManager().isInSystemMacro(loc: Loc))
8391 return;
8392
8393 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
8394 for (auto E : DiagnosticExprs)
8395 PDiag << E->getSourceRange();
8396
8397 CheckFormatHandler::EmitFormatDiagnostic(
8398 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0], PDiag, Loc,
8399 /*IsStringLocation*/ false, StringRange: DiagnosticExprs[0]->getSourceRange());
8400}
8401
8402bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8403 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8404 unsigned specifierLen, const char *csStart, unsigned csLen) {
8405 bool keepGoing = true;
8406 if (argIndex < NumDataArgs) {
8407 // Consider the argument coverered, even though the specifier doesn't
8408 // make sense.
8409 CoveredArgs.set(argIndex);
8410 } else {
8411 // If argIndex exceeds the number of data arguments we
8412 // don't issue a warning because that is just a cascade of warnings (and
8413 // they may have intended '%%' anyway). We don't want to continue processing
8414 // the format string after this point, however, as we will like just get
8415 // gibberish when trying to match arguments.
8416 keepGoing = false;
8417 }
8418
8419 StringRef Specifier(csStart, csLen);
8420
8421 // If the specifier in non-printable, it could be the first byte of a UTF-8
8422 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8423 // hex value.
8424 std::string CodePointStr;
8425 if (!llvm::sys::locale::isPrint(c: *csStart)) {
8426 llvm::UTF32 CodePoint;
8427 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8428 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8429 llvm::ConversionResult Result =
8430 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
8431
8432 if (Result != llvm::conversionOK) {
8433 unsigned char FirstChar = *csStart;
8434 CodePoint = (llvm::UTF32)FirstChar;
8435 }
8436
8437 llvm::raw_string_ostream OS(CodePointStr);
8438 if (CodePoint < 256)
8439 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
8440 else if (CodePoint <= 0xFFFF)
8441 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
8442 else
8443 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
8444 Specifier = CodePointStr;
8445 }
8446
8447 EmitFormatDiagnostic(
8448 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
8449 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8450
8451 return keepGoing;
8452}
8453
8454void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8455 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8456 EmitFormatDiagnostic(
8457 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args), Loc,
8458 /*isStringLoc*/ IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8459}
8460
8461bool CheckFormatHandler::CheckNumArgs(
8462 const analyze_format_string::FormatSpecifier &FS,
8463 const analyze_format_string::ConversionSpecifier &CS,
8464 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8465
8466 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8467 PartialDiagnostic PDiag =
8468 FS.usesPositionalArg()
8469 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
8470 << (argIndex + 1) << NumDataArgs)
8471 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
8472 EmitFormatDiagnostic(PDiag, Loc: getLocationOfByte(x: CS.getStart()),
8473 /*IsStringLocation*/ true,
8474 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8475
8476 // Since more arguments than conversion tokens are given, by extension
8477 // all arguments are covered, so mark this as so.
8478 UncoveredArg.setAllCovered();
8479 return false;
8480 }
8481 return true;
8482}
8483
8484template <typename Range>
8485void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8486 SourceLocation Loc,
8487 bool IsStringLocation,
8488 Range StringRange,
8489 ArrayRef<FixItHint> FixIt) {
8490 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8491 IsStringLocation, StringRange, FixIt);
8492}
8493
8494/// If the format string is not within the function call, emit a note
8495/// so that the function call and string are in diagnostic messages.
8496///
8497/// \param InFunctionCall if true, the format string is within the function
8498/// call and only one diagnostic message will be produced. Otherwise, an
8499/// extra note will be emitted pointing to location of the format string.
8500///
8501/// \param ArgumentExpr the expression that is passed as the format string
8502/// argument in the function call. Used for getting locations when two
8503/// diagnostics are emitted.
8504///
8505/// \param PDiag the callee should already have provided any strings for the
8506/// diagnostic message. This function only adds locations and fixits
8507/// to diagnostics.
8508///
8509/// \param Loc primary location for diagnostic. If two diagnostics are
8510/// required, one will be at Loc and a new SourceLocation will be created for
8511/// the other one.
8512///
8513/// \param IsStringLocation if true, Loc points to the format string should be
8514/// used for the note. Otherwise, Loc points to the argument list and will
8515/// be used with PDiag.
8516///
8517/// \param StringRange some or all of the string to highlight. This is
8518/// templated so it can accept either a CharSourceRange or a SourceRange.
8519///
8520/// \param FixIt optional fix it hint for the format string.
8521template <typename Range>
8522void CheckFormatHandler::EmitFormatDiagnostic(
8523 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8524 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8525 Range StringRange, ArrayRef<FixItHint> FixIt) {
8526 if (InFunctionCall) {
8527 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8528 D << StringRange;
8529 D << FixIt;
8530 } else {
8531 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8532 << ArgumentExpr->getSourceRange();
8533
8534 const Sema::SemaDiagnosticBuilder &Note =
8535 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8536 diag::note_format_string_defined);
8537
8538 Note << StringRange;
8539 Note << FixIt;
8540 }
8541}
8542
8543//===--- CHECK: Printf format string checking -----------------------------===//
8544
8545namespace {
8546
8547class CheckPrintfHandler : public CheckFormatHandler {
8548public:
8549 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8550 const Expr *origFormatExpr, const FormatStringType type,
8551 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8552 const char *beg, Sema::FormatArgumentPassingKind APK,
8553 ArrayRef<const Expr *> Args, unsigned formatIdx,
8554 bool inFunctionCall, VariadicCallType CallType,
8555 llvm::SmallBitVector &CheckedVarArgs,
8556 UncoveredArgHandler &UncoveredArg)
8557 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8558 numDataArgs, beg, APK, Args, formatIdx,
8559 inFunctionCall, CallType, CheckedVarArgs,
8560 UncoveredArg) {}
8561
8562 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8563
8564 /// Returns true if '%@' specifiers are allowed in the format string.
8565 bool allowsObjCArg() const {
8566 return FSType == FormatStringType::NSString ||
8567 FSType == FormatStringType::OSLog ||
8568 FSType == FormatStringType::OSTrace;
8569 }
8570
8571 bool HandleInvalidPrintfConversionSpecifier(
8572 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8573 unsigned specifierLen) override;
8574
8575 void handleInvalidMaskType(StringRef MaskType) override;
8576
8577 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8578 const char *startSpecifier, unsigned specifierLen,
8579 const TargetInfo &Target) override;
8580 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8581 const char *StartSpecifier, unsigned SpecifierLen,
8582 const Expr *E);
8583
8584 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8585 unsigned k, const char *startSpecifier,
8586 unsigned specifierLen);
8587 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8588 const analyze_printf::OptionalAmount &Amt,
8589 unsigned type, const char *startSpecifier,
8590 unsigned specifierLen);
8591 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8592 const analyze_printf::OptionalFlag &flag,
8593 const char *startSpecifier, unsigned specifierLen);
8594 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8595 const analyze_printf::OptionalFlag &ignoredFlag,
8596 const analyze_printf::OptionalFlag &flag,
8597 const char *startSpecifier, unsigned specifierLen);
8598 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8599
8600 void HandleEmptyObjCModifierFlag(const char *startFlag,
8601 unsigned flagLen) override;
8602
8603 void HandleInvalidObjCModifierFlag(const char *startFlag,
8604 unsigned flagLen) override;
8605
8606 void
8607 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8608 const char *flagsEnd,
8609 const char *conversionPosition) override;
8610};
8611
8612/// Keeps around the information needed to verify that two specifiers are
8613/// compatible.
8614class EquatableFormatArgument {
8615public:
8616 enum SpecifierSensitivity : unsigned {
8617 SS_None,
8618 SS_Private,
8619 SS_Public,
8620 SS_Sensitive
8621 };
8622
8623 enum FormatArgumentRole : unsigned {
8624 FAR_Data,
8625 FAR_FieldWidth,
8626 FAR_Precision,
8627 FAR_Auxiliary, // FreeBSD kernel %b and %D
8628 };
8629
8630private:
8631 analyze_format_string::ArgType ArgType;
8632 analyze_format_string::LengthModifier LengthMod;
8633 StringRef SpecifierLetter;
8634 CharSourceRange Range;
8635 SourceLocation ElementLoc;
8636 FormatArgumentRole Role : 2;
8637 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8638 unsigned Position : 14;
8639 unsigned ModifierFor : 14; // not set for FAR_Data
8640
8641 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8642 bool InFunctionCall) const;
8643
8644public:
8645 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8646 analyze_format_string::LengthModifier LengthMod,
8647 StringRef SpecifierLetter,
8648 analyze_format_string::ArgType ArgType,
8649 FormatArgumentRole Role,
8650 SpecifierSensitivity Sensitivity, unsigned Position,
8651 unsigned ModifierFor)
8652 : ArgType(ArgType), LengthMod(LengthMod),
8653 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8654 Role(Role), Sensitivity(Sensitivity), Position(Position),
8655 ModifierFor(ModifierFor) {}
8656
8657 unsigned getPosition() const { return Position; }
8658 SourceLocation getSourceLocation() const { return ElementLoc; }
8659 CharSourceRange getSourceRange() const { return Range; }
8660 analyze_format_string::LengthModifier getLengthModifier() const {
8661 return LengthMod;
8662 }
8663 void setModifierFor(unsigned V) { ModifierFor = V; }
8664
8665 std::string buildFormatSpecifier() const {
8666 std::string result;
8667 llvm::raw_string_ostream(result)
8668 << getLengthModifier().toString() << SpecifierLetter;
8669 return result;
8670 }
8671
8672 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8673 const Expr *FmtExpr, bool InFunctionCall) const;
8674};
8675
8676/// Turns format strings into lists of EquatableSpecifier objects.
8677class DecomposePrintfHandler : public CheckPrintfHandler {
8678 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8679 bool HadError;
8680
8681 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8682 const Expr *origFormatExpr,
8683 const FormatStringType type, unsigned firstDataArg,
8684 unsigned numDataArgs, bool isObjC, const char *beg,
8685 Sema::FormatArgumentPassingKind APK,
8686 ArrayRef<const Expr *> Args, unsigned formatIdx,
8687 bool inFunctionCall, VariadicCallType CallType,
8688 llvm::SmallBitVector &CheckedVarArgs,
8689 UncoveredArgHandler &UncoveredArg,
8690 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8691 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8692 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8693 inFunctionCall, CallType, CheckedVarArgs,
8694 UncoveredArg),
8695 Specs(Specs), HadError(false) {}
8696
8697public:
8698 static bool
8699 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8700 FormatStringType type, bool IsObjC, bool InFunctionCall,
8701 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8702
8703 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8704 const char *startSpecifier,
8705 unsigned specifierLen,
8706 const TargetInfo &Target) override;
8707};
8708
8709} // namespace
8710
8711bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8712 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8713 unsigned specifierLen) {
8714 const analyze_printf::PrintfConversionSpecifier &CS =
8715 FS.getConversionSpecifier();
8716
8717 return HandleInvalidConversionSpecifier(
8718 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
8719 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
8720}
8721
8722void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8723 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8724}
8725
8726// Error out if struct or complex type argments are passed to os_log.
8727static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8728 QualType T) {
8729 if (FSType != FormatStringType::OSLog)
8730 return false;
8731 return T->isRecordType() || T->isComplexType();
8732}
8733
8734bool CheckPrintfHandler::HandleAmount(
8735 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8736 const char *startSpecifier, unsigned specifierLen) {
8737 if (Amt.hasDataArgument()) {
8738 if (HasFormatArguments()) {
8739 unsigned argIndex = Amt.getArgIndex();
8740 if (argIndex >= NumDataArgs) {
8741 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8742 << k,
8743 Loc: getLocationOfByte(x: Amt.getStart()),
8744 /*IsStringLocation*/ true,
8745 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8746 // Don't do any more checking. We will just emit
8747 // spurious errors.
8748 return false;
8749 }
8750
8751 // Type check the data argument. It should be an 'int'.
8752 // Although not in conformance with C99, we also allow the argument to be
8753 // an 'unsigned int' as that is a reasonably safe case. GCC also
8754 // doesn't emit a warning for that case.
8755 CoveredArgs.set(argIndex);
8756 const Expr *Arg = getDataArg(i: argIndex);
8757 if (!Arg)
8758 return false;
8759
8760 QualType T = Arg->getType();
8761
8762 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8763 assert(AT.isValid());
8764
8765 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8766 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8767 ? diag::err_printf_asterisk_wrong_type
8768 : diag::warn_printf_asterisk_wrong_type;
8769 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8770 << k << AT.getRepresentativeTypeName(C&: S.Context)
8771 << T << Arg->getSourceRange(),
8772 Loc: getLocationOfByte(x: Amt.getStart()),
8773 /*IsStringLocation*/ true,
8774 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8775 // Don't do any more checking. We will just emit
8776 // spurious errors.
8777 return false;
8778 }
8779 }
8780 }
8781 return true;
8782}
8783
8784void CheckPrintfHandler::HandleInvalidAmount(
8785 const analyze_printf::PrintfSpecifier &FS,
8786 const analyze_printf::OptionalAmount &Amt, unsigned type,
8787 const char *startSpecifier, unsigned specifierLen) {
8788 const analyze_printf::PrintfConversionSpecifier &CS =
8789 FS.getConversionSpecifier();
8790
8791 FixItHint fixit =
8792 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8793 ? FixItHint::CreateRemoval(
8794 RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength()))
8795 : FixItHint();
8796
8797 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8798 << type << CS.toString(),
8799 Loc: getLocationOfByte(x: Amt.getStart()),
8800 /*IsStringLocation*/ true,
8801 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: fixit);
8802}
8803
8804void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8805 const analyze_printf::OptionalFlag &flag,
8806 const char *startSpecifier,
8807 unsigned specifierLen) {
8808 // Warn about pointless flag with a fixit removal.
8809 const analyze_printf::PrintfConversionSpecifier &CS =
8810 FS.getConversionSpecifier();
8811 EmitFormatDiagnostic(
8812 PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8813 << flag.toString() << CS.toString(),
8814 Loc: getLocationOfByte(x: flag.getPosition()),
8815 /*IsStringLocation*/ true,
8816 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8817 FixIt: FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8818}
8819
8820void CheckPrintfHandler::HandleIgnoredFlag(
8821 const analyze_printf::PrintfSpecifier &FS,
8822 const analyze_printf::OptionalFlag &ignoredFlag,
8823 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8824 unsigned specifierLen) {
8825 // Warn about ignored flag with a fixit removal.
8826 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8827 << ignoredFlag.toString() << flag.toString(),
8828 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8829 /*IsStringLocation*/ true,
8830 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8831 FixIt: FixItHint::CreateRemoval(
8832 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8833}
8834
8835void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8836 unsigned flagLen) {
8837 // Warn about an empty flag.
8838 EmitFormatDiagnostic(
8839 PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag), Loc: getLocationOfByte(x: startFlag),
8840 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8841}
8842
8843void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8844 unsigned flagLen) {
8845 // Warn about an invalid flag.
8846 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8847 StringRef flag(startFlag, flagLen);
8848 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8849 Loc: getLocationOfByte(x: startFlag),
8850 /*IsStringLocation*/ true, StringRange: Range,
8851 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8852}
8853
8854void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8855 const char *flagsStart, const char *flagsEnd,
8856 const char *conversionPosition) {
8857 // Warn about using '[...]' without a '@' conversion.
8858 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8859 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8860 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8861 Loc: getLocationOfByte(x: conversionPosition),
8862 /*IsStringLocation*/ true, StringRange: Range,
8863 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8864}
8865
8866void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8867 const Expr *FmtExpr,
8868 bool InFunctionCall) const {
8869 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8870 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8871}
8872
8873bool EquatableFormatArgument::VerifyCompatible(
8874 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8875 bool InFunctionCall) const {
8876 using MK = analyze_format_string::ArgType::MatchKind;
8877 if (Role != Other.Role) {
8878 // diagnose and stop
8879 EmitDiagnostic(
8880 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8881 FmtExpr, InFunctionCall);
8882 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8883 return false;
8884 }
8885
8886 if (Role != FAR_Data) {
8887 if (ModifierFor != Other.ModifierFor) {
8888 // diagnose and stop
8889 EmitDiagnostic(S,
8890 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8891 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8892 FmtExpr, InFunctionCall);
8893 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8894 return false;
8895 }
8896 return true;
8897 }
8898
8899 bool HadError = false;
8900 if (Sensitivity != Other.Sensitivity) {
8901 // diagnose and continue
8902 EmitDiagnostic(S,
8903 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8904 << Sensitivity << Other.Sensitivity,
8905 FmtExpr, InFunctionCall);
8906 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8907 << 0 << Other.Range;
8908 }
8909
8910 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8911 case MK::Match:
8912 break;
8913
8914 case MK::MatchPromotion:
8915 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8916 // MatchPromotion is treated as a failure by format_matches.
8917 case MK::NoMatch:
8918 case MK::NoMatchTypeConfusion:
8919 case MK::NoMatchPromotionTypeConfusion:
8920 EmitDiagnostic(S,
8921 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8922 << buildFormatSpecifier()
8923 << Other.buildFormatSpecifier(),
8924 FmtExpr, InFunctionCall);
8925 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8926 << 0 << Other.Range;
8927 break;
8928
8929 case MK::NoMatchPedantic:
8930 EmitDiagnostic(S,
8931 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8932 << buildFormatSpecifier()
8933 << Other.buildFormatSpecifier(),
8934 FmtExpr, InFunctionCall);
8935 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8936 << 0 << Other.Range;
8937 break;
8938
8939 case MK::NoMatchSignedness:
8940 EmitDiagnostic(S,
8941 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8942 << buildFormatSpecifier()
8943 << Other.buildFormatSpecifier(),
8944 FmtExpr, InFunctionCall);
8945 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8946 << 0 << Other.Range;
8947 break;
8948 }
8949 return !HadError;
8950}
8951
8952bool DecomposePrintfHandler::GetSpecifiers(
8953 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8954 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8955 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8956 StringRef Data = FSL->getString();
8957 const char *Str = Data.data();
8958 llvm::SmallBitVector BV;
8959 UncoveredArgHandler UA;
8960 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8961 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8962 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8963 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8964 UA, Args);
8965
8966 if (!analyze_format_string::ParsePrintfString(
8967 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8968 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8969 H.DoneProcessing();
8970 if (H.HadError)
8971 return false;
8972
8973 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8974 const EquatableFormatArgument &B) {
8975 return A.getPosition() < B.getPosition();
8976 });
8977 return true;
8978}
8979
8980bool DecomposePrintfHandler::HandlePrintfSpecifier(
8981 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8982 unsigned specifierLen, const TargetInfo &Target) {
8983 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8984 specifierLen, Target)) {
8985 HadError = true;
8986 return false;
8987 }
8988
8989 // Do not add any specifiers to the list for %%. This is possibly incorrect
8990 // if using a precision/width with a data argument, but that combination is
8991 // meaningless and we wouldn't know which format to attach the
8992 // precision/width to.
8993 const auto &CS = FS.getConversionSpecifier();
8994 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8995 return true;
8996
8997 // have to patch these to have the right ModifierFor if they are used
8998 const unsigned Unset = ~0;
8999 unsigned FieldWidthIndex = Unset;
9000 unsigned PrecisionIndex = Unset;
9001
9002 // field width?
9003 const auto &FieldWidth = FS.getFieldWidth();
9004 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9005 FieldWidthIndex = Specs.size();
9006 Specs.emplace_back(
9007 Args: getSpecifierRange(startSpecifier, specifierLen),
9008 Args: getLocationOfByte(x: FieldWidth.getStart()),
9009 Args: analyze_format_string::LengthModifier(), Args: FieldWidth.getCharacters(),
9010 Args: FieldWidth.getArgType(Ctx&: S.Context),
9011 Args: EquatableFormatArgument::FAR_FieldWidth,
9012 Args: EquatableFormatArgument::SS_None,
9013 Args: FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9014 : FieldWidthIndex,
9015 Args: 0);
9016 }
9017 // precision?
9018 const auto &Precision = FS.getPrecision();
9019 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9020 PrecisionIndex = Specs.size();
9021 Specs.emplace_back(
9022 Args: getSpecifierRange(startSpecifier, specifierLen),
9023 Args: getLocationOfByte(x: Precision.getStart()),
9024 Args: analyze_format_string::LengthModifier(), Args: Precision.getCharacters(),
9025 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
9026 Args: EquatableFormatArgument::SS_None,
9027 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9028 : PrecisionIndex,
9029 Args: 0);
9030 }
9031
9032 // this specifier
9033 unsigned SpecIndex =
9034 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9035 if (FieldWidthIndex != Unset)
9036 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9037 if (PrecisionIndex != Unset)
9038 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9039
9040 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9041 if (FS.isPrivate())
9042 Sensitivity = EquatableFormatArgument::SS_Private;
9043 else if (FS.isPublic())
9044 Sensitivity = EquatableFormatArgument::SS_Public;
9045 else if (FS.isSensitive())
9046 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9047 else
9048 Sensitivity = EquatableFormatArgument::SS_None;
9049
9050 Specs.emplace_back(
9051 Args: getSpecifierRange(startSpecifier, specifierLen),
9052 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier(),
9053 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
9054 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
9055
9056 // auxiliary argument?
9057 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
9058 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
9059 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
9060 Args: getLocationOfByte(x: CS.getStart()),
9061 Args: analyze_format_string::LengthModifier(),
9062 Args: CS.getCharacters(),
9063 Args: analyze_format_string::ArgType::CStrTy,
9064 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
9065 Args: SpecIndex + 1, Args&: SpecIndex);
9066 }
9067 return true;
9068}
9069
9070// Determines if the specified is a C++ class or struct containing
9071// a member with the specified name and kind (e.g. a CXXMethodDecl named
9072// "c_str()").
9073template<typename MemberKind>
9074static llvm::SmallPtrSet<MemberKind*, 1>
9075CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9076 auto *RD = Ty->getAsCXXRecordDecl();
9077 llvm::SmallPtrSet<MemberKind*, 1> Results;
9078
9079 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9080 return Results;
9081
9082 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9083 Sema::LookupMemberName);
9084 R.suppressDiagnostics();
9085
9086 // We just need to include all members of the right kind turned up by the
9087 // filter, at this point.
9088 if (S.LookupQualifiedName(R, LookupCtx: RD))
9089 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9090 NamedDecl *decl = (*I)->getUnderlyingDecl();
9091 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9092 Results.insert(FK);
9093 }
9094 return Results;
9095}
9096
9097/// Check if we could call '.c_str()' on an object.
9098///
9099/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9100/// allow the call, or if it would be ambiguous).
9101bool Sema::hasCStrMethod(const Expr *E) {
9102 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9103
9104 MethodSet Results =
9105 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
9106 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9107 MI != ME; ++MI)
9108 if ((*MI)->getMinRequiredArguments() == 0)
9109 return true;
9110 return false;
9111}
9112
9113// Check if a (w)string was passed when a (w)char* was needed, and offer a
9114// better diagnostic if so. AT is assumed to be valid.
9115// Returns true when a c_str() conversion method is found.
9116bool CheckPrintfHandler::checkForCStrMembers(
9117 const analyze_printf::ArgType &AT, const Expr *E) {
9118 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9119
9120 MethodSet Results =
9121 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
9122
9123 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9124 MI != ME; ++MI) {
9125 const CXXMethodDecl *Method = *MI;
9126 if (Method->getMinRequiredArguments() == 0 &&
9127 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
9128 // FIXME: Suggest parens if the expression needs them.
9129 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
9130 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
9131 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
9132 return true;
9133 }
9134 }
9135
9136 return false;
9137}
9138
9139bool CheckPrintfHandler::HandlePrintfSpecifier(
9140 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9141 unsigned specifierLen, const TargetInfo &Target) {
9142 using namespace analyze_format_string;
9143 using namespace analyze_printf;
9144
9145 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9146
9147 if (FS.consumesDataArgument()) {
9148 if (atFirstArg) {
9149 atFirstArg = false;
9150 usesPositionalArgs = FS.usesPositionalArg();
9151 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9152 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9153 startSpec: startSpecifier, specifierLen);
9154 return false;
9155 }
9156 }
9157
9158 // First check if the field width, precision, and conversion specifier
9159 // have matching data arguments.
9160 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0, startSpecifier,
9161 specifierLen)) {
9162 return false;
9163 }
9164
9165 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1, startSpecifier,
9166 specifierLen)) {
9167 return false;
9168 }
9169
9170 if (!CS.consumesDataArgument()) {
9171 // FIXME: Technically specifying a precision or field width here
9172 // makes no sense. Worth issuing a warning at some point.
9173 return true;
9174 }
9175
9176 // Consume the argument.
9177 unsigned argIndex = FS.getArgIndex();
9178 if (argIndex < NumDataArgs) {
9179 // The check to see if the argIndex is valid will come later.
9180 // We set the bit here because we may exit early from this
9181 // function if we encounter some other error.
9182 CoveredArgs.set(argIndex);
9183 }
9184
9185 // FreeBSD kernel extensions.
9186 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9187 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9188 // We need at least two arguments.
9189 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
9190 return false;
9191
9192 if (HasFormatArguments()) {
9193 // Claim the second argument.
9194 CoveredArgs.set(argIndex + 1);
9195
9196 // Type check the first argument (int for %b, pointer for %D)
9197 const Expr *Ex = getDataArg(i: argIndex);
9198 const analyze_printf::ArgType &AT =
9199 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9200 ? ArgType(S.Context.IntTy)
9201 : ArgType::CPointerTy;
9202 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
9203 EmitFormatDiagnostic(
9204 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9205 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9206 << false << Ex->getSourceRange(),
9207 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9208 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9209
9210 // Type check the second argument (char * for both %b and %D)
9211 Ex = getDataArg(i: argIndex + 1);
9212 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9213 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
9214 EmitFormatDiagnostic(
9215 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9216 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9217 << false << Ex->getSourceRange(),
9218 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9219 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9220 }
9221 return true;
9222 }
9223
9224 // Check for using an Objective-C specific conversion specifier
9225 // in a non-ObjC literal.
9226 if (!allowsObjCArg() && CS.isObjCArg()) {
9227 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9228 specifierLen);
9229 }
9230
9231 // %P can only be used with os_log.
9232 if (FSType != FormatStringType::OSLog &&
9233 CS.getKind() == ConversionSpecifier::PArg) {
9234 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9235 specifierLen);
9236 }
9237
9238 // %n is not allowed with os_log.
9239 if (FSType == FormatStringType::OSLog &&
9240 CS.getKind() == ConversionSpecifier::nArg) {
9241 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
9242 Loc: getLocationOfByte(x: CS.getStart()),
9243 /*IsStringLocation*/ false,
9244 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9245
9246 return true;
9247 }
9248
9249 // Only scalars are allowed for os_trace.
9250 if (FSType == FormatStringType::OSTrace &&
9251 (CS.getKind() == ConversionSpecifier::PArg ||
9252 CS.getKind() == ConversionSpecifier::sArg ||
9253 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9254 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9255 specifierLen);
9256 }
9257
9258 // Check for use of public/private annotation outside of os_log().
9259 if (FSType != FormatStringType::OSLog) {
9260 if (FS.isPublic().isSet()) {
9261 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9262 << "public",
9263 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
9264 /*IsStringLocation*/ false,
9265 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9266 }
9267 if (FS.isPrivate().isSet()) {
9268 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9269 << "private",
9270 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
9271 /*IsStringLocation*/ false,
9272 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9273 }
9274 }
9275
9276 const llvm::Triple &Triple = Target.getTriple();
9277 if (CS.getKind() == ConversionSpecifier::nArg &&
9278 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9279 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
9280 Loc: getLocationOfByte(x: CS.getStart()),
9281 /*IsStringLocation*/ false,
9282 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9283 }
9284
9285 // Check for invalid use of field width
9286 if (!FS.hasValidFieldWidth()) {
9287 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
9288 startSpecifier, specifierLen);
9289 }
9290
9291 // Check for invalid use of precision
9292 if (!FS.hasValidPrecision()) {
9293 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
9294 startSpecifier, specifierLen);
9295 }
9296
9297 // Precision is mandatory for %P specifier.
9298 if (CS.getKind() == ConversionSpecifier::PArg &&
9299 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9300 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
9301 Loc: getLocationOfByte(x: startSpecifier),
9302 /*IsStringLocation*/ false,
9303 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9304 }
9305
9306 // Check each flag does not conflict with any other component.
9307 if (!FS.hasValidThousandsGroupingPrefix())
9308 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9309 if (!FS.hasValidLeadingZeros())
9310 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
9311 if (!FS.hasValidPlusPrefix())
9312 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
9313 if (!FS.hasValidSpacePrefix())
9314 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
9315 if (!FS.hasValidAlternativeForm())
9316 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
9317 if (!FS.hasValidLeftJustified())
9318 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
9319
9320 // Check that flags are not ignored by another flag
9321 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9322 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
9323 startSpecifier, specifierLen);
9324 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9325 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
9326 startSpecifier, specifierLen);
9327
9328 // Check the length modifier is valid with the given conversion specifier.
9329 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9330 LO: S.getLangOpts()))
9331 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9332 DiagID: diag::warn_format_nonsensical_length);
9333 else if (!FS.hasStandardLengthModifier())
9334 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9335 else if (!FS.hasStandardLengthConversionCombination())
9336 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9337 DiagID: diag::warn_format_non_standard_conversion_spec);
9338
9339 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9340 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9341
9342 // The remaining checks depend on the data arguments.
9343 if (!HasFormatArguments())
9344 return true;
9345
9346 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9347 return false;
9348
9349 const Expr *Arg = getDataArg(i: argIndex);
9350 if (!Arg)
9351 return true;
9352
9353 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
9354}
9355
9356static bool requiresParensToAddCast(const Expr *E) {
9357 // FIXME: We should have a general way to reason about operator
9358 // precedence and whether parens are actually needed here.
9359 // Take care of a few common cases where they aren't.
9360 const Expr *Inside = E->IgnoreImpCasts();
9361 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
9362 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9363
9364 switch (Inside->getStmtClass()) {
9365 case Stmt::ArraySubscriptExprClass:
9366 case Stmt::CallExprClass:
9367 case Stmt::CharacterLiteralClass:
9368 case Stmt::CXXBoolLiteralExprClass:
9369 case Stmt::DeclRefExprClass:
9370 case Stmt::FloatingLiteralClass:
9371 case Stmt::IntegerLiteralClass:
9372 case Stmt::MemberExprClass:
9373 case Stmt::ObjCArrayLiteralClass:
9374 case Stmt::ObjCBoolLiteralExprClass:
9375 case Stmt::ObjCBoxedExprClass:
9376 case Stmt::ObjCDictionaryLiteralClass:
9377 case Stmt::ObjCEncodeExprClass:
9378 case Stmt::ObjCIvarRefExprClass:
9379 case Stmt::ObjCMessageExprClass:
9380 case Stmt::ObjCPropertyRefExprClass:
9381 case Stmt::ObjCStringLiteralClass:
9382 case Stmt::ObjCSubscriptRefExprClass:
9383 case Stmt::ParenExprClass:
9384 case Stmt::StringLiteralClass:
9385 case Stmt::UnaryOperatorClass:
9386 return false;
9387 default:
9388 return true;
9389 }
9390}
9391
9392static std::pair<QualType, StringRef>
9393shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9394 const Expr *E) {
9395 // Use a 'while' to peel off layers of typedefs.
9396 QualType TyTy = IntendedTy;
9397 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9398 StringRef Name = UserTy->getDecl()->getName();
9399 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9400 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
9401 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
9402 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
9403 .Case(S: "SInt32", Value: Context.IntTy)
9404 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
9405 .Default(Value: QualType());
9406
9407 if (!CastTy.isNull())
9408 return std::make_pair(x&: CastTy, y&: Name);
9409
9410 TyTy = UserTy->desugar();
9411 }
9412
9413 // Strip parens if necessary.
9414 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
9415 return shouldNotPrintDirectly(Context, IntendedTy: PE->getSubExpr()->getType(),
9416 E: PE->getSubExpr());
9417
9418 // If this is a conditional expression, then its result type is constructed
9419 // via usual arithmetic conversions and thus there might be no necessary
9420 // typedef sugar there. Recurse to operands to check for NSInteger &
9421 // Co. usage condition.
9422 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
9423 QualType TrueTy, FalseTy;
9424 StringRef TrueName, FalseName;
9425
9426 std::tie(args&: TrueTy, args&: TrueName) = shouldNotPrintDirectly(
9427 Context, IntendedTy: CO->getTrueExpr()->getType(), E: CO->getTrueExpr());
9428 std::tie(args&: FalseTy, args&: FalseName) = shouldNotPrintDirectly(
9429 Context, IntendedTy: CO->getFalseExpr()->getType(), E: CO->getFalseExpr());
9430
9431 if (TrueTy == FalseTy)
9432 return std::make_pair(x&: TrueTy, y&: TrueName);
9433 else if (TrueTy.isNull())
9434 return std::make_pair(x&: FalseTy, y&: FalseName);
9435 else if (FalseTy.isNull())
9436 return std::make_pair(x&: TrueTy, y&: TrueName);
9437 }
9438
9439 return std::make_pair(x: QualType(), y: StringRef());
9440}
9441
9442/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9443/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9444/// type do not count.
9445static bool isArithmeticArgumentPromotion(Sema &S,
9446 const ImplicitCastExpr *ICE) {
9447 QualType From = ICE->getSubExpr()->getType();
9448 QualType To = ICE->getType();
9449 // It's an integer promotion if the destination type is the promoted
9450 // source type.
9451 if (ICE->getCastKind() == CK_IntegralCast &&
9452 S.Context.isPromotableIntegerType(T: From) &&
9453 S.Context.getPromotedIntegerType(PromotableType: From) == To)
9454 return true;
9455 // Look through vector types, since we do default argument promotion for
9456 // those in OpenCL.
9457 if (const auto *VecTy = From->getAs<ExtVectorType>())
9458 From = VecTy->getElementType();
9459 if (const auto *VecTy = To->getAs<ExtVectorType>())
9460 To = VecTy->getElementType();
9461 // It's a floating promotion if the source type is a lower rank.
9462 return ICE->getCastKind() == CK_FloatingCast &&
9463 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9464}
9465
9466static analyze_format_string::ArgType::MatchKind
9467handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9468 DiagnosticsEngine &Diags, SourceLocation Loc) {
9469 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9470 if (Diags.isIgnored(
9471 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9472 Loc) ||
9473 Diags.isIgnored(
9474 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9475 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9476 return analyze_format_string::ArgType::Match;
9477 }
9478 }
9479 return Match;
9480}
9481
9482bool CheckPrintfHandler::checkFormatExpr(
9483 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9484 unsigned SpecifierLen, const Expr *E) {
9485 using namespace analyze_format_string;
9486 using namespace analyze_printf;
9487
9488 // Now type check the data expression that matches the
9489 // format specifier.
9490 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9491 if (!AT.isValid())
9492 return true;
9493
9494 QualType ExprTy = E->getType();
9495 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9496 ExprTy = TET->getUnderlyingExpr()->getType();
9497 }
9498
9499 if (const OverflowBehaviorType *OBT =
9500 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9501 ExprTy = OBT->getUnderlyingType();
9502
9503 // When using the format attribute in C++, you can receive a function or an
9504 // array that will necessarily decay to a pointer when passed to the final
9505 // format consumer. Apply decay before type comparison.
9506 if (ExprTy->canDecayToPointerType())
9507 ExprTy = S.Context.getDecayedType(T: ExprTy);
9508
9509 // Diagnose attempts to print a boolean value as a character. Unlike other
9510 // -Wformat diagnostics, this is fine from a type perspective, but it still
9511 // doesn't make sense.
9512 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9513 E->isKnownToHaveBooleanValue()) {
9514 const CharSourceRange &CSR =
9515 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9516 SmallString<4> FSString;
9517 llvm::raw_svector_ostream os(FSString);
9518 FS.toString(os);
9519 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9520 << FSString,
9521 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9522 return true;
9523 }
9524
9525 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9526 // dumping raw class data (like is-a pointer), not actual data.
9527 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9528 ExprTy->isObjCObjectPointerType()) {
9529 const CharSourceRange &CSR =
9530 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9531 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9532 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9533 return true;
9534 }
9535
9536 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9537 return true;
9538
9539 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9540 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9541 ArgType::MatchKind OrigMatch = Match;
9542
9543 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9544 if (Match == ArgType::Match)
9545 return true;
9546
9547 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9548 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9549
9550 // Look through argument promotions for our error message's reported type.
9551 // This includes the integral and floating promotions, but excludes array
9552 // and function pointer decay (seeing that an argument intended to be a
9553 // string has type 'char [6]' is probably more confusing than 'char *') and
9554 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9555 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9556 if (isArithmeticArgumentPromotion(S, ICE)) {
9557 E = ICE->getSubExpr();
9558 ExprTy = E->getType();
9559
9560 // Check if we didn't match because of an implicit cast from a 'char'
9561 // or 'short' to an 'int'. This is done because printf is a varargs
9562 // function.
9563 if (ICE->getType() == S.Context.IntTy ||
9564 ICE->getType() == S.Context.UnsignedIntTy) {
9565 // All further checking is done on the subexpression
9566 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9567 if (OrigMatch == ArgType::NoMatchSignedness &&
9568 ImplicitMatch != ArgType::NoMatchSignedness)
9569 // If the original match was a signedness match this match on the
9570 // implicit cast type also need to be signedness match otherwise we
9571 // might introduce new unexpected warnings from -Wformat-signedness.
9572 return true;
9573 ImplicitMatch = handleFormatSignedness(
9574 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9575 if (ImplicitMatch == ArgType::Match)
9576 return true;
9577 }
9578 }
9579 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9580 // Special case for 'a', which has type 'int' in C.
9581 // Note, however, that we do /not/ want to treat multibyte constants like
9582 // 'MooV' as characters! This form is deprecated but still exists. In
9583 // addition, don't treat expressions as of type 'char' if one byte length
9584 // modifier is provided.
9585 if (ExprTy == S.Context.IntTy &&
9586 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9587 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9588 ExprTy = S.Context.CharTy;
9589 // To improve check results, we consider a character literal in C
9590 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9591 // more likely a type confusion situation, so we will suggest to
9592 // use '%hhd' instead by discarding the MatchPromotion.
9593 if (Match == ArgType::MatchPromotion)
9594 Match = ArgType::NoMatch;
9595 }
9596 }
9597 if (Match == ArgType::MatchPromotion) {
9598 // WG14 N2562 only clarified promotions in *printf
9599 // For NSLog in ObjC, just preserve -Wformat behavior
9600 if (!S.getLangOpts().ObjC &&
9601 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9602 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9603 return true;
9604 Match = ArgType::NoMatch;
9605 }
9606 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9607 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9608 Match = ImplicitMatch;
9609 assert(Match != ArgType::MatchPromotion);
9610
9611 // Look through unscoped enums to their underlying type.
9612 bool IsEnum = false;
9613 bool IsScopedEnum = false;
9614 QualType IntendedTy = ExprTy;
9615 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9616 IntendedTy = ED->getIntegerType();
9617 if (!ED->isScoped()) {
9618 ExprTy = IntendedTy;
9619 // This controls whether we're talking about the underlying type or not,
9620 // which we only want to do when it's an unscoped enum.
9621 IsEnum = true;
9622 } else {
9623 IsScopedEnum = true;
9624 }
9625 }
9626
9627 // %C in an Objective-C context prints a unichar, not a wchar_t.
9628 // If the argument is an integer of some kind, believe the %C and suggest
9629 // a cast instead of changing the conversion specifier.
9630 if (isObjCContext() &&
9631 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9632 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9633 !ExprTy->isCharType()) {
9634 // 'unichar' is defined as a typedef of unsigned short, but we should
9635 // prefer using the typedef if it is visible.
9636 IntendedTy = S.Context.UnsignedShortTy;
9637
9638 // While we are here, check if the value is an IntegerLiteral that happens
9639 // to be within the valid range.
9640 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9641 const llvm::APInt &V = IL->getValue();
9642 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9643 return true;
9644 }
9645
9646 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9647 Sema::LookupOrdinaryName);
9648 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9649 NamedDecl *ND = Result.getFoundDecl();
9650 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9651 if (TD->getUnderlyingType() == IntendedTy)
9652 IntendedTy =
9653 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9654 /*Qualifier=*/std::nullopt, Decl: TD);
9655 }
9656 }
9657 }
9658
9659 // Special-case some of Darwin's platform-independence types by suggesting
9660 // casts to primitive types that are known to be large enough.
9661 bool ShouldNotPrintDirectly = false;
9662 StringRef CastTyName;
9663 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9664 QualType CastTy;
9665 std::tie(args&: CastTy, args&: CastTyName) =
9666 shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9667 if (!CastTy.isNull()) {
9668 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9669 // (long in ASTContext). Only complain to pedants or when they're the
9670 // underlying type of a scoped enum (which always needs a cast).
9671 if (!IsScopedEnum &&
9672 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9673 (AT.isSizeT() || AT.isPtrdiffT()) &&
9674 AT.matchesType(C&: S.Context, argTy: CastTy))
9675 Match = ArgType::NoMatchPedantic;
9676 IntendedTy = CastTy;
9677 ShouldNotPrintDirectly = true;
9678 }
9679 }
9680
9681 // We may be able to offer a FixItHint if it is a supported type.
9682 PrintfSpecifier fixedFS = FS;
9683 bool Success =
9684 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9685
9686 if (Success) {
9687 // Get the fix string from the fixed format specifier
9688 SmallString<16> buf;
9689 llvm::raw_svector_ostream os(buf);
9690 fixedFS.toString(os);
9691
9692 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9693
9694 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9695 unsigned Diag;
9696 switch (Match) {
9697 case ArgType::Match:
9698 case ArgType::MatchPromotion:
9699 case ArgType::NoMatchPromotionTypeConfusion:
9700 llvm_unreachable("expected non-matching");
9701 case ArgType::NoMatchSignedness:
9702 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9703 break;
9704 case ArgType::NoMatchPedantic:
9705 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9706 break;
9707 case ArgType::NoMatchTypeConfusion:
9708 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9709 break;
9710 case ArgType::NoMatch:
9711 Diag = diag::warn_format_conversion_argument_type_mismatch;
9712 break;
9713 }
9714
9715 // In this case, the specifier is wrong and should be changed to match
9716 // the argument.
9717 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9718 << AT.getRepresentativeTypeName(C&: S.Context)
9719 << IntendedTy << IsEnum << E->getSourceRange(),
9720 Loc: E->getBeginLoc(),
9721 /*IsStringLocation*/ false, StringRange: SpecRange,
9722 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9723 } else {
9724 // The canonical type for formatting this value is different from the
9725 // actual type of the expression. (This occurs, for example, with Darwin's
9726 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9727 // should be printed as 'long' for 64-bit compatibility.)
9728 // Rather than emitting a normal format/argument mismatch, we want to
9729 // add a cast to the recommended type (and correct the format string
9730 // if necessary). We should also do so for scoped enumerations.
9731 SmallString<16> CastBuf;
9732 llvm::raw_svector_ostream CastFix(CastBuf);
9733 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9734 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9735 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9736
9737 SmallVector<FixItHint, 4> Hints;
9738 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9739 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9740 Loc: E->getExprLoc());
9741 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9742 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9743
9744 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9745 // If there's already a cast present, just replace it.
9746 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9747 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9748
9749 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9750 // If the expression has high enough precedence,
9751 // just write the C-style cast.
9752 Hints.push_back(
9753 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9754 } else {
9755 // Otherwise, add parens around the expression as well as the cast.
9756 CastFix << "(";
9757 Hints.push_back(
9758 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9759
9760 // We don't use getLocForEndOfToken because it returns invalid source
9761 // locations for macro expansions (by design).
9762 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9763 SourceLocation After = EndLoc.getLocWithOffset(
9764 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9765 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9766 }
9767
9768 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9769 // The expression has a type that should not be printed directly.
9770 // We extract the name from the typedef because we don't want to show
9771 // the underlying type in the diagnostic.
9772 StringRef Name;
9773 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9774 Name = TypedefTy->getDecl()->getName();
9775 else
9776 Name = CastTyName;
9777 unsigned Diag = Match == ArgType::NoMatchPedantic
9778 ? diag::warn_format_argument_needs_cast_pedantic
9779 : diag::warn_format_argument_needs_cast;
9780 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9781 << E->getSourceRange(),
9782 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9783 StringRange: SpecRange, FixIt: Hints);
9784 } else {
9785 // In this case, the expression could be printed using a different
9786 // specifier, but we've decided that the specifier is probably correct
9787 // and we should cast instead. Just use the normal warning message.
9788
9789 unsigned Diag =
9790 IsScopedEnum
9791 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9792 : diag::warn_format_conversion_argument_type_mismatch;
9793
9794 EmitFormatDiagnostic(
9795 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9796 << IsEnum << E->getSourceRange(),
9797 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9798 }
9799 }
9800 } else {
9801 const CharSourceRange &CSR =
9802 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9803 // Since the warning for passing non-POD types to variadic functions
9804 // was deferred until now, we emit a warning for non-POD
9805 // arguments here.
9806 bool EmitTypeMismatch = false;
9807 // Record and complex type arguments cannot be code generated for os_log
9808 // and would crash CodeGen, so they are rejected with a hard error emitted
9809 // after the switch below.
9810 bool EmitOSLogError = false;
9811 switch (S.isValidVarArgType(Ty: ExprTy)) {
9812 case VarArgKind::Valid:
9813 case VarArgKind::ValidInCXX11: {
9814 unsigned Diag;
9815 switch (Match) {
9816 case ArgType::Match:
9817 case ArgType::MatchPromotion:
9818 case ArgType::NoMatchPromotionTypeConfusion:
9819 llvm_unreachable("expected non-matching");
9820 case ArgType::NoMatchSignedness:
9821 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9822 break;
9823 case ArgType::NoMatchPedantic:
9824 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9825 break;
9826 case ArgType::NoMatchTypeConfusion:
9827 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9828 break;
9829 case ArgType::NoMatch:
9830 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy);
9831 Diag = diag::warn_format_conversion_argument_type_mismatch;
9832 break;
9833 }
9834
9835 if (!EmitOSLogError)
9836 EmitFormatDiagnostic(
9837 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9838 << IsEnum << CSR << E->getSourceRange(),
9839 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9840 break;
9841 }
9842 case VarArgKind::Undefined:
9843 case VarArgKind::MSVCUndefined:
9844 if (CallType == VariadicCallType::DoesNotApply) {
9845 EmitTypeMismatch = true;
9846 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)) {
9847 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9848 // does not stop compilation.
9849 EmitOSLogError = true;
9850 } else {
9851 EmitFormatDiagnostic(
9852 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9853 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9854 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9855 << E->getSourceRange(),
9856 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9857 checkForCStrMembers(AT, E);
9858 }
9859 break;
9860
9861 case VarArgKind::Invalid:
9862 if (CallType == VariadicCallType::DoesNotApply)
9863 EmitTypeMismatch = true;
9864 else if (ExprTy->isObjCObjectType())
9865 EmitFormatDiagnostic(
9866 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9867 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9868 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9869 << E->getSourceRange(),
9870 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9871 else
9872 // FIXME: If this is an initializer list, suggest removing the braces
9873 // or inserting a cast to the target type.
9874 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9875 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9876 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9877 break;
9878 }
9879
9880 if (EmitOSLogError)
9881 EmitFormatDiagnostic(
9882 PDiag: S.PDiag(DiagID: diag::err_format_conversion_argument_type_mismatch)
9883 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << IsEnum
9884 << CSR << E->getSourceRange(),
9885 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9886
9887 if (EmitTypeMismatch) {
9888 // The function is not variadic, so we do not generate warnings about
9889 // being allowed to pass that object as a variadic argument. Instead,
9890 // since there are inherently no printf specifiers for types which cannot
9891 // be passed as variadic arguments, emit a plain old specifier mismatch
9892 // argument.
9893 EmitFormatDiagnostic(
9894 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9895 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9896 << E->getSourceRange(),
9897 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9898 }
9899
9900 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9901 "format string specifier index out of range");
9902 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9903 }
9904
9905 return true;
9906}
9907
9908//===--- CHECK: Scanf format string checking ------------------------------===//
9909
9910namespace {
9911
9912class CheckScanfHandler : public CheckFormatHandler {
9913public:
9914 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9915 const Expr *origFormatExpr, FormatStringType type,
9916 unsigned firstDataArg, unsigned numDataArgs,
9917 const char *beg, Sema::FormatArgumentPassingKind APK,
9918 ArrayRef<const Expr *> Args, unsigned formatIdx,
9919 bool inFunctionCall, VariadicCallType CallType,
9920 llvm::SmallBitVector &CheckedVarArgs,
9921 UncoveredArgHandler &UncoveredArg)
9922 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9923 numDataArgs, beg, APK, Args, formatIdx,
9924 inFunctionCall, CallType, CheckedVarArgs,
9925 UncoveredArg) {}
9926
9927 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9928 const char *startSpecifier,
9929 unsigned specifierLen) override;
9930
9931 bool
9932 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9933 const char *startSpecifier,
9934 unsigned specifierLen) override;
9935
9936 void HandleIncompleteScanList(const char *start, const char *end) override;
9937};
9938
9939} // namespace
9940
9941void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9942 const char *end) {
9943 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9944 Loc: getLocationOfByte(x: end), /*IsStringLocation*/ true,
9945 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9946}
9947
9948bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9949 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9950 unsigned specifierLen) {
9951 const analyze_scanf::ScanfConversionSpecifier &CS =
9952 FS.getConversionSpecifier();
9953
9954 return HandleInvalidConversionSpecifier(
9955 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
9956 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
9957}
9958
9959bool CheckScanfHandler::HandleScanfSpecifier(
9960 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9961 unsigned specifierLen) {
9962 using namespace analyze_scanf;
9963 using namespace analyze_format_string;
9964
9965 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9966
9967 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9968 // be used to decide if we are using positional arguments consistently.
9969 if (FS.consumesDataArgument()) {
9970 if (atFirstArg) {
9971 atFirstArg = false;
9972 usesPositionalArgs = FS.usesPositionalArg();
9973 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9974 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9975 startSpec: startSpecifier, specifierLen);
9976 return false;
9977 }
9978 }
9979
9980 // Check if the field with is non-zero.
9981 const OptionalAmount &Amt = FS.getFieldWidth();
9982 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9983 if (Amt.getConstantAmount() == 0) {
9984 const CharSourceRange &R =
9985 getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength());
9986 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9987 Loc: getLocationOfByte(x: Amt.getStart()),
9988 /*IsStringLocation*/ true, StringRange: R,
9989 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9990 }
9991 }
9992
9993 if (!FS.consumesDataArgument()) {
9994 // FIXME: Technically specifying a precision or field width here
9995 // makes no sense. Worth issuing a warning at some point.
9996 return true;
9997 }
9998
9999 // Consume the argument.
10000 unsigned argIndex = FS.getArgIndex();
10001 if (argIndex < NumDataArgs) {
10002 // The check to see if the argIndex is valid will come later.
10003 // We set the bit here because we may exit early from this
10004 // function if we encounter some other error.
10005 CoveredArgs.set(argIndex);
10006 }
10007
10008 // Check the length modifier is valid with the given conversion specifier.
10009 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
10010 LO: S.getLangOpts()))
10011 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10012 DiagID: diag::warn_format_nonsensical_length);
10013 else if (!FS.hasStandardLengthModifier())
10014 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10015 else if (!FS.hasStandardLengthConversionCombination())
10016 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10017 DiagID: diag::warn_format_non_standard_conversion_spec);
10018
10019 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
10020 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10021
10022 // The remaining checks depend on the data arguments.
10023 if (!HasFormatArguments())
10024 return true;
10025
10026 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10027 return false;
10028
10029 // Check that the argument type matches the format specifier.
10030 const Expr *Ex = getDataArg(i: argIndex);
10031 if (!Ex)
10032 return true;
10033
10034 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
10035
10036 if (!AT.isValid()) {
10037 return true;
10038 }
10039
10040 if (CheckUnsupportedType(AT, E: Ex, StartSpecifier: startSpecifier, SpecifierLen: specifierLen))
10041 return true;
10042
10043 analyze_format_string::ArgType::MatchKind Match =
10044 AT.matchesType(C&: S.Context, argTy: Ex->getType());
10045 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
10046 if (Match == analyze_format_string::ArgType::Match)
10047 return true;
10048 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10049 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
10050
10051 ScanfSpecifier fixedFS = FS;
10052 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
10053 LangOpt: S.getLangOpts(), Ctx&: S.Context);
10054
10055 unsigned Diag =
10056 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10057 : Signedness
10058 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10059 : diag::warn_format_conversion_argument_type_mismatch;
10060
10061 if (Success) {
10062 // Get the fix string from the fixed format specifier.
10063 SmallString<128> buf;
10064 llvm::raw_svector_ostream os(buf);
10065 fixedFS.toString(os);
10066
10067 EmitFormatDiagnostic(
10068 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
10069 << Ex->getType() << false << Ex->getSourceRange(),
10070 Loc: Ex->getBeginLoc(),
10071 /*IsStringLocation*/ false,
10072 StringRange: getSpecifierRange(startSpecifier, specifierLen),
10073 FixIt: FixItHint::CreateReplacement(
10074 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
10075 } else {
10076 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
10077 << AT.getRepresentativeTypeName(C&: S.Context)
10078 << Ex->getType() << false << Ex->getSourceRange(),
10079 Loc: Ex->getBeginLoc(),
10080 /*IsStringLocation*/ false,
10081 StringRange: getSpecifierRange(startSpecifier, specifierLen));
10082 }
10083
10084 return true;
10085}
10086
10087static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10088 ArrayRef<EquatableFormatArgument> RefArgs,
10089 const StringLiteral *Fmt,
10090 ArrayRef<EquatableFormatArgument> FmtArgs,
10091 const Expr *FmtExpr, bool InFunctionCall) {
10092 bool HadError = false;
10093 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10094 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10095 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10096 // In positional-style format strings, the same specifier can appear
10097 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10098 // are sorted by getPosition(), and we process each range of equal
10099 // getPosition() values as one group.
10100 // RefArgs are taken from a string literal that was given to
10101 // attribute(format_matches), and if we got this far, we have already
10102 // verified that if it has positional specifiers that appear in multiple
10103 // locations, then they are all mutually compatible. What's left for us to
10104 // do is verify that all specifiers with the same position in FmtArgs are
10105 // compatible with the RefArgs specifiers. We check each specifier from
10106 // FmtArgs against the first member of the RefArgs group.
10107 for (; FmtIter < FmtEnd; ++FmtIter) {
10108 // Clang does not diagnose missing format specifiers in positional-style
10109 // strings (TODO: which it probably should do, as it is UB to skip over a
10110 // format argument). Skip specifiers if needed.
10111 if (FmtIter->getPosition() < RefIter->getPosition())
10112 continue;
10113
10114 // Delimits a new getPosition() value.
10115 if (FmtIter->getPosition() > RefIter->getPosition())
10116 break;
10117
10118 HadError |=
10119 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
10120 }
10121
10122 // Jump RefIter to the start of the next group.
10123 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
10124 return Arg.getPosition() != RefIter->getPosition();
10125 });
10126 }
10127
10128 if (FmtIter < FmtEnd) {
10129 CheckFormatHandler::EmitFormatDiagnostic(
10130 S, InFunctionCall, ArgumentExpr: FmtExpr,
10131 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
10132 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
10133 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
10134 } else if (RefIter < RefEnd) {
10135 CheckFormatHandler::EmitFormatDiagnostic(
10136 S, InFunctionCall, ArgumentExpr: FmtExpr,
10137 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
10138 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
10139 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
10140 << 1 << RefIter->getSourceRange();
10141 }
10142 return !HadError;
10143}
10144
10145static void CheckFormatString(
10146 Sema &S, const FormatStringLiteral *FExpr,
10147 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10148 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10149 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10150 bool inFunctionCall, VariadicCallType CallType,
10151 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10152 bool IgnoreStringsWithoutSpecifiers) {
10153 // CHECK: is the format string a wide literal?
10154 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10155 CheckFormatHandler::EmitFormatDiagnostic(
10156 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10157 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
10158 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10159 return;
10160 }
10161
10162 // Str - The format string. NOTE: this is NOT null-terminated!
10163 StringRef StrRef = FExpr->getString();
10164 const char *Str = StrRef.data();
10165 // Account for cases where the string literal is truncated in a declaration.
10166 const ConstantArrayType *T =
10167 S.Context.getAsConstantArrayType(T: FExpr->getType());
10168 assert(T && "String literal not of constant array type!");
10169 size_t TypeSize = T->getZExtSize();
10170 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10171 const unsigned numDataArgs = Args.size() - firstDataArg;
10172
10173 if (IgnoreStringsWithoutSpecifiers &&
10174 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10175 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10176 return;
10177
10178 // Emit a warning if the string literal is truncated and does not contain an
10179 // embedded null character.
10180 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
10181 CheckFormatHandler::EmitFormatDiagnostic(
10182 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10183 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
10184 Loc: FExpr->getBeginLoc(),
10185 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
10186 return;
10187 }
10188
10189 // CHECK: empty format string?
10190 if (StrLen == 0 && numDataArgs > 0) {
10191 CheckFormatHandler::EmitFormatDiagnostic(
10192 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10193 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
10194 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10195 return;
10196 }
10197
10198 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
10199 Type == FormatStringType::Kprintf ||
10200 Type == FormatStringType::FreeBSDKPrintf ||
10201 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
10202 bool IsObjC =
10203 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10204 if (ReferenceFormatString == nullptr) {
10205 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10206 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10207 inFunctionCall, CallType, CheckedVarArgs,
10208 UncoveredArg);
10209
10210 if (!analyze_format_string::ParsePrintfString(
10211 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
10212 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
10213 Type == FormatStringType::FreeBSDKPrintf))
10214 H.DoneProcessing();
10215 } else {
10216 S.CheckFormatStringsCompatible(
10217 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
10218 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
10219 }
10220 } else if (Type == FormatStringType::Scanf) {
10221 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10222 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10223 CallType, CheckedVarArgs, UncoveredArg);
10224
10225 if (!analyze_format_string::ParseScanfString(
10226 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10227 H.DoneProcessing();
10228 } // TODO: handle other formats
10229}
10230
10231bool Sema::CheckFormatStringsCompatible(
10232 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10233 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10234 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10235 Type != FormatStringType::Kprintf &&
10236 Type != FormatStringType::FreeBSDKPrintf &&
10237 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10238 return true;
10239
10240 bool IsObjC =
10241 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10242 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
10243 FormatStringLiteral RefLit = AuthoritativeFormatString;
10244 FormatStringLiteral TestLit = TestedFormatString;
10245 const Expr *Arg;
10246 bool DiagAtStringLiteral;
10247 if (FunctionCallArg) {
10248 Arg = FunctionCallArg;
10249 DiagAtStringLiteral = false;
10250 } else {
10251 Arg = TestedFormatString;
10252 DiagAtStringLiteral = true;
10253 }
10254 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
10255 FmtExpr: AuthoritativeFormatString, Type,
10256 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
10257 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
10258 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
10259 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
10260 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
10261 InFunctionCall: DiagAtStringLiteral);
10262 }
10263 return false;
10264}
10265
10266bool Sema::ValidateFormatString(FormatStringType Type,
10267 const StringLiteral *Str) {
10268 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10269 Type != FormatStringType::Kprintf &&
10270 Type != FormatStringType::FreeBSDKPrintf &&
10271 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10272 return true;
10273
10274 FormatStringLiteral RefLit = Str;
10275 llvm::SmallVector<EquatableFormatArgument, 9> Args;
10276 bool IsObjC =
10277 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10278 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
10279 InFunctionCall: true, Args))
10280 return false;
10281
10282 // Group arguments by getPosition() value, and check that each member of the
10283 // group is compatible with the first member. This verifies that when
10284 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10285 // are mutually compatible. As an optimization, don't test the first member
10286 // against itself.
10287 bool HadError = false;
10288 auto Iter = Args.begin();
10289 auto End = Args.end();
10290 while (Iter != End) {
10291 const auto &FirstInGroup = *Iter;
10292 for (++Iter;
10293 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10294 ++Iter) {
10295 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
10296 }
10297 }
10298 return !HadError;
10299}
10300
10301bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10302 // Str - The format string. NOTE: this is NOT null-terminated!
10303 StringRef StrRef = FExpr->getString();
10304 const char *Str = StrRef.data();
10305 // Account for cases where the string literal is truncated in a declaration.
10306 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
10307 assert(T && "String literal not of constant array type!");
10308 size_t TypeSize = T->getZExtSize();
10309 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10310 return analyze_format_string::ParseFormatStringHasSArg(
10311 beg: Str, end: Str + StrLen, LO: getLangOpts(), Target: Context.getTargetInfo());
10312}
10313
10314//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10315
10316// Returns the related absolute value function that is larger, of 0 if one
10317// does not exist.
10318static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10319 switch (AbsFunction) {
10320 default:
10321 return 0;
10322
10323 case Builtin::BI__builtin_abs:
10324 return Builtin::BI__builtin_labs;
10325 case Builtin::BI__builtin_labs:
10326 return Builtin::BI__builtin_llabs;
10327 case Builtin::BI__builtin_llabs:
10328 return 0;
10329
10330 case Builtin::BI__builtin_fabsf:
10331 return Builtin::BI__builtin_fabs;
10332 case Builtin::BI__builtin_fabs:
10333 return Builtin::BI__builtin_fabsl;
10334 case Builtin::BI__builtin_fabsl:
10335 return 0;
10336
10337 case Builtin::BI__builtin_cabsf:
10338 return Builtin::BI__builtin_cabs;
10339 case Builtin::BI__builtin_cabs:
10340 return Builtin::BI__builtin_cabsl;
10341 case Builtin::BI__builtin_cabsl:
10342 return 0;
10343
10344 case Builtin::BIabs:
10345 return Builtin::BIlabs;
10346 case Builtin::BIlabs:
10347 return Builtin::BIllabs;
10348 case Builtin::BIllabs:
10349 return 0;
10350
10351 case Builtin::BIfabsf:
10352 return Builtin::BIfabs;
10353 case Builtin::BIfabs:
10354 return Builtin::BIfabsl;
10355 case Builtin::BIfabsl:
10356 return 0;
10357
10358 case Builtin::BIcabsf:
10359 return Builtin::BIcabs;
10360 case Builtin::BIcabs:
10361 return Builtin::BIcabsl;
10362 case Builtin::BIcabsl:
10363 return 0;
10364 }
10365}
10366
10367// Returns the argument type of the absolute value function.
10368static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10369 unsigned AbsType) {
10370 if (AbsType == 0)
10371 return QualType();
10372
10373 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10374 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
10375 if (Error != ASTContext::GE_None)
10376 return QualType();
10377
10378 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10379 if (!FT)
10380 return QualType();
10381
10382 if (FT->getNumParams() != 1)
10383 return QualType();
10384
10385 return FT->getParamType(i: 0);
10386}
10387
10388// Returns the best absolute value function, or zero, based on type and
10389// current absolute value function.
10390static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10391 unsigned AbsFunctionKind) {
10392 unsigned BestKind = 0;
10393 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
10394 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10395 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
10396 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
10397 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
10398 if (BestKind == 0)
10399 BestKind = Kind;
10400 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
10401 BestKind = Kind;
10402 break;
10403 }
10404 }
10405 }
10406 return BestKind;
10407}
10408
10409enum AbsoluteValueKind {
10410 AVK_Integer,
10411 AVK_Floating,
10412 AVK_Complex
10413};
10414
10415static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10416 if (T->isIntegralOrEnumerationType())
10417 return AVK_Integer;
10418 if (T->isRealFloatingType())
10419 return AVK_Floating;
10420 if (T->isAnyComplexType())
10421 return AVK_Complex;
10422
10423 llvm_unreachable("Type not integer, floating, or complex");
10424}
10425
10426// Changes the absolute value function to a different type. Preserves whether
10427// the function is a builtin.
10428static unsigned changeAbsFunction(unsigned AbsKind,
10429 AbsoluteValueKind ValueKind) {
10430 switch (ValueKind) {
10431 case AVK_Integer:
10432 switch (AbsKind) {
10433 default:
10434 return 0;
10435 case Builtin::BI__builtin_fabsf:
10436 case Builtin::BI__builtin_fabs:
10437 case Builtin::BI__builtin_fabsl:
10438 case Builtin::BI__builtin_cabsf:
10439 case Builtin::BI__builtin_cabs:
10440 case Builtin::BI__builtin_cabsl:
10441 return Builtin::BI__builtin_abs;
10442 case Builtin::BIfabsf:
10443 case Builtin::BIfabs:
10444 case Builtin::BIfabsl:
10445 case Builtin::BIcabsf:
10446 case Builtin::BIcabs:
10447 case Builtin::BIcabsl:
10448 return Builtin::BIabs;
10449 }
10450 case AVK_Floating:
10451 switch (AbsKind) {
10452 default:
10453 return 0;
10454 case Builtin::BI__builtin_abs:
10455 case Builtin::BI__builtin_labs:
10456 case Builtin::BI__builtin_llabs:
10457 case Builtin::BI__builtin_cabsf:
10458 case Builtin::BI__builtin_cabs:
10459 case Builtin::BI__builtin_cabsl:
10460 return Builtin::BI__builtin_fabsf;
10461 case Builtin::BIabs:
10462 case Builtin::BIlabs:
10463 case Builtin::BIllabs:
10464 case Builtin::BIcabsf:
10465 case Builtin::BIcabs:
10466 case Builtin::BIcabsl:
10467 return Builtin::BIfabsf;
10468 }
10469 case AVK_Complex:
10470 switch (AbsKind) {
10471 default:
10472 return 0;
10473 case Builtin::BI__builtin_abs:
10474 case Builtin::BI__builtin_labs:
10475 case Builtin::BI__builtin_llabs:
10476 case Builtin::BI__builtin_fabsf:
10477 case Builtin::BI__builtin_fabs:
10478 case Builtin::BI__builtin_fabsl:
10479 return Builtin::BI__builtin_cabsf;
10480 case Builtin::BIabs:
10481 case Builtin::BIlabs:
10482 case Builtin::BIllabs:
10483 case Builtin::BIfabsf:
10484 case Builtin::BIfabs:
10485 case Builtin::BIfabsl:
10486 return Builtin::BIcabsf;
10487 }
10488 }
10489 llvm_unreachable("Unable to convert function");
10490}
10491
10492static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10493 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10494 if (!FnInfo)
10495 return 0;
10496
10497 switch (FDecl->getBuiltinID()) {
10498 default:
10499 return 0;
10500 case Builtin::BI__builtin_abs:
10501 case Builtin::BI__builtin_fabs:
10502 case Builtin::BI__builtin_fabsf:
10503 case Builtin::BI__builtin_fabsl:
10504 case Builtin::BI__builtin_labs:
10505 case Builtin::BI__builtin_llabs:
10506 case Builtin::BI__builtin_cabs:
10507 case Builtin::BI__builtin_cabsf:
10508 case Builtin::BI__builtin_cabsl:
10509 case Builtin::BIabs:
10510 case Builtin::BIlabs:
10511 case Builtin::BIllabs:
10512 case Builtin::BIfabs:
10513 case Builtin::BIfabsf:
10514 case Builtin::BIfabsl:
10515 case Builtin::BIcabs:
10516 case Builtin::BIcabsf:
10517 case Builtin::BIcabsl:
10518 return FDecl->getBuiltinID();
10519 }
10520 llvm_unreachable("Unknown Builtin type");
10521}
10522
10523// If the replacement is valid, emit a note with replacement function.
10524// Additionally, suggest including the proper header if not already included.
10525static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10526 unsigned AbsKind, QualType ArgType) {
10527 bool EmitHeaderHint = true;
10528 const char *HeaderName = nullptr;
10529 std::string FunctionName;
10530 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10531 FunctionName = "std::abs";
10532 if (ArgType->isIntegralOrEnumerationType()) {
10533 HeaderName = "cstdlib";
10534 } else if (ArgType->isRealFloatingType()) {
10535 HeaderName = "cmath";
10536 } else {
10537 llvm_unreachable("Invalid Type");
10538 }
10539
10540 // Lookup all std::abs
10541 if (NamespaceDecl *Std = S.getStdNamespace()) {
10542 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10543 R.suppressDiagnostics();
10544 S.LookupQualifiedName(R, LookupCtx: Std);
10545
10546 for (const auto *I : R) {
10547 const FunctionDecl *FDecl = nullptr;
10548 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10549 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10550 } else {
10551 FDecl = dyn_cast<FunctionDecl>(Val: I);
10552 }
10553 if (!FDecl)
10554 continue;
10555
10556 // Found std::abs(), check that they are the right ones.
10557 if (FDecl->getNumParams() != 1)
10558 continue;
10559
10560 // Check that the parameter type can handle the argument.
10561 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10562 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10563 S.Context.getTypeSize(T: ArgType) <=
10564 S.Context.getTypeSize(T: ParamType)) {
10565 // Found a function, don't need the header hint.
10566 EmitHeaderHint = false;
10567 break;
10568 }
10569 }
10570 }
10571 } else {
10572 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10573 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10574
10575 if (HeaderName) {
10576 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10577 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10578 R.suppressDiagnostics();
10579 S.LookupName(R, S: S.getCurScope());
10580
10581 if (R.isSingleResult()) {
10582 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10583 if (FD && FD->getBuiltinID() == AbsKind) {
10584 EmitHeaderHint = false;
10585 } else {
10586 return;
10587 }
10588 } else if (!R.empty()) {
10589 return;
10590 }
10591 }
10592 }
10593
10594 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10595 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10596
10597 if (!HeaderName)
10598 return;
10599
10600 if (!EmitHeaderHint)
10601 return;
10602
10603 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10604 << FunctionName;
10605}
10606
10607template <std::size_t StrLen>
10608static bool IsStdFunction(const FunctionDecl *FDecl,
10609 const char (&Str)[StrLen]) {
10610 if (!FDecl)
10611 return false;
10612 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10613 return false;
10614 if (!FDecl->isInStdNamespace())
10615 return false;
10616
10617 return true;
10618}
10619
10620enum class MathCheck { NaN, Inf };
10621static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10622 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10623 return llvm::is_contained(Set: names, Element: calleeName);
10624 };
10625
10626 switch (Check) {
10627 case MathCheck::NaN:
10628 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10629 "__builtin_nanf16", "__builtin_nanf128"});
10630 case MathCheck::Inf:
10631 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10632 "__builtin_inff16", "__builtin_inff128"});
10633 }
10634 llvm_unreachable("unknown MathCheck");
10635}
10636
10637static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10638 if (FDecl->getName() != "infinity")
10639 return false;
10640
10641 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10642 const CXXRecordDecl *RDecl = MDecl->getParent();
10643 if (RDecl->getName() != "numeric_limits")
10644 return false;
10645
10646 if (const NamespaceDecl *NSDecl =
10647 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10648 return NSDecl->isStdNamespace();
10649 }
10650
10651 return false;
10652}
10653
10654void Sema::CheckInfNaNFunction(const CallExpr *Call,
10655 const FunctionDecl *FDecl) {
10656 if (!FDecl->getIdentifier())
10657 return;
10658
10659 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10660 if (FPO.getNoHonorNaNs() &&
10661 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10662 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10663 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10664 << 1 << 0 << Call->getSourceRange();
10665 return;
10666 }
10667
10668 if (FPO.getNoHonorInfs() &&
10669 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10670 IsInfinityFunction(FDecl) ||
10671 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10672 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10673 << 0 << 0 << Call->getSourceRange();
10674 }
10675}
10676
10677void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10678 const FunctionDecl *FDecl) {
10679 if (Call->getNumArgs() != 1)
10680 return;
10681
10682 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10683 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10684 if (AbsKind == 0 && !IsStdAbs)
10685 return;
10686
10687 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10688 QualType ParamType = Call->getArg(Arg: 0)->getType();
10689
10690 // Unsigned types cannot be negative. Suggest removing the absolute value
10691 // function call.
10692 if (ArgType->isUnsignedIntegerType()) {
10693 std::string FunctionName =
10694 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10695 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10696 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10697 << FunctionName
10698 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10699 return;
10700 }
10701
10702 // Taking the absolute value of a pointer is very suspicious, they probably
10703 // wanted to index into an array, dereference a pointer, call a function, etc.
10704 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10705 unsigned DiagType = 0;
10706 if (ArgType->isFunctionType())
10707 DiagType = 1;
10708 else if (ArgType->isArrayType())
10709 DiagType = 2;
10710
10711 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10712 return;
10713 }
10714
10715 // std::abs has overloads which prevent most of the absolute value problems
10716 // from occurring.
10717 if (IsStdAbs)
10718 return;
10719
10720 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10721 // types.
10722 if (!ArgType->isIntegralOrEnumerationType() &&
10723 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10724 return;
10725
10726 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10727 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10728
10729 // The argument and parameter are the same kind. Check if they are the right
10730 // size.
10731 if (ArgValueKind == ParamValueKind) {
10732 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10733 return;
10734
10735 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10736 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10737 << FDecl << ArgType << ParamType;
10738
10739 if (NewAbsKind == 0)
10740 return;
10741
10742 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10743 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10744 return;
10745 }
10746
10747 // ArgValueKind != ParamValueKind
10748 // The wrong type of absolute value function was used. Attempt to find the
10749 // proper one.
10750 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10751 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10752 if (NewAbsKind == 0)
10753 return;
10754
10755 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10756 << FDecl << ParamValueKind << ArgValueKind;
10757
10758 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10759 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10760}
10761
10762//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10763void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10764 const FunctionDecl *FDecl) {
10765 if (!Call || !FDecl) return;
10766
10767 // Ignore template specializations and macros.
10768 if (inTemplateInstantiation()) return;
10769 if (Call->getExprLoc().isMacroID()) return;
10770
10771 // Only care about the one template argument, two function parameter std::max
10772 if (Call->getNumArgs() != 2) return;
10773 if (!IsStdFunction(FDecl, Str: "max")) return;
10774 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10775 if (!ArgList) return;
10776 if (ArgList->size() != 1) return;
10777
10778 // Check that template type argument is unsigned integer.
10779 const auto& TA = ArgList->get(Idx: 0);
10780 if (TA.getKind() != TemplateArgument::Type) return;
10781 QualType ArgType = TA.getAsType();
10782 if (!ArgType->isUnsignedIntegerType()) return;
10783
10784 // See if either argument is a literal zero.
10785 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10786 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10787 if (!MTE) return false;
10788 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10789 if (!Num) return false;
10790 if (Num->getValue() != 0) return false;
10791 return true;
10792 };
10793
10794 const Expr *FirstArg = Call->getArg(Arg: 0);
10795 const Expr *SecondArg = Call->getArg(Arg: 1);
10796 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10797 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10798
10799 // Only warn when exactly one argument is zero.
10800 if (IsFirstArgZero == IsSecondArgZero) return;
10801
10802 SourceRange FirstRange = FirstArg->getSourceRange();
10803 SourceRange SecondRange = SecondArg->getSourceRange();
10804
10805 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10806
10807 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10808 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10809
10810 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10811 SourceRange RemovalRange;
10812 if (IsFirstArgZero) {
10813 RemovalRange = SourceRange(FirstRange.getBegin(),
10814 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10815 } else {
10816 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10817 SecondRange.getEnd());
10818 }
10819
10820 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10821 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10822 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10823}
10824
10825//===--- CHECK: Standard memory functions ---------------------------------===//
10826
10827/// Takes the expression passed to the size_t parameter of functions
10828/// such as memcmp, strncat, etc and warns if it's a comparison.
10829///
10830/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10831static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10832 const IdentifierInfo *FnName,
10833 SourceLocation FnLoc,
10834 SourceLocation RParenLoc) {
10835 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10836 if (!Size)
10837 return false;
10838
10839 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10840 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10841 return false;
10842
10843 SourceRange SizeRange = Size->getSourceRange();
10844 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10845 << SizeRange << FnName;
10846 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10847 << FnName
10848 << FixItHint::CreateInsertion(
10849 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10850 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10851 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10852 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10853 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10854 Code: ")");
10855
10856 return true;
10857}
10858
10859/// Determine whether the given type is or contains a dynamic class type
10860/// (e.g., whether it has a vtable).
10861static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10862 bool &IsContained) {
10863 // Look through array types while ignoring qualifiers.
10864 const Type *Ty = T->getBaseElementTypeUnsafe();
10865 IsContained = false;
10866
10867 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10868 RD = RD ? RD->getDefinition() : nullptr;
10869 if (!RD || RD->isInvalidDecl())
10870 return nullptr;
10871
10872 if (RD->isDynamicClass())
10873 return RD;
10874
10875 // Check all the fields. If any bases were dynamic, the class is dynamic.
10876 // It's impossible for a class to transitively contain itself by value, so
10877 // infinite recursion is impossible.
10878 for (auto *FD : RD->fields()) {
10879 bool SubContained;
10880 if (const CXXRecordDecl *ContainedRD =
10881 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10882 IsContained = true;
10883 return ContainedRD;
10884 }
10885 }
10886
10887 return nullptr;
10888}
10889
10890static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10891 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10892 if (Unary->getKind() == UETT_SizeOf)
10893 return Unary;
10894 return nullptr;
10895}
10896
10897/// If E is a sizeof expression, returns its argument expression,
10898/// otherwise returns NULL.
10899static const Expr *getSizeOfExprArg(const Expr *E) {
10900 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10901 if (!SizeOf->isArgumentType())
10902 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10903 return nullptr;
10904}
10905
10906/// If E is a sizeof expression, returns its argument type.
10907static QualType getSizeOfArgType(const Expr *E) {
10908 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10909 return SizeOf->getTypeOfArgument();
10910 return QualType();
10911}
10912
10913namespace {
10914
10915struct SearchNonTrivialToInitializeField
10916 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10917 using Super =
10918 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10919
10920 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10921
10922 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10923 SourceLocation SL) {
10924 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10925 asDerived().visitArray(PDIK, AT, SL);
10926 return;
10927 }
10928
10929 Super::visitWithKind(PDIK, FT, Args&: SL);
10930 }
10931
10932 void visitARCStrong(QualType FT, SourceLocation SL) {
10933 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10934 }
10935 void visitARCWeak(QualType FT, SourceLocation SL) {
10936 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10937 }
10938 void visitStruct(QualType FT, SourceLocation SL) {
10939 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10940 visit(FT: FD->getType(), Args: FD->getLocation());
10941 }
10942 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10943 const ArrayType *AT, SourceLocation SL) {
10944 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10945 }
10946 void visitTrivial(QualType FT, SourceLocation SL) {}
10947
10948 static void diag(QualType RT, const Expr *E, Sema &S) {
10949 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10950 }
10951
10952 ASTContext &getContext() { return S.getASTContext(); }
10953
10954 const Expr *E;
10955 Sema &S;
10956};
10957
10958struct SearchNonTrivialToCopyField
10959 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10960 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10961
10962 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10963
10964 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10965 SourceLocation SL) {
10966 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10967 asDerived().visitArray(PCK, AT, SL);
10968 return;
10969 }
10970
10971 Super::visitWithKind(PCK, FT, Args&: SL);
10972 }
10973
10974 void visitARCStrong(QualType FT, SourceLocation SL) {
10975 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10976 }
10977 void visitARCWeak(QualType FT, SourceLocation SL) {
10978 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10979 }
10980 void visitPtrAuth(QualType FT, SourceLocation SL) {
10981 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10982 }
10983 void visitStruct(QualType FT, SourceLocation SL) {
10984 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10985 visit(FT: FD->getType(), Args: FD->getLocation());
10986 }
10987 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10988 SourceLocation SL) {
10989 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10990 }
10991 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10992 SourceLocation SL) {}
10993 void visitTrivial(QualType FT, SourceLocation SL) {}
10994 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10995
10996 static void diag(QualType RT, const Expr *E, Sema &S) {
10997 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10998 }
10999
11000 ASTContext &getContext() { return S.getASTContext(); }
11001
11002 const Expr *E;
11003 Sema &S;
11004};
11005
11006}
11007
11008/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11009static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11010 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11011
11012 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
11013 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11014 return false;
11015
11016 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
11017 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
11018 }
11019
11020 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
11021}
11022
11023/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11024///
11025/// \code
11026/// #define MACRO 0
11027/// foo(MACRO);
11028/// foo(0);
11029/// \endcode
11030///
11031/// This should return true for the first call to foo, but not for the second
11032/// (regardless of whether foo is a macro or function).
11033static bool isArgumentExpandedFromMacro(SourceManager &SM,
11034 SourceLocation CallLoc,
11035 SourceLocation ArgLoc) {
11036 if (!CallLoc.isMacroID())
11037 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
11038
11039 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
11040 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
11041}
11042
11043/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11044/// last two arguments transposed.
11045static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11046 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11047 return;
11048
11049 const Expr *SizeArg =
11050 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11051
11052 auto isLiteralZero = [](const Expr *E) {
11053 return (isa<IntegerLiteral>(Val: E) &&
11054 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
11055 (isa<CharacterLiteral>(Val: E) &&
11056 cast<CharacterLiteral>(Val: E)->getValue() == 0);
11057 };
11058
11059 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11060 SourceLocation CallLoc = Call->getRParenLoc();
11061 SourceManager &SM = S.getSourceManager();
11062 if (isLiteralZero(SizeArg) &&
11063 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
11064
11065 SourceLocation DiagLoc = SizeArg->getExprLoc();
11066
11067 // Some platforms #define bzero to __builtin_memset. See if this is the
11068 // case, and if so, emit a better diagnostic.
11069 if (BId == Builtin::BIbzero ||
11070 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11071 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
11072 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
11073 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
11074 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
11075 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
11076 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
11077 }
11078 return;
11079 }
11080
11081 // If the second argument to a memset is a sizeof expression and the third
11082 // isn't, this is also likely an error. This should catch
11083 // 'memset(buf, sizeof(buf), 0xff)'.
11084 if (BId == Builtin::BImemset &&
11085 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
11086 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
11087 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
11088 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
11089 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
11090 return;
11091 }
11092}
11093
11094void Sema::CheckMemaccessArguments(const CallExpr *Call,
11095 unsigned BId,
11096 IdentifierInfo *FnName) {
11097 assert(BId != 0);
11098
11099 // It is possible to have a non-standard definition of memset. Validate
11100 // we have enough arguments, and if not, abort further checking.
11101 unsigned ExpectedNumArgs =
11102 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11103 if (Call->getNumArgs() < ExpectedNumArgs)
11104 return;
11105
11106 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11107 BId == Builtin::BIstrndup ? 1 : 2);
11108 unsigned LenArg =
11109 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11110 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
11111
11112 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
11113 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11114 return;
11115
11116 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11117 CheckMemaccessSize(S&: *this, BId, Call);
11118
11119 // We have special checking when the length is a sizeof expression.
11120 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
11121
11122 // Although widely used, 'bzero' is not a standard function. Be more strict
11123 // with the argument types before allowing diagnostics and only allow the
11124 // form bzero(ptr, sizeof(...)).
11125 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
11126 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11127 return;
11128
11129 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11130 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
11131 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
11132
11133 QualType DestTy = Dest->getType();
11134 QualType PointeeTy;
11135 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11136 PointeeTy = DestPtrTy->getPointeeType();
11137
11138 // Never warn about void type pointers. This can be used to suppress
11139 // false positives.
11140 if (PointeeTy->isVoidType())
11141 continue;
11142
11143 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11144 // actually comparing the expressions for equality. Because computing the
11145 // expression IDs can be expensive, we only do this if the diagnostic is
11146 // enabled.
11147 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
11148 break;
11149
11150 // Also check for cases where the sizeof argument is the exact same
11151 // type as the memory argument, and where it points to a user-defined
11152 // record type.
11153 if (SizeOfArgTy != QualType()) {
11154 if (PointeeTy->isRecordType() &&
11155 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
11156 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
11157 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
11158 << FnName << SizeOfArgTy << ArgIdx
11159 << PointeeTy << Dest->getSourceRange()
11160 << LenExpr->getSourceRange());
11161 break;
11162 }
11163 }
11164 } else if (DestTy->isArrayType()) {
11165 PointeeTy = DestTy;
11166 }
11167
11168 if (PointeeTy == QualType())
11169 continue;
11170
11171 // Always complain about dynamic classes.
11172 bool IsContained;
11173 if (const CXXRecordDecl *ContainedRD =
11174 getContainedDynamicClass(T: PointeeTy, IsContained)) {
11175
11176 unsigned OperationType = 0;
11177 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11178 // "overwritten" if we're warning about the destination for any call
11179 // but memcmp; otherwise a verb appropriate to the call.
11180 if (ArgIdx != 0 || IsCmp) {
11181 if (BId == Builtin::BImemcpy)
11182 OperationType = 1;
11183 else if(BId == Builtin::BImemmove)
11184 OperationType = 2;
11185 else if (IsCmp)
11186 OperationType = 3;
11187 }
11188
11189 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11190 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
11191 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11192 << IsContained << ContainedRD << OperationType
11193 << Call->getCallee()->getSourceRange());
11194 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11195 BId != Builtin::BImemset)
11196 DiagRuntimeBehavior(
11197 Loc: Dest->getExprLoc(), Statement: Dest,
11198 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
11199 << ArgIdx << FnName << PointeeTy
11200 << Call->getCallee()->getSourceRange());
11201 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11202
11203 // FIXME: Do not consider incomplete types even though they may be
11204 // completed later. GCC does not diagnose such code, but we may want to
11205 // consider diagnosing it in the future, perhaps under a different, but
11206 // related, diagnostic group.
11207 bool NonTriviallyCopyableCXXRecord =
11208 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11209 !PointeeTy.isTriviallyCopyableType(Context);
11210
11211 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11212 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
11213 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11214 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11215 << ArgIdx << FnName << PointeeTy << 0);
11216 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
11217 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11218 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11219 // FIXME: Limiting this warning to dest argument until we decide
11220 // whether it's valid for source argument too.
11221 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11222 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11223 << FnName << PointeeTy);
11224 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11225 RD->isNonTrivialToPrimitiveCopy()) {
11226 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11227 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11228 << ArgIdx << FnName << PointeeTy << 1);
11229 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
11230 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11231 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11232 // FIXME: Limiting this warning to dest argument until we decide
11233 // whether it's valid for source argument too.
11234 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11235 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11236 << FnName << PointeeTy);
11237 } else {
11238 continue;
11239 }
11240 } else
11241 continue;
11242
11243 DiagRuntimeBehavior(
11244 Loc: Dest->getExprLoc(), Statement: Dest,
11245 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
11246 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
11247 break;
11248 }
11249}
11250
11251bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11252 IdentifierInfo *FnName) {
11253 llvm::FoldingSetNodeID SizeOfArgID;
11254 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
11255 if (!SizeOfArg)
11256 return false;
11257 // Computing this warning is expensive, so we only do so if the warning is
11258 // enabled.
11259 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
11260 Loc: SizeOfArg->getExprLoc()))
11261 return false;
11262 QualType DestTy = Dest->getType();
11263 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11264 if (!DestPtrTy)
11265 return false;
11266
11267 QualType PointeeTy = DestPtrTy->getPointeeType();
11268
11269 if (SizeOfArgID == llvm::FoldingSetNodeID())
11270 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
11271
11272 llvm::FoldingSetNodeID DestID;
11273 Dest->Profile(ID&: DestID, Context, Canonical: true);
11274 if (DestID == SizeOfArgID) {
11275 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11276 // over sizeof(src) as well.
11277 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11278 StringRef ReadableName = FnName->getName();
11279
11280 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
11281 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11282 ActionIdx = 1; // If its an address-of operator, just remove it.
11283 if (!PointeeTy->isIncompleteType() &&
11284 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
11285 ActionIdx = 2; // If the pointee's size is sizeof(char),
11286 // suggest an explicit length.
11287
11288 // If the function is defined as a builtin macro, do not show macro
11289 // expansion.
11290 SourceLocation SL = SizeOfArg->getExprLoc();
11291 SourceRange DSR = Dest->getSourceRange();
11292 SourceRange SSR = SizeOfArg->getSourceRange();
11293 SourceManager &SM = getSourceManager();
11294
11295 if (SM.isMacroArgExpansion(Loc: SL)) {
11296 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
11297 SL = SM.getSpellingLoc(Loc: SL);
11298 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
11299 SM.getSpellingLoc(Loc: DSR.getEnd()));
11300 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
11301 SM.getSpellingLoc(Loc: SSR.getEnd()));
11302 }
11303
11304 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11305 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
11306 << ReadableName << PointeeTy << DestTy << DSR
11307 << SSR);
11308 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11309 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
11310 << ActionIdx << SSR);
11311 return true;
11312 }
11313 return false;
11314}
11315
11316// A little helper routine: ignore addition and subtraction of integer literals.
11317// This intentionally does not ignore all integer constant expressions because
11318// we don't want to remove sizeof().
11319static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11320 Ex = Ex->IgnoreParenCasts();
11321
11322 while (true) {
11323 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
11324 if (!BO || !BO->isAdditiveOp())
11325 break;
11326
11327 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11328 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11329
11330 if (isa<IntegerLiteral>(Val: RHS))
11331 Ex = LHS;
11332 else if (isa<IntegerLiteral>(Val: LHS))
11333 Ex = RHS;
11334 else
11335 break;
11336 }
11337
11338 return Ex;
11339}
11340
11341static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11342 ASTContext &Context) {
11343 // Only handle constant-sized or VLAs, but not flexible members.
11344 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
11345 // Only issue the FIXIT for arrays of size > 1.
11346 if (CAT->getZExtSize() <= 1)
11347 return false;
11348 } else if (!Ty->isVariableArrayType()) {
11349 return false;
11350 }
11351 return true;
11352}
11353
11354void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11355 IdentifierInfo *FnName) {
11356
11357 // Don't crash if the user has the wrong number of arguments
11358 unsigned NumArgs = Call->getNumArgs();
11359 if ((NumArgs != 3) && (NumArgs != 4))
11360 return;
11361
11362 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
11363 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
11364 const Expr *CompareWithSrc = nullptr;
11365
11366 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
11367 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11368 return;
11369
11370 // Look for 'strlcpy(dst, x, sizeof(x))'
11371 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
11372 CompareWithSrc = Ex;
11373 else {
11374 // Look for 'strlcpy(dst, x, strlen(x))'
11375 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
11376 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11377 SizeCall->getNumArgs() == 1)
11378 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
11379 }
11380 }
11381
11382 if (!CompareWithSrc)
11383 return;
11384
11385 // Determine if the argument to sizeof/strlen is equal to the source
11386 // argument. In principle there's all kinds of things you could do
11387 // here, for instance creating an == expression and evaluating it with
11388 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11389 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
11390 if (!SrcArgDRE)
11391 return;
11392
11393 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
11394 if (!CompareWithSrcDRE ||
11395 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11396 return;
11397
11398 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
11399 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
11400 << OriginalSizeArg->getSourceRange() << FnName;
11401
11402 // Output a FIXIT hint if the destination is an array (rather than a
11403 // pointer to an array). This could be enhanced to handle some
11404 // pointers if we know the actual size, like if DstArg is 'array+2'
11405 // we could say 'sizeof(array)-2'.
11406 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
11407 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
11408 return;
11409
11410 SmallString<128> sizeString;
11411 llvm::raw_svector_ostream OS(sizeString);
11412 OS << "sizeof(";
11413 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11414 OS << ")";
11415
11416 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
11417 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
11418 Code: OS.str());
11419}
11420
11421/// Check if two expressions refer to the same declaration.
11422static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11423 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
11424 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
11425 return D1->getDecl() == D2->getDecl();
11426 return false;
11427}
11428
11429static const Expr *getStrlenExprArg(const Expr *E) {
11430 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
11431 const FunctionDecl *FD = CE->getDirectCallee();
11432 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11433 return nullptr;
11434 return CE->getArg(Arg: 0)->IgnoreParenCasts();
11435 }
11436 return nullptr;
11437}
11438
11439void Sema::CheckStrncatArguments(const CallExpr *CE,
11440 const IdentifierInfo *FnName) {
11441 // Don't crash if the user has the wrong number of arguments.
11442 if (CE->getNumArgs() < 3)
11443 return;
11444 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
11445 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
11446 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
11447
11448 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
11449 RParenLoc: CE->getRParenLoc()))
11450 return;
11451
11452 // Identify common expressions, which are wrongly used as the size argument
11453 // to strncat and may lead to buffer overflows.
11454 unsigned PatternType = 0;
11455 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
11456 // - sizeof(dst)
11457 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
11458 PatternType = 1;
11459 // - sizeof(src)
11460 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
11461 PatternType = 2;
11462 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
11463 if (BE->getOpcode() == BO_Sub) {
11464 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11465 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11466 // - sizeof(dst) - strlen(dst)
11467 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
11468 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
11469 PatternType = 1;
11470 // - sizeof(src) - (anything)
11471 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
11472 PatternType = 2;
11473 }
11474 }
11475
11476 if (PatternType == 0)
11477 return;
11478
11479 // Generate the diagnostic.
11480 SourceLocation SL = LenArg->getBeginLoc();
11481 SourceRange SR = LenArg->getSourceRange();
11482 SourceManager &SM = getSourceManager();
11483
11484 // If the function is defined as a builtin macro, do not show macro expansion.
11485 if (SM.isMacroArgExpansion(Loc: SL)) {
11486 SL = SM.getSpellingLoc(Loc: SL);
11487 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11488 SM.getSpellingLoc(Loc: SR.getEnd()));
11489 }
11490
11491 // Check if the destination is an array (rather than a pointer to an array).
11492 QualType DstTy = DstArg->getType();
11493 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11494 Context);
11495 if (!isKnownSizeArray) {
11496 if (PatternType == 1)
11497 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11498 else
11499 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11500 return;
11501 }
11502
11503 if (PatternType == 1)
11504 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11505 else
11506 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11507
11508 SmallString<128> sizeString;
11509 llvm::raw_svector_ostream OS(sizeString);
11510 OS << "sizeof(";
11511 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11512 OS << ") - ";
11513 OS << "strlen(";
11514 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11515 OS << ") - 1";
11516
11517 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11518 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11519}
11520
11521namespace {
11522void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11523 const UnaryOperator *UnaryExpr, const Decl *D) {
11524 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11525 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11526 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11527 return;
11528 }
11529}
11530
11531void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11532 const UnaryOperator *UnaryExpr) {
11533 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11534 const Decl *D = Lvalue->getDecl();
11535 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11536 if (!DD->getType()->isReferenceType())
11537 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11538 }
11539 }
11540
11541 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11542 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11543 D: Lvalue->getMemberDecl());
11544}
11545
11546void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11547 const UnaryOperator *UnaryExpr) {
11548 const auto *Lambda = dyn_cast<LambdaExpr>(
11549 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11550 if (!Lambda)
11551 return;
11552
11553 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11554 << CalleeName << 2 /*object: lambda expression*/;
11555}
11556
11557void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11558 const DeclRefExpr *Lvalue) {
11559 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11560 if (Var == nullptr)
11561 return;
11562
11563 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11564 << CalleeName << 0 /*object: */ << Var;
11565}
11566
11567void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11568 const CastExpr *Cast) {
11569 SmallString<128> SizeString;
11570 llvm::raw_svector_ostream OS(SizeString);
11571
11572 clang::CastKind Kind = Cast->getCastKind();
11573 if (Kind == clang::CK_BitCast &&
11574 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11575 return;
11576 if (Kind == clang::CK_IntegralToPointer &&
11577 !isa<IntegerLiteral>(
11578 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11579 return;
11580
11581 switch (Cast->getCastKind()) {
11582 case clang::CK_BitCast:
11583 case clang::CK_IntegralToPointer:
11584 case clang::CK_FunctionToPointerDecay:
11585 OS << '\'';
11586 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11587 OS << '\'';
11588 break;
11589 default:
11590 return;
11591 }
11592
11593 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11594 << CalleeName << 0 /*object: */ << OS.str();
11595}
11596} // namespace
11597
11598void Sema::CheckFreeArguments(const CallExpr *E) {
11599 const std::string CalleeName =
11600 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11601
11602 { // Prefer something that doesn't involve a cast to make things simpler.
11603 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11604 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11605 switch (UnaryExpr->getOpcode()) {
11606 case UnaryOperator::Opcode::UO_AddrOf:
11607 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11608 case UnaryOperator::Opcode::UO_Plus:
11609 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11610 default:
11611 break;
11612 }
11613
11614 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11615 if (Lvalue->getType()->isArrayType())
11616 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11617
11618 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11619 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11620 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11621 return;
11622 }
11623
11624 if (isa<BlockExpr>(Val: Arg)) {
11625 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11626 << CalleeName << 1 /*object: block*/;
11627 return;
11628 }
11629 }
11630 // Maybe the cast was important, check after the other cases.
11631 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11632 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11633}
11634
11635void
11636Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11637 SourceLocation ReturnLoc,
11638 bool isObjCMethod,
11639 const AttrVec *Attrs,
11640 const FunctionDecl *FD) {
11641 // Check if the return value is null but should not be.
11642 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11643 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11644 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11645 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11646 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11647
11648 // C++11 [basic.stc.dynamic.allocation]p4:
11649 // If an allocation function declared with a non-throwing
11650 // exception-specification fails to allocate storage, it shall return
11651 // a null pointer. Any other allocation function that fails to allocate
11652 // storage shall indicate failure only by throwing an exception [...]
11653 if (FD) {
11654 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11655 if (Op == OO_New || Op == OO_Array_New) {
11656 const FunctionProtoType *Proto
11657 = FD->getType()->castAs<FunctionProtoType>();
11658 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11659 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11660 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11661 << FD << getLangOpts().CPlusPlus11;
11662 }
11663 }
11664
11665 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11666 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11667 }
11668
11669 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11670 // here prevent the user from using a PPC MMA type as trailing return type.
11671 if (Context.getTargetInfo().getTriple().isPPC64())
11672 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11673}
11674
11675void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11676 const Expr *RHS, BinaryOperatorKind Opcode) {
11677 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11678 return;
11679
11680 // Match and capture subexpressions such as "(float) X == 0.1".
11681 const FloatingLiteral *FPLiteral;
11682 const CastExpr *FPCast;
11683 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11684 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11685 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11686 return FPLiteral && FPCast;
11687 };
11688
11689 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11690 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11691 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11692 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11693 TargetTy->isFloatingPoint()) {
11694 bool Lossy;
11695 llvm::APFloat TargetC = FPLiteral->getValue();
11696 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11697 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11698 if (Lossy) {
11699 // If the literal cannot be represented in the source type, then a
11700 // check for == is always false and check for != is always true.
11701 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11702 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11703 << LHS->getSourceRange() << RHS->getSourceRange();
11704 return;
11705 }
11706 }
11707 }
11708
11709 // Match a more general floating-point equality comparison (-Wfloat-equal).
11710 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11711 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11712
11713 // Special case: check for x == x (which is OK).
11714 // Do not emit warnings for such cases.
11715 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11716 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11717 if (DRL->getDecl() == DRR->getDecl())
11718 return;
11719
11720 // Special case: check for comparisons against literals that can be exactly
11721 // represented by APFloat. In such cases, do not emit a warning. This
11722 // is a heuristic: often comparison against such literals are used to
11723 // detect if a value in a variable has not changed. This clearly can
11724 // lead to false negatives.
11725 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11726 if (FLL->isExact())
11727 return;
11728 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11729 if (FLR->isExact())
11730 return;
11731
11732 // Check for comparisons with builtin types.
11733 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11734 CL && CL->getBuiltinCallee())
11735 return;
11736
11737 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11738 CR && CR->getBuiltinCallee())
11739 return;
11740
11741 // Emit the diagnostic.
11742 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11743 << LHS->getSourceRange() << RHS->getSourceRange();
11744}
11745
11746//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11747//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11748
11749namespace {
11750
11751/// Structure recording the 'active' range of an integer-valued
11752/// expression.
11753struct IntRange {
11754 /// The number of bits active in the int. Note that this includes exactly one
11755 /// sign bit if !NonNegative.
11756 unsigned Width;
11757
11758 /// True if the int is known not to have negative values. If so, all leading
11759 /// bits before Width are known zero, otherwise they are known to be the
11760 /// same as the MSB within Width.
11761 bool NonNegative;
11762
11763 IntRange(unsigned Width, bool NonNegative)
11764 : Width(Width), NonNegative(NonNegative) {}
11765
11766 /// Number of bits excluding the sign bit.
11767 unsigned valueBits() const {
11768 return NonNegative ? Width : Width - 1;
11769 }
11770
11771 /// Returns the range of the bool type.
11772 static IntRange forBoolType() {
11773 return IntRange(1, true);
11774 }
11775
11776 /// Returns the range of an opaque value of the given integral type.
11777 static IntRange forValueOfType(ASTContext &C, QualType T) {
11778 return forValueOfCanonicalType(C,
11779 T: T->getCanonicalTypeInternal().getTypePtr());
11780 }
11781
11782 /// Returns the range of an opaque value of a canonical integral type.
11783 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11784 assert(T->isCanonicalUnqualified());
11785
11786 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11787 T = VT->getElementType().getTypePtr();
11788 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11789 T = MT->getElementType().getTypePtr();
11790 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11791 T = CT->getElementType().getTypePtr();
11792 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11793 T = AT->getValueType().getTypePtr();
11794 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11795 T = OBT->getUnderlyingType().getTypePtr();
11796
11797 if (!C.getLangOpts().CPlusPlus) {
11798 // For enum types in C code, use the underlying datatype.
11799 if (const auto *ED = T->getAsEnumDecl())
11800 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11801 } else if (auto *Enum = T->getAsEnumDecl()) {
11802 // For enum types in C++, use the known bit width of the enumerators.
11803 // In C++11, enums can have a fixed underlying type. Use this type to
11804 // compute the range.
11805 if (Enum->isFixed()) {
11806 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11807 !Enum->getIntegerType()->isSignedIntegerType());
11808 }
11809
11810 unsigned NumPositive = Enum->getNumPositiveBits();
11811 unsigned NumNegative = Enum->getNumNegativeBits();
11812
11813 if (NumNegative == 0)
11814 return IntRange(NumPositive, true/*NonNegative*/);
11815 else
11816 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11817 false/*NonNegative*/);
11818 }
11819
11820 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11821 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11822
11823 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11824 assert(BT->isInteger());
11825
11826 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11827 }
11828
11829 /// Returns the "target" range of a canonical integral type, i.e.
11830 /// the range of values expressible in the type.
11831 ///
11832 /// This matches forValueOfCanonicalType except that enums have the
11833 /// full range of their type, not the range of their enumerators.
11834 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11835 assert(T->isCanonicalUnqualified());
11836
11837 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11838 T = VT->getElementType().getTypePtr();
11839 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11840 T = MT->getElementType().getTypePtr();
11841 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11842 T = CT->getElementType().getTypePtr();
11843 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11844 T = AT->getValueType().getTypePtr();
11845 if (const auto *ED = T->getAsEnumDecl())
11846 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11847 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11848 T = OBT->getUnderlyingType().getTypePtr();
11849
11850 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11851 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11852
11853 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11854 assert(BT->isInteger());
11855
11856 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11857 }
11858
11859 /// Returns the supremum of two ranges: i.e. their conservative merge.
11860 static IntRange join(IntRange L, IntRange R) {
11861 bool Unsigned = L.NonNegative && R.NonNegative;
11862 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11863 L.NonNegative && R.NonNegative);
11864 }
11865
11866 /// Return the range of a bitwise-AND of the two ranges.
11867 static IntRange bit_and(IntRange L, IntRange R) {
11868 unsigned Bits = std::max(a: L.Width, b: R.Width);
11869 bool NonNegative = false;
11870 if (L.NonNegative) {
11871 Bits = std::min(a: Bits, b: L.Width);
11872 NonNegative = true;
11873 }
11874 if (R.NonNegative) {
11875 Bits = std::min(a: Bits, b: R.Width);
11876 NonNegative = true;
11877 }
11878 return IntRange(Bits, NonNegative);
11879 }
11880
11881 /// Return the range of a sum of the two ranges.
11882 static IntRange sum(IntRange L, IntRange R) {
11883 bool Unsigned = L.NonNegative && R.NonNegative;
11884 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11885 Unsigned);
11886 }
11887
11888 /// Return the range of a difference of the two ranges.
11889 static IntRange difference(IntRange L, IntRange R) {
11890 // We need a 1-bit-wider range if:
11891 // 1) LHS can be negative: least value can be reduced.
11892 // 2) RHS can be negative: greatest value can be increased.
11893 bool CanWiden = !L.NonNegative || !R.NonNegative;
11894 bool Unsigned = L.NonNegative && R.Width == 0;
11895 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11896 !Unsigned,
11897 Unsigned);
11898 }
11899
11900 /// Return the range of a product of the two ranges.
11901 static IntRange product(IntRange L, IntRange R) {
11902 // If both LHS and RHS can be negative, we can form
11903 // -2^L * -2^R = 2^(L + R)
11904 // which requires L + R + 1 value bits to represent.
11905 bool CanWiden = !L.NonNegative && !R.NonNegative;
11906 bool Unsigned = L.NonNegative && R.NonNegative;
11907 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11908 Unsigned);
11909 }
11910
11911 /// Return the range of a remainder operation between the two ranges.
11912 static IntRange rem(IntRange L, IntRange R) {
11913 // The result of a remainder can't be larger than the result of
11914 // either side. The sign of the result is the sign of the LHS.
11915 bool Unsigned = L.NonNegative;
11916 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11917 Unsigned);
11918 }
11919};
11920
11921} // namespace
11922
11923static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11924 if (value.isSigned() && value.isNegative())
11925 return IntRange(value.getSignificantBits(), false);
11926
11927 if (value.getBitWidth() > MaxWidth)
11928 value = value.trunc(width: MaxWidth);
11929
11930 // isNonNegative() just checks the sign bit without considering
11931 // signedness.
11932 return IntRange(value.getActiveBits(), true);
11933}
11934
11935static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11936 if (result.isInt())
11937 return GetValueRange(value&: result.getInt(), MaxWidth);
11938
11939 if (result.isVector()) {
11940 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11941 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11942 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11943 R = IntRange::join(L: R, R: El);
11944 }
11945 return R;
11946 }
11947
11948 if (result.isComplexInt()) {
11949 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11950 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11951 return IntRange::join(L: R, R: I);
11952 }
11953
11954 // This can happen with lossless casts to intptr_t of "based" lvalues.
11955 // Assume it might use arbitrary bits.
11956 // FIXME: The only reason we need to pass the type in here is to get
11957 // the sign right on this one case. It would be nice if APValue
11958 // preserved this.
11959 assert(result.isLValue() || result.isAddrLabelDiff());
11960 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11961}
11962
11963static QualType GetExprType(const Expr *E) {
11964 QualType Ty = E->getType();
11965 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11966 Ty = AtomicRHS->getValueType();
11967 return Ty;
11968}
11969
11970/// Attempts to estimate an approximate range for the given integer expression.
11971/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11972/// reliable estimation cannot be determined.
11973///
11974/// \param MaxWidth The width to which the value will be truncated.
11975/// \param InConstantContext If \c true, interpret the expression within a
11976/// constant context.
11977/// \param Approximate If \c true, provide a likely range of values by assuming
11978/// that arithmetic on narrower types remains within those types.
11979/// If \c false, return a range that includes all possible values
11980/// resulting from the expression.
11981/// \returns A range of values that the expression might take, or
11982/// std::nullopt if a reliable estimation cannot be determined.
11983static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11984 unsigned MaxWidth,
11985 bool InConstantContext,
11986 bool Approximate) {
11987 E = E->IgnoreParens();
11988
11989 // Try a full evaluation first.
11990 Expr::EvalResult result;
11991 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11992 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11993
11994 // I think we only want to look through implicit casts here; if the
11995 // user has an explicit widening cast, we should treat the value as
11996 // being of the new, wider type.
11997 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11998 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11999 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
12000 Approximate);
12001
12002 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
12003
12004 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12005 CE->getCastKind() == CK_BooleanToSignedIntegral;
12006
12007 // Assume that non-integer casts can span the full range of the type.
12008 if (!isIntegerCast)
12009 return OutputTypeRange;
12010
12011 std::optional<IntRange> SubRange = TryGetExprRange(
12012 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
12013 InConstantContext, Approximate);
12014 if (!SubRange)
12015 return std::nullopt;
12016
12017 // Bail out if the subexpr's range is as wide as the cast type.
12018 if (SubRange->Width >= OutputTypeRange.Width)
12019 return OutputTypeRange;
12020
12021 // Otherwise, we take the smaller width, and we're non-negative if
12022 // either the output type or the subexpr is.
12023 return IntRange(SubRange->Width,
12024 SubRange->NonNegative || OutputTypeRange.NonNegative);
12025 }
12026
12027 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12028 // If we can fold the condition, just take that operand.
12029 bool CondResult;
12030 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
12031 return TryGetExprRange(
12032 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12033 InConstantContext, Approximate);
12034
12035 // Otherwise, conservatively merge.
12036 // TryGetExprRange requires an integer expression, but a throw expression
12037 // results in a void type.
12038 Expr *TrueExpr = CO->getTrueExpr();
12039 if (TrueExpr->getType()->isVoidType())
12040 return std::nullopt;
12041
12042 std::optional<IntRange> L =
12043 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
12044 if (!L)
12045 return std::nullopt;
12046
12047 Expr *FalseExpr = CO->getFalseExpr();
12048 if (FalseExpr->getType()->isVoidType())
12049 return std::nullopt;
12050
12051 std::optional<IntRange> R =
12052 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
12053 if (!R)
12054 return std::nullopt;
12055
12056 return IntRange::join(L: *L, R: *R);
12057 }
12058
12059 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12060 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12061
12062 switch (BO->getOpcode()) {
12063 case BO_Cmp:
12064 llvm_unreachable("builtin <=> should have class type");
12065
12066 // Boolean-valued operations are single-bit and positive.
12067 case BO_LAnd:
12068 case BO_LOr:
12069 case BO_LT:
12070 case BO_GT:
12071 case BO_LE:
12072 case BO_GE:
12073 case BO_EQ:
12074 case BO_NE:
12075 return IntRange::forBoolType();
12076
12077 // The type of the assignments is the type of the LHS, so the RHS
12078 // is not necessarily the same type.
12079 case BO_MulAssign:
12080 case BO_DivAssign:
12081 case BO_RemAssign:
12082 case BO_AddAssign:
12083 case BO_SubAssign:
12084 case BO_XorAssign:
12085 case BO_OrAssign:
12086 // TODO: bitfields?
12087 return IntRange::forValueOfType(C, T: GetExprType(E));
12088
12089 // Simple assignments just pass through the RHS, which will have
12090 // been coerced to the LHS type.
12091 case BO_Assign:
12092 // TODO: bitfields?
12093 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12094 Approximate);
12095
12096 // Operations with opaque sources are black-listed.
12097 case BO_PtrMemD:
12098 case BO_PtrMemI:
12099 return IntRange::forValueOfType(C, T: GetExprType(E));
12100
12101 // Bitwise-and uses the *infinum* of the two source ranges.
12102 case BO_And:
12103 case BO_AndAssign:
12104 Combine = IntRange::bit_and;
12105 break;
12106
12107 // Left shift gets black-listed based on a judgement call.
12108 case BO_Shl:
12109 // ...except that we want to treat '1 << (blah)' as logically
12110 // positive. It's an important idiom.
12111 if (IntegerLiteral *I
12112 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
12113 if (I->getValue() == 1) {
12114 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
12115 return IntRange(R.Width, /*NonNegative*/ true);
12116 }
12117 }
12118 [[fallthrough]];
12119
12120 case BO_ShlAssign:
12121 return IntRange::forValueOfType(C, T: GetExprType(E));
12122
12123 // Right shift by a constant can narrow its left argument.
12124 case BO_Shr:
12125 case BO_ShrAssign: {
12126 std::optional<IntRange> L = TryGetExprRange(
12127 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12128 if (!L)
12129 return std::nullopt;
12130
12131 // If the shift amount is a positive constant, drop the width by
12132 // that much.
12133 if (std::optional<llvm::APSInt> shift =
12134 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12135 if (shift->isNonNegative()) {
12136 if (shift->uge(RHS: L->Width))
12137 L->Width = (L->NonNegative ? 0 : 1);
12138 else
12139 L->Width -= shift->getZExtValue();
12140 }
12141 }
12142
12143 return L;
12144 }
12145
12146 // Comma acts as its right operand.
12147 case BO_Comma:
12148 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12149 Approximate);
12150
12151 case BO_Add:
12152 if (!Approximate)
12153 Combine = IntRange::sum;
12154 break;
12155
12156 case BO_Sub:
12157 if (BO->getLHS()->getType()->isPointerType())
12158 return IntRange::forValueOfType(C, T: GetExprType(E));
12159 if (!Approximate)
12160 Combine = IntRange::difference;
12161 break;
12162
12163 case BO_Mul:
12164 if (!Approximate)
12165 Combine = IntRange::product;
12166 break;
12167
12168 // The width of a division result is mostly determined by the size
12169 // of the LHS.
12170 case BO_Div: {
12171 // Don't 'pre-truncate' the operands.
12172 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
12173 std::optional<IntRange> L = TryGetExprRange(
12174 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12175 if (!L)
12176 return std::nullopt;
12177
12178 // If the divisor is constant, use that.
12179 if (std::optional<llvm::APSInt> divisor =
12180 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12181 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12182 if (log2 >= L->Width)
12183 L->Width = (L->NonNegative ? 0 : 1);
12184 else
12185 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
12186 return L;
12187 }
12188
12189 // Otherwise, just use the LHS's width.
12190 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12191 // could be -1.
12192 std::optional<IntRange> R = TryGetExprRange(
12193 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12194 if (!R)
12195 return std::nullopt;
12196
12197 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12198 }
12199
12200 case BO_Rem:
12201 Combine = IntRange::rem;
12202 break;
12203
12204 // The default behavior is okay for these.
12205 case BO_Xor:
12206 case BO_Or:
12207 break;
12208 }
12209
12210 // Combine the two ranges, but limit the result to the type in which we
12211 // performed the computation.
12212 QualType T = GetExprType(E);
12213 unsigned opWidth = C.getIntWidth(T);
12214 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
12215 InConstantContext, Approximate);
12216 if (!L)
12217 return std::nullopt;
12218
12219 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
12220 InConstantContext, Approximate);
12221 if (!R)
12222 return std::nullopt;
12223
12224 IntRange C = Combine(*L, *R);
12225 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12226 C.Width = std::min(a: C.Width, b: MaxWidth);
12227 return C;
12228 }
12229
12230 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12231 switch (UO->getOpcode()) {
12232 // Boolean-valued operations are white-listed.
12233 case UO_LNot:
12234 return IntRange::forBoolType();
12235
12236 // Operations with opaque sources are black-listed.
12237 case UO_Deref:
12238 case UO_AddrOf: // should be impossible
12239 return IntRange::forValueOfType(C, T: GetExprType(E));
12240
12241 case UO_Minus: {
12242 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
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 // If the range was previously non-negative, we need an extra bit for the
12254 // sign bit. Otherwise, we need an extra bit because the negation of the
12255 // most-negative value is one bit wider than that value.
12256 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
12257 }
12258
12259 case UO_Not: {
12260 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12261 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12262 Approximate);
12263 }
12264
12265 std::optional<IntRange> SubRange = TryGetExprRange(
12266 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12267
12268 if (!SubRange)
12269 return std::nullopt;
12270
12271 // The width increments by 1 if the sub-expression cannot be negative
12272 // since it now can be.
12273 return IntRange(
12274 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
12275 false);
12276 }
12277
12278 default:
12279 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12280 Approximate);
12281 }
12282 }
12283
12284 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12285 // The source expression is null for the OpaqueValueExpr that stands in for
12286 // a non-type template argument of pointer or reference type; fall back to
12287 // the range of the type in that case.
12288 if (const Expr *SourceExpr = OVE->getSourceExpr())
12289 return TryGetExprRange(C, E: SourceExpr, MaxWidth, InConstantContext,
12290 Approximate);
12291 }
12292
12293 if (const auto *BitField = E->getSourceBitField())
12294 return IntRange(BitField->getBitWidthValue(),
12295 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12296
12297 if (GetExprType(E)->isVoidType())
12298 return std::nullopt;
12299
12300 return IntRange::forValueOfType(C, T: GetExprType(E));
12301}
12302
12303static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12304 bool InConstantContext,
12305 bool Approximate) {
12306 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
12307 Approximate);
12308}
12309
12310/// Checks whether the given value, which currently has the given
12311/// source semantics, has the same value when coerced through the
12312/// target semantics.
12313static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12314 const llvm::fltSemantics &Src,
12315 const llvm::fltSemantics &Tgt) {
12316 llvm::APFloat truncated = value;
12317
12318 bool ignored;
12319 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12320 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12321
12322 return truncated.bitwiseIsEqual(RHS: value);
12323}
12324
12325/// Checks whether the given value, which currently has the given
12326/// source semantics, has the same value when coerced through the
12327/// target semantics.
12328///
12329/// The value might be a vector of floats (or a complex number).
12330static bool IsSameFloatAfterCast(const APValue &value,
12331 const llvm::fltSemantics &Src,
12332 const llvm::fltSemantics &Tgt) {
12333 if (value.isFloat())
12334 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
12335
12336 if (value.isVector()) {
12337 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12338 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
12339 return false;
12340 return true;
12341 }
12342
12343 if (value.isMatrix()) {
12344 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12345 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
12346 return false;
12347 return true;
12348 }
12349
12350 assert(value.isComplexFloat());
12351 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
12352 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
12353}
12354
12355static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12356 bool IsListInit = false);
12357
12358static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12359 // Suppress cases where we are comparing against an enum constant.
12360 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
12361 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
12362 return true;
12363
12364 // Suppress cases where the value is expanded from a macro, unless that macro
12365 // is how a language represents a boolean literal. This is the case in both C
12366 // and Objective-C.
12367 SourceLocation BeginLoc = E->getBeginLoc();
12368 if (BeginLoc.isMacroID()) {
12369 StringRef MacroName = Lexer::getImmediateMacroName(
12370 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
12371 return MacroName != "YES" && MacroName != "NO" &&
12372 MacroName != "true" && MacroName != "false";
12373 }
12374
12375 return false;
12376}
12377
12378static bool isKnownToHaveUnsignedValue(const Expr *E) {
12379 return E->getType()->isIntegerType() &&
12380 (!E->getType()->isSignedIntegerType() ||
12381 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12382}
12383
12384namespace {
12385/// The promoted range of values of a type. In general this has the
12386/// following structure:
12387///
12388/// |-----------| . . . |-----------|
12389/// ^ ^ ^ ^
12390/// Min HoleMin HoleMax Max
12391///
12392/// ... where there is only a hole if a signed type is promoted to unsigned
12393/// (in which case Min and Max are the smallest and largest representable
12394/// values).
12395struct PromotedRange {
12396 // Min, or HoleMax if there is a hole.
12397 llvm::APSInt PromotedMin;
12398 // Max, or HoleMin if there is a hole.
12399 llvm::APSInt PromotedMax;
12400
12401 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12402 if (R.Width == 0)
12403 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12404 else if (R.Width >= BitWidth && !Unsigned) {
12405 // Promotion made the type *narrower*. This happens when promoting
12406 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12407 // Treat all values of 'signed int' as being in range for now.
12408 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
12409 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
12410 } else {
12411 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
12412 .extOrTrunc(width: BitWidth);
12413 PromotedMin.setIsUnsigned(Unsigned);
12414
12415 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
12416 .extOrTrunc(width: BitWidth);
12417 PromotedMax.setIsUnsigned(Unsigned);
12418 }
12419 }
12420
12421 // Determine whether this range is contiguous (has no hole).
12422 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12423
12424 // Where a constant value is within the range.
12425 enum ComparisonResult {
12426 LT = 0x1,
12427 LE = 0x2,
12428 GT = 0x4,
12429 GE = 0x8,
12430 EQ = 0x10,
12431 NE = 0x20,
12432 InRangeFlag = 0x40,
12433
12434 Less = LE | LT | NE,
12435 Min = LE | InRangeFlag,
12436 InRange = InRangeFlag,
12437 Max = GE | InRangeFlag,
12438 Greater = GE | GT | NE,
12439
12440 OnlyValue = LE | GE | EQ | InRangeFlag,
12441 InHole = NE
12442 };
12443
12444 ComparisonResult compare(const llvm::APSInt &Value) const {
12445 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12446 Value.isUnsigned() == PromotedMin.isUnsigned());
12447 if (!isContiguous()) {
12448 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12449 if (Value.isMinValue()) return Min;
12450 if (Value.isMaxValue()) return Max;
12451 if (Value >= PromotedMin) return InRange;
12452 if (Value <= PromotedMax) return InRange;
12453 return InHole;
12454 }
12455
12456 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
12457 case -1: return Less;
12458 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12459 case 1:
12460 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
12461 case -1: return InRange;
12462 case 0: return Max;
12463 case 1: return Greater;
12464 }
12465 }
12466
12467 llvm_unreachable("impossible compare result");
12468 }
12469
12470 static std::optional<StringRef>
12471 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12472 if (Op == BO_Cmp) {
12473 ComparisonResult LTFlag = LT, GTFlag = GT;
12474 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
12475
12476 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12477 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12478 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12479 return std::nullopt;
12480 }
12481
12482 ComparisonResult TrueFlag, FalseFlag;
12483 if (Op == BO_EQ) {
12484 TrueFlag = EQ;
12485 FalseFlag = NE;
12486 } else if (Op == BO_NE) {
12487 TrueFlag = NE;
12488 FalseFlag = EQ;
12489 } else {
12490 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12491 TrueFlag = LT;
12492 FalseFlag = GE;
12493 } else {
12494 TrueFlag = GT;
12495 FalseFlag = LE;
12496 }
12497 if (Op == BO_GE || Op == BO_LE)
12498 std::swap(a&: TrueFlag, b&: FalseFlag);
12499 }
12500 if (R & TrueFlag)
12501 return StringRef("true");
12502 if (R & FalseFlag)
12503 return StringRef("false");
12504 return std::nullopt;
12505 }
12506};
12507}
12508
12509static bool HasEnumType(const Expr *E) {
12510 // Strip off implicit integral promotions.
12511 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12512 if (ICE->getCastKind() != CK_IntegralCast &&
12513 ICE->getCastKind() != CK_NoOp)
12514 break;
12515 E = ICE->getSubExpr();
12516 }
12517
12518 return E->getType()->isEnumeralType();
12519}
12520
12521static int classifyConstantValue(Expr *Constant) {
12522 // The values of this enumeration are used in the diagnostics
12523 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12524 enum ConstantValueKind {
12525 Miscellaneous = 0,
12526 LiteralTrue,
12527 LiteralFalse
12528 };
12529 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12530 return BL->getValue() ? ConstantValueKind::LiteralTrue
12531 : ConstantValueKind::LiteralFalse;
12532 return ConstantValueKind::Miscellaneous;
12533}
12534
12535static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12536 Expr *Constant, Expr *Other,
12537 const llvm::APSInt &Value,
12538 bool RhsConstant) {
12539 if (S.inTemplateInstantiation())
12540 return false;
12541
12542 Expr *OriginalOther = Other;
12543
12544 Constant = Constant->IgnoreParenImpCasts();
12545 Other = Other->IgnoreParenImpCasts();
12546
12547 // Suppress warnings on tautological comparisons between values of the same
12548 // enumeration type. There are only two ways we could warn on this:
12549 // - If the constant is outside the range of representable values of
12550 // the enumeration. In such a case, we should warn about the cast
12551 // to enumeration type, not about the comparison.
12552 // - If the constant is the maximum / minimum in-range value. For an
12553 // enumeratin type, such comparisons can be meaningful and useful.
12554 if (Constant->getType()->isEnumeralType() &&
12555 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12556 return false;
12557
12558 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12559 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12560 if (!OtherValueRange)
12561 return false;
12562
12563 QualType OtherT = Other->getType();
12564 if (const auto *AT = OtherT->getAs<AtomicType>())
12565 OtherT = AT->getValueType();
12566 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12567
12568 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12569 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12570 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12571 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12572 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12573
12574 // Whether we're treating Other as being a bool because of the form of
12575 // expression despite it having another type (typically 'int' in C).
12576 bool OtherIsBooleanDespiteType =
12577 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12578 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12579 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12580
12581 // Check if all values in the range of possible values of this expression
12582 // lead to the same comparison outcome.
12583 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12584 Value.isUnsigned());
12585 auto Cmp = OtherPromotedValueRange.compare(Value);
12586 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12587 if (!Result)
12588 return false;
12589
12590 // Also consider the range determined by the type alone. This allows us to
12591 // classify the warning under the proper diagnostic group.
12592 bool TautologicalTypeCompare = false;
12593 {
12594 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12595 Value.isUnsigned());
12596 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12597 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12598 ConstantOnRHS: RhsConstant)) {
12599 TautologicalTypeCompare = true;
12600 Cmp = TypeCmp;
12601 Result = TypeResult;
12602 }
12603 }
12604
12605 // Don't warn if the non-constant operand actually always evaluates to the
12606 // same value.
12607 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12608 return false;
12609
12610 // Suppress the diagnostic for an in-range comparison if the constant comes
12611 // from a macro or enumerator. We don't want to diagnose
12612 //
12613 // some_long_value <= INT_MAX
12614 //
12615 // when sizeof(int) == sizeof(long).
12616 bool InRange = Cmp & PromotedRange::InRangeFlag;
12617 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12618 return false;
12619
12620 // A comparison of an unsigned bit-field against 0 is really a type problem,
12621 // even though at the type level the bit-field might promote to 'signed int'.
12622 if (Other->refersToBitField() && InRange && Value == 0 &&
12623 Other->getType()->isUnsignedIntegerOrEnumerationType())
12624 TautologicalTypeCompare = true;
12625
12626 // If this is a comparison to an enum constant, include that
12627 // constant in the diagnostic.
12628 const EnumConstantDecl *ED = nullptr;
12629 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12630 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12631
12632 // Should be enough for uint128 (39 decimal digits)
12633 SmallString<64> PrettySourceValue;
12634 llvm::raw_svector_ostream OS(PrettySourceValue);
12635 if (ED) {
12636 OS << '\'' << *ED << "' (" << Value << ")";
12637 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12638 Val: Constant->IgnoreParenImpCasts())) {
12639 OS << (BL->getValue() ? "YES" : "NO");
12640 } else {
12641 OS << Value;
12642 }
12643
12644 if (!TautologicalTypeCompare) {
12645 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12646 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12647 << E->getOpcodeStr() << OS.str() << *Result
12648 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12649 return true;
12650 }
12651
12652 if (IsObjCSignedCharBool) {
12653 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12654 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12655 << OS.str() << *Result);
12656 return true;
12657 }
12658
12659 // FIXME: We use a somewhat different formatting for the in-range cases and
12660 // cases involving boolean values for historical reasons. We should pick a
12661 // consistent way of presenting these diagnostics.
12662 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12663
12664 S.DiagRuntimeBehavior(
12665 Loc: E->getOperatorLoc(), Statement: E,
12666 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12667 : diag::warn_tautological_bool_compare)
12668 << OS.str() << classifyConstantValue(Constant) << OtherT
12669 << OtherIsBooleanDespiteType << *Result
12670 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12671 } else {
12672 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12673 unsigned Diag =
12674 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12675 ? (HasEnumType(E: OriginalOther)
12676 ? diag::warn_unsigned_enum_always_true_comparison
12677 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12678 : diag::warn_unsigned_always_true_comparison)
12679 : diag::warn_tautological_constant_compare;
12680
12681 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12682 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12683 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12684 }
12685
12686 return true;
12687}
12688
12689/// Analyze the operands of the given comparison. Implements the
12690/// fallback case from AnalyzeComparison.
12691static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12692 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12693 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12694}
12695
12696/// Implements -Wsign-compare.
12697///
12698/// \param E the binary operator to check for warnings
12699static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12700 // The type the comparison is being performed in.
12701 QualType T = E->getLHS()->getType();
12702
12703 // Only analyze comparison operators where both sides have been converted to
12704 // the same type.
12705 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12706 return AnalyzeImpConvsInComparison(S, E);
12707
12708 // Don't analyze value-dependent comparisons directly.
12709 if (E->isValueDependent())
12710 return AnalyzeImpConvsInComparison(S, E);
12711
12712 Expr *LHS = E->getLHS();
12713 Expr *RHS = E->getRHS();
12714
12715 if (T->isIntegralType(Ctx: S.Context)) {
12716 std::optional<llvm::APSInt> RHSValue =
12717 RHS->getIntegerConstantExpr(Ctx: S.Context);
12718 std::optional<llvm::APSInt> LHSValue =
12719 LHS->getIntegerConstantExpr(Ctx: S.Context);
12720
12721 // We don't care about expressions whose result is a constant.
12722 if (RHSValue && LHSValue)
12723 return AnalyzeImpConvsInComparison(S, E);
12724
12725 // We only care about expressions where just one side is literal
12726 if ((bool)RHSValue ^ (bool)LHSValue) {
12727 // Is the constant on the RHS or LHS?
12728 const bool RhsConstant = (bool)RHSValue;
12729 Expr *Const = RhsConstant ? RHS : LHS;
12730 Expr *Other = RhsConstant ? LHS : RHS;
12731 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12732
12733 // Check whether an integer constant comparison results in a value
12734 // of 'true' or 'false'.
12735 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12736 return AnalyzeImpConvsInComparison(S, E);
12737 }
12738 }
12739
12740 if (!T->hasUnsignedIntegerRepresentation()) {
12741 // We don't do anything special if this isn't an unsigned integral
12742 // comparison: we're only interested in integral comparisons, and
12743 // signed comparisons only happen in cases we don't care to warn about.
12744 return AnalyzeImpConvsInComparison(S, E);
12745 }
12746
12747 LHS = LHS->IgnoreParenImpCasts();
12748 RHS = RHS->IgnoreParenImpCasts();
12749
12750 if (!S.getLangOpts().CPlusPlus) {
12751 // Avoid warning about comparison of integers with different signs when
12752 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12753 // the type of `E`.
12754 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12755 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12756 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12757 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12758 }
12759
12760 // Check to see if one of the (unmodified) operands is of different
12761 // signedness.
12762 Expr *signedOperand, *unsignedOperand;
12763 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12764 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12765 "unsigned comparison between two signed integer expressions?");
12766 signedOperand = LHS;
12767 unsignedOperand = RHS;
12768 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12769 signedOperand = RHS;
12770 unsignedOperand = LHS;
12771 } else {
12772 return AnalyzeImpConvsInComparison(S, E);
12773 }
12774
12775 // Otherwise, calculate the effective range of the signed operand.
12776 std::optional<IntRange> signedRange =
12777 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12778 /*Approximate=*/true);
12779 if (!signedRange)
12780 return;
12781
12782 // Go ahead and analyze implicit conversions in the operands. Note
12783 // that we skip the implicit conversions on both sides.
12784 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12785 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12786
12787 // If the signed range is non-negative, -Wsign-compare won't fire.
12788 if (signedRange->NonNegative)
12789 return;
12790
12791 // For (in)equality comparisons, if the unsigned operand is a
12792 // constant which cannot collide with a overflowed signed operand,
12793 // then reinterpreting the signed operand as unsigned will not
12794 // change the result of the comparison.
12795 if (E->isEqualityOp()) {
12796 unsigned comparisonWidth = S.Context.getIntWidth(T);
12797 std::optional<IntRange> unsignedRange = TryGetExprRange(
12798 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12799 /*Approximate=*/true);
12800 if (!unsignedRange)
12801 return;
12802
12803 // We should never be unable to prove that the unsigned operand is
12804 // non-negative.
12805 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12806
12807 if (unsignedRange->Width < comparisonWidth)
12808 return;
12809 }
12810
12811 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12812 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12813 << LHS->getType() << RHS->getType()
12814 << LHS->getSourceRange() << RHS->getSourceRange());
12815}
12816
12817/// Analyzes an attempt to assign the given value to a bitfield.
12818///
12819/// Returns true if there was something fishy about the attempt.
12820static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12821 SourceLocation InitLoc) {
12822 assert(Bitfield->isBitField());
12823 if (Bitfield->isInvalidDecl())
12824 return false;
12825
12826 // White-list bool bitfields.
12827 QualType BitfieldType = Bitfield->getType();
12828 if (BitfieldType->isBooleanType())
12829 return false;
12830
12831 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12832 // If the underlying enum type was not explicitly specified as an unsigned
12833 // type and the enum contain only positive values, MSVC++ will cause an
12834 // inconsistency by storing this as a signed type.
12835 if (S.getLangOpts().CPlusPlus11 &&
12836 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12837 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12838 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12839 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12840 << BitfieldEnumDecl;
12841 }
12842 }
12843
12844 // Ignore value- or type-dependent expressions.
12845 if (Bitfield->getBitWidth()->isValueDependent() ||
12846 Bitfield->getBitWidth()->isTypeDependent() ||
12847 Init->isValueDependent() ||
12848 Init->isTypeDependent())
12849 return false;
12850
12851 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12852 unsigned FieldWidth = Bitfield->getBitWidthValue();
12853
12854 Expr::EvalResult Result;
12855 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12856 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12857 // The RHS is not constant. If the RHS has an enum type, make sure the
12858 // bitfield is wide enough to hold all the values of the enum without
12859 // truncation.
12860 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12861 const PreferredTypeAttr *PTAttr = nullptr;
12862 if (!ED) {
12863 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12864 if (PTAttr)
12865 ED = PTAttr->getType()->getAsEnumDecl();
12866 }
12867 if (ED) {
12868 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12869
12870 // Enum types are implicitly signed on Windows, so check if there are any
12871 // negative enumerators to see if the enum was intended to be signed or
12872 // not.
12873 bool SignedEnum = ED->getNumNegativeBits() > 0;
12874
12875 // Check for surprising sign changes when assigning enum values to a
12876 // bitfield of different signedness. If the bitfield is signed and we
12877 // have exactly the right number of bits to store this unsigned enum,
12878 // suggest changing the enum to an unsigned type. This typically happens
12879 // on Windows where unfixed enums always use an underlying type of 'int'.
12880 unsigned DiagID = 0;
12881 if (SignedEnum && !SignedBitfield) {
12882 DiagID =
12883 PTAttr == nullptr
12884 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12885 : diag::
12886 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12887 } else if (SignedBitfield && !SignedEnum &&
12888 ED->getNumPositiveBits() == FieldWidth) {
12889 DiagID =
12890 PTAttr == nullptr
12891 ? diag::warn_signed_bitfield_enum_conversion
12892 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12893 }
12894 if (DiagID) {
12895 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12896 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12897 SourceRange TypeRange =
12898 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12899 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12900 << SignedEnum << TypeRange;
12901 if (PTAttr)
12902 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12903 << ED;
12904 }
12905
12906 // Compute the required bitwidth. If the enum has negative values, we need
12907 // one more bit than the normal number of positive bits to represent the
12908 // sign bit.
12909 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12910 b: ED->getNumNegativeBits())
12911 : ED->getNumPositiveBits();
12912
12913 // Check the bitwidth.
12914 if (BitsNeeded > FieldWidth) {
12915 Expr *WidthExpr = Bitfield->getBitWidth();
12916 auto DiagID =
12917 PTAttr == nullptr
12918 ? diag::warn_bitfield_too_small_for_enum
12919 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12920 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12921 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12922 << BitsNeeded << ED << WidthExpr->getSourceRange();
12923 if (PTAttr)
12924 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12925 << ED;
12926 }
12927 }
12928
12929 return false;
12930 }
12931
12932 llvm::APSInt Value = Result.Val.getInt();
12933
12934 unsigned OriginalWidth = Value.getBitWidth();
12935
12936 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12937 // false positives where the user is demonstrating they intend to use the
12938 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12939 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12940 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12941 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12942 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12943 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12944 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12945 return false;
12946 }
12947
12948 if (!Value.isSigned() || Value.isNegative())
12949 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12950 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12951 OriginalWidth = Value.getSignificantBits();
12952
12953 if (OriginalWidth <= FieldWidth)
12954 return false;
12955
12956 // Compute the value which the bitfield will contain.
12957 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12958 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12959
12960 // Check whether the stored value is equal to the original value.
12961 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12962 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12963 return false;
12964
12965 std::string PrettyValue = toString(I: Value, Radix: 10);
12966 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12967
12968 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12969 ? diag::warn_impcast_single_bit_bitield_precision_constant
12970 : diag::warn_impcast_bitfield_precision_constant)
12971 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12972 << Init->getSourceRange();
12973
12974 return true;
12975}
12976
12977/// Analyze the given simple or compound assignment for warning-worthy
12978/// operations.
12979static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12980 // Just recurse on the LHS.
12981 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12982
12983 // We want to recurse on the RHS as normal unless we're assigning to
12984 // a bitfield.
12985 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12986 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12987 InitLoc: E->getOperatorLoc())) {
12988 // Recurse, ignoring any implicit conversions on the RHS.
12989 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12990 CC: E->getOperatorLoc());
12991 }
12992 }
12993
12994 // Set context flag for overflow behavior type assignment analysis, use RAII
12995 // pattern to handle nested assignments.
12996 llvm::SaveAndRestore OBTAssignmentContext(
12997 S.InOverflowBehaviorAssignmentContext, true);
12998
12999 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13000
13001 // Diagnose implicitly sequentially-consistent atomic assignment.
13002 if (E->getLHS()->getType()->isAtomicType())
13003 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13004}
13005
13006/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13007static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13008 QualType T, SourceLocation CContext, unsigned diag,
13009 bool PruneControlFlow = false) {
13010 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13011 // address space annotations isn't really useful. The warnings aren't because
13012 // you're converting a `private int` to `unsigned int`, it is because you're
13013 // conerting `int` to `unsigned int`.
13014 if (SourceType.hasAddressSpace())
13015 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
13016 if (T.hasAddressSpace())
13017 T = S.getASTContext().removeAddrSpaceQualType(T);
13018 if (PruneControlFlow) {
13019 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13020 PD: S.PDiag(DiagID: diag)
13021 << SourceType << T << E->getSourceRange()
13022 << SourceRange(CContext));
13023 return;
13024 }
13025 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
13026 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13027}
13028
13029/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13030static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13031 SourceLocation CContext, unsigned diag,
13032 bool PruneControlFlow = false) {
13033 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
13034}
13035
13036/// Diagnose an implicit cast from a floating point value to an integer value.
13037static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13038 SourceLocation CContext) {
13039 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
13040 bool PruneWarnings = S.inTemplateInstantiation();
13041
13042 const Expr *InnerE = E->IgnoreParenImpCasts();
13043 // We also want to warn on, e.g., "int i = -1.234"
13044 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
13045 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13046 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13047
13048 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
13049
13050 llvm::APFloat Value(0.0);
13051 bool IsConstant =
13052 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
13053 if (!IsConstant) {
13054 if (S.ObjC().isSignedCharBool(Ty: T)) {
13055 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13056 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
13057 << E->getType());
13058 }
13059
13060 return DiagnoseImpCast(S, E, T, CContext,
13061 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13062 }
13063
13064 bool isExact = false;
13065
13066 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13067 T->hasUnsignedIntegerRepresentation());
13068 llvm::APFloat::opStatus Result = Value.convertToInteger(
13069 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
13070
13071 // FIXME: Force the precision of the source value down so we don't print
13072 // digits which are usually useless (we don't really care here if we
13073 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13074 // would automatically print the shortest representation, but it's a bit
13075 // tricky to implement.
13076 SmallString<16> PrettySourceValue;
13077 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13078 precision = (precision * 59 + 195) / 196;
13079 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
13080
13081 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
13082 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13083 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13084 << PrettySourceValue);
13085 }
13086
13087 if (Result == llvm::APFloat::opOK && isExact) {
13088 if (IsLiteral) return;
13089 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
13090 PruneControlFlow: PruneWarnings);
13091 }
13092
13093 // Conversion of a floating-point value to a non-bool integer where the
13094 // integral part cannot be represented by the integer type is undefined.
13095 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13096 return DiagnoseImpCast(
13097 S, E, T, CContext,
13098 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13099 : diag::warn_impcast_float_to_integer_out_of_range,
13100 PruneControlFlow: PruneWarnings);
13101
13102 unsigned DiagID = 0;
13103 if (IsLiteral) {
13104 // Warn on floating point literal to integer.
13105 DiagID = diag::warn_impcast_literal_float_to_integer;
13106 } else if (IntegerValue == 0) {
13107 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13108 return DiagnoseImpCast(S, E, T, CContext,
13109 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13110 }
13111 // Warn on non-zero to zero conversion.
13112 DiagID = diag::warn_impcast_float_to_integer_zero;
13113 } else {
13114 if (IntegerValue.isUnsigned()) {
13115 if (!IntegerValue.isMaxValue()) {
13116 return DiagnoseImpCast(S, E, T, CContext,
13117 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13118 }
13119 } else { // IntegerValue.isSigned()
13120 if (!IntegerValue.isMaxSignedValue() &&
13121 !IntegerValue.isMinSignedValue()) {
13122 return DiagnoseImpCast(S, E, T, CContext,
13123 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13124 }
13125 }
13126 // Warn on evaluatable floating point expression to integer conversion.
13127 DiagID = diag::warn_impcast_float_to_integer;
13128 }
13129
13130 SmallString<16> PrettyTargetValue;
13131 if (IsBool)
13132 PrettyTargetValue = Value.isZero() ? "false" : "true";
13133 else
13134 IntegerValue.toString(Str&: PrettyTargetValue);
13135
13136 if (PruneWarnings) {
13137 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13138 PD: S.PDiag(DiagID)
13139 << E->getType() << T.getUnqualifiedType()
13140 << PrettySourceValue << PrettyTargetValue
13141 << E->getSourceRange() << SourceRange(CContext));
13142 } else {
13143 S.Diag(Loc: E->getExprLoc(), DiagID)
13144 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13145 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13146 }
13147}
13148
13149/// Analyze the given compound assignment for the possible losing of
13150/// floating-point precision.
13151static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13152 assert(isa<CompoundAssignOperator>(E) &&
13153 "Must be compound assignment operation");
13154 // Recurse on the LHS and RHS in here
13155 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13156 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13157
13158 if (E->getLHS()->getType()->isAtomicType())
13159 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13160
13161 // Now check the outermost expression
13162 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13163 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
13164 ->getComputationResultType()
13165 ->getAs<BuiltinType>();
13166
13167 // The below checks assume source is floating point.
13168 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13169
13170 // If source is floating point but target is an integer.
13171 if (ResultBT->isInteger())
13172 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
13173 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
13174
13175 if (!ResultBT->isFloatingPoint())
13176 return;
13177
13178 // If both source and target are floating points, warn about losing precision.
13179 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13180 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
13181 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
13182 // warn about dropping FP rank.
13183 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
13184 diag: diag::warn_impcast_float_result_precision);
13185}
13186
13187static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13188 IntRange Range) {
13189 if (!Range.Width) return "0";
13190
13191 llvm::APSInt ValueInRange = Value;
13192 ValueInRange.setIsSigned(!Range.NonNegative);
13193 ValueInRange = ValueInRange.trunc(width: Range.Width);
13194 return toString(I: ValueInRange, Radix: 10);
13195}
13196
13197static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13198 bool ToBool) {
13199 if (!isa<ImplicitCastExpr>(Val: Ex))
13200 return false;
13201
13202 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13203 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
13204 const Type *Source =
13205 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
13206 if (Target->isDependentType())
13207 return false;
13208
13209 const auto *FloatCandidateBT =
13210 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
13211 const Type *BoolCandidateType = ToBool ? Target : Source;
13212
13213 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
13214 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13215}
13216
13217static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13218 SourceLocation CC) {
13219 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13220 const Expr *CurrA = TheCall->getArg(Arg: I);
13221 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
13222 continue;
13223
13224 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13225 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
13226 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13227 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
13228 if (IsSwapped) {
13229 // Warn on this floating-point to bool conversion.
13230 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
13231 T: CurrA->getType(), CContext: CC,
13232 diag: diag::warn_impcast_floating_point_to_bool);
13233 }
13234 }
13235}
13236
13237static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13238 SourceLocation CC) {
13239 // Don't warn on functions which have return type nullptr_t.
13240 if (isa<CallExpr>(Val: E))
13241 return;
13242
13243 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13244 const Expr *NewE = E->IgnoreParenImpCasts();
13245 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
13246 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13247 if (!IsGNUNullExpr && !HasNullPtrType)
13248 return;
13249
13250 // Return if target type is a safe conversion.
13251 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13252 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13253 return;
13254
13255 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
13256 Loc: E->getExprLoc()))
13257 return;
13258
13259 SourceLocation Loc = E->getSourceRange().getBegin();
13260
13261 // Venture through the macro stacks to get to the source of macro arguments.
13262 // The new location is a better location than the complete location that was
13263 // passed in.
13264 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13265 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
13266
13267 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13268 if (IsGNUNullExpr && Loc.isMacroID()) {
13269 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13270 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
13271 if (MacroName == "NULL")
13272 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13273 }
13274
13275 // Only warn if the null and context location are in the same macro expansion.
13276 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
13277 return;
13278
13279 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
13280 << HasNullPtrType << T << SourceRange(CC)
13281 << FixItHint::CreateReplacement(RemoveRange: Loc,
13282 Code: S.getFixItZeroLiteralForType(T, Loc));
13283}
13284
13285// Helper function to filter out cases for constant width constant conversion.
13286// Don't warn on unsigned char array initialization or for non-decimal
13287// values.
13288static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13289 SourceLocation CC) {
13290 // If initializing from a constant, and the constant starts with '0',
13291 // then it is a binary, octal, or hexadecimal. Allow these constants
13292 // to fill all the bits, even if there is a sign change.
13293 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
13294 const char FirstLiteralCharacter =
13295 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
13296 if (FirstLiteralCharacter == '0')
13297 return false;
13298 }
13299
13300 // If the CC location points to a '{' and the type is an unsigned char
13301 // type, assume it is an array initialization.
13302 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13303 const char FirstContextCharacter =
13304 S.getSourceManager().getCharacterData(SL: CC)[0];
13305 if (FirstContextCharacter == '{')
13306 return false;
13307 }
13308
13309 return true;
13310}
13311
13312static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13313 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
13314 if (!IL) {
13315 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13316 if (UO->getOpcode() == UO_Minus)
13317 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13318 }
13319 }
13320
13321 return IL;
13322}
13323
13324static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13325 E = E->IgnoreParenImpCasts();
13326 SourceLocation ExprLoc = E->getExprLoc();
13327
13328 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
13329 BinaryOperator::Opcode Opc = BO->getOpcode();
13330 Expr::EvalResult Result;
13331 // Do not diagnose unsigned shifts.
13332 if (Opc == BO_Shl) {
13333 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
13334 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
13335 if (LHS && LHS->getValue() == 0)
13336 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
13337 else if (!E->isValueDependent() && LHS && RHS &&
13338 RHS->getValue().isNonNegative() &&
13339 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
13340 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
13341 << (Result.Val.getInt() != 0);
13342 else if (E->getType()->isSignedIntegerType())
13343 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
13344 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
13345 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
13346 Code: ") != 0");
13347 }
13348 }
13349
13350 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13351 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
13352 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
13353 if (!LHS || !RHS)
13354 return;
13355 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13356 (RHS->getValue() == 0 || RHS->getValue() == 1))
13357 // Do not diagnose common idioms.
13358 return;
13359 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13360 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
13361 }
13362}
13363
13364static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
13365 const Type *Target, Expr *E,
13366 QualType T,
13367 SourceLocation CC) {
13368 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13369 Source != Target);
13370
13371 // Lone surrogates have a distinct representation in UTF-32.
13372 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13373 // so don't warn on such conversion.
13374 if (Source->isChar16Type() && Target->isChar32Type())
13375 return;
13376
13377 Expr::EvalResult Result;
13378 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
13379 InConstantContext: S.isConstantEvaluatedContext())) {
13380 llvm::APSInt Value(32);
13381 Value = Result.Val.getInt();
13382 bool IsASCII = Value <= 0x7F;
13383 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13384 bool ConversionPreservesSemantics =
13385 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13386
13387 if (!ConversionPreservesSemantics) {
13388 auto IsSingleCodeUnitCP = [](const QualType &T,
13389 const llvm::APSInt &Value) {
13390 if (T->isChar8Type())
13391 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13392 if (T->isChar16Type())
13393 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13394 assert(T->isChar32Type());
13395 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13396 };
13397
13398 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
13399 << E->getType() << T
13400 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13401 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
13402 }
13403 } else {
13404 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
13405 S.getASTContext().getIntWidth(T);
13406 DiagnoseImpCast(S, E, T, CContext: CC,
13407 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
13408 : diag::warn_impcast_unicode_char_type);
13409 }
13410}
13411
13412bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
13413 From = Context.getCanonicalType(T: From);
13414 To = Context.getCanonicalType(T: To);
13415 QualType MaybePointee = From->getPointeeType();
13416 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13417 From = MaybePointee;
13418 MaybePointee = To->getPointeeType();
13419 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13420 To = MaybePointee;
13421
13422 if (const auto *FromFn = From->getAs<FunctionType>()) {
13423 if (const auto *ToFn = To->getAs<FunctionType>()) {
13424 if (FromFn->getCFIUncheckedCalleeAttr() &&
13425 !ToFn->getCFIUncheckedCalleeAttr())
13426 return true;
13427 }
13428 }
13429 return false;
13430}
13431
13432void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
13433 bool *ICContext, bool IsListInit) {
13434 if (E->isTypeDependent() || E->isValueDependent()) return;
13435
13436 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
13437 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13438 if (Source == Target) return;
13439 if (Target->isDependentType()) return;
13440
13441 // If the conversion context location is invalid don't complain. We also
13442 // don't want to emit a warning if the issue occurs from the expansion of
13443 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13444 // delay this check as long as possible. Once we detect we are in that
13445 // scenario, we just return.
13446 if (CC.isInvalid())
13447 return;
13448
13449 if (Source->isAtomicType())
13450 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13451
13452 // Diagnose implicit casts to bool.
13453 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
13454 if (isa<StringLiteral>(Val: E))
13455 // Warn on string literal to bool. Checks for string literals in logical
13456 // and expressions, for instance, assert(0 && "error here"), are
13457 // prevented by a check in AnalyzeImplicitConversions().
13458 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13459 diag: diag::warn_impcast_string_literal_to_bool);
13460 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
13461 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
13462 // This covers the literal expressions that evaluate to Objective-C
13463 // objects.
13464 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13465 diag: diag::warn_impcast_objective_c_literal_to_bool);
13466 }
13467 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13468 // Warn on pointer to bool conversion that is always true.
13469 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
13470 Range: SourceRange(CC));
13471 }
13472 }
13473
13474 CheckOverflowBehaviorTypeConversion(E, T, CC);
13475
13476 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13477 // is a typedef for signed char (macOS), then that constant value has to be 1
13478 // or 0.
13479 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
13480 Expr::EvalResult Result;
13481 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
13482 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13483 ObjC().adornBoolConversionDiagWithTernaryFixit(
13484 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13485 << toString(I: Result.Val.getInt(), Radix: 10));
13486 }
13487 return;
13488 }
13489 }
13490
13491 // Check implicit casts from Objective-C collection literals to specialized
13492 // collection types, e.g., NSArray<NSString *> *.
13493 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13494 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13495 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13496 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13497
13498 // Strip complex types.
13499 if (isa<ComplexType>(Val: Source)) {
13500 if (!isa<ComplexType>(Val: Target)) {
13501 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13502 return;
13503
13504 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13505 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13506 diag: diag::err_impcast_incompatible_type);
13507 }
13508
13509 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13510 diag: getLangOpts().CPlusPlus
13511 ? diag::err_impcast_complex_scalar
13512 : diag::warn_impcast_complex_scalar);
13513 }
13514
13515 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13516 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13517 }
13518
13519 // Strip vector types.
13520 if (isa<VectorType>(Val: Source)) {
13521 if (Target->isSveVLSBuiltinType() &&
13522 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13523 SecondType: QualType(Source, 0)) ||
13524 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13525 SecondType: QualType(Source, 0))))
13526 return;
13527
13528 if (Target->isRVVVLSBuiltinType() &&
13529 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13530 SecondType: QualType(Source, 0)) ||
13531 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13532 SecondType: QualType(Source, 0))))
13533 return;
13534
13535 if (!isa<VectorType>(Val: Target)) {
13536 if (SourceMgr.isInSystemMacro(loc: CC))
13537 return;
13538 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13539 }
13540 if (getLangOpts().HLSL &&
13541 Target->castAs<VectorType>()->getNumElements() <
13542 Source->castAs<VectorType>()->getNumElements()) {
13543 // Diagnose vector truncation but don't return. We may also want to
13544 // diagnose an element conversion.
13545 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13546 diag: diag::warn_hlsl_impcast_vector_truncation);
13547 }
13548
13549 // If the vector cast is cast between two vectors of the same size, it is
13550 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13551 if (!getLangOpts().HLSL &&
13552 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13553 return;
13554
13555 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13556 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13557 }
13558 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13559 Target = VecTy->getElementType().getTypePtr();
13560
13561 // Strip matrix types.
13562 if (isa<ConstantMatrixType>(Val: Source)) {
13563 if (Target->isScalarType())
13564 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13565
13566 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13567 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13568 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13569 // Diagnose Matrix truncation but don't return. We may also want to
13570 // diagnose an element conversion.
13571 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13572 diag: diag::warn_hlsl_impcast_matrix_truncation);
13573 }
13574
13575 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13576 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13577 }
13578 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13579 Target = MatTy->getElementType().getTypePtr();
13580
13581 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13582 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13583
13584 // Strip SVE vector types
13585 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13586 // Need the original target type for vector type checks
13587 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13588 // Handle conversion from scalable to fixed when msve-vector-bits is
13589 // specified
13590 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13591 SecondType: QualType(Source, 0)) ||
13592 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13593 SecondType: QualType(Source, 0)))
13594 return;
13595
13596 // If the vector cast is cast between two vectors of the same size, it is
13597 // a bitcast, not a conversion.
13598 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13599 return;
13600
13601 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13602 }
13603
13604 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13605 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13606
13607 // Nothing to diagnose if stripping the wrappers left identical element types
13608 // (e.g. a scalar splatted to a vector of its own type).
13609 if (Source == Target)
13610 return;
13611
13612 // If the source is floating point...
13613 if (SourceBT && SourceBT->isFloatingPoint()) {
13614 // ...and the target is floating point...
13615 if (TargetBT && TargetBT->isFloatingPoint()) {
13616 // ...then warn if we're dropping FP rank.
13617
13618 int Order = getASTContext().getFloatingTypeSemanticOrder(
13619 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13620 if (Order > 0) {
13621 // Don't warn about float constants that are precisely
13622 // representable in the target type.
13623 Expr::EvalResult result;
13624 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13625 // Value might be a float, a float vector, or a float complex.
13626 if (IsSameFloatAfterCast(
13627 value: result.Val,
13628 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13629 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13630 return;
13631 }
13632
13633 if (SourceMgr.isInSystemMacro(loc: CC))
13634 return;
13635
13636 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13637 }
13638 // ... or possibly if we're increasing rank, too
13639 else if (Order < 0) {
13640 if (SourceMgr.isInSystemMacro(loc: CC))
13641 return;
13642
13643 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13644 }
13645 return;
13646 }
13647
13648 // If the target is integral, always warn.
13649 if (TargetBT && TargetBT->isInteger()) {
13650 if (SourceMgr.isInSystemMacro(loc: CC))
13651 return;
13652
13653 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13654 }
13655
13656 // Detect the case where a call result is converted from floating-point to
13657 // to bool, and the final argument to the call is converted from bool, to
13658 // discover this typo:
13659 //
13660 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13661 //
13662 // FIXME: This is an incredibly special case; is there some more general
13663 // way to detect this class of misplaced-parentheses bug?
13664 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13665 // Check last argument of function call to see if it is an
13666 // implicit cast from a type matching the type the result
13667 // is being cast to.
13668 CallExpr *CEx = cast<CallExpr>(Val: E);
13669 if (unsigned NumArgs = CEx->getNumArgs()) {
13670 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13671 Expr *InnerE = LastA->IgnoreParenImpCasts();
13672 if (isa<ImplicitCastExpr>(Val: LastA) &&
13673 InnerE->getType()->isBooleanType()) {
13674 // Warn on this floating-point to bool conversion
13675 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13676 diag: diag::warn_impcast_floating_point_to_bool);
13677 }
13678 }
13679 }
13680 return;
13681 }
13682
13683 // Valid casts involving fixed point types should be accounted for here.
13684 if (Source->isFixedPointType()) {
13685 if (Target->isUnsaturatedFixedPointType()) {
13686 Expr::EvalResult Result;
13687 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13688 InConstantContext: isConstantEvaluatedContext())) {
13689 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13690 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13691 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13692 if (Value > MaxVal || Value < MinVal) {
13693 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13694 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13695 << Value.toString() << T
13696 << E->getSourceRange()
13697 << clang::SourceRange(CC));
13698 return;
13699 }
13700 }
13701 } else if (Target->isIntegerType()) {
13702 Expr::EvalResult Result;
13703 if (!isConstantEvaluatedContext() &&
13704 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13705 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13706
13707 bool Overflowed;
13708 llvm::APSInt IntResult = FXResult.convertToInt(
13709 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13710 Overflow: &Overflowed);
13711
13712 if (Overflowed) {
13713 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13714 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13715 << FXResult.toString() << T
13716 << E->getSourceRange()
13717 << clang::SourceRange(CC));
13718 return;
13719 }
13720 }
13721 }
13722 } else if (Target->isUnsaturatedFixedPointType()) {
13723 if (Source->isIntegerType()) {
13724 Expr::EvalResult Result;
13725 if (!isConstantEvaluatedContext() &&
13726 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13727 llvm::APSInt Value = Result.Val.getInt();
13728
13729 bool Overflowed;
13730 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13731 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13732
13733 if (Overflowed) {
13734 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13735 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13736 << toString(I: Value, /*Radix=*/10) << T
13737 << E->getSourceRange()
13738 << clang::SourceRange(CC));
13739 return;
13740 }
13741 }
13742 }
13743 }
13744
13745 // If we are casting an integer type to a floating point type without
13746 // initialization-list syntax, we might lose accuracy if the floating
13747 // point type has a narrower significand than the integer type.
13748 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13749 TargetBT->isFloatingType() && !IsListInit) {
13750 // Determine the number of precision bits in the source integer type.
13751 std::optional<IntRange> SourceRange =
13752 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13753 /*Approximate=*/true);
13754 if (!SourceRange)
13755 return;
13756 unsigned int SourcePrecision = SourceRange->Width;
13757
13758 // Determine the number of precision bits in the
13759 // target floating point type.
13760 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13761 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13762
13763 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13764 SourcePrecision > TargetPrecision) {
13765
13766 if (std::optional<llvm::APSInt> SourceInt =
13767 E->getIntegerConstantExpr(Ctx: Context)) {
13768 // If the source integer is a constant, convert it to the target
13769 // floating point type. Issue a warning if the value changes
13770 // during the whole conversion.
13771 llvm::APFloat TargetFloatValue(
13772 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13773 llvm::APFloat::opStatus ConversionStatus =
13774 TargetFloatValue.convertFromAPInt(
13775 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13776 RM: llvm::APFloat::rmNearestTiesToEven);
13777
13778 if (ConversionStatus != llvm::APFloat::opOK) {
13779 SmallString<32> PrettySourceValue;
13780 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13781 SmallString<32> PrettyTargetValue;
13782 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13783
13784 DiagRuntimeBehavior(
13785 Loc: E->getExprLoc(), Statement: E,
13786 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13787 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13788 << E->getSourceRange() << clang::SourceRange(CC));
13789 }
13790 } else {
13791 // Otherwise, the implicit conversion may lose precision.
13792 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13793 diag: diag::warn_impcast_integer_float_precision);
13794 }
13795 }
13796 }
13797
13798 DiagnoseNullConversion(S&: *this, E, T, CC);
13799
13800 DiscardMisalignedMemberAddress(T: Target, E);
13801
13802 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13803 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13804 return;
13805 }
13806
13807 if (Target->isBooleanType())
13808 DiagnoseIntInBoolContext(S&: *this, E);
13809
13810 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13811 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13812 << QualType(Source, 0) << QualType(Target, 0);
13813 }
13814
13815 if (!Source->isIntegerType() || !Target->isIntegerType())
13816 return;
13817
13818 // TODO: remove this early return once the false positives for constant->bool
13819 // in templates, macros, etc, are reduced or removed.
13820 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13821 return;
13822
13823 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13824 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13825 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13826 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13827 << E->getType());
13828 }
13829 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13830 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13831 if (!LikelySourceRange)
13832 return;
13833
13834 IntRange SourceTypeRange =
13835 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13836 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13837
13838 if (LikelySourceRange->Width > TargetRange.Width) {
13839 // Check if target is a wrapping OBT - if so, don't warn about constant
13840 // conversion as this type may be used intentionally with implicit
13841 // truncation, especially during assignments.
13842 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13843 if (TargetOBT->isWrapKind()) {
13844 return;
13845 }
13846 }
13847
13848 // Check if source expression has an explicit __ob_wrap cast because if so,
13849 // wrapping was explicitly requested and we shouldn't warn
13850 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13851 if (SourceOBT->isWrapKind()) {
13852 return;
13853 }
13854 }
13855
13856 // If the source is a constant, use a default-on diagnostic.
13857 // TODO: this should happen for bitfield stores, too.
13858 Expr::EvalResult Result;
13859 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13860 InConstantContext: isConstantEvaluatedContext())) {
13861 llvm::APSInt Value(32);
13862 Value = Result.Val.getInt();
13863
13864 if (SourceMgr.isInSystemMacro(loc: CC))
13865 return;
13866
13867 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13868 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13869
13870 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13871 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13872 << PrettySourceValue << PrettyTargetValue
13873 << E->getType() << T << E->getSourceRange()
13874 << SourceRange(CC));
13875 return;
13876 }
13877
13878 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13879 if (SourceMgr.isInSystemMacro(loc: CC))
13880 return;
13881
13882 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13883 if (UO->getOpcode() == UO_Minus)
13884 return DiagnoseImpCast(
13885 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13886 }
13887
13888 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13889 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13890 /* pruneControlFlow */ PruneControlFlow: true);
13891 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13892 diag: diag::warn_impcast_integer_precision);
13893 }
13894
13895 if (TargetRange.Width > SourceTypeRange.Width) {
13896 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13897 if (UO->getOpcode() == UO_Minus)
13898 if (Source->isUnsignedIntegerType()) {
13899 if (Target->isUnsignedIntegerType())
13900 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13901 diag: diag::warn_impcast_high_order_zero_bits);
13902 if (Target->isSignedIntegerType())
13903 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13904 diag: diag::warn_impcast_nonnegative_result);
13905 }
13906 }
13907
13908 if (TargetRange.Width == LikelySourceRange->Width &&
13909 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13910 Source->isSignedIntegerType()) {
13911 // Warn when doing a signed to signed conversion, warn if the positive
13912 // source value is exactly the width of the target type, which will
13913 // cause a negative value to be stored.
13914
13915 Expr::EvalResult Result;
13916 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13917 !SourceMgr.isInSystemMacro(loc: CC)) {
13918 llvm::APSInt Value = Result.Val.getInt();
13919 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13920 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13921 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13922
13923 Diag(Loc: E->getExprLoc(),
13924 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13925 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13926 << E->getSourceRange() << SourceRange(CC));
13927 return;
13928 }
13929 }
13930
13931 // Fall through for non-constants to give a sign conversion warning.
13932 }
13933
13934 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13935 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13936 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13937 LikelySourceRange->Width == TargetRange.Width))) {
13938 if (SourceMgr.isInSystemMacro(loc: CC))
13939 return;
13940
13941 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13942 TargetBT->isInteger() &&
13943 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13944 return;
13945 }
13946
13947 unsigned DiagID = diag::warn_impcast_integer_sign;
13948
13949 // Traditionally, gcc has warned about this under -Wsign-compare.
13950 // We also want to warn about it in -Wconversion.
13951 // So if -Wconversion is off, use a completely identical diagnostic
13952 // in the sign-compare group.
13953 // The conditional-checking code will
13954 if (ICContext) {
13955 DiagID = diag::warn_impcast_integer_sign_conditional;
13956 *ICContext = true;
13957 }
13958
13959 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13960 }
13961
13962 // If we're implicitly converting from an integer into an enumeration, that
13963 // is valid in C but invalid in C++.
13964 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13965 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13966 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13967 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13968
13969 // Diagnose conversions between different enumeration types.
13970 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13971 // type, to give us better diagnostics.
13972 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13973
13974 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13975 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13976 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13977 TargetEnum->getDecl()->hasNameForLinkage() &&
13978 SourceEnum != TargetEnum) {
13979 if (SourceMgr.isInSystemMacro(loc: CC))
13980 return;
13981
13982 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13983 diag: diag::warn_impcast_different_enum_types);
13984 }
13985}
13986
13987static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13988 SourceLocation CC, QualType T);
13989
13990static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13991 SourceLocation CC, bool &ICContext) {
13992 E = E->IgnoreParenImpCasts();
13993 // Diagnose incomplete type for second or third operand in C.
13994 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13995 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13996
13997 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13998 return CheckConditionalOperator(S, E: CO, CC, T);
13999
14000 AnalyzeImplicitConversions(S, E, CC);
14001 if (E->getType() != T)
14002 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
14003}
14004
14005static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14006 SourceLocation CC, QualType T) {
14007 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
14008
14009 Expr *TrueExpr = E->getTrueExpr();
14010 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
14011 TrueExpr = BCO->getCommon();
14012
14013 bool Suspicious = false;
14014 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
14015 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
14016
14017 if (T->isBooleanType())
14018 DiagnoseIntInBoolContext(S, E);
14019
14020 // If -Wconversion would have warned about either of the candidates
14021 // for a signedness conversion to the context type...
14022 if (!Suspicious) return;
14023
14024 // ...but it's currently ignored...
14025 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
14026 return;
14027
14028 // ...then check whether it would have warned about either of the
14029 // candidates for a signedness conversion to the condition type.
14030 if (E->getType() == T) return;
14031
14032 Suspicious = false;
14033 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
14034 ICContext: &Suspicious);
14035 if (!Suspicious)
14036 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
14037 T: E->getType(), CC, ICContext: &Suspicious);
14038}
14039
14040/// Check conversion of given expression to boolean.
14041/// Input argument E is a logical expression.
14042static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
14043 // Run the bool-like conversion checks only for C since there bools are
14044 // still not used as the return type from "boolean" operators or as the input
14045 // type for conditional operators.
14046 if (S.getLangOpts().CPlusPlus)
14047 return;
14048 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
14049 return;
14050 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
14051}
14052
14053namespace {
14054struct AnalyzeImplicitConversionsWorkItem {
14055 Expr *E;
14056 SourceLocation CC;
14057 bool IsListInit;
14058};
14059}
14060
14061static void CheckCommaOperand(
14062 Sema &S, Expr *E, QualType T, SourceLocation CC,
14063 bool ExtraCheckForImplicitConversion,
14064 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14065 E = E->IgnoreParenImpCasts();
14066 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
14067
14068 if (ExtraCheckForImplicitConversion && E->getType() != T)
14069 S.CheckImplicitConversion(E, T, CC);
14070}
14071
14072/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14073/// that should be visited are added to WorkList.
14074static void AnalyzeImplicitConversions(
14075 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14076 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14077 Expr *OrigE = Item.E;
14078 SourceLocation CC = Item.CC;
14079
14080 QualType T = OrigE->getType();
14081 Expr *E = OrigE->IgnoreParenImpCasts();
14082
14083 // Propagate whether we are in a C++ list initialization expression.
14084 // If so, we do not issue warnings for implicit int-float conversion
14085 // precision loss, because C++11 narrowing already handles it.
14086 //
14087 // HLSL's initialization lists are special, so they shouldn't observe the C++
14088 // behavior here.
14089 bool IsListInit =
14090 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
14091 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14092
14093 if (E->isTypeDependent() || E->isValueDependent())
14094 return;
14095
14096 Expr *SourceExpr = E;
14097 // Examine, but don't traverse into the source expression of an
14098 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14099 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14100 // evaluate it in the context of checking the specific conversion to T though.
14101 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
14102 if (auto *Src = OVE->getSourceExpr())
14103 SourceExpr = Src;
14104
14105 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
14106 if (UO->getOpcode() == UO_Not &&
14107 UO->getSubExpr()->isKnownToHaveBooleanValue())
14108 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
14109 << OrigE->getSourceRange() << T->isBooleanType()
14110 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
14111
14112 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
14113 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14114 BO->getLHS()->isKnownToHaveBooleanValue() &&
14115 BO->getRHS()->isKnownToHaveBooleanValue() &&
14116 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
14117 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
14118 SourceManager &SM = S.getSourceManager();
14119 const LangOptions &LO = S.getLangOpts();
14120 SourceLocation BLoc = BO->getOperatorLoc();
14121 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
14122 StringRef SR = clang::Lexer::getSourceText(
14123 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
14124 // To reduce false positives, only issue the diagnostic if the operator
14125 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14126 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14127 // in C, along with other macro spellings the user might invent.
14128 if (SR.str() == "&" || SR.str() == "|") {
14129
14130 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
14131 << (BO->getOpcode() == BO_And ? "&" : "|")
14132 << OrigE->getSourceRange()
14133 << FixItHint::CreateReplacement(
14134 RemoveRange: BO->getOperatorLoc(),
14135 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
14136 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
14137 }
14138 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14139 /// Analyze the given comma operator. The basic idea behind the analysis
14140 /// is to analyze the left and right operands slightly differently. The
14141 /// left operand needs to check whether the operand itself has an implicit
14142 /// conversion, but not whether the left operand induces an implicit
14143 /// conversion for the entire comma expression itself. This is similar to
14144 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14145 /// were directly used for the implicit conversion check.
14146 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
14147 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14148 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
14149 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14150 return;
14151 }
14152 }
14153
14154 // For conditional operators, we analyze the arguments as if they
14155 // were being fed directly into the output.
14156 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
14157 CheckConditionalOperator(S, E: CO, CC, T);
14158 return;
14159 }
14160
14161 // Check implicit argument conversions for function calls.
14162 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
14163 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
14164
14165 // Go ahead and check any implicit conversions we might have skipped.
14166 // The non-canonical typecheck is just an optimization;
14167 // CheckImplicitConversion will filter out dead implicit conversions.
14168 if (SourceExpr->getType() != T)
14169 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
14170
14171 // Now continue drilling into this expression.
14172
14173 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
14174 // The bound subexpressions in a PseudoObjectExpr are not reachable
14175 // as transitive children.
14176 // FIXME: Use a more uniform representation for this.
14177 for (auto *SE : POE->semantics())
14178 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
14179 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14180 }
14181
14182 // Skip past explicit casts.
14183 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
14184 E = CE->getSubExpr();
14185 // In the special case of a C++ function-style cast with braces,
14186 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14187 // initializer. This InitListExpr basically belongs to the cast itself, so
14188 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14189 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
14190 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
14191 if (InitListE->getNumInits() == 1) {
14192 E = InitListE->getInit(Init: 0);
14193 }
14194 }
14195 }
14196 E = E->IgnoreParenImpCasts();
14197 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14198 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
14199 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
14200 return;
14201 }
14202
14203 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
14204 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
14205 // The base expression is only used to initialize the parameter for
14206 // arguments to `inout` parameters, so we only traverse down the base
14207 // expression for `inout` cases.
14208 if (OutArgE->isInOut())
14209 WorkList.push_back(
14210 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14211 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
14212 return;
14213 }
14214
14215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14216 // Do a somewhat different check with comparison operators.
14217 if (BO->isComparisonOp())
14218 return AnalyzeComparison(S, E: BO);
14219
14220 // And with simple assignments.
14221 if (BO->getOpcode() == BO_Assign)
14222 return AnalyzeAssignment(S, E: BO);
14223 // And with compound assignments.
14224 if (BO->isAssignmentOp())
14225 return AnalyzeCompoundAssignment(S, E: BO);
14226 }
14227
14228 // These break the otherwise-useful invariant below. Fortunately,
14229 // we don't really need to recurse into them, because any internal
14230 // expressions should have been analyzed already when they were
14231 // built into statements.
14232 if (isa<StmtExpr>(Val: E)) return;
14233
14234 // Don't descend into unevaluated contexts.
14235 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
14236
14237 // Now just recurse over the expression's children.
14238 CC = E->getExprLoc();
14239 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
14240 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14241 for (Stmt *SubStmt : E->children()) {
14242 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
14243 if (!ChildExpr)
14244 continue;
14245
14246 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
14247 if (ChildExpr == CSE->getOperand())
14248 // Do not recurse over a CoroutineSuspendExpr's operand.
14249 // The operand is also a subexpression of getCommonExpr(), and
14250 // recursing into it directly would produce duplicate diagnostics.
14251 continue;
14252
14253 if (IsLogicalAndOperator &&
14254 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
14255 // Ignore checking string literals that are in logical and operators.
14256 // This is a common pattern for asserts.
14257 continue;
14258 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
14259 }
14260
14261 if (BO && BO->isLogicalOp()) {
14262 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14263 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14264 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14265
14266 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14267 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14268 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14269 }
14270
14271 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
14272 if (U->getOpcode() == UO_LNot) {
14273 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
14274 } else if (U->getOpcode() != UO_AddrOf) {
14275 if (U->getSubExpr()->getType()->isAtomicType())
14276 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
14277 DiagID: diag::warn_atomic_implicit_seq_cst);
14278 }
14279 }
14280}
14281
14282/// AnalyzeImplicitConversions - Find and report any interesting
14283/// implicit conversions in the given expression. There are a couple
14284/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14285static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14286 bool IsListInit/*= false*/) {
14287 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14288 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
14289 while (!WorkList.empty())
14290 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
14291}
14292
14293// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14294// Returns true when emitting a warning about taking the address of a reference.
14295static bool CheckForReference(Sema &SemaRef, const Expr *E,
14296 const PartialDiagnostic &PD) {
14297 E = E->IgnoreParenImpCasts();
14298
14299 const FunctionDecl *FD = nullptr;
14300
14301 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14302 if (!DRE->getDecl()->getType()->isReferenceType())
14303 return false;
14304 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14305 if (!M->getMemberDecl()->getType()->isReferenceType())
14306 return false;
14307 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
14308 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
14309 return false;
14310 FD = Call->getDirectCallee();
14311 } else {
14312 return false;
14313 }
14314
14315 SemaRef.Diag(Loc: E->getExprLoc(), PD);
14316
14317 // If possible, point to location of function.
14318 if (FD) {
14319 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
14320 }
14321
14322 return true;
14323}
14324
14325// Returns true if the SourceLocation is expanded from any macro body.
14326// Returns false if the SourceLocation is invalid, is from not in a macro
14327// expansion, or is from expanded from a top-level macro argument.
14328static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14329 if (Loc.isInvalid())
14330 return false;
14331
14332 while (Loc.isMacroID()) {
14333 if (SM.isMacroBodyExpansion(Loc))
14334 return true;
14335 Loc = SM.getImmediateMacroCallerLoc(Loc);
14336 }
14337
14338 return false;
14339}
14340
14341void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14342 Expr::NullPointerConstantKind NullKind,
14343 bool IsEqual, SourceRange Range) {
14344 if (!E)
14345 return;
14346
14347 // Don't warn inside macros.
14348 if (E->getExprLoc().isMacroID()) {
14349 const SourceManager &SM = getSourceManager();
14350 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
14351 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
14352 return;
14353 }
14354 E = E->IgnoreImpCasts();
14355
14356 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14357
14358 if (isa<CXXThisExpr>(Val: E)) {
14359 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14360 : diag::warn_this_bool_conversion;
14361 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14362 return;
14363 }
14364
14365 bool IsAddressOf = false;
14366
14367 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
14368 if (UO->getOpcode() != UO_AddrOf)
14369 return;
14370 IsAddressOf = true;
14371 E = UO->getSubExpr();
14372 }
14373
14374 if (IsAddressOf) {
14375 unsigned DiagID = IsCompare
14376 ? diag::warn_address_of_reference_null_compare
14377 : diag::warn_address_of_reference_bool_conversion;
14378 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14379 << IsEqual;
14380 if (CheckForReference(SemaRef&: *this, E, PD)) {
14381 return;
14382 }
14383 }
14384
14385 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14386 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
14387 std::string Str;
14388 llvm::raw_string_ostream S(Str);
14389 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14390 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14391 : diag::warn_cast_nonnull_to_bool;
14392 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
14393 << E->getSourceRange() << Range << IsEqual;
14394 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
14395 };
14396
14397 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14398 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
14399 if (auto *Callee = Call->getDirectCallee()) {
14400 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14401 ComplainAboutNonnullParamOrCall(A);
14402 return;
14403 }
14404 }
14405 }
14406
14407 // Complain if we are converting a lambda expression to a boolean value
14408 // outside of instantiation.
14409 if (!inTemplateInstantiation()) {
14410 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
14411 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14412 MRecordDecl && MRecordDecl->isLambda()) {
14413 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
14414 << /*LambdaPointerConversionOperatorType=*/3
14415 << MRecordDecl->getSourceRange() << Range << IsEqual;
14416 return;
14417 }
14418 }
14419 }
14420
14421 // Expect to find a single Decl. Skip anything more complicated.
14422 ValueDecl *D = nullptr;
14423 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
14424 D = R->getDecl();
14425 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14426 D = M->getMemberDecl();
14427 }
14428
14429 // Weak Decls can be null.
14430 if (!D || D->isWeak())
14431 return;
14432
14433 // Check for parameter decl with nonnull attribute
14434 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
14435 if (getCurFunction() &&
14436 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
14437 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14438 ComplainAboutNonnullParamOrCall(A);
14439 return;
14440 }
14441
14442 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
14443 // Skip function template not specialized yet.
14444 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14445 return;
14446 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
14447 assert(ParamIter != FD->param_end());
14448 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
14449
14450 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14451 if (!NonNull->args_size()) {
14452 ComplainAboutNonnullParamOrCall(NonNull);
14453 return;
14454 }
14455
14456 for (const ParamIdx &ArgNo : NonNull->args()) {
14457 if (ArgNo.getASTIndex() == ParamNo) {
14458 ComplainAboutNonnullParamOrCall(NonNull);
14459 return;
14460 }
14461 }
14462 }
14463 }
14464 }
14465 }
14466
14467 QualType T = D->getType();
14468 // A reference to a function is never null either; look through it.
14469 const bool IsFunctionReference =
14470 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14471 if (IsFunctionReference)
14472 T = T->getPointeeType();
14473 const bool IsArray = T->isArrayType();
14474 const bool IsFunction = T->isFunctionType();
14475
14476 // Address of function is used to silence the function warning.
14477 if (IsAddressOf && IsFunction) {
14478 return;
14479 }
14480
14481 // Found nothing.
14482 if (!IsAddressOf && !IsFunction && !IsArray)
14483 return;
14484
14485 // Pretty print the expression for the diagnostic.
14486 std::string Str;
14487 llvm::raw_string_ostream S(Str);
14488 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14489
14490 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14491 : diag::warn_impcast_pointer_to_bool;
14492 enum {
14493 AddressOf,
14494 FunctionPointer,
14495 ArrayPointer
14496 } DiagType;
14497 if (IsAddressOf)
14498 DiagType = AddressOf;
14499 else if (IsFunction)
14500 DiagType = FunctionPointer;
14501 else if (IsArray)
14502 DiagType = ArrayPointer;
14503 else
14504 llvm_unreachable("Could not determine diagnostic.");
14505 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14506 << Range << IsEqual;
14507
14508 // The fix-it notes below only apply to a bare function name, not a reference.
14509 if (!IsFunction || IsFunctionReference)
14510 return;
14511
14512 // Suggest '&' to silence the function warning.
14513 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14514 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14515
14516 // Check to see if '()' fixit should be emitted.
14517 QualType ReturnType;
14518 UnresolvedSet<4> NonTemplateOverloads;
14519 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14520 if (ReturnType.isNull())
14521 return;
14522
14523 if (IsCompare) {
14524 // There are two cases here. If there is null constant, the only suggest
14525 // for a pointer return type. If the null is 0, then suggest if the return
14526 // type is a pointer or an integer type.
14527 if (!ReturnType->isPointerType()) {
14528 if (NullKind == Expr::NPCK_ZeroExpression ||
14529 NullKind == Expr::NPCK_ZeroLiteral) {
14530 if (!ReturnType->isIntegerType())
14531 return;
14532 } else {
14533 return;
14534 }
14535 }
14536 } else { // !IsCompare
14537 // For function to bool, only suggest if the function pointer has bool
14538 // return type.
14539 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14540 return;
14541 }
14542 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14543 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14544}
14545
14546bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14547 SourceLocation CC) {
14548 QualType Source = E->getType();
14549 QualType Target = T;
14550
14551 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14552 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14553 // Overflow behavior type is being stripped - issue warning
14554 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14555 Target->isUnsignedIntegerType()) {
14556 // For unsigned wrap to unsigned conversions, use pedantic version
14557 unsigned DiagId =
14558 InOverflowBehaviorAssignmentContext
14559 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14560 : diag::warn_impcast_overflow_behavior_pedantic;
14561 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14562 } else {
14563 unsigned DiagId = InOverflowBehaviorAssignmentContext
14564 ? diag::warn_impcast_overflow_behavior_assignment
14565 : diag::warn_impcast_overflow_behavior;
14566 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14567 }
14568 }
14569 }
14570
14571 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14572 if (TargetOBT->isWrapKind()) {
14573 return true;
14574 }
14575 }
14576
14577 return false;
14578}
14579
14580void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14581 // Don't diagnose in unevaluated contexts.
14582 if (isUnevaluatedContext())
14583 return;
14584
14585 // Don't diagnose for value- or type-dependent expressions.
14586 if (E->isTypeDependent() || E->isValueDependent())
14587 return;
14588
14589 // Check for array bounds violations in cases where the check isn't triggered
14590 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14591 // ArraySubscriptExpr is on the RHS of a variable initialization.
14592 CheckArrayAccess(E);
14593
14594 // This is not the right CC for (e.g.) a variable initialization.
14595 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14596}
14597
14598void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14599 ::CheckBoolLikeConversion(S&: *this, E, CC);
14600}
14601
14602void Sema::CheckForIntOverflow (const Expr *E) {
14603 // Use a work list to deal with nested struct initializers.
14604 SmallVector<const Expr *, 2> Exprs(1, E);
14605
14606 do {
14607 const Expr *OriginalE = Exprs.pop_back_val();
14608 const Expr *E = OriginalE->IgnoreParenCasts();
14609
14610 if (isa<BinaryOperator>(Val: E) ||
14611 (isa<UnaryOperator>(Val: E) && cast<UnaryOperator>(Val: E)->canOverflow())) {
14612 E->EvaluateForOverflow(Ctx: Context);
14613 continue;
14614 }
14615
14616 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14617 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14618 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14619 E->EvaluateForOverflow(Ctx: Context);
14620 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14621 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14622 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14623 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14624 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14625 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14626 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14627 Exprs.push_back(Elt: Temporary->getSubExpr());
14628 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14629 Exprs.push_back(Elt: Array->getIdx());
14630 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14631 Exprs.push_back(Elt: Compound->getInitializer());
14632 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14633 New && New->isArray()) {
14634 if (auto ArraySize = New->getArraySize())
14635 Exprs.push_back(Elt: *ArraySize);
14636 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14637 Exprs.push_back(Elt: MTE->getSubExpr());
14638 } while (!Exprs.empty());
14639}
14640
14641namespace {
14642
14643/// Visitor for expressions which looks for unsequenced operations on the
14644/// same object.
14645class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14646 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14647
14648 /// A tree of sequenced regions within an expression. Two regions are
14649 /// unsequenced if one is an ancestor or a descendent of the other. When we
14650 /// finish processing an expression with sequencing, such as a comma
14651 /// expression, we fold its tree nodes into its parent, since they are
14652 /// unsequenced with respect to nodes we will visit later.
14653 class SequenceTree {
14654 struct Value {
14655 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14656 unsigned Parent : 31;
14657 LLVM_PREFERRED_TYPE(bool)
14658 unsigned Merged : 1;
14659 };
14660 SmallVector<Value, 8> Values;
14661
14662 public:
14663 /// A region within an expression which may be sequenced with respect
14664 /// to some other region.
14665 class Seq {
14666 friend class SequenceTree;
14667
14668 unsigned Index;
14669
14670 explicit Seq(unsigned N) : Index(N) {}
14671
14672 public:
14673 Seq() : Index(0) {}
14674 };
14675
14676 SequenceTree() { Values.push_back(Elt: Value(0)); }
14677 Seq root() const { return Seq(0); }
14678
14679 /// Create a new sequence of operations, which is an unsequenced
14680 /// subset of \p Parent. This sequence of operations is sequenced with
14681 /// respect to other children of \p Parent.
14682 Seq allocate(Seq Parent) {
14683 Values.push_back(Elt: Value(Parent.Index));
14684 return Seq(Values.size() - 1);
14685 }
14686
14687 /// Merge a sequence of operations into its parent.
14688 void merge(Seq S) {
14689 Values[S.Index].Merged = true;
14690 }
14691
14692 /// Determine whether two operations are unsequenced. This operation
14693 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14694 /// should have been merged into its parent as appropriate.
14695 bool isUnsequenced(Seq Cur, Seq Old) {
14696 unsigned C = representative(K: Cur.Index);
14697 unsigned Target = representative(K: Old.Index);
14698 while (C >= Target) {
14699 if (C == Target)
14700 return true;
14701 C = Values[C].Parent;
14702 }
14703 return false;
14704 }
14705
14706 private:
14707 /// Pick a representative for a sequence.
14708 unsigned representative(unsigned K) {
14709 if (Values[K].Merged)
14710 // Perform path compression as we go.
14711 return Values[K].Parent = representative(K: Values[K].Parent);
14712 return K;
14713 }
14714 };
14715
14716 /// An object for which we can track unsequenced uses.
14717 using Object = const NamedDecl *;
14718
14719 /// Different flavors of object usage which we track. We only track the
14720 /// least-sequenced usage of each kind.
14721 enum UsageKind {
14722 /// A read of an object. Multiple unsequenced reads are OK.
14723 UK_Use,
14724
14725 /// A modification of an object which is sequenced before the value
14726 /// computation of the expression, such as ++n in C++.
14727 UK_ModAsValue,
14728
14729 /// A modification of an object which is not sequenced before the value
14730 /// computation of the expression, such as n++.
14731 UK_ModAsSideEffect,
14732
14733 UK_Count = UK_ModAsSideEffect + 1
14734 };
14735
14736 /// Bundle together a sequencing region and the expression corresponding
14737 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14738 struct Usage {
14739 const Expr *UsageExpr = nullptr;
14740 SequenceTree::Seq Seq;
14741
14742 Usage() = default;
14743 };
14744
14745 struct UsageInfo {
14746 Usage Uses[UK_Count];
14747
14748 /// Have we issued a diagnostic for this object already?
14749 bool Diagnosed = false;
14750
14751 UsageInfo();
14752 };
14753 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14754
14755 Sema &SemaRef;
14756
14757 /// Sequenced regions within the expression.
14758 SequenceTree Tree;
14759
14760 /// Declaration modifications and references which we have seen.
14761 UsageInfoMap UsageMap;
14762
14763 /// The region we are currently within.
14764 SequenceTree::Seq Region;
14765
14766 /// Filled in with declarations which were modified as a side-effect
14767 /// (that is, post-increment operations).
14768 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14769
14770 /// Expressions to check later. We defer checking these to reduce
14771 /// stack usage.
14772 SmallVectorImpl<const Expr *> &WorkList;
14773
14774 /// RAII object wrapping the visitation of a sequenced subexpression of an
14775 /// expression. At the end of this process, the side-effects of the evaluation
14776 /// become sequenced with respect to the value computation of the result, so
14777 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14778 /// UK_ModAsValue.
14779 struct SequencedSubexpression {
14780 SequencedSubexpression(SequenceChecker &Self)
14781 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14782 Self.ModAsSideEffect = &ModAsSideEffect;
14783 }
14784
14785 ~SequencedSubexpression() {
14786 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14787 // Add a new usage with usage kind UK_ModAsValue, and then restore
14788 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14789 // the previous one was empty).
14790 UsageInfo &UI = Self.UsageMap[M.first];
14791 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14792 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14793 SideEffectUsage = M.second;
14794 }
14795 Self.ModAsSideEffect = OldModAsSideEffect;
14796 }
14797
14798 SequenceChecker &Self;
14799 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14800 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14801 };
14802
14803 /// RAII object wrapping the visitation of a subexpression which we might
14804 /// choose to evaluate as a constant. If any subexpression is evaluated and
14805 /// found to be non-constant, this allows us to suppress the evaluation of
14806 /// the outer expression.
14807 class EvaluationTracker {
14808 public:
14809 EvaluationTracker(SequenceChecker &Self)
14810 : Self(Self), Prev(Self.EvalTracker) {
14811 Self.EvalTracker = this;
14812 }
14813
14814 ~EvaluationTracker() {
14815 Self.EvalTracker = Prev;
14816 if (Prev)
14817 Prev->EvalOK &= EvalOK;
14818 }
14819
14820 bool evaluate(const Expr *E, bool &Result) {
14821 if (!EvalOK || E->isValueDependent())
14822 return false;
14823 EvalOK = E->EvaluateAsBooleanCondition(
14824 Result, Ctx: Self.SemaRef.Context,
14825 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14826 return EvalOK;
14827 }
14828
14829 private:
14830 SequenceChecker &Self;
14831 EvaluationTracker *Prev;
14832 bool EvalOK = true;
14833 } *EvalTracker = nullptr;
14834
14835 /// Find the object which is produced by the specified expression,
14836 /// if any.
14837 Object getObject(const Expr *E, bool Mod) const {
14838 E = E->IgnoreParenCasts();
14839 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14840 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14841 return getObject(E: UO->getSubExpr(), Mod);
14842 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14843 if (BO->getOpcode() == BO_Comma)
14844 return getObject(E: BO->getRHS(), Mod);
14845 if (Mod && BO->isAssignmentOp())
14846 return getObject(E: BO->getLHS(), Mod);
14847 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14848 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14849 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14850 return ME->getMemberDecl();
14851 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14852 // FIXME: If this is a reference, map through to its value.
14853 return DRE->getDecl();
14854 return nullptr;
14855 }
14856
14857 /// Note that an object \p O was modified or used by an expression
14858 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14859 /// the object \p O as obtained via the \p UsageMap.
14860 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14861 // Get the old usage for the given object and usage kind.
14862 Usage &U = UI.Uses[UK];
14863 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14864 // If we have a modification as side effect and are in a sequenced
14865 // subexpression, save the old Usage so that we can restore it later
14866 // in SequencedSubexpression::~SequencedSubexpression.
14867 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14868 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14869 // Then record the new usage with the current sequencing region.
14870 U.UsageExpr = UsageExpr;
14871 U.Seq = Region;
14872 }
14873 }
14874
14875 /// Check whether a modification or use of an object \p O in an expression
14876 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14877 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14878 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14879 /// usage and false we are checking for a mod-use unsequenced usage.
14880 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14881 UsageKind OtherKind, bool IsModMod) {
14882 if (UI.Diagnosed)
14883 return;
14884
14885 const Usage &U = UI.Uses[OtherKind];
14886 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14887 return;
14888
14889 const Expr *Mod = U.UsageExpr;
14890 const Expr *ModOrUse = UsageExpr;
14891 if (OtherKind == UK_Use)
14892 std::swap(a&: Mod, b&: ModOrUse);
14893
14894 SemaRef.DiagRuntimeBehavior(
14895 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14896 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14897 : diag::warn_unsequenced_mod_use)
14898 << O << SourceRange(ModOrUse->getExprLoc()));
14899 UI.Diagnosed = true;
14900 }
14901
14902 // A note on note{Pre, Post}{Use, Mod}:
14903 //
14904 // (It helps to follow the algorithm with an expression such as
14905 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14906 // operations before C++17 and both are well-defined in C++17).
14907 //
14908 // When visiting a node which uses/modify an object we first call notePreUse
14909 // or notePreMod before visiting its sub-expression(s). At this point the
14910 // children of the current node have not yet been visited and so the eventual
14911 // uses/modifications resulting from the children of the current node have not
14912 // been recorded yet.
14913 //
14914 // We then visit the children of the current node. After that notePostUse or
14915 // notePostMod is called. These will 1) detect an unsequenced modification
14916 // as side effect (as in "k++ + k") and 2) add a new usage with the
14917 // appropriate usage kind.
14918 //
14919 // We also have to be careful that some operation sequences modification as
14920 // side effect as well (for example: || or ,). To account for this we wrap
14921 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14922 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14923 // which record usages which are modifications as side effect, and then
14924 // downgrade them (or more accurately restore the previous usage which was a
14925 // modification as side effect) when exiting the scope of the sequenced
14926 // subexpression.
14927
14928 void notePreUse(Object O, const Expr *UseExpr) {
14929 UsageInfo &UI = UsageMap[O];
14930 // Uses conflict with other modifications.
14931 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14932 }
14933
14934 void notePostUse(Object O, const Expr *UseExpr) {
14935 UsageInfo &UI = UsageMap[O];
14936 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14937 /*IsModMod=*/false);
14938 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14939 }
14940
14941 void notePreMod(Object O, const Expr *ModExpr) {
14942 UsageInfo &UI = UsageMap[O];
14943 // Modifications conflict with other modifications and with uses.
14944 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14945 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14946 }
14947
14948 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14949 UsageInfo &UI = UsageMap[O];
14950 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14951 /*IsModMod=*/true);
14952 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14953 }
14954
14955public:
14956 SequenceChecker(Sema &S, const Expr *E,
14957 SmallVectorImpl<const Expr *> &WorkList)
14958 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14959 Visit(S: E);
14960 // Silence a -Wunused-private-field since WorkList is now unused.
14961 // TODO: Evaluate if it can be used, and if not remove it.
14962 (void)this->WorkList;
14963 }
14964
14965 void VisitStmt(const Stmt *S) {
14966 // Skip all statements which aren't expressions for now.
14967 }
14968
14969 void VisitExpr(const Expr *E) {
14970 // By default, just recurse to evaluated subexpressions.
14971 Base::VisitStmt(S: E);
14972 }
14973
14974 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14975 for (auto *Sub : CSE->children()) {
14976 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14977 if (!ChildExpr)
14978 continue;
14979
14980 if (ChildExpr == CSE->getOperand())
14981 // Do not recurse over a CoroutineSuspendExpr's operand.
14982 // The operand is also a subexpression of getCommonExpr(), and
14983 // recursing into it directly could confuse object management
14984 // for the sake of sequence tracking.
14985 continue;
14986
14987 Visit(S: Sub);
14988 }
14989 }
14990
14991 void VisitCastExpr(const CastExpr *E) {
14992 Object O = Object();
14993 if (E->getCastKind() == CK_LValueToRValue)
14994 O = getObject(E: E->getSubExpr(), Mod: false);
14995
14996 if (O)
14997 notePreUse(O, UseExpr: E);
14998 VisitExpr(E);
14999 if (O)
15000 notePostUse(O, UseExpr: E);
15001 }
15002
15003 void VisitSequencedExpressions(const Expr *SequencedBefore,
15004 const Expr *SequencedAfter) {
15005 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
15006 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
15007 SequenceTree::Seq OldRegion = Region;
15008
15009 {
15010 SequencedSubexpression SeqBefore(*this);
15011 Region = BeforeRegion;
15012 Visit(S: SequencedBefore);
15013 }
15014
15015 Region = AfterRegion;
15016 Visit(S: SequencedAfter);
15017
15018 Region = OldRegion;
15019
15020 Tree.merge(S: BeforeRegion);
15021 Tree.merge(S: AfterRegion);
15022 }
15023
15024 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15025 // C++17 [expr.sub]p1:
15026 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15027 // expression E1 is sequenced before the expression E2.
15028 if (SemaRef.getLangOpts().CPlusPlus17)
15029 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
15030 else {
15031 Visit(S: ASE->getLHS());
15032 Visit(S: ASE->getRHS());
15033 }
15034 }
15035
15036 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15037 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15038 void VisitBinPtrMem(const BinaryOperator *BO) {
15039 // C++17 [expr.mptr.oper]p4:
15040 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15041 // the expression E1 is sequenced before the expression E2.
15042 if (SemaRef.getLangOpts().CPlusPlus17)
15043 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15044 else {
15045 Visit(S: BO->getLHS());
15046 Visit(S: BO->getRHS());
15047 }
15048 }
15049
15050 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15051 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15052 void VisitBinShlShr(const BinaryOperator *BO) {
15053 // C++17 [expr.shift]p4:
15054 // The expression E1 is sequenced before the expression E2.
15055 if (SemaRef.getLangOpts().CPlusPlus17)
15056 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15057 else {
15058 Visit(S: BO->getLHS());
15059 Visit(S: BO->getRHS());
15060 }
15061 }
15062
15063 void VisitBinComma(const BinaryOperator *BO) {
15064 // C++11 [expr.comma]p1:
15065 // Every value computation and side effect associated with the left
15066 // expression is sequenced before every value computation and side
15067 // effect associated with the right expression.
15068 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15069 }
15070
15071 void VisitBinAssign(const BinaryOperator *BO) {
15072 SequenceTree::Seq RHSRegion;
15073 SequenceTree::Seq LHSRegion;
15074 if (SemaRef.getLangOpts().CPlusPlus17) {
15075 RHSRegion = Tree.allocate(Parent: Region);
15076 LHSRegion = Tree.allocate(Parent: Region);
15077 } else {
15078 RHSRegion = Region;
15079 LHSRegion = Region;
15080 }
15081 SequenceTree::Seq OldRegion = Region;
15082
15083 // C++11 [expr.ass]p1:
15084 // [...] the assignment is sequenced after the value computation
15085 // of the right and left operands, [...]
15086 //
15087 // so check it before inspecting the operands and update the
15088 // map afterwards.
15089 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
15090 if (O)
15091 notePreMod(O, ModExpr: BO);
15092
15093 if (SemaRef.getLangOpts().CPlusPlus17) {
15094 // C++17 [expr.ass]p1:
15095 // [...] The right operand is sequenced before the left operand. [...]
15096 {
15097 SequencedSubexpression SeqBefore(*this);
15098 Region = RHSRegion;
15099 Visit(S: BO->getRHS());
15100 }
15101
15102 Region = LHSRegion;
15103 Visit(S: BO->getLHS());
15104
15105 if (O && isa<CompoundAssignOperator>(Val: BO))
15106 notePostUse(O, UseExpr: BO);
15107
15108 } else {
15109 // C++11 does not specify any sequencing between the LHS and RHS.
15110 Region = LHSRegion;
15111 Visit(S: BO->getLHS());
15112
15113 if (O && isa<CompoundAssignOperator>(Val: BO))
15114 notePostUse(O, UseExpr: BO);
15115
15116 Region = RHSRegion;
15117 Visit(S: BO->getRHS());
15118 }
15119
15120 // C++11 [expr.ass]p1:
15121 // the assignment is sequenced [...] before the value computation of the
15122 // assignment expression.
15123 // C11 6.5.16/3 has no such rule.
15124 Region = OldRegion;
15125 if (O)
15126 notePostMod(O, ModExpr: BO,
15127 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15128 : UK_ModAsSideEffect);
15129 if (SemaRef.getLangOpts().CPlusPlus17) {
15130 Tree.merge(S: RHSRegion);
15131 Tree.merge(S: LHSRegion);
15132 }
15133 }
15134
15135 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15136 VisitBinAssign(BO: CAO);
15137 }
15138
15139 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15140 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15141 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15142 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15143 if (!O)
15144 return VisitExpr(E: UO);
15145
15146 notePreMod(O, ModExpr: UO);
15147 Visit(S: UO->getSubExpr());
15148 // C++11 [expr.pre.incr]p1:
15149 // the expression ++x is equivalent to x+=1
15150 notePostMod(O, ModExpr: UO,
15151 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15152 : UK_ModAsSideEffect);
15153 }
15154
15155 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15156 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15157 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15158 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15159 if (!O)
15160 return VisitExpr(E: UO);
15161
15162 notePreMod(O, ModExpr: UO);
15163 Visit(S: UO->getSubExpr());
15164 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
15165 }
15166
15167 void VisitBinLOr(const BinaryOperator *BO) {
15168 // C++11 [expr.log.or]p2:
15169 // If the second expression is evaluated, every value computation and
15170 // side effect associated with the first expression is sequenced before
15171 // every value computation and side effect associated with the
15172 // second expression.
15173 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15174 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15175 SequenceTree::Seq OldRegion = Region;
15176
15177 EvaluationTracker Eval(*this);
15178 {
15179 SequencedSubexpression Sequenced(*this);
15180 Region = LHSRegion;
15181 Visit(S: BO->getLHS());
15182 }
15183
15184 // C++11 [expr.log.or]p1:
15185 // [...] the second operand is not evaluated if the first operand
15186 // evaluates to true.
15187 bool EvalResult = false;
15188 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15189 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15190 if (ShouldVisitRHS) {
15191 Region = RHSRegion;
15192 Visit(S: BO->getRHS());
15193 }
15194
15195 Region = OldRegion;
15196 Tree.merge(S: LHSRegion);
15197 Tree.merge(S: RHSRegion);
15198 }
15199
15200 void VisitBinLAnd(const BinaryOperator *BO) {
15201 // C++11 [expr.log.and]p2:
15202 // If the second expression is evaluated, every value computation and
15203 // side effect associated with the first expression is sequenced before
15204 // every value computation and side effect associated with the
15205 // second expression.
15206 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15207 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15208 SequenceTree::Seq OldRegion = Region;
15209
15210 EvaluationTracker Eval(*this);
15211 {
15212 SequencedSubexpression Sequenced(*this);
15213 Region = LHSRegion;
15214 Visit(S: BO->getLHS());
15215 }
15216
15217 // C++11 [expr.log.and]p1:
15218 // [...] the second operand is not evaluated if the first operand is false.
15219 bool EvalResult = false;
15220 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15221 bool ShouldVisitRHS = !EvalOK || EvalResult;
15222 if (ShouldVisitRHS) {
15223 Region = RHSRegion;
15224 Visit(S: BO->getRHS());
15225 }
15226
15227 Region = OldRegion;
15228 Tree.merge(S: LHSRegion);
15229 Tree.merge(S: RHSRegion);
15230 }
15231
15232 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15233 // C++11 [expr.cond]p1:
15234 // [...] Every value computation and side effect associated with the first
15235 // expression is sequenced before every value computation and side effect
15236 // associated with the second or third expression.
15237 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
15238
15239 // No sequencing is specified between the true and false expression.
15240 // However since exactly one of both is going to be evaluated we can
15241 // consider them to be sequenced. This is needed to avoid warning on
15242 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15243 // both the true and false expressions because we can't evaluate x.
15244 // This will still allow us to detect an expression like (pre C++17)
15245 // "(x ? y += 1 : y += 2) = y".
15246 //
15247 // We don't wrap the visitation of the true and false expression with
15248 // SequencedSubexpression because we don't want to downgrade modifications
15249 // as side effect in the true and false expressions after the visition
15250 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15251 // not warn between the two "y++", but we should warn between the "y++"
15252 // and the "y".
15253 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
15254 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
15255 SequenceTree::Seq OldRegion = Region;
15256
15257 EvaluationTracker Eval(*this);
15258 {
15259 SequencedSubexpression Sequenced(*this);
15260 Region = ConditionRegion;
15261 Visit(S: CO->getCond());
15262 }
15263
15264 // C++11 [expr.cond]p1:
15265 // [...] The first expression is contextually converted to bool (Clause 4).
15266 // It is evaluated and if it is true, the result of the conditional
15267 // expression is the value of the second expression, otherwise that of the
15268 // third expression. Only one of the second and third expressions is
15269 // evaluated. [...]
15270 bool EvalResult = false;
15271 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
15272 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15273 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15274 if (ShouldVisitTrueExpr) {
15275 Region = TrueRegion;
15276 Visit(S: CO->getTrueExpr());
15277 }
15278 if (ShouldVisitFalseExpr) {
15279 Region = FalseRegion;
15280 Visit(S: CO->getFalseExpr());
15281 }
15282
15283 Region = OldRegion;
15284 Tree.merge(S: ConditionRegion);
15285 Tree.merge(S: TrueRegion);
15286 Tree.merge(S: FalseRegion);
15287 }
15288
15289 void VisitCallExpr(const CallExpr *CE) {
15290 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15291
15292 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
15293 return;
15294
15295 // C++11 [intro.execution]p15:
15296 // When calling a function [...], every value computation and side effect
15297 // associated with any argument expression, or with the postfix expression
15298 // designating the called function, is sequenced before execution of every
15299 // expression or statement in the body of the function [and thus before
15300 // the value computation of its result].
15301 SequencedSubexpression Sequenced(*this);
15302 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
15303 // C++17 [expr.call]p5
15304 // The postfix-expression is sequenced before each expression in the
15305 // expression-list and any default argument. [...]
15306 SequenceTree::Seq CalleeRegion;
15307 SequenceTree::Seq OtherRegion;
15308 if (SemaRef.getLangOpts().CPlusPlus17) {
15309 CalleeRegion = Tree.allocate(Parent: Region);
15310 OtherRegion = Tree.allocate(Parent: Region);
15311 } else {
15312 CalleeRegion = Region;
15313 OtherRegion = Region;
15314 }
15315 SequenceTree::Seq OldRegion = Region;
15316
15317 // Visit the callee expression first.
15318 Region = CalleeRegion;
15319 if (SemaRef.getLangOpts().CPlusPlus17) {
15320 SequencedSubexpression Sequenced(*this);
15321 Visit(S: CE->getCallee());
15322 } else {
15323 Visit(S: CE->getCallee());
15324 }
15325
15326 // Then visit the argument expressions.
15327 Region = OtherRegion;
15328 for (const Expr *Argument : CE->arguments())
15329 Visit(S: Argument);
15330
15331 Region = OldRegion;
15332 if (SemaRef.getLangOpts().CPlusPlus17) {
15333 Tree.merge(S: CalleeRegion);
15334 Tree.merge(S: OtherRegion);
15335 }
15336 });
15337 }
15338
15339 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15340 // C++17 [over.match.oper]p2:
15341 // [...] the operator notation is first transformed to the equivalent
15342 // function-call notation as summarized in Table 12 (where @ denotes one
15343 // of the operators covered in the specified subclause). However, the
15344 // operands are sequenced in the order prescribed for the built-in
15345 // operator (Clause 8).
15346 //
15347 // From the above only overloaded binary operators and overloaded call
15348 // operators have sequencing rules in C++17 that we need to handle
15349 // separately.
15350 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15351 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15352 return VisitCallExpr(CE: CXXOCE);
15353
15354 enum {
15355 NoSequencing,
15356 LHSBeforeRHS,
15357 RHSBeforeLHS,
15358 LHSBeforeRest
15359 } SequencingKind;
15360 switch (CXXOCE->getOperator()) {
15361 case OO_Equal:
15362 case OO_PlusEqual:
15363 case OO_MinusEqual:
15364 case OO_StarEqual:
15365 case OO_SlashEqual:
15366 case OO_PercentEqual:
15367 case OO_CaretEqual:
15368 case OO_AmpEqual:
15369 case OO_PipeEqual:
15370 case OO_LessLessEqual:
15371 case OO_GreaterGreaterEqual:
15372 SequencingKind = RHSBeforeLHS;
15373 break;
15374
15375 case OO_LessLess:
15376 case OO_GreaterGreater:
15377 case OO_AmpAmp:
15378 case OO_PipePipe:
15379 case OO_Comma:
15380 case OO_ArrowStar:
15381 case OO_Subscript:
15382 SequencingKind = LHSBeforeRHS;
15383 break;
15384
15385 case OO_Call:
15386 SequencingKind = LHSBeforeRest;
15387 break;
15388
15389 default:
15390 SequencingKind = NoSequencing;
15391 break;
15392 }
15393
15394 if (SequencingKind == NoSequencing)
15395 return VisitCallExpr(CE: CXXOCE);
15396
15397 // This is a call, so all subexpressions are sequenced before the result.
15398 SequencedSubexpression Sequenced(*this);
15399
15400 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
15401 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15402 "Should only get there with C++17 and above!");
15403 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15404 "Should only get there with an overloaded binary operator"
15405 " or an overloaded call operator!");
15406
15407 if (SequencingKind == LHSBeforeRest) {
15408 assert(CXXOCE->getOperator() == OO_Call &&
15409 "We should only have an overloaded call operator here!");
15410
15411 // This is very similar to VisitCallExpr, except that we only have the
15412 // C++17 case. The postfix-expression is the first argument of the
15413 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15414 // are in the following arguments.
15415 //
15416 // Note that we intentionally do not visit the callee expression since
15417 // it is just a decayed reference to a function.
15418 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
15419 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
15420 SequenceTree::Seq OldRegion = Region;
15421
15422 assert(CXXOCE->getNumArgs() >= 1 &&
15423 "An overloaded call operator must have at least one argument"
15424 " for the postfix-expression!");
15425 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15426 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15427 CXXOCE->getNumArgs() - 1);
15428
15429 // Visit the postfix-expression first.
15430 {
15431 Region = PostfixExprRegion;
15432 SequencedSubexpression Sequenced(*this);
15433 Visit(S: PostfixExpr);
15434 }
15435
15436 // Then visit the argument expressions.
15437 Region = ArgsRegion;
15438 for (const Expr *Arg : Args)
15439 Visit(S: Arg);
15440
15441 Region = OldRegion;
15442 Tree.merge(S: PostfixExprRegion);
15443 Tree.merge(S: ArgsRegion);
15444 } else {
15445 assert(CXXOCE->getNumArgs() == 2 &&
15446 "Should only have two arguments here!");
15447 assert((SequencingKind == LHSBeforeRHS ||
15448 SequencingKind == RHSBeforeLHS) &&
15449 "Unexpected sequencing kind!");
15450
15451 // We do not visit the callee expression since it is just a decayed
15452 // reference to a function.
15453 const Expr *E1 = CXXOCE->getArg(Arg: 0);
15454 const Expr *E2 = CXXOCE->getArg(Arg: 1);
15455 if (SequencingKind == RHSBeforeLHS)
15456 std::swap(a&: E1, b&: E2);
15457
15458 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
15459 }
15460 });
15461 }
15462
15463 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15464 // This is a call, so all subexpressions are sequenced before the result.
15465 SequencedSubexpression Sequenced(*this);
15466
15467 if (!CCE->isListInitialization())
15468 return VisitExpr(E: CCE);
15469
15470 // In C++11, list initializations are sequenced.
15471 SequenceExpressionsInOrder(
15472 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15473 }
15474
15475 void VisitInitListExpr(const InitListExpr *ILE) {
15476 if (!SemaRef.getLangOpts().CPlusPlus11)
15477 return VisitExpr(E: ILE);
15478
15479 // In C++11, list initializations are sequenced.
15480 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
15481 }
15482
15483 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15484 // C++20 parenthesized list initializations are sequenced. See C++20
15485 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15486 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
15487 }
15488
15489private:
15490 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15491 SmallVector<SequenceTree::Seq, 32> Elts;
15492 SequenceTree::Seq Parent = Region;
15493 for (const Expr *E : ExpressionList) {
15494 if (!E)
15495 continue;
15496 Region = Tree.allocate(Parent);
15497 Elts.push_back(Elt: Region);
15498 Visit(S: E);
15499 }
15500
15501 // Forget that the initializers are sequenced.
15502 Region = Parent;
15503 for (unsigned I = 0; I < Elts.size(); ++I)
15504 Tree.merge(S: Elts[I]);
15505 }
15506};
15507
15508SequenceChecker::UsageInfo::UsageInfo() = default;
15509
15510} // namespace
15511
15512void Sema::CheckUnsequencedOperations(const Expr *E) {
15513 SmallVector<const Expr *, 8> WorkList;
15514 WorkList.push_back(Elt: E);
15515 while (!WorkList.empty()) {
15516 const Expr *Item = WorkList.pop_back_val();
15517 SequenceChecker(*this, Item, WorkList);
15518 }
15519}
15520
15521void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15522 bool IsConstexpr) {
15523 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15524 IsConstexpr || isa<ConstantExpr>(Val: E));
15525 CheckImplicitConversions(E, CC: CheckLoc);
15526 if (!E->isInstantiationDependent())
15527 CheckUnsequencedOperations(E);
15528 if (!IsConstexpr && !E->isValueDependent())
15529 CheckForIntOverflow(E);
15530}
15531
15532void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15533 FieldDecl *BitField,
15534 Expr *Init) {
15535 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15536}
15537
15538static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15539 SourceLocation Loc) {
15540 if (!PType->isVariablyModifiedType())
15541 return;
15542 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15543 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15544 return;
15545 }
15546 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15547 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15548 return;
15549 }
15550 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15551 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15552 return;
15553 }
15554
15555 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15556 if (!AT)
15557 return;
15558
15559 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15560 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15561 return;
15562 }
15563
15564 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15565}
15566
15567bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15568 bool CheckParameterNames) {
15569 bool HasInvalidParm = false;
15570 for (ParmVarDecl *Param : Parameters) {
15571 assert(Param && "null in a parameter list");
15572 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15573 // function declarator that is part of a function definition of
15574 // that function shall not have incomplete type.
15575 //
15576 // C++23 [dcl.fct.def.general]/p2
15577 // The type of a parameter [...] for a function definition
15578 // shall not be a (possibly cv-qualified) class type that is incomplete
15579 // or abstract within the function body unless the function is deleted.
15580 if (!Param->isInvalidDecl() &&
15581 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15582 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15583 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15584 DiagID: diag::err_abstract_type_in_decl,
15585 Args: AbstractParamType))) {
15586 Param->setInvalidDecl();
15587 HasInvalidParm = true;
15588 }
15589
15590 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15591 // declaration of each parameter shall include an identifier.
15592 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15593 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15594 // Diagnose this as an extension in C17 and earlier.
15595 if (!getLangOpts().C23)
15596 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15597 }
15598
15599 // C99 6.7.5.3p12:
15600 // If the function declarator is not part of a definition of that
15601 // function, parameters may have incomplete type and may use the [*]
15602 // notation in their sequences of declarator specifiers to specify
15603 // variable length array types.
15604 QualType PType = Param->getOriginalType();
15605 // FIXME: This diagnostic should point the '[*]' if source-location
15606 // information is added for it.
15607 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15608
15609 // If the parameter is a c++ class type and it has to be destructed in the
15610 // callee function, declare the destructor so that it can be called by the
15611 // callee function. Do not perform any direct access check on the dtor here.
15612 if (!Param->isInvalidDecl()) {
15613 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15614 if (!ClassDecl->isInvalidDecl() &&
15615 !ClassDecl->hasIrrelevantDestructor() &&
15616 !ClassDecl->isDependentContext() &&
15617 ClassDecl->isParamDestroyedInCallee()) {
15618 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15619 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15620 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15621 }
15622 }
15623 }
15624
15625 // Parameters with the pass_object_size attribute only need to be marked
15626 // constant at function definitions. Because we lack information about
15627 // whether we're on a declaration or definition when we're instantiating the
15628 // attribute, we need to check for constness here.
15629 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15630 if (!Param->getType().isConstQualified())
15631 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15632 << Attr->getSpelling() << 1;
15633
15634 // Check for parameter names shadowing fields from the class.
15635 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15636 // The owning context for the parameter should be the function, but we
15637 // want to see if this function's declaration context is a record.
15638 DeclContext *DC = Param->getDeclContext();
15639 if (DC && DC->isFunctionOrMethod()) {
15640 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15641 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15642 RD, /*DeclIsField*/ false);
15643 }
15644 }
15645
15646 if (!Param->isInvalidDecl() &&
15647 Param->getOriginalType()->isWebAssemblyTableType()) {
15648 Param->setInvalidDecl();
15649 HasInvalidParm = true;
15650 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15651 }
15652 }
15653
15654 return HasInvalidParm;
15655}
15656
15657std::optional<std::pair<
15658 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15659 *E,
15660 ASTContext
15661 &Ctx);
15662
15663/// Compute the alignment and offset of the base class object given the
15664/// derived-to-base cast expression and the alignment and offset of the derived
15665/// class object.
15666static std::pair<CharUnits, CharUnits>
15667getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15668 CharUnits BaseAlignment, CharUnits Offset,
15669 ASTContext &Ctx) {
15670 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15671 ++PathI) {
15672 const CXXBaseSpecifier *Base = *PathI;
15673 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15674 if (Base->isVirtual()) {
15675 // The complete object may have a lower alignment than the non-virtual
15676 // alignment of the base, in which case the base may be misaligned. Choose
15677 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15678 // conservative lower bound of the complete object alignment.
15679 CharUnits NonVirtualAlignment =
15680 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15681 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15682 Offset = CharUnits::Zero();
15683 } else {
15684 const ASTRecordLayout &RL =
15685 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15686 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15687 }
15688 DerivedType = Base->getType();
15689 }
15690
15691 return std::make_pair(x&: BaseAlignment, y&: Offset);
15692}
15693
15694/// Compute the alignment and offset of a binary additive operator.
15695static std::optional<std::pair<CharUnits, CharUnits>>
15696getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15697 bool IsSub, ASTContext &Ctx) {
15698 QualType PointeeType = PtrE->getType()->getPointeeType();
15699
15700 if (!PointeeType->isConstantSizeType())
15701 return std::nullopt;
15702
15703 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15704
15705 if (!P)
15706 return std::nullopt;
15707
15708 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15709 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15710 CharUnits Offset = EltSize * IdxRes->getExtValue();
15711 if (IsSub)
15712 Offset = -Offset;
15713 return std::make_pair(x&: P->first, y: P->second + Offset);
15714 }
15715
15716 // If the integer expression isn't a constant expression, compute the lower
15717 // bound of the alignment using the alignment and offset of the pointer
15718 // expression and the element size.
15719 return std::make_pair(
15720 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15721 y: CharUnits::Zero());
15722}
15723
15724/// This helper function takes an lvalue expression and returns the alignment of
15725/// a VarDecl and a constant offset from the VarDecl.
15726std::optional<std::pair<
15727 CharUnits,
15728 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15729 ASTContext &Ctx) {
15730 E = E->IgnoreParens();
15731 switch (E->getStmtClass()) {
15732 default:
15733 break;
15734 case Stmt::CStyleCastExprClass:
15735 case Stmt::CXXStaticCastExprClass:
15736 case Stmt::ImplicitCastExprClass: {
15737 auto *CE = cast<CastExpr>(Val: E);
15738 const Expr *From = CE->getSubExpr();
15739 switch (CE->getCastKind()) {
15740 default:
15741 break;
15742 case CK_NoOp:
15743 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15744 case CK_UncheckedDerivedToBase:
15745 case CK_DerivedToBase: {
15746 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15747 if (!P)
15748 break;
15749 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15750 Offset: P->second, Ctx);
15751 }
15752 }
15753 break;
15754 }
15755 case Stmt::ArraySubscriptExprClass: {
15756 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15757 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15758 IsSub: false, Ctx);
15759 }
15760 case Stmt::DeclRefExprClass: {
15761 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15762 // FIXME: If VD is captured by copy or is an escaping __block variable,
15763 // use the alignment of VD's type.
15764 if (!VD->getType()->isReferenceType()) {
15765 // Dependent alignment cannot be resolved -> bail out.
15766 if (VD->hasDependentAlignment())
15767 break;
15768 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15769 }
15770 if (VD->hasInit())
15771 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15772 }
15773 break;
15774 }
15775 case Stmt::MemberExprClass: {
15776 auto *ME = cast<MemberExpr>(Val: E);
15777 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15778 if (!FD || FD->getType()->isReferenceType() ||
15779 !ASTContext::hasLayout(D: FD->getParent()))
15780 break;
15781 std::optional<std::pair<CharUnits, CharUnits>> P;
15782 if (ME->isArrow())
15783 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15784 else
15785 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15786 if (!P)
15787 break;
15788 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15789 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15790 return std::make_pair(x&: P->first,
15791 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15792 }
15793 case Stmt::UnaryOperatorClass: {
15794 auto *UO = cast<UnaryOperator>(Val: E);
15795 switch (UO->getOpcode()) {
15796 default:
15797 break;
15798 case UO_Deref:
15799 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15800 }
15801 break;
15802 }
15803 case Stmt::BinaryOperatorClass: {
15804 auto *BO = cast<BinaryOperator>(Val: E);
15805 auto Opcode = BO->getOpcode();
15806 switch (Opcode) {
15807 default:
15808 break;
15809 case BO_Comma:
15810 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15811 }
15812 break;
15813 }
15814 }
15815 return std::nullopt;
15816}
15817
15818/// This helper function takes a pointer expression and returns the alignment of
15819/// a VarDecl and a constant offset from the VarDecl.
15820std::optional<std::pair<
15821 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15822 *E,
15823 ASTContext
15824 &Ctx) {
15825 E = E->IgnoreParens();
15826 switch (E->getStmtClass()) {
15827 default:
15828 break;
15829 case Stmt::CStyleCastExprClass:
15830 case Stmt::CXXStaticCastExprClass:
15831 case Stmt::ImplicitCastExprClass: {
15832 auto *CE = cast<CastExpr>(Val: E);
15833 const Expr *From = CE->getSubExpr();
15834 switch (CE->getCastKind()) {
15835 default:
15836 break;
15837 case CK_NoOp:
15838 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15839 case CK_ArrayToPointerDecay:
15840 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15841 case CK_UncheckedDerivedToBase:
15842 case CK_DerivedToBase: {
15843 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15844 if (!P)
15845 break;
15846 return getDerivedToBaseAlignmentAndOffset(
15847 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15848 }
15849 }
15850 break;
15851 }
15852 case Stmt::CXXThisExprClass: {
15853 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15854 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15855 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15856 }
15857 case Stmt::UnaryOperatorClass: {
15858 auto *UO = cast<UnaryOperator>(Val: E);
15859 if (UO->getOpcode() == UO_AddrOf)
15860 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15861 break;
15862 }
15863 case Stmt::BinaryOperatorClass: {
15864 auto *BO = cast<BinaryOperator>(Val: E);
15865 auto Opcode = BO->getOpcode();
15866 switch (Opcode) {
15867 default:
15868 break;
15869 case BO_Add:
15870 case BO_Sub: {
15871 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15872 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15873 std::swap(a&: LHS, b&: RHS);
15874 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15875 Ctx);
15876 }
15877 case BO_Comma:
15878 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15879 }
15880 break;
15881 }
15882 }
15883 return std::nullopt;
15884}
15885
15886static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15887 // See if we can compute the alignment of a VarDecl and an offset from it.
15888 std::optional<std::pair<CharUnits, CharUnits>> P =
15889 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15890
15891 if (P)
15892 return P->first.alignmentAtOffset(offset: P->second);
15893
15894 // If that failed, return the type's alignment.
15895 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15896}
15897
15898void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15899 // This is actually a lot of work to potentially be doing on every
15900 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15901 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15902 return;
15903
15904 // Ignore dependent types.
15905 if (T->isDependentType() || Op->getType()->isDependentType())
15906 return;
15907
15908 // Require that the destination be a pointer type.
15909 const PointerType *DestPtr = T->getAs<PointerType>();
15910 if (!DestPtr) return;
15911
15912 // If the destination has alignment 1, we're done.
15913 QualType DestPointee = DestPtr->getPointeeType();
15914 if (DestPointee->isIncompleteType()) return;
15915 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15916 if (DestAlign.isOne()) return;
15917
15918 // Require that the source be a pointer type.
15919 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15920 if (!SrcPtr) return;
15921 QualType SrcPointee = SrcPtr->getPointeeType();
15922
15923 // Explicitly allow casts from cv void*. We already implicitly
15924 // allowed casts to cv void*, since they have alignment 1.
15925 // Also allow casts involving incomplete types, which implicitly
15926 // includes 'void'.
15927 if (SrcPointee->isIncompleteType()) return;
15928
15929 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15930
15931 if (SrcAlign >= DestAlign) return;
15932
15933 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15934 << Op->getType() << T
15935 << static_cast<unsigned>(SrcAlign.getQuantity())
15936 << static_cast<unsigned>(DestAlign.getQuantity())
15937 << TRange << Op->getSourceRange();
15938}
15939
15940void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15941 const ArraySubscriptExpr *ASE,
15942 bool AllowOnePastEnd, bool IndexNegated) {
15943 // Already diagnosed by the constant evaluator.
15944 if (isConstantEvaluatedContext())
15945 return;
15946
15947 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15948 if (IndexExpr->isValueDependent())
15949 return;
15950
15951 const Type *EffectiveType =
15952 BaseExpr->getType()->getPointeeOrArrayElementType();
15953 BaseExpr = BaseExpr->IgnoreParenCasts();
15954 const ConstantArrayType *ArrayTy =
15955 Context.getAsConstantArrayType(T: BaseExpr->getType());
15956
15957 LangOptions::StrictFlexArraysLevelKind
15958 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15959
15960 const Type *BaseType =
15961 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15962 bool IsUnboundedArray =
15963 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15964 Context, StrictFlexArraysLevel,
15965 /*IgnoreTemplateOrMacroSubstitution=*/true);
15966 if (EffectiveType->isDependentType() ||
15967 (!IsUnboundedArray && BaseType->isDependentType()))
15968 return;
15969
15970 Expr::EvalResult Result;
15971 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15972 return;
15973
15974 llvm::APSInt index = Result.Val.getInt();
15975 if (IndexNegated) {
15976 index.setIsUnsigned(false);
15977 index = -index;
15978 }
15979
15980 if (IsUnboundedArray) {
15981 if (EffectiveType->isFunctionType())
15982 return;
15983 if (index.isUnsigned() || !index.isNegative()) {
15984 const auto &ASTC = getASTContext();
15985 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15986 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15987 if (index.getBitWidth() < AddrBits)
15988 index = index.zext(width: AddrBits);
15989 std::optional<CharUnits> ElemCharUnits =
15990 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15991 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15992 // pointer) bounds-checking isn't meaningful.
15993 if (!ElemCharUnits || ElemCharUnits->isZero())
15994 return;
15995 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15996 // If index has more active bits than address space, we already know
15997 // we have a bounds violation to warn about. Otherwise, compute
15998 // address of (index + 1)th element, and warn about bounds violation
15999 // only if that address exceeds address space.
16000 if (index.getActiveBits() <= AddrBits) {
16001 bool Overflow;
16002 llvm::APInt Product(index);
16003 Product += 1;
16004 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
16005 if (!Overflow && Product.getActiveBits() <= AddrBits)
16006 return;
16007 }
16008
16009 // Need to compute max possible elements in address space, since that
16010 // is included in diag message.
16011 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
16012 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
16013 MaxElems += 1;
16014 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
16015 MaxElems = MaxElems.udiv(RHS: ElemBytes);
16016
16017 unsigned DiagID =
16018 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16019 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16020
16021 // Diag message shows element size in bits and in "bytes" (platform-
16022 // dependent CharUnits)
16023 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16024 PD: PDiag(DiagID) << index << AddrBits
16025 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
16026 << ElemBytes << MaxElems
16027 << MaxElems.getZExtValue()
16028 << IndexExpr->getSourceRange());
16029
16030 const NamedDecl *ND = nullptr;
16031 // Try harder to find a NamedDecl to point at in the note.
16032 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16033 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16034 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16035 ND = DRE->getDecl();
16036 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16037 ND = ME->getMemberDecl();
16038
16039 if (ND)
16040 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16041 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16042 }
16043 return;
16044 }
16045
16046 if (index.isUnsigned() || !index.isNegative()) {
16047 // It is possible that the type of the base expression after
16048 // IgnoreParenCasts is incomplete, even though the type of the base
16049 // expression before IgnoreParenCasts is complete (see PR39746 for an
16050 // example). In this case we have no information about whether the array
16051 // access exceeds the array bounds. However we can still diagnose an array
16052 // access which precedes the array bounds.
16053 if (BaseType->isIncompleteType())
16054 return;
16055
16056 llvm::APInt size = ArrayTy->getSize();
16057
16058 if (BaseType != EffectiveType) {
16059 // Make sure we're comparing apples to apples when comparing index to
16060 // size.
16061 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
16062 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
16063
16064 // Handle ptrarith_typesize being zero, such as when casting to void*.
16065 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16066 if (!ptrarith_typesize)
16067 ptrarith_typesize = Context.getCharWidth();
16068
16069 if (ptrarith_typesize != array_typesize) {
16070 // There's a cast to a different size type involved.
16071 uint64_t ratio = array_typesize / ptrarith_typesize;
16072
16073 // TODO: Be smarter about handling cases where array_typesize is not a
16074 // multiple of ptrarith_typesize.
16075 if (ptrarith_typesize * ratio == array_typesize)
16076 size *= llvm::APInt(size.getBitWidth(), ratio);
16077 }
16078 }
16079
16080 if (size.getBitWidth() > index.getBitWidth())
16081 index = index.zext(width: size.getBitWidth());
16082 else if (size.getBitWidth() < index.getBitWidth())
16083 size = size.zext(width: index.getBitWidth());
16084
16085 // For array subscripting the index must be less than size, but for pointer
16086 // arithmetic also allow the index (offset) to be equal to size since
16087 // computing the next address after the end of the array is legal and
16088 // commonly done e.g. in C++ iterators and range-based for loops.
16089 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
16090 return;
16091
16092 // Suppress the warning if the subscript expression (as identified by the
16093 // ']' location) and the index expression are both from macro expansions
16094 // within a system header.
16095 if (ASE) {
16096 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16097 Loc: ASE->getRBracketLoc());
16098 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
16099 SourceLocation IndexLoc =
16100 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
16101 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
16102 return;
16103 }
16104 }
16105
16106 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16107 : diag::warn_ptr_arith_exceeds_bounds;
16108 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16109 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16110
16111 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16112 PD: PDiag(DiagID)
16113 << index << ArrayTy->desugar() << CastMsg
16114 << CastMsgTy << IndexExpr->getSourceRange());
16115 } else {
16116 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16117 if (!ASE) {
16118 DiagID = diag::warn_ptr_arith_precedes_bounds;
16119 if (index.isNegative()) index = -index;
16120 }
16121
16122 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16123 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
16124 }
16125
16126 const NamedDecl *ND = nullptr;
16127 // Try harder to find a NamedDecl to point at in the note.
16128 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16129 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16130 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16131 ND = DRE->getDecl();
16132 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16133 ND = ME->getMemberDecl();
16134
16135 if (ND)
16136 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16137 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16138}
16139
16140void Sema::CheckArrayAccess(const Expr *expr) {
16141 int AllowOnePastEnd = 0;
16142 while (expr) {
16143 expr = expr->IgnoreParenImpCasts();
16144 switch (expr->getStmtClass()) {
16145 case Stmt::ArraySubscriptExprClass: {
16146 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
16147 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
16148 AllowOnePastEnd: AllowOnePastEnd > 0);
16149 expr = ASE->getBase();
16150 break;
16151 }
16152 case Stmt::MemberExprClass: {
16153 expr = cast<MemberExpr>(Val: expr)->getBase();
16154 break;
16155 }
16156 case Stmt::CXXMemberCallExprClass: {
16157 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
16158 break;
16159 }
16160 case Stmt::ArraySectionExprClass: {
16161 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
16162 // FIXME: We should probably be checking all of the elements to the
16163 // 'length' here as well.
16164 if (ASE->getLowerBound())
16165 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
16166 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
16167 return;
16168 }
16169 case Stmt::UnaryOperatorClass: {
16170 // Only unwrap the * and & unary operators
16171 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
16172 expr = UO->getSubExpr();
16173 switch (UO->getOpcode()) {
16174 case UO_AddrOf:
16175 AllowOnePastEnd++;
16176 break;
16177 case UO_Deref:
16178 AllowOnePastEnd--;
16179 break;
16180 default:
16181 return;
16182 }
16183 break;
16184 }
16185 case Stmt::ConditionalOperatorClass: {
16186 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
16187 if (const Expr *lhs = cond->getLHS())
16188 CheckArrayAccess(expr: lhs);
16189 if (const Expr *rhs = cond->getRHS())
16190 CheckArrayAccess(expr: rhs);
16191 return;
16192 }
16193 case Stmt::CXXOperatorCallExprClass: {
16194 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
16195 for (const auto *Arg : OCE->arguments())
16196 CheckArrayAccess(expr: Arg);
16197 return;
16198 }
16199 default:
16200 return;
16201 }
16202 }
16203}
16204
16205static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16206 Expr *RHS, bool isProperty) {
16207 // Check if RHS is an Objective-C object literal, which also can get
16208 // immediately zapped in a weak reference. Note that we explicitly
16209 // allow ObjCStringLiterals, since those are designed to never really die.
16210 RHS = RHS->IgnoreParenImpCasts();
16211
16212 // This enum needs to match with the 'select' in
16213 // warn_objc_arc_literal_assign (off-by-1).
16214 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
16215 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16216 return false;
16217
16218 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
16219 << (unsigned) Kind
16220 << (isProperty ? 0 : 1)
16221 << RHS->getSourceRange();
16222
16223 return true;
16224}
16225
16226static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16227 Qualifiers::ObjCLifetime LT,
16228 Expr *RHS, bool isProperty) {
16229 // Strip off any implicit cast added to get to the one ARC-specific.
16230 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16231 if (cast->getCastKind() == CK_ARCConsumeObject) {
16232 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
16233 << (LT == Qualifiers::OCL_ExplicitNone)
16234 << (isProperty ? 0 : 1)
16235 << RHS->getSourceRange();
16236 return true;
16237 }
16238 RHS = cast->getSubExpr();
16239 }
16240
16241 if (LT == Qualifiers::OCL_Weak &&
16242 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16243 return true;
16244
16245 return false;
16246}
16247
16248bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16249 QualType LHS, Expr *RHS) {
16250 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16251
16252 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16253 return false;
16254
16255 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
16256 return true;
16257
16258 return false;
16259}
16260
16261void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16262 Expr *LHS, Expr *RHS) {
16263 QualType LHSType;
16264 // PropertyRef on LHS type need be directly obtained from
16265 // its declaration as it has a PseudoType.
16266 ObjCPropertyRefExpr *PRE
16267 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
16268 if (PRE && !PRE->isImplicitProperty()) {
16269 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16270 if (PD)
16271 LHSType = PD->getType();
16272 }
16273
16274 if (LHSType.isNull())
16275 LHSType = LHS->getType();
16276
16277 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16278
16279 if (LT == Qualifiers::OCL_Weak) {
16280 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
16281 getCurFunction()->markSafeWeakUse(E: LHS);
16282 }
16283
16284 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
16285 return;
16286
16287 // FIXME. Check for other life times.
16288 if (LT != Qualifiers::OCL_None)
16289 return;
16290
16291 if (PRE) {
16292 if (PRE->isImplicitProperty())
16293 return;
16294 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16295 if (!PD)
16296 return;
16297
16298 unsigned Attributes = PD->getPropertyAttributes();
16299 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16300 // when 'assign' attribute was not explicitly specified
16301 // by user, ignore it and rely on property type itself
16302 // for lifetime info.
16303 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16304 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16305 LHSType->isObjCRetainableType())
16306 return;
16307
16308 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16309 if (cast->getCastKind() == CK_ARCConsumeObject) {
16310 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
16311 << RHS->getSourceRange();
16312 return;
16313 }
16314 RHS = cast->getSubExpr();
16315 }
16316 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16317 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
16318 return;
16319 }
16320 }
16321}
16322
16323//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16324
16325static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16326 SourceLocation StmtLoc,
16327 const NullStmt *Body) {
16328 // Do not warn if the body is a macro that expands to nothing, e.g:
16329 //
16330 // #define CALL(x)
16331 // if (condition)
16332 // CALL(0);
16333 if (Body->hasLeadingEmptyMacro())
16334 return false;
16335
16336 // Get line numbers of statement and body.
16337 bool StmtLineInvalid;
16338 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
16339 Invalid: &StmtLineInvalid);
16340 if (StmtLineInvalid)
16341 return false;
16342
16343 bool BodyLineInvalid;
16344 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
16345 Invalid: &BodyLineInvalid);
16346 if (BodyLineInvalid)
16347 return false;
16348
16349 // Warn if null statement and body are on the same line.
16350 if (StmtLine != BodyLine)
16351 return false;
16352
16353 return true;
16354}
16355
16356void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16357 const Stmt *Body,
16358 unsigned DiagID) {
16359 // Since this is a syntactic check, don't emit diagnostic for template
16360 // instantiations, this just adds noise.
16361 if (CurrentInstantiationScope)
16362 return;
16363
16364 // The body should be a null statement.
16365 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16366 if (!NBody)
16367 return;
16368
16369 // Do the usual checks.
16370 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16371 return;
16372
16373 Diag(Loc: NBody->getSemiLoc(), DiagID);
16374 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16375}
16376
16377void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16378 const Stmt *PossibleBody) {
16379 assert(!CurrentInstantiationScope); // Ensured by caller
16380
16381 SourceLocation StmtLoc;
16382 const Stmt *Body;
16383 unsigned DiagID;
16384 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
16385 StmtLoc = FS->getRParenLoc();
16386 Body = FS->getBody();
16387 DiagID = diag::warn_empty_for_body;
16388 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
16389 StmtLoc = WS->getRParenLoc();
16390 Body = WS->getBody();
16391 DiagID = diag::warn_empty_while_body;
16392 } else
16393 return; // Neither `for' nor `while'.
16394
16395 // The body should be a null statement.
16396 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16397 if (!NBody)
16398 return;
16399
16400 // Skip expensive checks if diagnostic is disabled.
16401 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
16402 return;
16403
16404 // Do the usual checks.
16405 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16406 return;
16407
16408 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16409 // noise level low, emit diagnostics only if for/while is followed by a
16410 // CompoundStmt, e.g.:
16411 // for (int i = 0; i < n; i++);
16412 // {
16413 // a(i);
16414 // }
16415 // or if for/while is followed by a statement with more indentation
16416 // than for/while itself:
16417 // for (int i = 0; i < n; i++);
16418 // a(i);
16419 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
16420 if (!ProbableTypo) {
16421 bool BodyColInvalid;
16422 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16423 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
16424 if (BodyColInvalid)
16425 return;
16426
16427 bool StmtColInvalid;
16428 unsigned StmtCol =
16429 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
16430 if (StmtColInvalid)
16431 return;
16432
16433 if (BodyCol > StmtCol)
16434 ProbableTypo = true;
16435 }
16436
16437 if (ProbableTypo) {
16438 Diag(Loc: NBody->getSemiLoc(), DiagID);
16439 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16440 }
16441}
16442
16443//===--- CHECK: Warn on self move with std::move. -------------------------===//
16444
16445void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16446 SourceLocation OpLoc) {
16447 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
16448 return;
16449
16450 if (inTemplateInstantiation())
16451 return;
16452
16453 // Strip parens and casts away.
16454 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16455 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16456
16457 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16458 // which we can treat as an inlined std::move
16459 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
16460 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16461 RHSExpr = CE->getArg(Arg: 0);
16462 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
16463 CXXSCE && CXXSCE->isXValue())
16464 RHSExpr = CXXSCE->getSubExpr();
16465 else
16466 return;
16467
16468 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
16469 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
16470
16471 // Two DeclRefExpr's, check that the decls are the same.
16472 if (LHSDeclRef && RHSDeclRef) {
16473 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16474 return;
16475 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16476 RHSDeclRef->getDecl()->getCanonicalDecl())
16477 return;
16478
16479 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16480 << LHSExpr->getType() << LHSExpr->getSourceRange()
16481 << RHSExpr->getSourceRange();
16482 if (const FieldDecl *F =
16483 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
16484 D << 1 << F
16485 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
16486 else
16487 D << 0;
16488 return;
16489 }
16490
16491 // Member variables require a different approach to check for self moves.
16492 // MemberExpr's are the same if every nested MemberExpr refers to the same
16493 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16494 // the base Expr's are CXXThisExpr's.
16495 const Expr *LHSBase = LHSExpr;
16496 const Expr *RHSBase = RHSExpr;
16497 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
16498 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
16499 if (!LHSME || !RHSME)
16500 return;
16501
16502 while (LHSME && RHSME) {
16503 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16504 RHSME->getMemberDecl()->getCanonicalDecl())
16505 return;
16506
16507 LHSBase = LHSME->getBase();
16508 RHSBase = RHSME->getBase();
16509 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16510 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16511 }
16512
16513 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16514 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16515 if (LHSDeclRef && RHSDeclRef) {
16516 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16517 return;
16518 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16519 RHSDeclRef->getDecl()->getCanonicalDecl())
16520 return;
16521
16522 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16523 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16524 << RHSExpr->getSourceRange();
16525 return;
16526 }
16527
16528 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16529 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16530 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16531 << RHSExpr->getSourceRange();
16532}
16533
16534//===--- Layout compatibility ----------------------------------------------//
16535
16536static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16537
16538/// Check if two enumeration types are layout-compatible.
16539static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16540 const EnumDecl *ED2) {
16541 // C++11 [dcl.enum] p8:
16542 // Two enumeration types are layout-compatible if they have the same
16543 // underlying type.
16544 return ED1->isComplete() && ED2->isComplete() &&
16545 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16546}
16547
16548/// Check if two fields are layout-compatible.
16549/// Can be used on union members, which are exempt from alignment requirement
16550/// of common initial sequence.
16551static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16552 const FieldDecl *Field2,
16553 bool AreUnionMembers = false) {
16554#ifndef NDEBUG
16555 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16556 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16557 assert(((Field1Parent->isStructureOrClassType() &&
16558 Field2Parent->isStructureOrClassType()) ||
16559 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16560 "Can't evaluate layout compatibility between a struct field and a "
16561 "union field.");
16562 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16563 (AreUnionMembers && Field1Parent->isUnionType())) &&
16564 "AreUnionMembers should be 'true' for union fields (only).");
16565#endif
16566
16567 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16568 return false;
16569
16570 if (Field1->isBitField() != Field2->isBitField())
16571 return false;
16572
16573 if (Field1->isBitField()) {
16574 // Make sure that the bit-fields are the same length.
16575 unsigned Bits1 = Field1->getBitWidthValue();
16576 unsigned Bits2 = Field2->getBitWidthValue();
16577
16578 if (Bits1 != Bits2)
16579 return false;
16580 }
16581
16582 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16583 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16584 return false;
16585
16586 if (!AreUnionMembers &&
16587 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16588 return false;
16589
16590 return true;
16591}
16592
16593/// Check if two standard-layout structs are layout-compatible.
16594/// (C++11 [class.mem] p17)
16595static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16596 const RecordDecl *RD2) {
16597 // Get to the class where the fields are declared
16598 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16599 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16600
16601 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16602 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16603
16604 // Check the fields.
16605 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16606 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16607 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16608 });
16609}
16610
16611/// Check if two standard-layout unions are layout-compatible.
16612/// (C++11 [class.mem] p18)
16613static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16614 const RecordDecl *RD2) {
16615 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16616 RD2->fields());
16617
16618 for (auto *Field1 : RD1->fields()) {
16619 auto It = llvm::find_if(Range&: UnmatchedFields, P: [&](const FieldDecl *Field2) {
16620 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/AreUnionMembers: true);
16621 });
16622 if (It == UnmatchedFields.end())
16623 return false;
16624 [[maybe_unused]] bool Result = UnmatchedFields.erase(Ptr: *It);
16625 assert(Result);
16626 }
16627
16628 return UnmatchedFields.empty();
16629}
16630
16631static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16632 const RecordDecl *RD2) {
16633 if (RD1->isUnion() != RD2->isUnion())
16634 return false;
16635
16636 if (RD1->isUnion())
16637 return isLayoutCompatibleUnion(C, RD1, RD2);
16638 else
16639 return isLayoutCompatibleStruct(C, RD1, RD2);
16640}
16641
16642/// Check if two types are layout-compatible in C++11 sense.
16643static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16644 if (T1.isNull() || T2.isNull())
16645 return false;
16646
16647 // C++20 [basic.types] p11:
16648 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16649 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16650 // or layout-compatible standard-layout class types (11.4).
16651 T1 = T1.getCanonicalType().getUnqualifiedType();
16652 T2 = T2.getCanonicalType().getUnqualifiedType();
16653
16654 if (C.hasSameType(T1, T2))
16655 return true;
16656
16657 const Type::TypeClass TC1 = T1->getTypeClass();
16658 const Type::TypeClass TC2 = T2->getTypeClass();
16659
16660 if (TC1 != TC2)
16661 return false;
16662
16663 if (TC1 == Type::Enum)
16664 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16665 if (TC1 == Type::Record) {
16666 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16667 return false;
16668
16669 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16670 RD2: T2->castAsRecordDecl());
16671 }
16672
16673 return false;
16674}
16675
16676bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16677 return isLayoutCompatible(C: getASTContext(), T1, T2);
16678}
16679
16680//===-------------- Pointer interconvertibility ----------------------------//
16681
16682bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16683 const TypeSourceInfo *Derived) {
16684 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16685 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16686
16687 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16688 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16689 return true;
16690
16691 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16692 return false;
16693
16694 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16695 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16696 return true;
16697
16698 return false;
16699}
16700
16701//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16702
16703/// Given a type tag expression find the type tag itself.
16704///
16705/// \param TypeExpr Type tag expression, as it appears in user's code.
16706///
16707/// \param VD Declaration of an identifier that appears in a type tag.
16708///
16709/// \param MagicValue Type tag magic value.
16710///
16711/// \param isConstantEvaluated whether the evalaution should be performed in
16712
16713/// constant context.
16714static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16715 const ValueDecl **VD, uint64_t *MagicValue,
16716 bool isConstantEvaluated) {
16717 while(true) {
16718 if (!TypeExpr)
16719 return false;
16720
16721 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16722
16723 switch (TypeExpr->getStmtClass()) {
16724 case Stmt::UnaryOperatorClass: {
16725 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16726 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16727 TypeExpr = UO->getSubExpr();
16728 continue;
16729 }
16730 return false;
16731 }
16732
16733 case Stmt::DeclRefExprClass: {
16734 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16735 *VD = DRE->getDecl();
16736 return true;
16737 }
16738
16739 case Stmt::IntegerLiteralClass: {
16740 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16741 llvm::APInt MagicValueAPInt = IL->getValue();
16742 if (MagicValueAPInt.getActiveBits() <= 64) {
16743 *MagicValue = MagicValueAPInt.getZExtValue();
16744 return true;
16745 } else
16746 return false;
16747 }
16748
16749 case Stmt::BinaryConditionalOperatorClass:
16750 case Stmt::ConditionalOperatorClass: {
16751 const AbstractConditionalOperator *ACO =
16752 cast<AbstractConditionalOperator>(Val: TypeExpr);
16753 bool Result;
16754 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16755 InConstantContext: isConstantEvaluated)) {
16756 if (Result)
16757 TypeExpr = ACO->getTrueExpr();
16758 else
16759 TypeExpr = ACO->getFalseExpr();
16760 continue;
16761 }
16762 return false;
16763 }
16764
16765 case Stmt::BinaryOperatorClass: {
16766 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16767 if (BO->getOpcode() == BO_Comma) {
16768 TypeExpr = BO->getRHS();
16769 continue;
16770 }
16771 return false;
16772 }
16773
16774 default:
16775 return false;
16776 }
16777 }
16778}
16779
16780/// Retrieve the C type corresponding to type tag TypeExpr.
16781///
16782/// \param TypeExpr Expression that specifies a type tag.
16783///
16784/// \param MagicValues Registered magic values.
16785///
16786/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16787/// kind.
16788///
16789/// \param TypeInfo Information about the corresponding C type.
16790///
16791/// \param isConstantEvaluated whether the evalaution should be performed in
16792/// constant context.
16793///
16794/// \returns true if the corresponding C type was found.
16795static bool GetMatchingCType(
16796 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16797 const ASTContext &Ctx,
16798 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16799 *MagicValues,
16800 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16801 bool isConstantEvaluated) {
16802 FoundWrongKind = false;
16803
16804 // Variable declaration that has type_tag_for_datatype attribute.
16805 const ValueDecl *VD = nullptr;
16806
16807 uint64_t MagicValue;
16808
16809 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16810 return false;
16811
16812 if (VD) {
16813 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16814 if (I->getArgumentKind() != ArgumentKind) {
16815 FoundWrongKind = true;
16816 return false;
16817 }
16818 TypeInfo.Type = I->getMatchingCType();
16819 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16820 TypeInfo.MustBeNull = I->getMustBeNull();
16821 return true;
16822 }
16823 return false;
16824 }
16825
16826 if (!MagicValues)
16827 return false;
16828
16829 llvm::DenseMap<Sema::TypeTagMagicValue,
16830 Sema::TypeTagData>::const_iterator I =
16831 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16832 if (I == MagicValues->end())
16833 return false;
16834
16835 TypeInfo = I->second;
16836 return true;
16837}
16838
16839void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16840 uint64_t MagicValue, QualType Type,
16841 bool LayoutCompatible,
16842 bool MustBeNull) {
16843 if (!TypeTagForDatatypeMagicValues)
16844 TypeTagForDatatypeMagicValues.reset(
16845 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16846
16847 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16848 (*TypeTagForDatatypeMagicValues)[Magic] =
16849 TypeTagData(Type, LayoutCompatible, MustBeNull);
16850}
16851
16852static bool IsSameCharType(QualType T1, QualType T2) {
16853 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16854 if (!BT1)
16855 return false;
16856
16857 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16858 if (!BT2)
16859 return false;
16860
16861 BuiltinType::Kind T1Kind = BT1->getKind();
16862 BuiltinType::Kind T2Kind = BT2->getKind();
16863
16864 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16865 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16866 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16867 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16868}
16869
16870void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16871 const ArrayRef<const Expr *> ExprArgs,
16872 SourceLocation CallSiteLoc) {
16873 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16874 bool IsPointerAttr = Attr->getIsPointer();
16875
16876 // Retrieve the argument representing the 'type_tag'.
16877 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16878 if (TypeTagIdxAST >= ExprArgs.size()) {
16879 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16880 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16881 return;
16882 }
16883 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16884 bool FoundWrongKind;
16885 TypeTagData TypeInfo;
16886 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16887 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16888 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16889 if (FoundWrongKind)
16890 Diag(Loc: TypeTagExpr->getExprLoc(),
16891 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16892 << TypeTagExpr->getSourceRange();
16893 return;
16894 }
16895
16896 // Retrieve the argument representing the 'arg_idx'.
16897 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16898 if (ArgumentIdxAST >= ExprArgs.size()) {
16899 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16900 << 1 << Attr->getArgumentIdx().getSourceIndex();
16901 return;
16902 }
16903 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16904 if (IsPointerAttr) {
16905 // Skip implicit cast of pointer to `void *' (as a function argument).
16906 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16907 if (ICE->getType()->isVoidPointerType() &&
16908 ICE->getCastKind() == CK_BitCast)
16909 ArgumentExpr = ICE->getSubExpr();
16910 }
16911 QualType ArgumentType = ArgumentExpr->getType();
16912
16913 // Passing a `void*' pointer shouldn't trigger a warning.
16914 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16915 return;
16916
16917 if (TypeInfo.MustBeNull) {
16918 // Type tag with matching void type requires a null pointer.
16919 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16920 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16921 Diag(Loc: ArgumentExpr->getExprLoc(),
16922 DiagID: diag::warn_type_safety_null_pointer_required)
16923 << ArgumentKind->getName()
16924 << ArgumentExpr->getSourceRange()
16925 << TypeTagExpr->getSourceRange();
16926 }
16927 return;
16928 }
16929
16930 QualType RequiredType = TypeInfo.Type;
16931 if (IsPointerAttr)
16932 RequiredType = Context.getPointerType(T: RequiredType);
16933
16934 bool mismatch = false;
16935 if (!TypeInfo.LayoutCompatible) {
16936 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16937
16938 // C++11 [basic.fundamental] p1:
16939 // Plain char, signed char, and unsigned char are three distinct types.
16940 //
16941 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16942 // char' depending on the current char signedness mode.
16943 if (mismatch)
16944 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16945 T2: RequiredType->getPointeeType())) ||
16946 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16947 mismatch = false;
16948 } else
16949 if (IsPointerAttr)
16950 mismatch = !isLayoutCompatible(C: Context,
16951 T1: ArgumentType->getPointeeType(),
16952 T2: RequiredType->getPointeeType());
16953 else
16954 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16955
16956 if (mismatch)
16957 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16958 << ArgumentType << ArgumentKind
16959 << TypeInfo.LayoutCompatible << RequiredType
16960 << ArgumentExpr->getSourceRange()
16961 << TypeTagExpr->getSourceRange();
16962}
16963
16964void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16965 CharUnits Alignment) {
16966 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16967 Args&: Alignment);
16968}
16969
16970void Sema::DiagnoseMisalignedMembers() {
16971 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16972 const NamedDecl *ND = m.RD;
16973 if (ND->getName().empty()) {
16974 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16975 ND = TD;
16976 }
16977 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16978 << m.MD << ND << m.E->getSourceRange();
16979 }
16980 currentEvaluationContext().MisalignedMembers.clear();
16981}
16982
16983void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16984 E = E->IgnoreParens();
16985 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16986 return;
16987 if (isa<UnaryOperator>(Val: E) &&
16988 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16989 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16990 if (isa<MemberExpr>(Val: Op)) {
16991 auto &MisalignedMembersForExpr =
16992 currentEvaluationContext().MisalignedMembers;
16993 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16994 if (MA != MisalignedMembersForExpr.end() &&
16995 (T->isDependentType() || T->isIntegerType() ||
16996 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16997 Context.getTypeAlignInChars(
16998 T: T->getPointeeType()) <= MA->Alignment))))
16999 MisalignedMembersForExpr.erase(CI: MA);
17000 }
17001 }
17002}
17003
17004void Sema::RefersToMemberWithReducedAlignment(
17005 Expr *E,
17006 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17007 Action) {
17008 const auto *ME = dyn_cast<MemberExpr>(Val: E);
17009 if (!ME)
17010 return;
17011
17012 // No need to check expressions with an __unaligned-qualified type.
17013 if (E->getType().getQualifiers().hasUnaligned())
17014 return;
17015
17016 // For a chain of MemberExpr like "a.b.c.d" this list
17017 // will keep FieldDecl's like [d, c, b].
17018 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17019 const MemberExpr *TopME = nullptr;
17020 bool AnyIsPacked = false;
17021 do {
17022 QualType BaseType = ME->getBase()->getType();
17023 if (BaseType->isDependentType())
17024 return;
17025 if (ME->isArrow())
17026 BaseType = BaseType->getPointeeType();
17027 auto *RD = BaseType->castAsRecordDecl();
17028 if (RD->isInvalidDecl())
17029 return;
17030
17031 ValueDecl *MD = ME->getMemberDecl();
17032 auto *FD = dyn_cast<FieldDecl>(Val: MD);
17033 // We do not care about non-data members.
17034 if (!FD || FD->isInvalidDecl())
17035 return;
17036
17037 AnyIsPacked =
17038 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17039 ReverseMemberChain.push_back(Elt: FD);
17040
17041 TopME = ME;
17042 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
17043 } while (ME);
17044 assert(TopME && "We did not compute a topmost MemberExpr!");
17045
17046 // Not the scope of this diagnostic.
17047 if (!AnyIsPacked)
17048 return;
17049
17050 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17051 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
17052 // TODO: The innermost base of the member expression may be too complicated.
17053 // For now, just disregard these cases. This is left for future
17054 // improvement.
17055 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
17056 return;
17057
17058 // Alignment expected by the whole expression.
17059 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
17060
17061 // No need to do anything else with this case.
17062 if (ExpectedAlignment.isOne())
17063 return;
17064
17065 // Synthesize offset of the whole access.
17066 CharUnits Offset;
17067 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
17068 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
17069
17070 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17071 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17072 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
17073
17074 // The base expression of the innermost MemberExpr may give
17075 // stronger guarantees than the class containing the member.
17076 if (DRE && !TopME->isArrow()) {
17077 const ValueDecl *VD = DRE->getDecl();
17078 if (!VD->getType()->isReferenceType())
17079 CompleteObjectAlignment =
17080 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
17081 }
17082
17083 // Check if the synthesized offset fulfills the alignment.
17084 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
17085 // It may fulfill the offset it but the effective alignment may still be
17086 // lower than the expected expression alignment.
17087 CompleteObjectAlignment < ExpectedAlignment) {
17088 // If this happens, we want to determine a sensible culprit of this.
17089 // Intuitively, watching the chain of member expressions from right to
17090 // left, we start with the required alignment (as required by the field
17091 // type) but some packed attribute in that chain has reduced the alignment.
17092 // It may happen that another packed structure increases it again. But if
17093 // we are here such increase has not been enough. So pointing the first
17094 // FieldDecl that either is packed or else its RecordDecl is,
17095 // seems reasonable.
17096 FieldDecl *FD = nullptr;
17097 CharUnits Alignment;
17098 for (FieldDecl *FDI : ReverseMemberChain) {
17099 if (FDI->hasAttr<PackedAttr>() ||
17100 FDI->getParent()->hasAttr<PackedAttr>()) {
17101 FD = FDI;
17102 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
17103 b: Context.getTypeAlignInChars(
17104 T: Context.getCanonicalTagType(TD: FD->getParent())));
17105 break;
17106 }
17107 }
17108 assert(FD && "We did not find a packed FieldDecl!");
17109 Action(E, FD->getParent(), FD, Alignment);
17110 }
17111}
17112
17113void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17114 using namespace std::placeholders;
17115
17116 RefersToMemberWithReducedAlignment(
17117 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
17118 args: _2, args: _3, args: _4));
17119}
17120
17121bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
17122 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17123 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17124 return true;
17125
17126 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
17127 if (A.isInvalid())
17128 return true;
17129
17130 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17131 QualType TyA = A.get()->getType();
17132
17133 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
17134 ArgTyRestr, ArgOrdinal: 1))
17135 return true;
17136
17137 TheCall->setType(TyA);
17138 return false;
17139}
17140
17141bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17142 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17143 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17144 TheCall->setType(*Res);
17145 return false;
17146 }
17147 return true;
17148}
17149
17150bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
17151 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17152 if (!Res)
17153 return true;
17154
17155 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17156 TheCall->setType(VecTy0->getElementType());
17157 else
17158 TheCall->setType(*Res);
17159
17160 return false;
17161}
17162
17163static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
17164 SourceLocation Loc) {
17165 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
17166 R = RHS->getEnumCoercedType(Ctx: S.Context);
17167 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17168 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
17169 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
17170 << LHS->getSourceRange() << RHS->getSourceRange()
17171 << /*Arithmetic Between*/ 0 << L << R;
17172 }
17173 return false;
17174}
17175
17176/// Check if all arguments have the same type. If the types don't match, emit an
17177/// error message and return true. Otherwise return false.
17178///
17179/// For scalars we directly compare their unqualified types. But even if we
17180/// compare unqualified vector types, a difference in qualifiers in the element
17181/// types can make the vector types be considered not equal. For example,
17182/// vector of 4 'const float' values vs vector of 4 'float' values.
17183/// So we compare unqualified types of their elements and number of elements.
17184static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
17185 ArrayRef<Expr *> Args) {
17186 assert(!Args.empty() && "Should have at least one argument.");
17187
17188 Expr *Arg0 = Args.front();
17189 QualType Ty0 = Arg0->getType();
17190
17191 auto EmitError = [&](Expr *ArgI) {
17192 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
17193 DiagID: diag::err_typecheck_call_different_arg_types)
17194 << Arg0->getType() << ArgI->getType();
17195 };
17196
17197 // Compare scalar types.
17198 if (!Ty0->isVectorType()) {
17199 for (Expr *ArgI : Args.drop_front())
17200 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
17201 EmitError(ArgI);
17202 return true;
17203 }
17204
17205 return false;
17206 }
17207
17208 // Compare vector types.
17209 const auto *Vec0 = Ty0->castAs<VectorType>();
17210 for (Expr *ArgI : Args.drop_front()) {
17211 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17212 if (!VecI ||
17213 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
17214 T2: VecI->getElementType()) ||
17215 Vec0->getNumElements() != VecI->getNumElements()) {
17216 EmitError(ArgI);
17217 return true;
17218 }
17219 }
17220
17221 return false;
17222}
17223
17224std::optional<QualType>
17225Sema::BuiltinVectorMath(CallExpr *TheCall,
17226 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17227 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
17228 return std::nullopt;
17229
17230 if (checkBuiltinVectorMathMixedEnums(
17231 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
17232 return std::nullopt;
17233
17234 Expr *Args[2];
17235 for (int I = 0; I < 2; ++I) {
17236 ExprResult Converted =
17237 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17238 if (Converted.isInvalid())
17239 return std::nullopt;
17240 Args[I] = Converted.get();
17241 }
17242
17243 SourceLocation LocA = Args[0]->getBeginLoc();
17244 QualType TyA = Args[0]->getType();
17245
17246 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
17247 return std::nullopt;
17248
17249 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17250 return std::nullopt;
17251
17252 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
17253 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
17254 return TyA;
17255}
17256
17257bool Sema::BuiltinElementwiseTernaryMath(
17258 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17259 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17260 return true;
17261
17262 SourceLocation Loc = TheCall->getExprLoc();
17263 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
17264 RHS: TheCall->getArg(Arg: 1), Loc) ||
17265 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
17266 RHS: TheCall->getArg(Arg: 2), Loc))
17267 return true;
17268
17269 Expr *Args[3];
17270 for (int I = 0; I < 3; ++I) {
17271 ExprResult Converted =
17272 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17273 if (Converted.isInvalid())
17274 return true;
17275 Args[I] = Converted.get();
17276 }
17277
17278 int ArgOrdinal = 1;
17279 for (Expr *Arg : Args) {
17280 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
17281 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
17282 return true;
17283 }
17284
17285 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17286 return true;
17287
17288 for (int I = 0; I < 3; ++I)
17289 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
17290
17291 TheCall->setType(Args[0]->getType());
17292 return false;
17293}
17294
17295bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17296 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17297 return true;
17298
17299 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
17300 if (A.isInvalid())
17301 return true;
17302
17303 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17304 return false;
17305}
17306
17307bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17308 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17309 return true;
17310
17311 ExprResult Arg = TheCall->getArg(Arg: 0);
17312 QualType TyArg = Arg.get()->getType();
17313
17314 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17315 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
17316 DiagID: diag::err_builtin_invalid_arg_type)
17317 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17318
17319 TheCall->setType(TyArg);
17320 return false;
17321}
17322
17323ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17324 ExprResult CallResult) {
17325 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17326 return ExprError();
17327
17328 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
17329 if (MatrixArg.isInvalid())
17330 return MatrixArg;
17331 Expr *Matrix = MatrixArg.get();
17332
17333 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17334 if (!MType) {
17335 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17336 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17337 << Matrix->getType();
17338 return ExprError();
17339 }
17340
17341 // Create returned matrix type by swapping rows and columns of the argument
17342 // matrix type.
17343 QualType ResultType = Context.getConstantMatrixType(
17344 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
17345
17346 // Change the return type to the type of the returned matrix.
17347 TheCall->setType(ResultType);
17348
17349 // Update call argument to use the possibly converted matrix argument.
17350 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
17351 return CallResult;
17352}
17353
17354// Get and verify the matrix dimensions.
17355static std::optional<unsigned>
17356getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17357 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
17358 if (!Value) {
17359 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
17360 << Name;
17361 return {};
17362 }
17363 uint64_t Dim = Value->getZExtValue();
17364 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17365 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
17366 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17367 return {};
17368 }
17369 return Dim;
17370}
17371
17372ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17373 ExprResult CallResult) {
17374 if (!getLangOpts().MatrixTypes) {
17375 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17376 return ExprError();
17377 }
17378
17379 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17380 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17381 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17382 << /*column*/ 1 << /*load*/ 0;
17383 return ExprError();
17384 }
17385
17386 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
17387 return ExprError();
17388
17389 unsigned PtrArgIdx = 0;
17390 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17391 Expr *RowsExpr = TheCall->getArg(Arg: 1);
17392 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
17393 Expr *StrideExpr = TheCall->getArg(Arg: 3);
17394
17395 bool ArgError = false;
17396
17397 // Check pointer argument.
17398 {
17399 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17400 if (PtrConv.isInvalid())
17401 return PtrConv;
17402 PtrExpr = PtrConv.get();
17403 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
17404 if (PtrExpr->isTypeDependent()) {
17405 TheCall->setType(Context.DependentTy);
17406 return TheCall;
17407 }
17408 }
17409
17410 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17411 QualType ElementTy;
17412 if (!PtrTy) {
17413 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17414 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17415 << PtrExpr->getType();
17416 ArgError = true;
17417 } else {
17418 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17419
17420 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
17421 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17422 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17423 << /* no fp */ 0 << PtrExpr->getType();
17424 ArgError = true;
17425 }
17426 }
17427
17428 // Apply default Lvalue conversions and convert the expression to size_t.
17429 auto ApplyArgumentConversions = [this](Expr *E) {
17430 ExprResult Conv = DefaultLvalueConversion(E);
17431 if (Conv.isInvalid())
17432 return Conv;
17433
17434 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
17435 };
17436
17437 // Apply conversion to row and column expressions.
17438 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17439 if (!RowsConv.isInvalid()) {
17440 RowsExpr = RowsConv.get();
17441 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
17442 } else
17443 RowsExpr = nullptr;
17444
17445 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17446 if (!ColumnsConv.isInvalid()) {
17447 ColumnsExpr = ColumnsConv.get();
17448 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
17449 } else
17450 ColumnsExpr = nullptr;
17451
17452 // If any part of the result matrix type is still pending, just use
17453 // Context.DependentTy, until all parts are resolved.
17454 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17455 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17456 TheCall->setType(Context.DependentTy);
17457 return CallResult;
17458 }
17459
17460 // Check row and column dimensions.
17461 std::optional<unsigned> MaybeRows;
17462 if (RowsExpr)
17463 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
17464
17465 std::optional<unsigned> MaybeColumns;
17466 if (ColumnsExpr)
17467 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
17468
17469 // Check stride argument.
17470 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17471 if (StrideConv.isInvalid())
17472 return ExprError();
17473 StrideExpr = StrideConv.get();
17474 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
17475
17476 if (MaybeRows) {
17477 if (std::optional<llvm::APSInt> Value =
17478 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17479 uint64_t Stride = Value->getZExtValue();
17480 if (Stride < *MaybeRows) {
17481 Diag(Loc: StrideExpr->getBeginLoc(),
17482 DiagID: diag::err_builtin_matrix_stride_too_small);
17483 ArgError = true;
17484 }
17485 }
17486 }
17487
17488 if (ArgError || !MaybeRows || !MaybeColumns)
17489 return ExprError();
17490
17491 TheCall->setType(
17492 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
17493 return CallResult;
17494}
17495
17496ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17497 ExprResult CallResult) {
17498 if (!getLangOpts().MatrixTypes) {
17499 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17500 return ExprError();
17501 }
17502
17503 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17504 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17505 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17506 << /*column*/ 1 << /*store*/ 1;
17507 return ExprError();
17508 }
17509
17510 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17511 return ExprError();
17512
17513 unsigned PtrArgIdx = 1;
17514 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17515 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17516 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17517
17518 bool ArgError = false;
17519
17520 {
17521 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17522 if (MatrixConv.isInvalid())
17523 return MatrixConv;
17524 MatrixExpr = MatrixConv.get();
17525 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17526 }
17527 if (MatrixExpr->isTypeDependent()) {
17528 TheCall->setType(Context.DependentTy);
17529 return TheCall;
17530 }
17531
17532 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17533 if (!MatrixTy) {
17534 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17535 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17536 ArgError = true;
17537 }
17538
17539 {
17540 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17541 if (PtrConv.isInvalid())
17542 return PtrConv;
17543 PtrExpr = PtrConv.get();
17544 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17545 if (PtrExpr->isTypeDependent()) {
17546 TheCall->setType(Context.DependentTy);
17547 return TheCall;
17548 }
17549 }
17550
17551 // Check pointer argument.
17552 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17553 if (!PtrTy) {
17554 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17555 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17556 << PtrExpr->getType();
17557 ArgError = true;
17558 } else {
17559 QualType ElementTy = PtrTy->getPointeeType();
17560 if (ElementTy.isConstQualified()) {
17561 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17562 ArgError = true;
17563 }
17564 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17565 if (MatrixTy &&
17566 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17567 Diag(Loc: PtrExpr->getBeginLoc(),
17568 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17569 << ElementTy << MatrixTy->getElementType();
17570 ArgError = true;
17571 }
17572 }
17573
17574 // Apply default Lvalue conversions and convert the stride expression to
17575 // size_t.
17576 {
17577 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17578 if (StrideConv.isInvalid())
17579 return StrideConv;
17580
17581 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17582 if (StrideConv.isInvalid())
17583 return StrideConv;
17584 StrideExpr = StrideConv.get();
17585 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17586 }
17587
17588 // Check stride argument.
17589 if (MatrixTy) {
17590 if (std::optional<llvm::APSInt> Value =
17591 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17592 uint64_t Stride = Value->getZExtValue();
17593 if (Stride < MatrixTy->getNumRows()) {
17594 Diag(Loc: StrideExpr->getBeginLoc(),
17595 DiagID: diag::err_builtin_matrix_stride_too_small);
17596 ArgError = true;
17597 }
17598 }
17599 }
17600
17601 if (ArgError)
17602 return ExprError();
17603
17604 return CallResult;
17605}
17606
17607void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17608 const NamedDecl *Callee) {
17609 // This warning does not make sense in code that has no runtime behavior.
17610 if (isUnevaluatedContext())
17611 return;
17612
17613 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17614
17615 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17616 return;
17617
17618 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17619 // all TCBs the callee is a part of.
17620 llvm::StringSet<> CalleeTCBs;
17621 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17622 CalleeTCBs.insert(key: A->getTCBName());
17623 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17624 CalleeTCBs.insert(key: A->getTCBName());
17625
17626 // Go through the TCBs the caller is a part of and emit warnings if Caller
17627 // is in a TCB that the Callee is not.
17628 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17629 StringRef CallerTCB = A->getTCBName();
17630 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17631 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17632 << Callee << CallerTCB;
17633 }
17634 }
17635}
17636