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/Diagnostic.h"
45#include "clang/Basic/DiagnosticSema.h"
46#include "clang/Basic/IdentifierTable.h"
47#include "clang/Basic/LLVM.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/OpenCLOptions.h"
50#include "clang/Basic/OperatorKinds.h"
51#include "clang/Basic/PartialDiagnostic.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/SourceManager.h"
54#include "clang/Basic/Specifiers.h"
55#include "clang/Basic/SyncScope.h"
56#include "clang/Basic/TargetInfo.h"
57#include "clang/Basic/TypeTraits.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/SemaSystemZ.h"
80#include "clang/Sema/SemaWasm.h"
81#include "clang/Sema/SemaX86.h"
82#include "llvm/ADT/APFloat.h"
83#include "llvm/ADT/APInt.h"
84#include "llvm/ADT/APSInt.h"
85#include "llvm/ADT/ArrayRef.h"
86#include "llvm/ADT/DenseMap.h"
87#include "llvm/ADT/FoldingSet.h"
88#include "llvm/ADT/STLExtras.h"
89#include "llvm/ADT/STLForwardCompat.h"
90#include "llvm/ADT/SmallBitVector.h"
91#include "llvm/ADT/SmallPtrSet.h"
92#include "llvm/ADT/SmallString.h"
93#include "llvm/ADT/SmallVector.h"
94#include "llvm/ADT/StringExtras.h"
95#include "llvm/ADT/StringRef.h"
96#include "llvm/ADT/StringSet.h"
97#include "llvm/ADT/StringSwitch.h"
98#include "llvm/Support/AtomicOrdering.h"
99#include "llvm/Support/Compiler.h"
100#include "llvm/Support/ConvertUTF.h"
101#include "llvm/Support/ErrorHandling.h"
102#include "llvm/Support/Format.h"
103#include "llvm/Support/Locale.h"
104#include "llvm/Support/MathExtras.h"
105#include "llvm/Support/SaveAndRestore.h"
106#include "llvm/Support/raw_ostream.h"
107#include "llvm/TargetParser/RISCVTargetParser.h"
108#include "llvm/TargetParser/Triple.h"
109#include <algorithm>
110#include <cassert>
111#include <cctype>
112#include <cstddef>
113#include <cstdint>
114#include <functional>
115#include <limits>
116#include <optional>
117#include <string>
118#include <tuple>
119#include <utility>
120
121using namespace clang;
122using namespace sema;
123
124SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
125 unsigned ByteNo) const {
126 return SL->getLocationOfByte(ByteNo, SM: getSourceManager(), Features: LangOpts,
127 Target: Context.getTargetInfo());
128}
129
130static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
131 Sema::FormatArgumentPassingKind B) {
132 return (A << 8) | B;
133}
134
135bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
136 unsigned ArgCount = Call->getNumArgs();
137 if (ArgCount >= MinArgCount)
138 return false;
139
140 return Diag(Loc: Call->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
141 << 0 /*function call*/ << MinArgCount << ArgCount
142 << /*is non object*/ 0 << Call->getSourceRange();
143}
144
145bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
146 unsigned ArgCount = Call->getNumArgs();
147 if (ArgCount <= MaxArgCount)
148 return false;
149 return Diag(Loc: Call->getEndLoc(), DiagID: diag::err_typecheck_call_too_many_args_at_most)
150 << 0 /*function call*/ << MaxArgCount << ArgCount
151 << /*is non object*/ 0 << Call->getSourceRange();
152}
153
154bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
155 unsigned MaxArgCount) {
156 return checkArgCountAtLeast(Call, MinArgCount) ||
157 checkArgCountAtMost(Call, MaxArgCount);
158}
159
160bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
161 unsigned ArgCount = Call->getNumArgs();
162 if (ArgCount == DesiredArgCount)
163 return false;
164
165 if (checkArgCountAtLeast(Call, MinArgCount: DesiredArgCount))
166 return true;
167 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
168
169 // Highlight all the excess arguments.
170 SourceRange Range(Call->getArg(Arg: DesiredArgCount)->getBeginLoc(),
171 Call->getArg(Arg: ArgCount - 1)->getEndLoc());
172
173 return Diag(Loc: Range.getBegin(), DiagID: diag::err_typecheck_call_too_many_args)
174 << 0 /*function call*/ << DesiredArgCount << ArgCount
175 << /*is non object*/ 0 << Range;
176}
177
178static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {
179 bool HasError = false;
180
181 for (const Expr *Arg : Call->arguments()) {
182 if (Arg->isValueDependent())
183 continue;
184
185 std::optional<std::string> ArgString = Arg->tryEvaluateString(Ctx&: S.Context);
186 int DiagMsgKind = -1;
187 // Arguments must be pointers to constant strings and cannot use '$'.
188 if (!ArgString.has_value())
189 DiagMsgKind = 0;
190 else if (ArgString->find(c: '$') != std::string::npos)
191 DiagMsgKind = 1;
192
193 if (DiagMsgKind >= 0) {
194 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_verbose_trap_arg)
195 << DiagMsgKind << Arg->getSourceRange();
196 HasError = true;
197 }
198 }
199
200 return !HasError;
201}
202
203static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
204 if (Value->isTypeDependent())
205 return false;
206
207 InitializedEntity Entity =
208 InitializedEntity::InitializeParameter(Context&: S.Context, Type: Ty, Consumed: false);
209 ExprResult Result =
210 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
211 if (Result.isInvalid())
212 return true;
213 Value = Result.get();
214 return false;
215}
216
217/// Check that the first argument to __builtin_annotation is an integer
218/// and the second argument is a non-wide string literal.
219static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
220 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
221 return true;
222
223 // First argument should be an integer.
224 Expr *ValArg = TheCall->getArg(Arg: 0);
225 QualType Ty = ValArg->getType();
226 if (!Ty->isIntegerType()) {
227 S.Diag(Loc: ValArg->getBeginLoc(), DiagID: diag::err_builtin_annotation_first_arg)
228 << ValArg->getSourceRange();
229 return true;
230 }
231
232 // Second argument should be a constant string.
233 Expr *StrArg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
234 StringLiteral *Literal = dyn_cast<StringLiteral>(Val: StrArg);
235 if (!Literal || !Literal->isOrdinary()) {
236 S.Diag(Loc: StrArg->getBeginLoc(), DiagID: diag::err_builtin_annotation_second_arg)
237 << StrArg->getSourceRange();
238 return true;
239 }
240
241 TheCall->setType(Ty);
242 return false;
243}
244
245static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
246 // We need at least one argument.
247 if (TheCall->getNumArgs() < 1) {
248 S.Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
249 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
250 << TheCall->getCallee()->getSourceRange();
251 return true;
252 }
253
254 // All arguments should be wide string literals.
255 for (Expr *Arg : TheCall->arguments()) {
256 auto *Literal = dyn_cast<StringLiteral>(Val: Arg->IgnoreParenCasts());
257 if (!Literal || !Literal->isWide()) {
258 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_msvc_annotation_wide_str)
259 << Arg->getSourceRange();
260 return true;
261 }
262 }
263
264 return false;
265}
266
267/// Check that the argument to __builtin_addressof is a glvalue, and set the
268/// result type to the corresponding pointer type.
269static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
270 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
271 return true;
272
273 ExprResult Arg(TheCall->getArg(Arg: 0));
274 QualType ResultType = S.CheckAddressOfOperand(Operand&: Arg, OpLoc: TheCall->getBeginLoc());
275 if (ResultType.isNull())
276 return true;
277
278 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
279 TheCall->setType(ResultType);
280 return false;
281}
282
283/// Check that the argument to __builtin_function_start is a function.
284static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
285 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
286 return true;
287
288 if (TheCall->getArg(Arg: 0)->containsErrors())
289 return true;
290
291 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
292 if (Arg.isInvalid())
293 return true;
294
295 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
296 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
297 Val: Arg.get()->getAsBuiltinConstantDeclRef(Context: S.getASTContext()));
298
299 if (!FD) {
300 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_function_start_invalid_type)
301 << TheCall->getSourceRange();
302 return true;
303 }
304
305 return !S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
306 Loc: TheCall->getBeginLoc());
307}
308
309/// Check the number of arguments and set the result type to
310/// the argument type.
311static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
312 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
313 return true;
314
315 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
316 return false;
317}
318
319/// Check that the value argument for __builtin_is_aligned(value, alignment) and
320/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
321/// type (but not a function pointer) and that the alignment is a power-of-two.
322static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
323 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
324 return true;
325
326 clang::Expr *Source = TheCall->getArg(Arg: 0);
327 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
328
329 auto IsValidIntegerType = [](QualType Ty) {
330 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
331 };
332 QualType SrcTy = Source->getType();
333 // We should also be able to use it with arrays (but not functions!).
334 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
335 SrcTy = S.Context.getDecayedType(T: SrcTy);
336 }
337 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
338 SrcTy->isFunctionPointerType()) {
339 // FIXME: this is not quite the right error message since we don't allow
340 // floating point types, or member pointers.
341 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::err_typecheck_expect_scalar_operand)
342 << SrcTy;
343 return true;
344 }
345
346 clang::Expr *AlignOp = TheCall->getArg(Arg: 1);
347 if (!IsValidIntegerType(AlignOp->getType())) {
348 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_typecheck_expect_int)
349 << AlignOp->getType();
350 return true;
351 }
352 Expr::EvalResult AlignResult;
353 unsigned MaxAlignmentBits = S.Context.getIntWidth(T: SrcTy) - 1;
354 // We can't check validity of alignment if it is value dependent.
355 if (!AlignOp->isValueDependent() &&
356 AlignOp->EvaluateAsInt(Result&: AlignResult, Ctx: S.Context,
357 AllowSideEffects: Expr::SE_AllowSideEffects)) {
358 llvm::APSInt AlignValue = AlignResult.Val.getInt();
359 llvm::APSInt MaxValue(
360 llvm::APInt::getOneBitSet(numBits: MaxAlignmentBits + 1, BitNo: MaxAlignmentBits));
361 if (AlignValue < 1) {
362 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_small) << 1;
363 return true;
364 }
365 if (llvm::APSInt::compareValues(I1: AlignValue, I2: MaxValue) > 0) {
366 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_big)
367 << toString(I: MaxValue, Radix: 10);
368 return true;
369 }
370 if (!AlignValue.isPowerOf2()) {
371 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_not_power_of_two);
372 return true;
373 }
374 if (AlignValue == 1) {
375 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::warn_alignment_builtin_useless)
376 << IsBooleanAlignBuiltin;
377 }
378 }
379
380 ExprResult SrcArg = S.PerformCopyInitialization(
381 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Type: SrcTy, Consumed: false),
382 EqualLoc: SourceLocation(), Init: Source);
383 if (SrcArg.isInvalid())
384 return true;
385 TheCall->setArg(Arg: 0, ArgExpr: SrcArg.get());
386 ExprResult AlignArg =
387 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
388 Context&: S.Context, Type: AlignOp->getType(), Consumed: false),
389 EqualLoc: SourceLocation(), Init: AlignOp);
390 if (AlignArg.isInvalid())
391 return true;
392 TheCall->setArg(Arg: 1, ArgExpr: AlignArg.get());
393 // For align_up/align_down, the return type is the same as the (potentially
394 // decayed) argument type including qualifiers. For is_aligned(), the result
395 // is always bool.
396 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
397 return false;
398}
399
400static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
401 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
402 return true;
403
404 std::pair<unsigned, const char *> Builtins[] = {
405 { Builtin::BI__builtin_add_overflow, "ckd_add" },
406 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
407 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
408 };
409
410 bool CkdOperation = llvm::any_of(Range&: Builtins, P: [&](const std::pair<unsigned,
411 const char *> &P) {
412 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
413 Lexer::getImmediateMacroName(Loc: TheCall->getExprLoc(),
414 SM: S.getSourceManager(), LangOpts: S.getLangOpts()) == P.second;
415 });
416
417 auto ValidCkdIntType = [](QualType QT) {
418 // A valid checked integer type is an integer type other than a plain char,
419 // bool, a bit-precise type, or an enumeration type.
420 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
421 return (BT->getKind() >= BuiltinType::Short &&
422 BT->getKind() <= BuiltinType::Int128) || (
423 BT->getKind() >= BuiltinType::UShort &&
424 BT->getKind() <= BuiltinType::UInt128) ||
425 BT->getKind() == BuiltinType::UChar ||
426 BT->getKind() == BuiltinType::SChar;
427 return false;
428 };
429
430 // First two arguments should be integers.
431 for (unsigned I = 0; I < 2; ++I) {
432 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: I));
433 if (Arg.isInvalid()) return true;
434 TheCall->setArg(Arg: I, ArgExpr: Arg.get());
435
436 QualType Ty = Arg.get()->getType();
437 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
438 if (!IsValid) {
439 S.Diag(Loc: Arg.get()->getBeginLoc(), DiagID: diag::err_overflow_builtin_must_be_int)
440 << CkdOperation << Ty << Arg.get()->getSourceRange();
441 return true;
442 }
443 }
444
445 // Third argument should be a pointer to a non-const integer.
446 // IRGen correctly handles volatile, restrict, and address spaces, and
447 // the other qualifiers aren't possible.
448 {
449 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 2));
450 if (Arg.isInvalid()) return true;
451 TheCall->setArg(Arg: 2, ArgExpr: Arg.get());
452
453 QualType Ty = Arg.get()->getType();
454 const auto *PtrTy = Ty->getAs<PointerType>();
455 if (!PtrTy ||
456 !PtrTy->getPointeeType()->isIntegerType() ||
457 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
458 PtrTy->getPointeeType().isConstQualified()) {
459 S.Diag(Loc: Arg.get()->getBeginLoc(),
460 DiagID: diag::err_overflow_builtin_must_be_ptr_int)
461 << CkdOperation << Ty << Arg.get()->getSourceRange();
462 return true;
463 }
464 }
465
466 // Disallow signed bit-precise integer args larger than 128 bits to mul
467 // function until we improve backend support.
468 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
469 for (unsigned I = 0; I < 3; ++I) {
470 const auto Arg = TheCall->getArg(Arg: I);
471 // Third argument will be a pointer.
472 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
473 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
474 S.getASTContext().getIntWidth(T: Ty) > 128)
475 return S.Diag(Loc: Arg->getBeginLoc(),
476 DiagID: diag::err_overflow_builtin_bit_int_max_size)
477 << 128;
478 }
479 }
480
481 return false;
482}
483
484namespace {
485struct BuiltinDumpStructGenerator {
486 Sema &S;
487 CallExpr *TheCall;
488 SourceLocation Loc = TheCall->getBeginLoc();
489 SmallVector<Expr *, 32> Actions;
490 DiagnosticErrorTrap ErrorTracker;
491 PrintingPolicy Policy;
492
493 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
494 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
495 Policy(S.Context.getPrintingPolicy()) {
496 Policy.AnonymousTagLocations = false;
497 }
498
499 Expr *makeOpaqueValueExpr(Expr *Inner) {
500 auto *OVE = new (S.Context)
501 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
502 Inner->getObjectKind(), Inner);
503 Actions.push_back(Elt: OVE);
504 return OVE;
505 }
506
507 Expr *getStringLiteral(llvm::StringRef Str) {
508 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
509 // Wrap the literal in parentheses to attach a source location.
510 return new (S.Context) ParenExpr(Loc, Loc, Lit);
511 }
512
513 bool callPrintFunction(llvm::StringRef Format,
514 llvm::ArrayRef<Expr *> Exprs = {}) {
515 SmallVector<Expr *, 8> Args;
516 assert(TheCall->getNumArgs() >= 2);
517 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
518 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
519 Args.push_back(Elt: getStringLiteral(Str: Format));
520 llvm::append_range(C&: Args, R&: Exprs);
521
522 // Register a note to explain why we're performing the call.
523 Sema::CodeSynthesisContext Ctx;
524 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
525 Ctx.PointOfInstantiation = Loc;
526 Ctx.CallArgs = Args.data();
527 Ctx.NumCallArgs = Args.size();
528 S.pushCodeSynthesisContext(Ctx);
529
530 ExprResult RealCall =
531 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
532 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
533
534 S.popCodeSynthesisContext();
535 if (!RealCall.isInvalid())
536 Actions.push_back(Elt: RealCall.get());
537 // Bail out if we've hit any errors, even if we managed to build the
538 // call. We don't want to produce more than one error.
539 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
540 }
541
542 Expr *getIndentString(unsigned Depth) {
543 if (!Depth)
544 return nullptr;
545
546 llvm::SmallString<32> Indent;
547 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
548 return getStringLiteral(Str: Indent);
549 }
550
551 Expr *getTypeString(QualType T) {
552 return getStringLiteral(Str: T.getAsString(Policy));
553 }
554
555 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
556 llvm::raw_svector_ostream OS(Str);
557
558 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
559 // than trying to print a single character.
560 if (auto *BT = T->getAs<BuiltinType>()) {
561 switch (BT->getKind()) {
562 case BuiltinType::Bool:
563 OS << "%d";
564 return true;
565 case BuiltinType::Char_U:
566 case BuiltinType::UChar:
567 OS << "%hhu";
568 return true;
569 case BuiltinType::Char_S:
570 case BuiltinType::SChar:
571 OS << "%hhd";
572 return true;
573 default:
574 break;
575 }
576 }
577
578 analyze_printf::PrintfSpecifier Specifier;
579 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
580 // We were able to guess how to format this.
581 if (Specifier.getConversionSpecifier().getKind() ==
582 analyze_printf::PrintfConversionSpecifier::sArg) {
583 // Wrap double-quotes around a '%s' specifier and limit its maximum
584 // length. Ideally we'd also somehow escape special characters in the
585 // contents but printf doesn't support that.
586 // FIXME: '%s' formatting is not safe in general.
587 OS << '"';
588 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
589 Specifier.toString(os&: OS);
590 OS << '"';
591 // FIXME: It would be nice to include a '...' if the string doesn't fit
592 // in the length limit.
593 } else {
594 Specifier.toString(os&: OS);
595 }
596 return true;
597 }
598
599 if (T->isPointerType()) {
600 // Format all pointers with '%p'.
601 OS << "%p";
602 return true;
603 }
604
605 return false;
606 }
607
608 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
609 Expr *IndentLit = getIndentString(Depth);
610 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
611 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
612 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
613 return true;
614
615 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
616 }
617
618 // Dump a record value. E should be a pointer or lvalue referring to an RD.
619 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
620 unsigned Depth) {
621 // FIXME: Decide what to do if RD is a union. At least we should probably
622 // turn off printing `const char*` members with `%s`, because that is very
623 // likely to crash if that's not the active member. Whatever we decide, we
624 // should document it.
625
626 // Build an OpaqueValueExpr so we can refer to E more than once without
627 // triggering re-evaluation.
628 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
629 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
630
631 if (callPrintFunction(Format: " {\n"))
632 return true;
633
634 // Dump each base class, regardless of whether they're aggregates.
635 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
636 for (const auto &Base : CXXRD->bases()) {
637 QualType BaseType =
638 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
639 : S.Context.getLValueReferenceType(T: Base.getType());
640 ExprResult BasePtr = S.BuildCStyleCastExpr(
641 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
642 Op: RecordArg);
643 if (BasePtr.isInvalid() ||
644 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
645 Depth: Depth + 1))
646 return true;
647 }
648 }
649
650 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
651
652 // Dump each field.
653 for (auto *D : RD->decls()) {
654 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
655 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
656 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
657 continue;
658
659 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
660 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
661 getTypeString(T: FD->getType()),
662 getStringLiteral(Str: FD->getName())};
663
664 if (FD->isBitField()) {
665 Format += ": %zu ";
666 QualType SizeT = S.Context.getSizeType();
667 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
668 FD->getBitWidthValue());
669 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
670 }
671
672 Format += "=";
673
674 ExprResult Field =
675 IFD ? S.BuildAnonymousStructUnionMemberReference(
676 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
677 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
678 : S.BuildFieldReferenceExpr(
679 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
680 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
681 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
682 if (Field.isInvalid())
683 return true;
684
685 auto *InnerRD = FD->getType()->getAsRecordDecl();
686 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
687 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
688 // Recursively print the values of members of aggregate record type.
689 if (callPrintFunction(Format, Exprs: Args) ||
690 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
691 return true;
692 } else {
693 Format += " ";
694 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
695 // We know how to print this field.
696 Args.push_back(Elt: Field.get());
697 } else {
698 // We don't know how to print this field. Print out its address
699 // with a format specifier that a smart tool will be able to
700 // recognize and treat specially.
701 Format += "*%p";
702 ExprResult FieldAddr =
703 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
704 if (FieldAddr.isInvalid())
705 return true;
706 Args.push_back(Elt: FieldAddr.get());
707 }
708 Format += "\n";
709 if (callPrintFunction(Format, Exprs: Args))
710 return true;
711 }
712 }
713
714 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
715 : callPrintFunction(Format: "}\n");
716 }
717
718 Expr *buildWrapper() {
719 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
720 resultIndex: PseudoObjectExpr::NoResult);
721 TheCall->setType(Wrapper->getType());
722 TheCall->setValueKind(Wrapper->getValueKind());
723 return Wrapper;
724 }
725};
726} // namespace
727
728static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
729 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
730 return ExprError();
731
732 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
733 if (PtrArgResult.isInvalid())
734 return ExprError();
735 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
736
737 // First argument should be a pointer to a struct.
738 QualType PtrArgType = PtrArgResult.get()->getType();
739 if (!PtrArgType->isPointerType() ||
740 !PtrArgType->getPointeeType()->isRecordType()) {
741 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
742 DiagID: diag::err_expected_struct_pointer_argument)
743 << 1 << TheCall->getDirectCallee() << PtrArgType;
744 return ExprError();
745 }
746 QualType Pointee = PtrArgType->getPointeeType();
747 const RecordDecl *RD = Pointee->getAsRecordDecl();
748 // Try to instantiate the class template as appropriate; otherwise, access to
749 // its data() may lead to a crash.
750 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
751 DiagID: diag::err_incomplete_type))
752 return ExprError();
753 // Second argument is a callable, but we can't fully validate it until we try
754 // calling it.
755 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
756 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
757 !FnArgType->isBlockPointerType() &&
758 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
759 auto *BT = FnArgType->getAs<BuiltinType>();
760 switch (BT ? BT->getKind() : BuiltinType::Void) {
761 case BuiltinType::Dependent:
762 case BuiltinType::Overload:
763 case BuiltinType::BoundMember:
764 case BuiltinType::PseudoObject:
765 case BuiltinType::UnknownAny:
766 case BuiltinType::BuiltinFn:
767 // This might be a callable.
768 break;
769
770 default:
771 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
772 DiagID: diag::err_expected_callable_argument)
773 << 2 << TheCall->getDirectCallee() << FnArgType;
774 return ExprError();
775 }
776 }
777
778 BuiltinDumpStructGenerator Generator(S, TheCall);
779
780 // Wrap parentheses around the given pointer. This is not necessary for
781 // correct code generation, but it means that when we pretty-print the call
782 // arguments in our diagnostics we will produce '(&s)->n' instead of the
783 // incorrect '&s->n'.
784 Expr *PtrArg = PtrArgResult.get();
785 PtrArg = new (S.Context)
786 ParenExpr(PtrArg->getBeginLoc(),
787 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
788 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
789 return ExprError();
790
791 return Generator.buildWrapper();
792}
793
794static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
795 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
796 return true;
797
798 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
799 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
800 Expr *Call = BuiltinCall->getArg(Arg: 0);
801 Expr *Chain = BuiltinCall->getArg(Arg: 1);
802
803 if (Call->getStmtClass() != Stmt::CallExprClass) {
804 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
805 << Call->getSourceRange();
806 return true;
807 }
808
809 auto CE = cast<CallExpr>(Val: Call);
810 if (CE->getCallee()->getType()->isBlockPointerType()) {
811 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 const Decl *TargetDecl = CE->getCalleeDecl();
817 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
818 if (FD->getBuiltinID()) {
819 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
820 << Call->getSourceRange();
821 return true;
822 }
823
824 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
825 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
826 << Call->getSourceRange();
827 return true;
828 }
829
830 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
831 if (ChainResult.isInvalid())
832 return true;
833 if (!ChainResult.get()->getType()->isPointerType()) {
834 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
835 << Chain->getSourceRange();
836 return true;
837 }
838
839 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
840 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
841 QualType BuiltinTy = S.Context.getFunctionType(
842 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
843 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
844
845 Builtin =
846 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
847
848 BuiltinCall->setType(CE->getType());
849 BuiltinCall->setValueKind(CE->getValueKind());
850 BuiltinCall->setObjectKind(CE->getObjectKind());
851 BuiltinCall->setCallee(Builtin);
852 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
853
854 return false;
855}
856
857namespace {
858
859class ScanfDiagnosticFormatHandler
860 : public analyze_format_string::FormatStringHandler {
861 // Accepts the argument index (relative to the first destination index) of the
862 // argument whose size we want.
863 using ComputeSizeFunction =
864 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
865
866 // Accepts the argument index (relative to the first destination index), the
867 // destination size, and the source size).
868 using DiagnoseFunction =
869 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
870
871 ComputeSizeFunction ComputeSizeArgument;
872 DiagnoseFunction Diagnose;
873
874public:
875 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
876 DiagnoseFunction Diagnose)
877 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
878
879 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
880 const char *StartSpecifier,
881 unsigned specifierLen) override {
882 if (!FS.consumesDataArgument())
883 return true;
884
885 unsigned NulByte = 0;
886 switch ((FS.getConversionSpecifier().getKind())) {
887 default:
888 return true;
889 case analyze_format_string::ConversionSpecifier::sArg:
890 case analyze_format_string::ConversionSpecifier::ScanListArg:
891 NulByte = 1;
892 break;
893 case analyze_format_string::ConversionSpecifier::cArg:
894 break;
895 }
896
897 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
898 if (FW.getHowSpecified() !=
899 analyze_format_string::OptionalAmount::HowSpecified::Constant)
900 return true;
901
902 unsigned SourceSize = FW.getConstantAmount() + NulByte;
903
904 std::optional<llvm::APSInt> DestSizeAPS =
905 ComputeSizeArgument(FS.getArgIndex());
906 if (!DestSizeAPS)
907 return true;
908
909 unsigned DestSize = DestSizeAPS->getZExtValue();
910
911 if (DestSize < SourceSize)
912 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
913
914 return true;
915 }
916};
917
918class EstimateSizeFormatHandler
919 : public analyze_format_string::FormatStringHandler {
920 size_t Size;
921 /// Whether the format string contains Linux kernel's format specifier
922 /// extension.
923 bool IsKernelCompatible = true;
924
925public:
926 EstimateSizeFormatHandler(StringRef Format)
927 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
928 1 /* null byte always written by sprintf */) {}
929
930 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
931 const char *, unsigned SpecifierLen,
932 const TargetInfo &) override {
933
934 const size_t FieldWidth = computeFieldWidth(FS);
935 const size_t Precision = computePrecision(FS);
936
937 // The actual format.
938 switch (FS.getConversionSpecifier().getKind()) {
939 // Just a char.
940 case analyze_format_string::ConversionSpecifier::cArg:
941 case analyze_format_string::ConversionSpecifier::CArg:
942 Size += std::max(a: FieldWidth, b: (size_t)1);
943 break;
944 // Just an integer.
945 case analyze_format_string::ConversionSpecifier::dArg:
946 case analyze_format_string::ConversionSpecifier::DArg:
947 case analyze_format_string::ConversionSpecifier::iArg:
948 case analyze_format_string::ConversionSpecifier::oArg:
949 case analyze_format_string::ConversionSpecifier::OArg:
950 case analyze_format_string::ConversionSpecifier::uArg:
951 case analyze_format_string::ConversionSpecifier::UArg:
952 case analyze_format_string::ConversionSpecifier::xArg:
953 case analyze_format_string::ConversionSpecifier::XArg:
954 Size += std::max(a: FieldWidth, b: Precision);
955 break;
956
957 // %g style conversion switches between %f or %e style dynamically.
958 // %g removes trailing zeros, and does not print decimal point if there are
959 // no digits that follow it. Thus %g can print a single digit.
960 // FIXME: If it is alternative form:
961 // For g and G conversions, trailing zeros are not removed from the result.
962 case analyze_format_string::ConversionSpecifier::gArg:
963 case analyze_format_string::ConversionSpecifier::GArg:
964 Size += 1;
965 break;
966
967 // Floating point number in the form '[+]ddd.ddd'.
968 case analyze_format_string::ConversionSpecifier::fArg:
969 case analyze_format_string::ConversionSpecifier::FArg:
970 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
971 (Precision ? 1 + Precision
972 : 0) /* period + decimal */);
973 break;
974
975 // Floating point number in the form '[-]d.ddde[+-]dd'.
976 case analyze_format_string::ConversionSpecifier::eArg:
977 case analyze_format_string::ConversionSpecifier::EArg:
978 Size +=
979 std::max(a: FieldWidth,
980 b: 1 /* integer part */ +
981 (Precision ? 1 + Precision : 0) /* period + decimal */ +
982 1 /* e or E letter */ + 2 /* exponent */);
983 break;
984
985 // Floating point number in the form '[-]0xh.hhhhp±dd'.
986 case analyze_format_string::ConversionSpecifier::aArg:
987 case analyze_format_string::ConversionSpecifier::AArg:
988 Size +=
989 std::max(a: FieldWidth,
990 b: 2 /* 0x */ + 1 /* integer part */ +
991 (Precision ? 1 + Precision : 0) /* period + decimal */ +
992 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
993 break;
994
995 // Just a string.
996 case analyze_format_string::ConversionSpecifier::sArg:
997 case analyze_format_string::ConversionSpecifier::SArg:
998 Size += FieldWidth;
999 break;
1000
1001 // Just a pointer in the form '0xddd'.
1002 case analyze_format_string::ConversionSpecifier::pArg:
1003 // Linux kernel has its own extesion for `%p` specifier.
1004 // Kernel Document:
1005 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1006 IsKernelCompatible = false;
1007 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1008 break;
1009
1010 // A plain percent.
1011 case analyze_format_string::ConversionSpecifier::PercentArg:
1012 Size += 1;
1013 break;
1014
1015 default:
1016 break;
1017 }
1018
1019 // If field width is specified, the sign/space is already accounted for
1020 // within the field width, so no additional size is needed.
1021 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1022 Size += 1;
1023
1024 if (FS.hasAlternativeForm()) {
1025 switch (FS.getConversionSpecifier().getKind()) {
1026 // For o conversion, it increases the precision, if and only if necessary,
1027 // to force the first digit of the result to be a zero
1028 // (if the value and precision are both 0, a single 0 is printed)
1029 case analyze_format_string::ConversionSpecifier::oArg:
1030 // For b conversion, a nonzero result has 0b prefixed to it.
1031 case analyze_format_string::ConversionSpecifier::bArg:
1032 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1033 // it.
1034 case analyze_format_string::ConversionSpecifier::xArg:
1035 case analyze_format_string::ConversionSpecifier::XArg:
1036 // Note: even when the prefix is added, if
1037 // (prefix_width <= FieldWidth - formatted_length) holds,
1038 // the prefix does not increase the format
1039 // size. e.g.(("%#3x", 0xf) is "0xf")
1040
1041 // If the result is zero, o, b, x, X adds nothing.
1042 break;
1043 // For a, A, e, E, f, F, g, and G conversions,
1044 // the result of converting a floating-point number always contains a
1045 // decimal-point
1046 case analyze_format_string::ConversionSpecifier::aArg:
1047 case analyze_format_string::ConversionSpecifier::AArg:
1048 case analyze_format_string::ConversionSpecifier::eArg:
1049 case analyze_format_string::ConversionSpecifier::EArg:
1050 case analyze_format_string::ConversionSpecifier::fArg:
1051 case analyze_format_string::ConversionSpecifier::FArg:
1052 case analyze_format_string::ConversionSpecifier::gArg:
1053 case analyze_format_string::ConversionSpecifier::GArg:
1054 Size += (Precision ? 0 : 1);
1055 break;
1056 // For other conversions, the behavior is undefined.
1057 default:
1058 break;
1059 }
1060 }
1061 assert(SpecifierLen <= Size && "no underflow");
1062 Size -= SpecifierLen;
1063 return true;
1064 }
1065
1066 size_t getSizeLowerBound() const { return Size; }
1067 bool isKernelCompatible() const { return IsKernelCompatible; }
1068
1069private:
1070 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1071 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1072 size_t FieldWidth = 0;
1073 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1074 FieldWidth = FW.getConstantAmount();
1075 return FieldWidth;
1076 }
1077
1078 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1079 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1080 size_t Precision = 0;
1081
1082 // See man 3 printf for default precision value based on the specifier.
1083 switch (FW.getHowSpecified()) {
1084 case analyze_format_string::OptionalAmount::NotSpecified:
1085 switch (FS.getConversionSpecifier().getKind()) {
1086 default:
1087 break;
1088 case analyze_format_string::ConversionSpecifier::dArg: // %d
1089 case analyze_format_string::ConversionSpecifier::DArg: // %D
1090 case analyze_format_string::ConversionSpecifier::iArg: // %i
1091 Precision = 1;
1092 break;
1093 case analyze_format_string::ConversionSpecifier::oArg: // %d
1094 case analyze_format_string::ConversionSpecifier::OArg: // %D
1095 case analyze_format_string::ConversionSpecifier::uArg: // %d
1096 case analyze_format_string::ConversionSpecifier::UArg: // %D
1097 case analyze_format_string::ConversionSpecifier::xArg: // %d
1098 case analyze_format_string::ConversionSpecifier::XArg: // %D
1099 Precision = 1;
1100 break;
1101 case analyze_format_string::ConversionSpecifier::fArg: // %f
1102 case analyze_format_string::ConversionSpecifier::FArg: // %F
1103 case analyze_format_string::ConversionSpecifier::eArg: // %e
1104 case analyze_format_string::ConversionSpecifier::EArg: // %E
1105 case analyze_format_string::ConversionSpecifier::gArg: // %g
1106 case analyze_format_string::ConversionSpecifier::GArg: // %G
1107 Precision = 6;
1108 break;
1109 case analyze_format_string::ConversionSpecifier::pArg: // %d
1110 Precision = 1;
1111 break;
1112 }
1113 break;
1114 case analyze_format_string::OptionalAmount::Constant:
1115 Precision = FW.getConstantAmount();
1116 break;
1117 default:
1118 break;
1119 }
1120 return Precision;
1121 }
1122};
1123
1124} // namespace
1125
1126static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1127 StringRef &FormatStrRef, size_t &StrLen,
1128 ASTContext &Context) {
1129 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1130 Format && (Format->isOrdinary() || Format->isUTF8())) {
1131 FormatStrRef = Format->getString();
1132 const ConstantArrayType *T =
1133 Context.getAsConstantArrayType(T: Format->getType());
1134 assert(T && "String literal not of constant array type!");
1135 size_t TypeSize = T->getZExtSize();
1136 // In case there's a null byte somewhere.
1137 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1138 return true;
1139 }
1140 return false;
1141}
1142
1143void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1144 CallExpr *TheCall) {
1145 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1146 isConstantEvaluatedContext())
1147 return;
1148
1149 bool UseDABAttr = false;
1150 const FunctionDecl *UseDecl = FD;
1151
1152 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1153 if (DABAttr) {
1154 UseDecl = DABAttr->getFunction();
1155 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1156 UseDABAttr = true;
1157 }
1158
1159 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1160
1161 if (!BuiltinID)
1162 return;
1163
1164 const TargetInfo &TI = getASTContext().getTargetInfo();
1165 unsigned SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1166
1167 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1168 // If we refer to a diagnose_as_builtin attribute, we need to change the
1169 // argument index to refer to the arguments of the called function. Unless
1170 // the index is out of bounds, which presumably means it's a variadic
1171 // function.
1172 if (!UseDABAttr)
1173 return Index;
1174 unsigned DABIndices = DABAttr->argIndices_size();
1175 unsigned NewIndex = Index < DABIndices
1176 ? DABAttr->argIndices_begin()[Index]
1177 : Index - DABIndices + FD->getNumParams();
1178 if (NewIndex >= TheCall->getNumArgs())
1179 return std::nullopt;
1180 return NewIndex;
1181 };
1182
1183 auto ComputeExplicitObjectSizeArgument =
1184 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1185 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1186 if (!IndexOptional)
1187 return std::nullopt;
1188 unsigned NewIndex = *IndexOptional;
1189 Expr::EvalResult Result;
1190 Expr *SizeArg = TheCall->getArg(Arg: NewIndex);
1191 if (!SizeArg->EvaluateAsInt(Result, Ctx: getASTContext()))
1192 return std::nullopt;
1193 llvm::APSInt Integer = Result.Val.getInt();
1194 Integer.setIsUnsigned(true);
1195 return Integer;
1196 };
1197
1198 auto ComputeSizeArgument =
1199 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1200 // If the parameter has a pass_object_size attribute, then we should use its
1201 // (potentially) more strict checking mode. Otherwise, conservatively assume
1202 // type 0.
1203 int BOSType = 0;
1204 // This check can fail for variadic functions.
1205 if (Index < FD->getNumParams()) {
1206 if (const auto *POS =
1207 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1208 BOSType = POS->getType();
1209 }
1210
1211 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1212 if (!IndexOptional)
1213 return std::nullopt;
1214 unsigned NewIndex = *IndexOptional;
1215
1216 if (NewIndex >= TheCall->getNumArgs())
1217 return std::nullopt;
1218
1219 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1220 uint64_t Result;
1221 if (!ObjArg->tryEvaluateObjectSize(Result, Ctx&: getASTContext(), Type: BOSType))
1222 return std::nullopt;
1223
1224 // Get the object size in the target's size_t width.
1225 return llvm::APSInt::getUnsigned(X: Result).extOrTrunc(width: SizeTypeWidth);
1226 };
1227
1228 auto ComputeStrLenArgument =
1229 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1230 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1231 if (!IndexOptional)
1232 return std::nullopt;
1233 unsigned NewIndex = *IndexOptional;
1234
1235 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1236 uint64_t Result;
1237 if (!ObjArg->tryEvaluateStrLen(Result, Ctx&: getASTContext()))
1238 return std::nullopt;
1239 // Add 1 for null byte.
1240 return llvm::APSInt::getUnsigned(X: Result + 1).extOrTrunc(width: SizeTypeWidth);
1241 };
1242
1243 std::optional<llvm::APSInt> SourceSize;
1244 std::optional<llvm::APSInt> DestinationSize;
1245 unsigned DiagID = 0;
1246 bool IsChkVariant = false;
1247
1248 auto GetFunctionName = [&]() {
1249 std::string FunctionNameStr =
1250 getASTContext().BuiltinInfo.getName(ID: BuiltinID);
1251 llvm::StringRef FunctionName = FunctionNameStr;
1252 // Skim off the details of whichever builtin was called to produce a better
1253 // diagnostic, as it's unlikely that the user wrote the __builtin
1254 // explicitly.
1255 if (IsChkVariant) {
1256 FunctionName = FunctionName.drop_front(N: std::strlen(s: "__builtin___"));
1257 FunctionName = FunctionName.drop_back(N: std::strlen(s: "_chk"));
1258 } else {
1259 FunctionName.consume_front(Prefix: "__builtin_");
1260 }
1261 return FunctionName.str();
1262 };
1263
1264 switch (BuiltinID) {
1265 default:
1266 return;
1267 case Builtin::BI__builtin_strcat:
1268 case Builtin::BIstrcat:
1269 case Builtin::BI__builtin_stpcpy:
1270 case Builtin::BIstpcpy:
1271 case Builtin::BI__builtin_strcpy:
1272 case Builtin::BIstrcpy: {
1273 DiagID = diag::warn_fortify_strlen_overflow;
1274 SourceSize = ComputeStrLenArgument(1);
1275 DestinationSize = ComputeSizeArgument(0);
1276 break;
1277 }
1278
1279 case Builtin::BI__builtin___strcat_chk:
1280 case Builtin::BI__builtin___stpcpy_chk:
1281 case Builtin::BI__builtin___strcpy_chk: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1285 IsChkVariant = true;
1286 break;
1287 }
1288
1289 case Builtin::BIscanf:
1290 case Builtin::BIfscanf:
1291 case Builtin::BIsscanf: {
1292 unsigned FormatIndex = 1;
1293 unsigned DataIndex = 2;
1294 if (BuiltinID == Builtin::BIscanf) {
1295 FormatIndex = 0;
1296 DataIndex = 1;
1297 }
1298
1299 const auto *FormatExpr =
1300 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1301
1302 StringRef FormatStrRef;
1303 size_t StrLen;
1304 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1305 return;
1306
1307 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1308 unsigned SourceSize) {
1309 DiagID = diag::warn_fortify_scanf_overflow;
1310 unsigned Index = ArgIndex + DataIndex;
1311 std::string FunctionName = GetFunctionName();
1312 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1313 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1314 << DestSize << SourceSize);
1315 };
1316
1317 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1318 return ComputeSizeArgument(Index + DataIndex);
1319 };
1320 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1321 const char *FormatBytes = FormatStrRef.data();
1322 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1323 end: FormatBytes + StrLen, LO: getLangOpts(),
1324 Target: Context.getTargetInfo());
1325
1326 // Unlike the other cases, in this one we have already issued the diagnostic
1327 // here, so no need to continue (because unlike the other cases, here the
1328 // diagnostic refers to the argument number).
1329 return;
1330 }
1331
1332 case Builtin::BIsprintf:
1333 case Builtin::BI__builtin___sprintf_chk: {
1334 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1335 auto *FormatExpr = TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1336
1337 StringRef FormatStrRef;
1338 size_t StrLen;
1339 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1340 EstimateSizeFormatHandler H(FormatStrRef);
1341 const char *FormatBytes = FormatStrRef.data();
1342 if (!analyze_format_string::ParsePrintfString(
1343 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1344 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1345 DiagID = H.isKernelCompatible()
1346 ? diag::warn_format_overflow
1347 : diag::warn_format_overflow_non_kprintf;
1348 SourceSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1349 .extOrTrunc(width: SizeTypeWidth);
1350 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1351 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1352 IsChkVariant = true;
1353 } else {
1354 DestinationSize = ComputeSizeArgument(0);
1355 }
1356 break;
1357 }
1358 }
1359 return;
1360 }
1361 case Builtin::BI__builtin___memcpy_chk:
1362 case Builtin::BI__builtin___memmove_chk:
1363 case Builtin::BI__builtin___memset_chk:
1364 case Builtin::BI__builtin___strlcat_chk:
1365 case Builtin::BI__builtin___strlcpy_chk:
1366 case Builtin::BI__builtin___strncat_chk:
1367 case Builtin::BI__builtin___strncpy_chk:
1368 case Builtin::BI__builtin___stpncpy_chk:
1369 case Builtin::BI__builtin___memccpy_chk:
1370 case Builtin::BI__builtin___mempcpy_chk: {
1371 DiagID = diag::warn_builtin_chk_overflow;
1372 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1373 DestinationSize =
1374 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1375 IsChkVariant = true;
1376 break;
1377 }
1378
1379 case Builtin::BI__builtin___snprintf_chk:
1380 case Builtin::BI__builtin___vsnprintf_chk: {
1381 DiagID = diag::warn_builtin_chk_overflow;
1382 SourceSize = ComputeExplicitObjectSizeArgument(1);
1383 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BIstrncat:
1389 case Builtin::BI__builtin_strncat:
1390 case Builtin::BIstrncpy:
1391 case Builtin::BI__builtin_strncpy:
1392 case Builtin::BIstpncpy:
1393 case Builtin::BI__builtin_stpncpy: {
1394 // Whether these functions overflow depends on the runtime strlen of the
1395 // string, not just the buffer size, so emitting the "always overflow"
1396 // diagnostic isn't quite right. We should still diagnose passing a buffer
1397 // size larger than the destination buffer though; this is a runtime abort
1398 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1399 DiagID = diag::warn_fortify_source_size_mismatch;
1400 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1401 DestinationSize = ComputeSizeArgument(0);
1402 break;
1403 }
1404
1405 case Builtin::BImemcpy:
1406 case Builtin::BI__builtin_memcpy:
1407 case Builtin::BImemmove:
1408 case Builtin::BI__builtin_memmove:
1409 case Builtin::BImemset:
1410 case Builtin::BI__builtin_memset:
1411 case Builtin::BImempcpy:
1412 case Builtin::BI__builtin_mempcpy: {
1413 DiagID = diag::warn_fortify_source_overflow;
1414 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1415 DestinationSize = ComputeSizeArgument(0);
1416 break;
1417 }
1418 case Builtin::BIsnprintf:
1419 case Builtin::BI__builtin_snprintf:
1420 case Builtin::BIvsnprintf:
1421 case Builtin::BI__builtin_vsnprintf: {
1422 DiagID = diag::warn_fortify_source_size_mismatch;
1423 SourceSize = ComputeExplicitObjectSizeArgument(1);
1424 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1425 StringRef FormatStrRef;
1426 size_t StrLen;
1427 if (SourceSize &&
1428 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1429 EstimateSizeFormatHandler H(FormatStrRef);
1430 const char *FormatBytes = FormatStrRef.data();
1431 if (!analyze_format_string::ParsePrintfString(
1432 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1433 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1434 llvm::APSInt FormatSize =
1435 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1436 .extOrTrunc(width: SizeTypeWidth);
1437 if (FormatSize > *SourceSize && *SourceSize != 0) {
1438 unsigned TruncationDiagID =
1439 H.isKernelCompatible() ? diag::warn_format_truncation
1440 : diag::warn_format_truncation_non_kprintf;
1441 SmallString<16> SpecifiedSizeStr;
1442 SmallString<16> FormatSizeStr;
1443 SourceSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1444 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1445 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1446 PD: PDiag(DiagID: TruncationDiagID)
1447 << GetFunctionName() << SpecifiedSizeStr
1448 << FormatSizeStr);
1449 }
1450 }
1451 }
1452 DestinationSize = ComputeSizeArgument(0);
1453 }
1454 }
1455
1456 if (!SourceSize || !DestinationSize ||
1457 llvm::APSInt::compareValues(I1: *SourceSize, I2: *DestinationSize) <= 0)
1458 return;
1459
1460 std::string FunctionName = GetFunctionName();
1461
1462 SmallString<16> DestinationStr;
1463 SmallString<16> SourceStr;
1464 DestinationSize->toString(Str&: DestinationStr, /*Radix=*/10);
1465 SourceSize->toString(Str&: SourceStr, /*Radix=*/10);
1466 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1467 PD: PDiag(DiagID)
1468 << FunctionName << DestinationStr << SourceStr);
1469}
1470
1471static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1472 Scope::ScopeFlags NeededScopeFlags,
1473 unsigned DiagID) {
1474 // Scopes aren't available during instantiation. Fortunately, builtin
1475 // functions cannot be template args so they cannot be formed through template
1476 // instantiation. Therefore checking once during the parse is sufficient.
1477 if (SemaRef.inTemplateInstantiation())
1478 return false;
1479
1480 Scope *S = SemaRef.getCurScope();
1481 while (S && !S->isSEHExceptScope())
1482 S = S->getParent();
1483 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1484 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1485 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1486 << DRE->getDecl()->getIdentifier();
1487 return true;
1488 }
1489
1490 return false;
1491}
1492
1493// In OpenCL, __builtin_alloca_* should return a pointer to address space
1494// that corresponds to the stack address space i.e private address space.
1495static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1496 QualType RT = TheCall->getType();
1497 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1498 "__builtin_alloca has invalid address space");
1499
1500 RT = RT->getPointeeType();
1501 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1502 TheCall->setType(S.Context.getPointerType(T: RT));
1503}
1504
1505static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1506 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1507 return true;
1508
1509 for (Expr *Arg : TheCall->arguments()) {
1510 // If argument is dependent on a template parameter, we can't resolve now.
1511 if (Arg->isTypeDependent() || Arg->isValueDependent())
1512 continue;
1513 // Reject void types.
1514 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1515 if (ArgTy->isVoidType())
1516 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1517 }
1518
1519 TheCall->setType(S.Context.getSizeType());
1520 return false;
1521}
1522
1523namespace {
1524enum PointerAuthOpKind {
1525 PAO_Strip,
1526 PAO_Sign,
1527 PAO_Auth,
1528 PAO_SignGeneric,
1529 PAO_Discriminator,
1530 PAO_BlendPointer,
1531 PAO_BlendInteger
1532};
1533}
1534
1535bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1536 if (getLangOpts().PointerAuthIntrinsics)
1537 return false;
1538
1539 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1540 return true;
1541}
1542
1543static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1544 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1545}
1546
1547static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1548 // Convert it to type 'int'.
1549 if (convertArgumentToType(S, Value&: Arg, Ty: S.Context.IntTy))
1550 return true;
1551
1552 // Value-dependent expressions are okay; wait for template instantiation.
1553 if (Arg->isValueDependent())
1554 return false;
1555
1556 unsigned KeyValue;
1557 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1558}
1559
1560bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1561 // Attempt to constant-evaluate the expression.
1562 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1563 if (!KeyValue) {
1564 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1565 << 0 << Arg->getSourceRange();
1566 return true;
1567 }
1568
1569 // Ask the target to validate the key parameter.
1570 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1571 llvm::SmallString<32> Value;
1572 {
1573 llvm::raw_svector_ostream Str(Value);
1574 Str << *KeyValue;
1575 }
1576
1577 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1578 << Value << Arg->getSourceRange();
1579 return true;
1580 }
1581
1582 Result = KeyValue->getZExtValue();
1583 return false;
1584}
1585
1586bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1587 PointerAuthDiscArgKind Kind,
1588 unsigned &IntVal) {
1589 if (!Arg) {
1590 IntVal = 0;
1591 return true;
1592 }
1593
1594 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1595 if (!Result) {
1596 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1597 return false;
1598 }
1599
1600 unsigned Max;
1601 bool IsAddrDiscArg = false;
1602
1603 switch (Kind) {
1604 case PointerAuthDiscArgKind::Addr:
1605 Max = 1;
1606 IsAddrDiscArg = true;
1607 break;
1608 case PointerAuthDiscArgKind::Extra:
1609 Max = PointerAuthQualifier::MaxDiscriminator;
1610 break;
1611 };
1612
1613 if (*Result < 0 || *Result > Max) {
1614 if (IsAddrDiscArg)
1615 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1616 << Result->getExtValue();
1617 else
1618 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1619 << Result->getExtValue() << Max;
1620
1621 return false;
1622 };
1623
1624 IntVal = Result->getZExtValue();
1625 return true;
1626}
1627
1628static std::pair<const ValueDecl *, CharUnits>
1629findConstantBaseAndOffset(Sema &S, Expr *E) {
1630 // Must evaluate as a pointer.
1631 Expr::EvalResult Result;
1632 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1633 return {nullptr, CharUnits()};
1634
1635 const auto *BaseDecl =
1636 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1637 if (!BaseDecl)
1638 return {nullptr, CharUnits()};
1639
1640 return {BaseDecl, Result.Val.getLValueOffset()};
1641}
1642
1643static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1644 bool RequireConstant = false) {
1645 if (Arg->hasPlaceholderType()) {
1646 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1647 if (R.isInvalid())
1648 return true;
1649 Arg = R.get();
1650 }
1651
1652 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1653 return OpKind != PAO_BlendInteger;
1654 };
1655 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1656 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1657 OpKind == PAO_SignGeneric;
1658 };
1659
1660 // Require the value to have the right range of type.
1661 QualType ExpectedTy;
1662 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1663 ExpectedTy = Arg->getType().getUnqualifiedType();
1664 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1665 ExpectedTy = S.Context.VoidPtrTy;
1666 } else if (AllowsInteger(OpKind) &&
1667 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1668 ExpectedTy = S.Context.getUIntPtrType();
1669
1670 } else {
1671 // Diagnose the failures.
1672 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1673 << unsigned(OpKind == PAO_Discriminator ? 1
1674 : OpKind == PAO_BlendPointer ? 2
1675 : OpKind == PAO_BlendInteger ? 3
1676 : 0)
1677 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1678 << Arg->getType() << Arg->getSourceRange();
1679 return true;
1680 }
1681
1682 // Convert to that type. This should just be an lvalue-to-rvalue
1683 // conversion.
1684 if (convertArgumentToType(S, Value&: Arg, Ty: ExpectedTy))
1685 return true;
1686
1687 if (!RequireConstant) {
1688 // Warn about null pointers for non-generic sign and auth operations.
1689 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1690 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1691 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1692 ? diag::warn_ptrauth_sign_null_pointer
1693 : diag::warn_ptrauth_auth_null_pointer)
1694 << Arg->getSourceRange();
1695 }
1696
1697 return false;
1698 }
1699
1700 // Perform special checking on the arguments to ptrauth_sign_constant.
1701
1702 // The main argument.
1703 if (OpKind == PAO_Sign) {
1704 // Require the value we're signing to have a special form.
1705 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1706 bool Invalid;
1707
1708 // Must be rooted in a declaration reference.
1709 if (!BaseDecl)
1710 Invalid = true;
1711
1712 // If it's a function declaration, we can't have an offset.
1713 else if (isa<FunctionDecl>(Val: BaseDecl))
1714 Invalid = !Offset.isZero();
1715
1716 // Otherwise we're fine.
1717 else
1718 Invalid = false;
1719
1720 if (Invalid)
1721 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1722 return Invalid;
1723 }
1724
1725 // The discriminator argument.
1726 assert(OpKind == PAO_Discriminator);
1727
1728 // Must be a pointer or integer or blend thereof.
1729 Expr *Pointer = nullptr;
1730 Expr *Integer = nullptr;
1731 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1732 if (Call->getBuiltinCallee() ==
1733 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1734 Pointer = Call->getArg(Arg: 0);
1735 Integer = Call->getArg(Arg: 1);
1736 }
1737 }
1738 if (!Pointer && !Integer) {
1739 if (Arg->getType()->isPointerType())
1740 Pointer = Arg;
1741 else
1742 Integer = Arg;
1743 }
1744
1745 // Check the pointer.
1746 bool Invalid = false;
1747 if (Pointer) {
1748 assert(Pointer->getType()->isPointerType());
1749
1750 // TODO: if we're initializing a global, check that the address is
1751 // somehow related to what we're initializing. This probably will
1752 // never really be feasible and we'll have to catch it at link-time.
1753 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1754 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
1755 Invalid = true;
1756 }
1757
1758 // Check the integer.
1759 if (Integer) {
1760 assert(Integer->getType()->isIntegerType());
1761 if (!Integer->isEvaluatable(Ctx: S.Context))
1762 Invalid = true;
1763 }
1764
1765 if (Invalid)
1766 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
1767 return Invalid;
1768}
1769
1770static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
1771 if (S.checkArgCount(Call, DesiredArgCount: 2))
1772 return ExprError();
1773 if (checkPointerAuthEnabled(S, E: Call))
1774 return ExprError();
1775 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
1776 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
1777 return ExprError();
1778
1779 Call->setType(Call->getArgs()[0]->getType());
1780 return Call;
1781}
1782
1783static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
1784 if (S.checkArgCount(Call, DesiredArgCount: 2))
1785 return ExprError();
1786 if (checkPointerAuthEnabled(S, E: Call))
1787 return ExprError();
1788 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
1789 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
1790 return ExprError();
1791
1792 Call->setType(S.Context.getUIntPtrType());
1793 return Call;
1794}
1795
1796static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
1797 if (S.checkArgCount(Call, DesiredArgCount: 2))
1798 return ExprError();
1799 if (checkPointerAuthEnabled(S, E: Call))
1800 return ExprError();
1801 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
1802 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
1803 return ExprError();
1804
1805 Call->setType(S.Context.getUIntPtrType());
1806 return Call;
1807}
1808
1809static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
1810 PointerAuthOpKind OpKind,
1811 bool RequireConstant) {
1812 if (S.checkArgCount(Call, DesiredArgCount: 3))
1813 return ExprError();
1814 if (checkPointerAuthEnabled(S, E: Call))
1815 return ExprError();
1816 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
1817 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1818 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
1819 RequireConstant))
1820 return ExprError();
1821
1822 Call->setType(Call->getArgs()[0]->getType());
1823 return Call;
1824}
1825
1826static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
1827 if (S.checkArgCount(Call, DesiredArgCount: 5))
1828 return ExprError();
1829 if (checkPointerAuthEnabled(S, E: Call))
1830 return ExprError();
1831 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1832 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1833 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1834 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1835 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
1836 return ExprError();
1837
1838 Call->setType(Call->getArgs()[0]->getType());
1839 return Call;
1840}
1841
1842static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
1843 if (S.checkArgCount(Call, DesiredArgCount: 6))
1844 return ExprError();
1845 if (checkPointerAuthEnabled(S, E: Call))
1846 return ExprError();
1847 const Expr *AddendExpr = Call->getArg(Arg: 5);
1848 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
1849 if (!AddendIsConstInt) {
1850 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
1851 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
1852 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
1853 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
1854 << FDecl->getDeclName() << Arg->getSourceRange();
1855 }
1856 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1857 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1858 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1859 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1860 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
1861 !AddendIsConstInt)
1862 return ExprError();
1863
1864 Call->setType(Call->getArgs()[0]->getType());
1865 return Call;
1866}
1867
1868static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
1869 if (checkPointerAuthEnabled(S, E: Call))
1870 return ExprError();
1871
1872 // We've already performed normal call type-checking.
1873 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
1874
1875 // Operand must be an ordinary or UTF-8 string literal.
1876 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
1877 if (!Literal || Literal->getCharByteWidth() != 1) {
1878 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
1879 << (Literal ? 1 : 0) << Arg->getSourceRange();
1880 return ExprError();
1881 }
1882
1883 return Call;
1884}
1885
1886static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
1887 if (S.checkArgCount(Call, DesiredArgCount: 1))
1888 return ExprError();
1889 Expr *FirstArg = Call->getArg(Arg: 0);
1890 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
1891 if (FirstValue.isInvalid())
1892 return ExprError();
1893 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
1894 QualType FirstArgType = FirstArg->getType();
1895 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1896 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
1897
1898 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1899 if (!FirstArgRecord) {
1900 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
1901 << /*isPolymorphic=*/0 << FirstArgType;
1902 return ExprError();
1903 }
1904 if (S.RequireCompleteType(
1905 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
1906 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
1907 return ExprError();
1908 }
1909
1910 if (!FirstArgRecord->isPolymorphic()) {
1911 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
1912 << /*isPolymorphic=*/1 << FirstArgRecord;
1913 return ExprError();
1914 }
1915 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
1916 Call->setType(ReturnType);
1917 return Call;
1918}
1919
1920static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
1921 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
1922 return ExprError();
1923
1924 // Compute __builtin_launder's parameter type from the argument.
1925 // The parameter type is:
1926 // * The type of the argument if it's not an array or function type,
1927 // Otherwise,
1928 // * The decayed argument type.
1929 QualType ParamTy = [&]() {
1930 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
1931 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1932 return S.Context.getPointerType(T: Ty->getElementType());
1933 if (ArgTy->isFunctionType()) {
1934 return S.Context.getPointerType(T: ArgTy);
1935 }
1936 return ArgTy;
1937 }();
1938
1939 TheCall->setType(ParamTy);
1940
1941 auto DiagSelect = [&]() -> std::optional<unsigned> {
1942 if (!ParamTy->isPointerType())
1943 return 0;
1944 if (ParamTy->isFunctionPointerType())
1945 return 1;
1946 if (ParamTy->isVoidPointerType())
1947 return 2;
1948 return std::optional<unsigned>{};
1949 }();
1950 if (DiagSelect) {
1951 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
1952 << *DiagSelect << TheCall->getSourceRange();
1953 return ExprError();
1954 }
1955
1956 // We either have an incomplete class type, or we have a class template
1957 // whose instantiation has not been forced. Example:
1958 //
1959 // template <class T> struct Foo { T value; };
1960 // Foo<int> *p = nullptr;
1961 // auto *d = __builtin_launder(p);
1962 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
1963 DiagID: diag::err_incomplete_type))
1964 return ExprError();
1965
1966 assert(ParamTy->getPointeeType()->isObjectType() &&
1967 "Unhandled non-object pointer case");
1968
1969 InitializedEntity Entity =
1970 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
1971 ExprResult Arg =
1972 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
1973 if (Arg.isInvalid())
1974 return ExprError();
1975 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
1976
1977 return TheCall;
1978}
1979
1980static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
1981 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
1982 return ExprError();
1983
1984 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
1985 if (Arg.isInvalid())
1986 return ExprError();
1987 QualType ParamTy = Arg.get()->getType();
1988 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
1989 TheCall->setType(S.Context.BoolTy);
1990
1991 // Only accept pointers to objects as arguments, which should have object
1992 // pointer or void pointer types.
1993 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1994 // LWG4138: Function pointer types not allowed
1995 if (PT->getPointeeType()->isFunctionType()) {
1996 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
1997 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
1998 << 1;
1999 return ExprError();
2000 }
2001 // Disallow VLAs too since those shouldn't be able to
2002 // be a template parameter for `std::is_within_lifetime`
2003 if (PT->getPointeeType()->isVariableArrayType()) {
2004 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2005 << 1 << "__builtin_is_within_lifetime";
2006 return ExprError();
2007 }
2008 } else {
2009 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2010 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2011 << 0;
2012 return ExprError();
2013 }
2014 return TheCall;
2015}
2016
2017static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2018 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2019 return ExprError();
2020
2021 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2022 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2023 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2024 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2025 << /*a pointer*/ 0;
2026 return ExprError();
2027 }
2028
2029 QualType T = Dest->getPointeeType();
2030 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2031 DiagID: diag::err_incomplete_type))
2032 return ExprError();
2033
2034 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2035 T->isIncompleteArrayType()) {
2036 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2037 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2038 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2039 return ExprError();
2040 }
2041
2042 TheCall->setType(Dest);
2043
2044 QualType Src = TheCall->getArg(Arg: 1)->getType();
2045 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2046 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2047 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2048 << /*the same*/ 3;
2049 return ExprError();
2050 }
2051
2052 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2053 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2054 if (Size.isInvalid())
2055 return ExprError();
2056
2057 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2058 if (Size.isInvalid())
2059 return ExprError();
2060 SizeExpr = Size.get();
2061 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2062
2063 return TheCall;
2064}
2065
2066// Emit an error and return true if the current object format type is in the
2067// list of unsupported types.
2068static bool CheckBuiltinTargetNotInUnsupported(
2069 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2070 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2071 llvm::Triple::ObjectFormatType CurObjFormat =
2072 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2073 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2074 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2075 << TheCall->getSourceRange();
2076 return true;
2077 }
2078 return false;
2079}
2080
2081// Emit an error and return true if the current architecture is not in the list
2082// of supported architectures.
2083static bool
2084CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2085 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2086 llvm::Triple::ArchType CurArch =
2087 S.getASTContext().getTargetInfo().getTriple().getArch();
2088 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2089 return false;
2090 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2091 << TheCall->getSourceRange();
2092 return true;
2093}
2094
2095static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2096 SourceLocation CallSiteLoc);
2097
2098bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2099 CallExpr *TheCall) {
2100 switch (TI.getTriple().getArch()) {
2101 default:
2102 // Some builtins don't require additional checking, so just consider these
2103 // acceptable.
2104 return false;
2105 case llvm::Triple::arm:
2106 case llvm::Triple::armeb:
2107 case llvm::Triple::thumb:
2108 case llvm::Triple::thumbeb:
2109 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2110 case llvm::Triple::aarch64:
2111 case llvm::Triple::aarch64_32:
2112 case llvm::Triple::aarch64_be:
2113 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2114 case llvm::Triple::bpfeb:
2115 case llvm::Triple::bpfel:
2116 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2117 case llvm::Triple::dxil:
2118 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2119 case llvm::Triple::hexagon:
2120 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2121 case llvm::Triple::mips:
2122 case llvm::Triple::mipsel:
2123 case llvm::Triple::mips64:
2124 case llvm::Triple::mips64el:
2125 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2126 case llvm::Triple::spirv:
2127 case llvm::Triple::spirv32:
2128 case llvm::Triple::spirv64:
2129 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2130 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2131 return false;
2132 case llvm::Triple::systemz:
2133 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2134 case llvm::Triple::x86:
2135 case llvm::Triple::x86_64:
2136 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2137 case llvm::Triple::ppc:
2138 case llvm::Triple::ppcle:
2139 case llvm::Triple::ppc64:
2140 case llvm::Triple::ppc64le:
2141 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2142 case llvm::Triple::amdgcn:
2143 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2144 case llvm::Triple::riscv32:
2145 case llvm::Triple::riscv64:
2146 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2147 case llvm::Triple::loongarch32:
2148 case llvm::Triple::loongarch64:
2149 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2150 TheCall);
2151 case llvm::Triple::wasm32:
2152 case llvm::Triple::wasm64:
2153 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2154 case llvm::Triple::nvptx:
2155 case llvm::Triple::nvptx64:
2156 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2157 }
2158}
2159
2160static bool isValidMathElementType(QualType T) {
2161 return T->isDependentType() ||
2162 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2163}
2164
2165// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2166// not a valid type, emit an error message and return true. Otherwise return
2167// false.
2168static bool
2169checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2170 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2171 int ArgOrdinal) {
2172 QualType EltTy = ArgTy;
2173 if (auto *VecTy = EltTy->getAs<VectorType>())
2174 EltTy = VecTy->getElementType();
2175
2176 switch (ArgTyRestr) {
2177 case Sema::EltwiseBuiltinArgTyRestriction::None:
2178 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(T: ArgTy)) {
2179 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2180 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2181 << ArgTy;
2182 }
2183 break;
2184 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2185 if (!EltTy->isRealFloatingType()) {
2186 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2187 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2188 << /* floating-point */ 1 << ArgTy;
2189 }
2190 break;
2191 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2192 if (!EltTy->isIntegerType()) {
2193 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2194 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2195 << /* no fp */ 0 << ArgTy;
2196 }
2197 break;
2198 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2199 if (EltTy->isUnsignedIntegerType()) {
2200 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2201 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2202 << /* or fp */ 1 << ArgTy;
2203 }
2204 break;
2205 }
2206
2207 return false;
2208}
2209
2210/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2211/// This checks that the target supports the builtin and that the string
2212/// argument is constant and valid.
2213static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2214 const TargetInfo *AuxTI, unsigned BuiltinID) {
2215 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2216 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2217 "Expecting __builtin_cpu_...");
2218
2219 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2220 const TargetInfo *TheTI = &TI;
2221 auto SupportsBI = [=](const TargetInfo *TInfo) {
2222 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2223 (!IsCPUSupports && TInfo->supportsCpuIs()));
2224 };
2225 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2226 TheTI = AuxTI;
2227
2228 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2229 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2230 return S.Diag(Loc: TheCall->getBeginLoc(),
2231 DiagID: TI.getTriple().isOSAIX()
2232 ? diag::err_builtin_aix_os_unsupported
2233 : diag::err_builtin_target_unsupported)
2234 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2235
2236 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2237 // Check if the argument is a string literal.
2238 if (!isa<StringLiteral>(Val: Arg))
2239 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2240 << Arg->getSourceRange();
2241
2242 // Check the contents of the string.
2243 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2244 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2245 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2246 << Arg->getSourceRange();
2247 return false;
2248 }
2249 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2250 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2251 << Arg->getSourceRange();
2252 return false;
2253}
2254
2255/// Checks that __builtin_bswapg was called with a single argument, which is an
2256/// unsigned integer, and overrides the return value type to the integer type.
2257static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2258 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2259 return true;
2260 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2261 if (ArgRes.isInvalid())
2262 return true;
2263
2264 Expr *Arg = ArgRes.get();
2265 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2266 if (Arg->isTypeDependent())
2267 return false;
2268
2269 QualType ArgTy = Arg->getType();
2270
2271 if (!ArgTy->isIntegerType()) {
2272 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2273 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2274 << ArgTy;
2275 return true;
2276 }
2277 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2278 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8) {
2279 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2280 << ArgTy << BT->getNumBits();
2281 return true;
2282 }
2283 }
2284 TheCall->setType(ArgTy);
2285 return false;
2286}
2287
2288/// Checks that __builtin_popcountg was called with a single argument, which is
2289/// an unsigned integer.
2290static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2291 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2292 return true;
2293
2294 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2295 if (ArgRes.isInvalid())
2296 return true;
2297
2298 Expr *Arg = ArgRes.get();
2299 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2300
2301 QualType ArgTy = Arg->getType();
2302
2303 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2304 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2305 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2306 << ArgTy;
2307 return true;
2308 }
2309 return false;
2310}
2311
2312/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2313/// an unsigned integer, and an optional second argument, which is promoted to
2314/// an 'int'.
2315static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2316 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2317 return true;
2318
2319 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2320 if (Arg0Res.isInvalid())
2321 return true;
2322
2323 Expr *Arg0 = Arg0Res.get();
2324 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2325
2326 QualType Arg0Ty = Arg0->getType();
2327
2328 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2329 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2330 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2331 << Arg0Ty;
2332 return true;
2333 }
2334
2335 if (TheCall->getNumArgs() > 1) {
2336 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2337 if (Arg1Res.isInvalid())
2338 return true;
2339
2340 Expr *Arg1 = Arg1Res.get();
2341 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2342
2343 QualType Arg1Ty = Arg1->getType();
2344
2345 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2346 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2347 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2348 return true;
2349 }
2350 }
2351
2352 return false;
2353}
2354
2355class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2356 unsigned ArgIndex;
2357 bool OnlyUnsigned;
2358
2359 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2360 QualType T) {
2361 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2362 << ArgIndex << /*scalar*/ 1
2363 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2364 << /*no fp*/ 0 << T;
2365 }
2366
2367public:
2368 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2369 : ContextualImplicitConverter(/*Suppress=*/false,
2370 /*SuppressConversion=*/true),
2371 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2372
2373 bool match(QualType T) override {
2374 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2375 }
2376
2377 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2378 QualType T) override {
2379 return emitError(S, Loc, T);
2380 }
2381
2382 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2383 QualType T) override {
2384 return emitError(S, Loc, T);
2385 }
2386
2387 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2388 QualType T,
2389 QualType ConvTy) override {
2390 return emitError(S, Loc, T);
2391 }
2392
2393 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2394 QualType ConvTy) override {
2395 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2396 }
2397
2398 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2399 QualType T) override {
2400 return emitError(S, Loc, T);
2401 }
2402
2403 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2404 QualType ConvTy) override {
2405 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2406 }
2407
2408 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2409 QualType T,
2410 QualType ConvTy) override {
2411 llvm_unreachable("conversion functions are permitted");
2412 }
2413};
2414
2415/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2416/// arguments, that the first argument is an unsigned integer type, and that
2417/// the second argument is an integer type.
2418static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2419 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2420 return true;
2421
2422 // First argument (value to rotate) must be unsigned integer type.
2423 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2424 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2425 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2426 if (Arg0Res.isInvalid())
2427 return true;
2428
2429 Expr *Arg0 = Arg0Res.get();
2430 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2431
2432 QualType Arg0Ty = Arg0->getType();
2433 if (!Arg0Ty->isUnsignedIntegerType())
2434 return true;
2435
2436 // Second argument (rotation count) must be integer type.
2437 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2438 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2439 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2440 if (Arg1Res.isInvalid())
2441 return true;
2442
2443 Expr *Arg1 = Arg1Res.get();
2444 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2445
2446 QualType Arg1Ty = Arg1->getType();
2447 if (!Arg1Ty->isIntegerType())
2448 return true;
2449
2450 TheCall->setType(Arg0Ty);
2451 return false;
2452}
2453
2454static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2455 unsigned Pos, bool AllowConst,
2456 bool AllowAS) {
2457 QualType MaskTy = MaskArg->getType();
2458 if (!MaskTy->isExtVectorBoolType())
2459 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2460 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2461 << MaskTy;
2462
2463 QualType PtrTy = PtrArg->getType();
2464 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2465 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2466 << Pos << "scalar pointer";
2467
2468 QualType PointeeTy = PtrTy->getPointeeType();
2469 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2470 (!AllowConst && PointeeTy.isConstQualified()) ||
2471 (!AllowAS && PointeeTy.hasAddressSpace())) {
2472 QualType Target =
2473 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2474 return S.Diag(Loc: PtrArg->getExprLoc(),
2475 DiagID: diag::err_typecheck_convert_incompatible)
2476 << PtrTy << Target << /*different qualifiers=*/5
2477 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2478 << PtrTy << Target;
2479 }
2480 return false;
2481}
2482
2483static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2484 bool TypeDependent = false;
2485 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2486 ExprResult Converted =
2487 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2488 if (Converted.isInvalid())
2489 return true;
2490 TheCall->setArg(Arg, ArgExpr: Converted.get());
2491 TypeDependent |= Converted.get()->isTypeDependent();
2492 }
2493
2494 if (TypeDependent)
2495 TheCall->setType(S.Context.DependentTy);
2496 return false;
2497}
2498
2499static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2500 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2501 return ExprError();
2502
2503 if (ConvertMaskedBuiltinArgs(S, TheCall))
2504 return ExprError();
2505
2506 Expr *MaskArg = TheCall->getArg(Arg: 0);
2507 Expr *PtrArg = TheCall->getArg(Arg: 1);
2508 if (TheCall->isTypeDependent())
2509 return TheCall;
2510
2511 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2512 AllowAS: TheCall->getBuiltinCallee() ==
2513 Builtin::BI__builtin_masked_load))
2514 return ExprError();
2515
2516 QualType MaskTy = MaskArg->getType();
2517 QualType PtrTy = PtrArg->getType();
2518 QualType PointeeTy = PtrTy->getPointeeType();
2519 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2520
2521 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2522 NumElts: MaskVecTy->getNumElements());
2523 if (TheCall->getNumArgs() == 3) {
2524 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2525 QualType PassThruTy = PassThruArg->getType();
2526 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2527 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2528 << /* third argument */ 3 << RetTy;
2529 }
2530
2531 TheCall->setType(RetTy);
2532 return TheCall;
2533}
2534
2535static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2536 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2537 return ExprError();
2538
2539 if (ConvertMaskedBuiltinArgs(S, TheCall))
2540 return ExprError();
2541
2542 Expr *MaskArg = TheCall->getArg(Arg: 0);
2543 Expr *ValArg = TheCall->getArg(Arg: 1);
2544 Expr *PtrArg = TheCall->getArg(Arg: 2);
2545 if (TheCall->isTypeDependent())
2546 return TheCall;
2547
2548 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2549 AllowAS: TheCall->getBuiltinCallee() ==
2550 Builtin::BI__builtin_masked_store))
2551 return ExprError();
2552
2553 QualType MaskTy = MaskArg->getType();
2554 QualType PtrTy = PtrArg->getType();
2555 QualType ValTy = ValArg->getType();
2556 if (!ValTy->isVectorType())
2557 return ExprError(
2558 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2559 << 2 << "vector");
2560
2561 QualType PointeeTy = PtrTy->getPointeeType();
2562 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2563 QualType MemoryTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2564 NumElts: MaskVecTy->getNumElements());
2565 if (!S.Context.hasSameType(T1: ValTy.getUnqualifiedType(),
2566 T2: MemoryTy.getUnqualifiedType()))
2567 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2568 DiagID: diag::err_vec_builtin_incompatible_vector)
2569 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2570 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2571 TheCall->getArg(Arg: 1)->getEndLoc()));
2572
2573 TheCall->setType(S.Context.VoidTy);
2574 return TheCall;
2575}
2576
2577static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2578 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2579 return ExprError();
2580
2581 if (ConvertMaskedBuiltinArgs(S, TheCall))
2582 return ExprError();
2583
2584 Expr *MaskArg = TheCall->getArg(Arg: 0);
2585 Expr *IdxArg = TheCall->getArg(Arg: 1);
2586 Expr *PtrArg = TheCall->getArg(Arg: 2);
2587 if (TheCall->isTypeDependent())
2588 return TheCall;
2589
2590 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2591 /*AllowAS=*/true))
2592 return ExprError();
2593
2594 QualType IdxTy = IdxArg->getType();
2595 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2596 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2597 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2598 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2599 << IdxTy;
2600
2601 QualType MaskTy = MaskArg->getType();
2602 QualType PtrTy = PtrArg->getType();
2603 QualType PointeeTy = PtrTy->getPointeeType();
2604 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2605 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2606 return ExprError(
2607 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2608 << S.getASTContext().BuiltinInfo.getQuotedName(
2609 ID: TheCall->getBuiltinCallee())
2610 << MaskTy << IdxTy);
2611
2612 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2613 NumElts: MaskVecTy->getNumElements());
2614 if (TheCall->getNumArgs() == 4) {
2615 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2616 QualType PassThruTy = PassThruArg->getType();
2617 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2618 return S.Diag(Loc: PassThruArg->getExprLoc(),
2619 DiagID: diag::err_vec_masked_load_store_ptr)
2620 << /* fourth argument */ 4 << RetTy;
2621 }
2622
2623 TheCall->setType(RetTy);
2624 return TheCall;
2625}
2626
2627static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2628 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2629 return ExprError();
2630
2631 if (ConvertMaskedBuiltinArgs(S, TheCall))
2632 return ExprError();
2633
2634 Expr *MaskArg = TheCall->getArg(Arg: 0);
2635 Expr *IdxArg = TheCall->getArg(Arg: 1);
2636 Expr *ValArg = TheCall->getArg(Arg: 2);
2637 Expr *PtrArg = TheCall->getArg(Arg: 3);
2638 if (TheCall->isTypeDependent())
2639 return TheCall;
2640
2641 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2642 /*AllowAS=*/true))
2643 return ExprError();
2644
2645 QualType IdxTy = IdxArg->getType();
2646 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2647 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2648 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2649 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2650 << IdxTy;
2651
2652 QualType ValTy = ValArg->getType();
2653 QualType MaskTy = MaskArg->getType();
2654 QualType PtrTy = PtrArg->getType();
2655 QualType PointeeTy = PtrTy->getPointeeType();
2656
2657 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2658 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2659 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2660 return ExprError(
2661 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2662 << S.getASTContext().BuiltinInfo.getQuotedName(
2663 ID: TheCall->getBuiltinCallee())
2664 << MaskTy << IdxTy);
2665 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2666 return ExprError(
2667 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2668 << S.getASTContext().BuiltinInfo.getQuotedName(
2669 ID: TheCall->getBuiltinCallee())
2670 << MaskTy << ValTy);
2671
2672 QualType ArgTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2673 NumElts: MaskVecTy->getNumElements());
2674 if (!S.Context.hasSameType(T1: ValTy.getUnqualifiedType(), T2: ArgTy))
2675 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2676 DiagID: diag::err_vec_builtin_incompatible_vector)
2677 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2678 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2679 TheCall->getArg(Arg: 1)->getEndLoc()));
2680
2681 TheCall->setType(S.Context.VoidTy);
2682 return TheCall;
2683}
2684
2685static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
2686 SourceLocation Loc = TheCall->getBeginLoc();
2687 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2688 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2689
2690 if (Args.size() == 0) {
2691 S.Diag(Loc: TheCall->getBeginLoc(),
2692 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2693 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2694 << /*is_non_object=*/0 << TheCall->getSourceRange();
2695 return ExprError();
2696 }
2697
2698 QualType FuncT = Args[0]->getType();
2699
2700 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2701 if (Args.size() < 2) {
2702 S.Diag(Loc: TheCall->getBeginLoc(),
2703 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2704 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2705 << /*is_non_object=*/0 << TheCall->getSourceRange();
2706 return ExprError();
2707 }
2708
2709 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2710 QualType ObjectT = Args[1]->getType();
2711
2712 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2713 return ExprError();
2714
2715 ExprResult ObjectArg = [&]() -> ExprResult {
2716 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2717 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2718 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2719 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2720 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2721 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2722 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
2723 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
2724 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
2725 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
2726 return Args[1];
2727 }
2728
2729 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2730 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2731 // reference_wrapper;
2732 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2733 if (RD->isInStdNamespace() &&
2734 RD->getDeclName().getAsString() == "reference_wrapper") {
2735 CXXScopeSpec SS;
2736 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
2737 UnqualifiedId GetID;
2738 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
2739
2740 ExprResult MemExpr = S.ActOnMemberAccessExpr(
2741 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
2742 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
2743
2744 if (MemExpr.isInvalid())
2745 return ExprError();
2746
2747 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
2748 }
2749 }
2750
2751 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2752 // class T and t1 does not satisfy the previous two items;
2753
2754 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
2755 }();
2756
2757 if (ObjectArg.isInvalid())
2758 return ExprError();
2759
2760 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
2761 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
2762 if (BinOp.isInvalid())
2763 return ExprError();
2764
2765 if (MPT->isMemberDataPointer())
2766 return BinOp;
2767
2768 auto *MemCall = new (S.Context)
2769 ParenExpr(SourceLocation(), SourceLocation(), BinOp.get());
2770
2771 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
2772 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
2773 }
2774 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
2775 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
2776}
2777
2778// Performs a similar job to Sema::UsualUnaryConversions, but without any
2779// implicit promotion of integral/enumeration types.
2780static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
2781 // First, convert to an r-value.
2782 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
2783 if (Res.isInvalid())
2784 return ExprError();
2785
2786 // Promote floating-point types.
2787 return S.UsualUnaryFPConversions(E: Res.get());
2788}
2789
2790ExprResult
2791Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2792 CallExpr *TheCall) {
2793 ExprResult TheCallResult(TheCall);
2794
2795 // Find out if any arguments are required to be integer constant expressions.
2796 unsigned ICEArguments = 0;
2797 ASTContext::GetBuiltinTypeError Error;
2798 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
2799 if (Error != ASTContext::GE_None)
2800 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2801
2802 // If any arguments are required to be ICE's, check and diagnose.
2803 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2804 // Skip arguments not required to be ICE's.
2805 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2806
2807 llvm::APSInt Result;
2808 // If we don't have enough arguments, continue so we can issue better
2809 // diagnostic in checkArgCount(...)
2810 if (ArgNo < TheCall->getNumArgs() &&
2811 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
2812 return true;
2813 ICEArguments &= ~(1 << ArgNo);
2814 }
2815
2816 FPOptions FPO;
2817 switch (BuiltinID) {
2818 case Builtin::BI__builtin_cpu_supports:
2819 case Builtin::BI__builtin_cpu_is:
2820 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
2821 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
2822 return ExprError();
2823 break;
2824 case Builtin::BI__builtin_cpu_init:
2825 if (!Context.getTargetInfo().supportsCpuInit()) {
2826 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2827 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2828 return ExprError();
2829 }
2830 break;
2831 case Builtin::BI__builtin___CFStringMakeConstantString:
2832 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2833 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2834 if (CheckBuiltinTargetNotInUnsupported(
2835 S&: *this, BuiltinID, TheCall,
2836 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2837 return ExprError();
2838 assert(TheCall->getNumArgs() == 1 &&
2839 "Wrong # arguments to builtin CFStringMakeConstantString");
2840 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
2841 return ExprError();
2842 break;
2843 case Builtin::BI__builtin_ms_va_start:
2844 case Builtin::BI__builtin_stdarg_start:
2845 case Builtin::BI__builtin_va_start:
2846 case Builtin::BI__builtin_c23_va_start:
2847 if (BuiltinVAStart(BuiltinID, TheCall))
2848 return ExprError();
2849 break;
2850 case Builtin::BI__va_start: {
2851 switch (Context.getTargetInfo().getTriple().getArch()) {
2852 case llvm::Triple::aarch64:
2853 case llvm::Triple::arm:
2854 case llvm::Triple::thumb:
2855 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
2856 return ExprError();
2857 break;
2858 default:
2859 if (BuiltinVAStart(BuiltinID, TheCall))
2860 return ExprError();
2861 break;
2862 }
2863 break;
2864 }
2865
2866 // The acquire, release, and no fence variants are ARM and AArch64 only.
2867 case Builtin::BI_interlockedbittestandset_acq:
2868 case Builtin::BI_interlockedbittestandset_rel:
2869 case Builtin::BI_interlockedbittestandset_nf:
2870 case Builtin::BI_interlockedbittestandreset_acq:
2871 case Builtin::BI_interlockedbittestandreset_rel:
2872 case Builtin::BI_interlockedbittestandreset_nf:
2873 if (CheckBuiltinTargetInSupported(
2874 S&: *this, TheCall,
2875 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2876 return ExprError();
2877 break;
2878
2879 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2880 case Builtin::BI_bittest64:
2881 case Builtin::BI_bittestandcomplement64:
2882 case Builtin::BI_bittestandreset64:
2883 case Builtin::BI_bittestandset64:
2884 case Builtin::BI_interlockedbittestandreset64:
2885 case Builtin::BI_interlockedbittestandset64:
2886 if (CheckBuiltinTargetInSupported(
2887 S&: *this, TheCall,
2888 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2889 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2890 return ExprError();
2891 break;
2892
2893 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2894 case Builtin::BI_interlockedbittestandreset64_acq:
2895 case Builtin::BI_interlockedbittestandreset64_rel:
2896 case Builtin::BI_interlockedbittestandreset64_nf:
2897 case Builtin::BI_interlockedbittestandset64_acq:
2898 case Builtin::BI_interlockedbittestandset64_rel:
2899 case Builtin::BI_interlockedbittestandset64_nf:
2900 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
2901 return ExprError();
2902 break;
2903
2904 case Builtin::BI__builtin_set_flt_rounds:
2905 if (CheckBuiltinTargetInSupported(
2906 S&: *this, TheCall,
2907 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2908 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2909 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2910 llvm::Triple::ppc64le}))
2911 return ExprError();
2912 break;
2913
2914 case Builtin::BI__builtin_isgreater:
2915 case Builtin::BI__builtin_isgreaterequal:
2916 case Builtin::BI__builtin_isless:
2917 case Builtin::BI__builtin_islessequal:
2918 case Builtin::BI__builtin_islessgreater:
2919 case Builtin::BI__builtin_isunordered:
2920 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2921 return ExprError();
2922 break;
2923 case Builtin::BI__builtin_fpclassify:
2924 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
2925 return ExprError();
2926 break;
2927 case Builtin::BI__builtin_isfpclass:
2928 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
2929 return ExprError();
2930 break;
2931 case Builtin::BI__builtin_isfinite:
2932 case Builtin::BI__builtin_isinf:
2933 case Builtin::BI__builtin_isinf_sign:
2934 case Builtin::BI__builtin_isnan:
2935 case Builtin::BI__builtin_issignaling:
2936 case Builtin::BI__builtin_isnormal:
2937 case Builtin::BI__builtin_issubnormal:
2938 case Builtin::BI__builtin_iszero:
2939 case Builtin::BI__builtin_signbit:
2940 case Builtin::BI__builtin_signbitf:
2941 case Builtin::BI__builtin_signbitl:
2942 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
2943 return ExprError();
2944 break;
2945 case Builtin::BI__builtin_shufflevector:
2946 return BuiltinShuffleVector(TheCall);
2947 // TheCall will be freed by the smart pointer here, but that's fine, since
2948 // BuiltinShuffleVector guts it, but then doesn't release it.
2949 case Builtin::BI__builtin_masked_load:
2950 case Builtin::BI__builtin_masked_expand_load:
2951 return BuiltinMaskedLoad(S&: *this, TheCall);
2952 case Builtin::BI__builtin_masked_store:
2953 case Builtin::BI__builtin_masked_compress_store:
2954 return BuiltinMaskedStore(S&: *this, TheCall);
2955 case Builtin::BI__builtin_masked_gather:
2956 return BuiltinMaskedGather(S&: *this, TheCall);
2957 case Builtin::BI__builtin_masked_scatter:
2958 return BuiltinMaskedScatter(S&: *this, TheCall);
2959 case Builtin::BI__builtin_invoke:
2960 return BuiltinInvoke(S&: *this, TheCall);
2961 case Builtin::BI__builtin_prefetch:
2962 if (BuiltinPrefetch(TheCall))
2963 return ExprError();
2964 break;
2965 case Builtin::BI__builtin_alloca_with_align:
2966 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2967 if (BuiltinAllocaWithAlign(TheCall))
2968 return ExprError();
2969 [[fallthrough]];
2970 case Builtin::BI__builtin_alloca:
2971 case Builtin::BI__builtin_alloca_uninitialized:
2972 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
2973 << TheCall->getDirectCallee();
2974 if (getLangOpts().OpenCL) {
2975 builtinAllocaAddrSpace(S&: *this, TheCall);
2976 }
2977 break;
2978 case Builtin::BI__builtin_infer_alloc_token:
2979 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
2980 return ExprError();
2981 break;
2982 case Builtin::BI__arithmetic_fence:
2983 if (BuiltinArithmeticFence(TheCall))
2984 return ExprError();
2985 break;
2986 case Builtin::BI__assume:
2987 case Builtin::BI__builtin_assume:
2988 if (BuiltinAssume(TheCall))
2989 return ExprError();
2990 break;
2991 case Builtin::BI__builtin_assume_aligned:
2992 if (BuiltinAssumeAligned(TheCall))
2993 return ExprError();
2994 break;
2995 case Builtin::BI__builtin_dynamic_object_size:
2996 case Builtin::BI__builtin_object_size:
2997 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
2998 return ExprError();
2999 break;
3000 case Builtin::BI__builtin_longjmp:
3001 if (BuiltinLongjmp(TheCall))
3002 return ExprError();
3003 break;
3004 case Builtin::BI__builtin_setjmp:
3005 if (BuiltinSetjmp(TheCall))
3006 return ExprError();
3007 break;
3008 case Builtin::BI__builtin_classify_type:
3009 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3010 return true;
3011 TheCall->setType(Context.IntTy);
3012 break;
3013 case Builtin::BI__builtin_complex:
3014 if (BuiltinComplex(TheCall))
3015 return ExprError();
3016 break;
3017 case Builtin::BI__builtin_constant_p: {
3018 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3019 return true;
3020 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3021 if (Arg.isInvalid()) return true;
3022 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3023 TheCall->setType(Context.IntTy);
3024 break;
3025 }
3026 case Builtin::BI__builtin_launder:
3027 return BuiltinLaunder(S&: *this, TheCall);
3028 case Builtin::BI__builtin_is_within_lifetime:
3029 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3030 case Builtin::BI__builtin_trivially_relocate:
3031 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3032
3033 case Builtin::BI__sync_fetch_and_add:
3034 case Builtin::BI__sync_fetch_and_add_1:
3035 case Builtin::BI__sync_fetch_and_add_2:
3036 case Builtin::BI__sync_fetch_and_add_4:
3037 case Builtin::BI__sync_fetch_and_add_8:
3038 case Builtin::BI__sync_fetch_and_add_16:
3039 case Builtin::BI__sync_fetch_and_sub:
3040 case Builtin::BI__sync_fetch_and_sub_1:
3041 case Builtin::BI__sync_fetch_and_sub_2:
3042 case Builtin::BI__sync_fetch_and_sub_4:
3043 case Builtin::BI__sync_fetch_and_sub_8:
3044 case Builtin::BI__sync_fetch_and_sub_16:
3045 case Builtin::BI__sync_fetch_and_or:
3046 case Builtin::BI__sync_fetch_and_or_1:
3047 case Builtin::BI__sync_fetch_and_or_2:
3048 case Builtin::BI__sync_fetch_and_or_4:
3049 case Builtin::BI__sync_fetch_and_or_8:
3050 case Builtin::BI__sync_fetch_and_or_16:
3051 case Builtin::BI__sync_fetch_and_and:
3052 case Builtin::BI__sync_fetch_and_and_1:
3053 case Builtin::BI__sync_fetch_and_and_2:
3054 case Builtin::BI__sync_fetch_and_and_4:
3055 case Builtin::BI__sync_fetch_and_and_8:
3056 case Builtin::BI__sync_fetch_and_and_16:
3057 case Builtin::BI__sync_fetch_and_xor:
3058 case Builtin::BI__sync_fetch_and_xor_1:
3059 case Builtin::BI__sync_fetch_and_xor_2:
3060 case Builtin::BI__sync_fetch_and_xor_4:
3061 case Builtin::BI__sync_fetch_and_xor_8:
3062 case Builtin::BI__sync_fetch_and_xor_16:
3063 case Builtin::BI__sync_fetch_and_nand:
3064 case Builtin::BI__sync_fetch_and_nand_1:
3065 case Builtin::BI__sync_fetch_and_nand_2:
3066 case Builtin::BI__sync_fetch_and_nand_4:
3067 case Builtin::BI__sync_fetch_and_nand_8:
3068 case Builtin::BI__sync_fetch_and_nand_16:
3069 case Builtin::BI__sync_add_and_fetch:
3070 case Builtin::BI__sync_add_and_fetch_1:
3071 case Builtin::BI__sync_add_and_fetch_2:
3072 case Builtin::BI__sync_add_and_fetch_4:
3073 case Builtin::BI__sync_add_and_fetch_8:
3074 case Builtin::BI__sync_add_and_fetch_16:
3075 case Builtin::BI__sync_sub_and_fetch:
3076 case Builtin::BI__sync_sub_and_fetch_1:
3077 case Builtin::BI__sync_sub_and_fetch_2:
3078 case Builtin::BI__sync_sub_and_fetch_4:
3079 case Builtin::BI__sync_sub_and_fetch_8:
3080 case Builtin::BI__sync_sub_and_fetch_16:
3081 case Builtin::BI__sync_and_and_fetch:
3082 case Builtin::BI__sync_and_and_fetch_1:
3083 case Builtin::BI__sync_and_and_fetch_2:
3084 case Builtin::BI__sync_and_and_fetch_4:
3085 case Builtin::BI__sync_and_and_fetch_8:
3086 case Builtin::BI__sync_and_and_fetch_16:
3087 case Builtin::BI__sync_or_and_fetch:
3088 case Builtin::BI__sync_or_and_fetch_1:
3089 case Builtin::BI__sync_or_and_fetch_2:
3090 case Builtin::BI__sync_or_and_fetch_4:
3091 case Builtin::BI__sync_or_and_fetch_8:
3092 case Builtin::BI__sync_or_and_fetch_16:
3093 case Builtin::BI__sync_xor_and_fetch:
3094 case Builtin::BI__sync_xor_and_fetch_1:
3095 case Builtin::BI__sync_xor_and_fetch_2:
3096 case Builtin::BI__sync_xor_and_fetch_4:
3097 case Builtin::BI__sync_xor_and_fetch_8:
3098 case Builtin::BI__sync_xor_and_fetch_16:
3099 case Builtin::BI__sync_nand_and_fetch:
3100 case Builtin::BI__sync_nand_and_fetch_1:
3101 case Builtin::BI__sync_nand_and_fetch_2:
3102 case Builtin::BI__sync_nand_and_fetch_4:
3103 case Builtin::BI__sync_nand_and_fetch_8:
3104 case Builtin::BI__sync_nand_and_fetch_16:
3105 case Builtin::BI__sync_val_compare_and_swap:
3106 case Builtin::BI__sync_val_compare_and_swap_1:
3107 case Builtin::BI__sync_val_compare_and_swap_2:
3108 case Builtin::BI__sync_val_compare_and_swap_4:
3109 case Builtin::BI__sync_val_compare_and_swap_8:
3110 case Builtin::BI__sync_val_compare_and_swap_16:
3111 case Builtin::BI__sync_bool_compare_and_swap:
3112 case Builtin::BI__sync_bool_compare_and_swap_1:
3113 case Builtin::BI__sync_bool_compare_and_swap_2:
3114 case Builtin::BI__sync_bool_compare_and_swap_4:
3115 case Builtin::BI__sync_bool_compare_and_swap_8:
3116 case Builtin::BI__sync_bool_compare_and_swap_16:
3117 case Builtin::BI__sync_lock_test_and_set:
3118 case Builtin::BI__sync_lock_test_and_set_1:
3119 case Builtin::BI__sync_lock_test_and_set_2:
3120 case Builtin::BI__sync_lock_test_and_set_4:
3121 case Builtin::BI__sync_lock_test_and_set_8:
3122 case Builtin::BI__sync_lock_test_and_set_16:
3123 case Builtin::BI__sync_lock_release:
3124 case Builtin::BI__sync_lock_release_1:
3125 case Builtin::BI__sync_lock_release_2:
3126 case Builtin::BI__sync_lock_release_4:
3127 case Builtin::BI__sync_lock_release_8:
3128 case Builtin::BI__sync_lock_release_16:
3129 case Builtin::BI__sync_swap:
3130 case Builtin::BI__sync_swap_1:
3131 case Builtin::BI__sync_swap_2:
3132 case Builtin::BI__sync_swap_4:
3133 case Builtin::BI__sync_swap_8:
3134 case Builtin::BI__sync_swap_16:
3135 return BuiltinAtomicOverloaded(TheCallResult);
3136 case Builtin::BI__sync_synchronize:
3137 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3138 << TheCall->getCallee()->getSourceRange();
3139 break;
3140 case Builtin::BI__builtin_nontemporal_load:
3141 case Builtin::BI__builtin_nontemporal_store:
3142 return BuiltinNontemporalOverloaded(TheCallResult);
3143 case Builtin::BI__builtin_memcpy_inline: {
3144 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3145 // We warn about copying to or from `nullptr` pointers when `size` is
3146 // greater than 0. When `size` is value dependent we cannot evaluate its
3147 // value so we bail out.
3148 if (SizeOp->isValueDependent())
3149 break;
3150 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3151 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3152 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3153 }
3154 break;
3155 }
3156 case Builtin::BI__builtin_memset_inline: {
3157 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3158 // We warn about filling to `nullptr` pointers when `size` is greater than
3159 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3160 // out.
3161 if (SizeOp->isValueDependent())
3162 break;
3163 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3164 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3165 break;
3166 }
3167#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3168 case Builtin::BI##ID: \
3169 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3170#include "clang/Basic/Builtins.inc"
3171 case Builtin::BI__annotation:
3172 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3173 return ExprError();
3174 break;
3175 case Builtin::BI__builtin_annotation:
3176 if (BuiltinAnnotation(S&: *this, TheCall))
3177 return ExprError();
3178 break;
3179 case Builtin::BI__builtin_addressof:
3180 if (BuiltinAddressof(S&: *this, TheCall))
3181 return ExprError();
3182 break;
3183 case Builtin::BI__builtin_function_start:
3184 if (BuiltinFunctionStart(S&: *this, TheCall))
3185 return ExprError();
3186 break;
3187 case Builtin::BI__builtin_is_aligned:
3188 case Builtin::BI__builtin_align_up:
3189 case Builtin::BI__builtin_align_down:
3190 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3191 return ExprError();
3192 break;
3193 case Builtin::BI__builtin_add_overflow:
3194 case Builtin::BI__builtin_sub_overflow:
3195 case Builtin::BI__builtin_mul_overflow:
3196 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3197 return ExprError();
3198 break;
3199 case Builtin::BI__builtin_operator_new:
3200 case Builtin::BI__builtin_operator_delete: {
3201 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3202 ExprResult Res =
3203 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3204 return Res;
3205 }
3206 case Builtin::BI__builtin_dump_struct:
3207 return BuiltinDumpStruct(S&: *this, TheCall);
3208 case Builtin::BI__builtin_expect_with_probability: {
3209 // We first want to ensure we are called with 3 arguments
3210 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3211 return ExprError();
3212 // then check probability is constant float in range [0.0, 1.0]
3213 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3214 SmallVector<PartialDiagnosticAt, 8> Notes;
3215 Expr::EvalResult Eval;
3216 Eval.Diag = &Notes;
3217 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3218 !Eval.Val.isFloat()) {
3219 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3220 << ProbArg->getSourceRange();
3221 for (const PartialDiagnosticAt &PDiag : Notes)
3222 Diag(Loc: PDiag.first, PD: PDiag.second);
3223 return ExprError();
3224 }
3225 llvm::APFloat Probability = Eval.Val.getFloat();
3226 bool LoseInfo = false;
3227 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3228 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3229 if (!(Probability >= llvm::APFloat(0.0) &&
3230 Probability <= llvm::APFloat(1.0))) {
3231 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3232 << ProbArg->getSourceRange();
3233 return ExprError();
3234 }
3235 break;
3236 }
3237 case Builtin::BI__builtin_preserve_access_index:
3238 if (BuiltinPreserveAI(S&: *this, TheCall))
3239 return ExprError();
3240 break;
3241 case Builtin::BI__builtin_call_with_static_chain:
3242 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3243 return ExprError();
3244 break;
3245 case Builtin::BI__exception_code:
3246 case Builtin::BI_exception_code:
3247 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3248 DiagID: diag::err_seh___except_block))
3249 return ExprError();
3250 break;
3251 case Builtin::BI__exception_info:
3252 case Builtin::BI_exception_info:
3253 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3254 DiagID: diag::err_seh___except_filter))
3255 return ExprError();
3256 break;
3257 case Builtin::BI__GetExceptionInfo:
3258 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3259 return ExprError();
3260
3261 if (CheckCXXThrowOperand(
3262 ThrowLoc: TheCall->getBeginLoc(),
3263 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3264 E: TheCall))
3265 return ExprError();
3266
3267 TheCall->setType(Context.VoidPtrTy);
3268 break;
3269 case Builtin::BIaddressof:
3270 case Builtin::BI__addressof:
3271 case Builtin::BIforward:
3272 case Builtin::BIforward_like:
3273 case Builtin::BImove:
3274 case Builtin::BImove_if_noexcept:
3275 case Builtin::BIas_const: {
3276 // These are all expected to be of the form
3277 // T &/&&/* f(U &/&&)
3278 // where T and U only differ in qualification.
3279 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3280 return ExprError();
3281 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3282 QualType Result = FDecl->getReturnType();
3283 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3284 BuiltinID == Builtin::BI__addressof;
3285 if (!(Param->isReferenceType() &&
3286 (ReturnsPointer ? Result->isAnyPointerType()
3287 : Result->isReferenceType()) &&
3288 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3289 T2: Result->getPointeeType()))) {
3290 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3291 << FDecl;
3292 return ExprError();
3293 }
3294 break;
3295 }
3296 case Builtin::BI__builtin_ptrauth_strip:
3297 return PointerAuthStrip(S&: *this, Call: TheCall);
3298 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3299 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3300 case Builtin::BI__builtin_ptrauth_sign_constant:
3301 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3302 /*RequireConstant=*/true);
3303 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3304 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3305 /*RequireConstant=*/false);
3306 case Builtin::BI__builtin_ptrauth_auth:
3307 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3308 /*RequireConstant=*/false);
3309 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3310 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3311 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3312 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3313 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3314 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3315 case Builtin::BI__builtin_ptrauth_string_discriminator:
3316 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3317
3318 case Builtin::BI__builtin_get_vtable_pointer:
3319 return GetVTablePointer(S&: *this, Call: TheCall);
3320
3321 // OpenCL v2.0, s6.13.16 - Pipe functions
3322 case Builtin::BIread_pipe:
3323 case Builtin::BIwrite_pipe:
3324 // Since those two functions are declared with var args, we need a semantic
3325 // check for the argument.
3326 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3327 return ExprError();
3328 break;
3329 case Builtin::BIreserve_read_pipe:
3330 case Builtin::BIreserve_write_pipe:
3331 case Builtin::BIwork_group_reserve_read_pipe:
3332 case Builtin::BIwork_group_reserve_write_pipe:
3333 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3334 return ExprError();
3335 break;
3336 case Builtin::BIsub_group_reserve_read_pipe:
3337 case Builtin::BIsub_group_reserve_write_pipe:
3338 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3339 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3340 return ExprError();
3341 break;
3342 case Builtin::BIcommit_read_pipe:
3343 case Builtin::BIcommit_write_pipe:
3344 case Builtin::BIwork_group_commit_read_pipe:
3345 case Builtin::BIwork_group_commit_write_pipe:
3346 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3347 return ExprError();
3348 break;
3349 case Builtin::BIsub_group_commit_read_pipe:
3350 case Builtin::BIsub_group_commit_write_pipe:
3351 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3352 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3353 return ExprError();
3354 break;
3355 case Builtin::BIget_pipe_num_packets:
3356 case Builtin::BIget_pipe_max_packets:
3357 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3358 return ExprError();
3359 break;
3360 case Builtin::BIto_global:
3361 case Builtin::BIto_local:
3362 case Builtin::BIto_private:
3363 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3364 return ExprError();
3365 break;
3366 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3367 case Builtin::BIenqueue_kernel:
3368 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BIget_kernel_work_group_size:
3372 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3373 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3374 return ExprError();
3375 break;
3376 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3377 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3378 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3379 return ExprError();
3380 break;
3381 case Builtin::BI__builtin_os_log_format:
3382 Cleanup.setExprNeedsCleanups(true);
3383 [[fallthrough]];
3384 case Builtin::BI__builtin_os_log_format_buffer_size:
3385 if (BuiltinOSLogFormat(TheCall))
3386 return ExprError();
3387 break;
3388 case Builtin::BI__builtin_frame_address:
3389 case Builtin::BI__builtin_return_address: {
3390 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3391 return ExprError();
3392
3393 // -Wframe-address warning if non-zero passed to builtin
3394 // return/frame address.
3395 Expr::EvalResult Result;
3396 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3397 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3398 Result.Val.getInt() != 0)
3399 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3400 << ((BuiltinID == Builtin::BI__builtin_return_address)
3401 ? "__builtin_return_address"
3402 : "__builtin_frame_address")
3403 << TheCall->getSourceRange();
3404 break;
3405 }
3406
3407 case Builtin::BI__builtin_nondeterministic_value: {
3408 if (BuiltinNonDeterministicValue(TheCall))
3409 return ExprError();
3410 break;
3411 }
3412
3413 // __builtin_elementwise_abs restricts the element type to signed integers or
3414 // floating point types only.
3415 case Builtin::BI__builtin_elementwise_abs:
3416 if (PrepareBuiltinElementwiseMathOneArgCall(
3417 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3418 return ExprError();
3419 break;
3420
3421 // These builtins restrict the element type to floating point
3422 // types only.
3423 case Builtin::BI__builtin_elementwise_acos:
3424 case Builtin::BI__builtin_elementwise_asin:
3425 case Builtin::BI__builtin_elementwise_atan:
3426 case Builtin::BI__builtin_elementwise_ceil:
3427 case Builtin::BI__builtin_elementwise_cos:
3428 case Builtin::BI__builtin_elementwise_cosh:
3429 case Builtin::BI__builtin_elementwise_exp:
3430 case Builtin::BI__builtin_elementwise_exp2:
3431 case Builtin::BI__builtin_elementwise_exp10:
3432 case Builtin::BI__builtin_elementwise_floor:
3433 case Builtin::BI__builtin_elementwise_log:
3434 case Builtin::BI__builtin_elementwise_log2:
3435 case Builtin::BI__builtin_elementwise_log10:
3436 case Builtin::BI__builtin_elementwise_roundeven:
3437 case Builtin::BI__builtin_elementwise_round:
3438 case Builtin::BI__builtin_elementwise_rint:
3439 case Builtin::BI__builtin_elementwise_nearbyint:
3440 case Builtin::BI__builtin_elementwise_sin:
3441 case Builtin::BI__builtin_elementwise_sinh:
3442 case Builtin::BI__builtin_elementwise_sqrt:
3443 case Builtin::BI__builtin_elementwise_tan:
3444 case Builtin::BI__builtin_elementwise_tanh:
3445 case Builtin::BI__builtin_elementwise_trunc:
3446 case Builtin::BI__builtin_elementwise_canonicalize:
3447 if (PrepareBuiltinElementwiseMathOneArgCall(
3448 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3449 return ExprError();
3450 break;
3451 case Builtin::BI__builtin_elementwise_fma:
3452 if (BuiltinElementwiseTernaryMath(TheCall))
3453 return ExprError();
3454 break;
3455
3456 case Builtin::BI__builtin_elementwise_ldexp: {
3457 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3458 return ExprError();
3459
3460 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3461 if (A.isInvalid())
3462 return ExprError();
3463 QualType TyA = A.get()->getType();
3464 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3465 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3466 return ExprError();
3467
3468 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3469 if (Exp.isInvalid())
3470 return ExprError();
3471 QualType TyExp = Exp.get()->getType();
3472 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3473 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3474 ArgOrdinal: 2))
3475 return ExprError();
3476
3477 // Check the two arguments are either scalars or vectors of equal length.
3478 const auto *Vec0 = TyA->getAs<VectorType>();
3479 const auto *Vec1 = TyExp->getAs<VectorType>();
3480 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3481 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3482 if (Arg0Length != Arg1Length) {
3483 Diag(Loc: Exp.get()->getBeginLoc(),
3484 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3485 << TyA << TyExp << A.get()->getSourceRange()
3486 << Exp.get()->getSourceRange();
3487 return ExprError();
3488 }
3489
3490 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3491 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3492 TheCall->setType(TyA);
3493 break;
3494 }
3495
3496 // These builtins restrict the element type to floating point
3497 // types only, and take in two arguments.
3498 case Builtin::BI__builtin_elementwise_minnum:
3499 case Builtin::BI__builtin_elementwise_maxnum:
3500 case Builtin::BI__builtin_elementwise_minimum:
3501 case Builtin::BI__builtin_elementwise_maximum:
3502 case Builtin::BI__builtin_elementwise_minimumnum:
3503 case Builtin::BI__builtin_elementwise_maximumnum:
3504 case Builtin::BI__builtin_elementwise_atan2:
3505 case Builtin::BI__builtin_elementwise_fmod:
3506 case Builtin::BI__builtin_elementwise_pow:
3507 if (BuiltinElementwiseMath(TheCall,
3508 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3509 return ExprError();
3510 break;
3511 // These builtins restrict the element type to integer
3512 // types only.
3513 case Builtin::BI__builtin_elementwise_add_sat:
3514 case Builtin::BI__builtin_elementwise_sub_sat:
3515 if (BuiltinElementwiseMath(TheCall,
3516 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3517 return ExprError();
3518 break;
3519 case Builtin::BI__builtin_elementwise_fshl:
3520 case Builtin::BI__builtin_elementwise_fshr:
3521 if (BuiltinElementwiseTernaryMath(
3522 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3523 return ExprError();
3524 break;
3525 case Builtin::BI__builtin_elementwise_min:
3526 case Builtin::BI__builtin_elementwise_max:
3527 if (BuiltinElementwiseMath(TheCall))
3528 return ExprError();
3529 break;
3530 case Builtin::BI__builtin_elementwise_popcount:
3531 case Builtin::BI__builtin_elementwise_bitreverse:
3532 if (PrepareBuiltinElementwiseMathOneArgCall(
3533 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3534 return ExprError();
3535 break;
3536 case Builtin::BI__builtin_elementwise_copysign: {
3537 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3538 return ExprError();
3539
3540 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3541 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3542 if (Magnitude.isInvalid() || Sign.isInvalid())
3543 return ExprError();
3544
3545 QualType MagnitudeTy = Magnitude.get()->getType();
3546 QualType SignTy = Sign.get()->getType();
3547 if (checkMathBuiltinElementType(
3548 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3549 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3550 checkMathBuiltinElementType(
3551 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3552 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3553 return ExprError();
3554 }
3555
3556 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3557 return Diag(Loc: Sign.get()->getBeginLoc(),
3558 DiagID: diag::err_typecheck_call_different_arg_types)
3559 << MagnitudeTy << SignTy;
3560 }
3561
3562 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3563 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3564 TheCall->setType(Magnitude.get()->getType());
3565 break;
3566 }
3567 case Builtin::BI__builtin_elementwise_clzg:
3568 case Builtin::BI__builtin_elementwise_ctzg:
3569 // These builtins can be unary or binary. Note for empty calls we call the
3570 // unary checker in order to not emit an error that says the function
3571 // expects 2 arguments, which would be misleading.
3572 if (TheCall->getNumArgs() <= 1) {
3573 if (PrepareBuiltinElementwiseMathOneArgCall(
3574 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3575 return ExprError();
3576 } else if (BuiltinElementwiseMath(
3577 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3578 return ExprError();
3579 break;
3580 case Builtin::BI__builtin_reduce_max:
3581 case Builtin::BI__builtin_reduce_min: {
3582 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3583 return ExprError();
3584
3585 const Expr *Arg = TheCall->getArg(Arg: 0);
3586 const auto *TyA = Arg->getType()->getAs<VectorType>();
3587
3588 QualType ElTy;
3589 if (TyA)
3590 ElTy = TyA->getElementType();
3591 else if (Arg->getType()->isSizelessVectorType())
3592 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3593
3594 if (ElTy.isNull()) {
3595 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3596 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3597 << Arg->getType();
3598 return ExprError();
3599 }
3600
3601 TheCall->setType(ElTy);
3602 break;
3603 }
3604 case Builtin::BI__builtin_reduce_maximum:
3605 case Builtin::BI__builtin_reduce_minimum: {
3606 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3607 return ExprError();
3608
3609 const Expr *Arg = TheCall->getArg(Arg: 0);
3610 const auto *TyA = Arg->getType()->getAs<VectorType>();
3611
3612 QualType ElTy;
3613 if (TyA)
3614 ElTy = TyA->getElementType();
3615 else if (Arg->getType()->isSizelessVectorType())
3616 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3617
3618 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3619 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3620 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3621 << Arg->getType();
3622 return ExprError();
3623 }
3624
3625 TheCall->setType(ElTy);
3626 break;
3627 }
3628
3629 // These builtins support vectors of integers only.
3630 // TODO: ADD/MUL should support floating-point types.
3631 case Builtin::BI__builtin_reduce_add:
3632 case Builtin::BI__builtin_reduce_mul:
3633 case Builtin::BI__builtin_reduce_xor:
3634 case Builtin::BI__builtin_reduce_or:
3635 case Builtin::BI__builtin_reduce_and: {
3636 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3637 return ExprError();
3638
3639 const Expr *Arg = TheCall->getArg(Arg: 0);
3640 const auto *TyA = Arg->getType()->getAs<VectorType>();
3641
3642 QualType ElTy;
3643 if (TyA)
3644 ElTy = TyA->getElementType();
3645 else if (Arg->getType()->isSizelessVectorType())
3646 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3647
3648 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3649 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3650 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3651 << Arg->getType();
3652 return ExprError();
3653 }
3654
3655 TheCall->setType(ElTy);
3656 break;
3657 }
3658
3659 case Builtin::BI__builtin_matrix_transpose:
3660 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
3661
3662 case Builtin::BI__builtin_matrix_column_major_load:
3663 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
3664
3665 case Builtin::BI__builtin_matrix_column_major_store:
3666 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
3667
3668 case Builtin::BI__builtin_verbose_trap:
3669 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
3670 return ExprError();
3671 break;
3672
3673 case Builtin::BI__builtin_get_device_side_mangled_name: {
3674 auto Check = [](CallExpr *TheCall) {
3675 if (TheCall->getNumArgs() != 1)
3676 return false;
3677 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
3678 if (!DRE)
3679 return false;
3680 auto *D = DRE->getDecl();
3681 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
3682 return false;
3683 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3684 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3685 };
3686 if (!Check(TheCall)) {
3687 Diag(Loc: TheCall->getBeginLoc(),
3688 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
3689 return ExprError();
3690 }
3691 break;
3692 }
3693 case Builtin::BI__builtin_bswapg:
3694 if (BuiltinBswapg(S&: *this, TheCall))
3695 return ExprError();
3696 break;
3697 case Builtin::BI__builtin_popcountg:
3698 if (BuiltinPopcountg(S&: *this, TheCall))
3699 return ExprError();
3700 break;
3701 case Builtin::BI__builtin_clzg:
3702 case Builtin::BI__builtin_ctzg:
3703 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
3704 return ExprError();
3705 break;
3706
3707 case Builtin::BI__builtin_stdc_rotate_left:
3708 case Builtin::BI__builtin_stdc_rotate_right:
3709 if (BuiltinRotateGeneric(S&: *this, TheCall))
3710 return ExprError();
3711 break;
3712
3713 case Builtin::BI__builtin_allow_runtime_check: {
3714 Expr *Arg = TheCall->getArg(Arg: 0);
3715 // Check if the argument is a string literal.
3716 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
3717 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3718 << Arg->getSourceRange();
3719 return ExprError();
3720 }
3721 break;
3722 }
3723
3724 case Builtin::BI__builtin_allow_sanitize_check: {
3725 Expr *Arg = TheCall->getArg(Arg: 0);
3726 // Check if the argument is a string literal.
3727 const StringLiteral *SanitizerName =
3728 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
3729 if (!SanitizerName) {
3730 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3731 << Arg->getSourceRange();
3732 return ExprError();
3733 }
3734 // Validate the sanitizer name.
3735 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3736 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
3737 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3738 Value: true)
3739 .Default(Value: false)) {
3740 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
3741 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3742 << Arg->getSourceRange();
3743 return ExprError();
3744 }
3745 break;
3746 }
3747 case Builtin::BI__builtin_counted_by_ref:
3748 if (BuiltinCountedByRef(TheCall))
3749 return ExprError();
3750 break;
3751 }
3752
3753 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3754 return ExprError();
3755
3756 // Since the target specific builtins for each arch overlap, only check those
3757 // of the arch we are compiling for.
3758 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
3759 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
3760 assert(Context.getAuxTargetInfo() &&
3761 "Aux Target Builtin, but not an aux target?");
3762
3763 if (CheckTSBuiltinFunctionCall(
3764 TI: *Context.getAuxTargetInfo(),
3765 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
3766 return ExprError();
3767 } else {
3768 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
3769 TheCall))
3770 return ExprError();
3771 }
3772 }
3773
3774 return TheCallResult;
3775}
3776
3777bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3778 llvm::APSInt Result;
3779 // We can't check the value of a dependent argument.
3780 Expr *Arg = TheCall->getArg(Arg: ArgNum);
3781 if (Arg->isTypeDependent() || Arg->isValueDependent())
3782 return false;
3783
3784 // Check constant-ness first.
3785 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3786 return true;
3787
3788 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3789 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3790 return false;
3791
3792 return Diag(Loc: TheCall->getBeginLoc(),
3793 DiagID: diag::err_argument_not_contiguous_bit_field)
3794 << ArgNum << Arg->getSourceRange();
3795}
3796
3797bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3798 unsigned FirstArg, FormatStringInfo *FSI) {
3799 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3800 bool IsVariadic = false;
3801 if (const FunctionType *FnTy = D->getFunctionType())
3802 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
3803 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
3804 IsVariadic = BD->isVariadic();
3805 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
3806 IsVariadic = OMD->isVariadic();
3807
3808 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3809 IsVariadic, FSI);
3810}
3811
3812bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3813 bool HasImplicitThisParam, bool IsVariadic,
3814 FormatStringInfo *FSI) {
3815 if (FirstArg == 0)
3816 FSI->ArgPassingKind = FAPK_VAList;
3817 else if (IsVariadic)
3818 FSI->ArgPassingKind = FAPK_Variadic;
3819 else
3820 FSI->ArgPassingKind = FAPK_Fixed;
3821 FSI->FormatIdx = FormatIdx - 1;
3822 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3823
3824 // The way the format attribute works in GCC, the implicit this argument
3825 // of member functions is counted. However, it doesn't appear in our own
3826 // lists, so decrement format_idx in that case.
3827 if (HasImplicitThisParam) {
3828 if(FSI->FormatIdx == 0)
3829 return false;
3830 --FSI->FormatIdx;
3831 if (FSI->FirstDataArg != 0)
3832 --FSI->FirstDataArg;
3833 }
3834 return true;
3835}
3836
3837/// Checks if a the given expression evaluates to null.
3838///
3839/// Returns true if the value evaluates to null.
3840static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3841 // Treat (smart) pointers constructed from nullptr as null, whether we can
3842 // const-evaluate them or not.
3843 // This must happen first: the smart pointer expr might have _Nonnull type!
3844 if (isa<CXXNullPtrLiteralExpr>(
3845 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
3846 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
3847 return true;
3848
3849 // If the expression has non-null type, it doesn't evaluate to null.
3850 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3851 if (*nullability == NullabilityKind::NonNull)
3852 return false;
3853 }
3854
3855 // As a special case, transparent unions initialized with zero are
3856 // considered null for the purposes of the nonnull attribute.
3857 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3858 UT &&
3859 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3860 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
3861 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
3862 Expr = ILE->getInit(Init: 0);
3863 }
3864
3865 bool Result;
3866 return (!Expr->isValueDependent() &&
3867 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
3868 !Result);
3869}
3870
3871static void CheckNonNullArgument(Sema &S,
3872 const Expr *ArgExpr,
3873 SourceLocation CallSiteLoc) {
3874 if (CheckNonNullExpr(S, Expr: ArgExpr))
3875 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
3876 PD: S.PDiag(DiagID: diag::warn_null_arg)
3877 << ArgExpr->getSourceRange());
3878}
3879
3880/// Determine whether the given type has a non-null nullability annotation.
3881static bool isNonNullType(QualType type) {
3882 if (auto nullability = type->getNullability())
3883 return *nullability == NullabilityKind::NonNull;
3884
3885 return false;
3886}
3887
3888static void CheckNonNullArguments(Sema &S,
3889 const NamedDecl *FDecl,
3890 const FunctionProtoType *Proto,
3891 ArrayRef<const Expr *> Args,
3892 SourceLocation CallSiteLoc) {
3893 assert((FDecl || Proto) && "Need a function declaration or prototype");
3894
3895 // Already checked by constant evaluator.
3896 if (S.isConstantEvaluatedContext())
3897 return;
3898 // Check the attributes attached to the method/function itself.
3899 llvm::SmallBitVector NonNullArgs;
3900 if (FDecl) {
3901 // Handle the nonnull attribute on the function/method declaration itself.
3902 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3903 if (!NonNull->args_size()) {
3904 // Easy case: all pointer arguments are nonnull.
3905 for (const auto *Arg : Args)
3906 if (S.isValidPointerAttrType(T: Arg->getType()))
3907 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
3908 return;
3909 }
3910
3911 for (const ParamIdx &Idx : NonNull->args()) {
3912 unsigned IdxAST = Idx.getASTIndex();
3913 if (IdxAST >= Args.size())
3914 continue;
3915 if (NonNullArgs.empty())
3916 NonNullArgs.resize(N: Args.size());
3917 NonNullArgs.set(IdxAST);
3918 }
3919 }
3920 }
3921
3922 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
3923 // Handle the nonnull attribute on the parameters of the
3924 // function/method.
3925 ArrayRef<ParmVarDecl*> parms;
3926 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
3927 parms = FD->parameters();
3928 else
3929 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
3930
3931 unsigned ParamIndex = 0;
3932 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3933 I != E; ++I, ++ParamIndex) {
3934 const ParmVarDecl *PVD = *I;
3935 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
3936 if (NonNullArgs.empty())
3937 NonNullArgs.resize(N: Args.size());
3938
3939 NonNullArgs.set(ParamIndex);
3940 }
3941 }
3942 } else {
3943 // If we have a non-function, non-method declaration but no
3944 // function prototype, try to dig out the function prototype.
3945 if (!Proto) {
3946 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
3947 QualType type = VD->getType().getNonReferenceType();
3948 if (auto pointerType = type->getAs<PointerType>())
3949 type = pointerType->getPointeeType();
3950 else if (auto blockType = type->getAs<BlockPointerType>())
3951 type = blockType->getPointeeType();
3952 // FIXME: data member pointers?
3953
3954 // Dig out the function prototype, if there is one.
3955 Proto = type->getAs<FunctionProtoType>();
3956 }
3957 }
3958
3959 // Fill in non-null argument information from the nullability
3960 // information on the parameter types (if we have them).
3961 if (Proto) {
3962 unsigned Index = 0;
3963 for (auto paramType : Proto->getParamTypes()) {
3964 if (isNonNullType(type: paramType)) {
3965 if (NonNullArgs.empty())
3966 NonNullArgs.resize(N: Args.size());
3967
3968 NonNullArgs.set(Index);
3969 }
3970
3971 ++Index;
3972 }
3973 }
3974 }
3975
3976 // Check for non-null arguments.
3977 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3978 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3979 if (NonNullArgs[ArgIndex])
3980 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
3981 }
3982}
3983
3984void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3985 StringRef ParamName, QualType ArgTy,
3986 QualType ParamTy) {
3987
3988 // If a function accepts a pointer or reference type
3989 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3990 return;
3991
3992 // If the parameter is a pointer type, get the pointee type for the
3993 // argument too. If the parameter is a reference type, don't try to get
3994 // the pointee type for the argument.
3995 if (ParamTy->isPointerType())
3996 ArgTy = ArgTy->getPointeeType();
3997
3998 // Remove reference or pointer
3999 ParamTy = ParamTy->getPointeeType();
4000
4001 // Find expected alignment, and the actual alignment of the passed object.
4002 // getTypeAlignInChars requires complete types
4003 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4004 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4005 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4006 return;
4007
4008 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4009 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4010
4011 // If the argument is less aligned than the parameter, there is a
4012 // potential alignment issue.
4013 if (ArgAlign < ParamAlign)
4014 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4015 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4016 << ParamName << (FDecl != nullptr) << FDecl;
4017}
4018
4019void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4020 const Expr *ThisArg,
4021 ArrayRef<const Expr *> Args) {
4022 if (!FD || Args.empty())
4023 return;
4024 auto GetArgAt = [&](int Idx) -> const Expr * {
4025 if (Idx == LifetimeCaptureByAttr::Global ||
4026 Idx == LifetimeCaptureByAttr::Unknown)
4027 return nullptr;
4028 if (IsMemberFunction && Idx == 0)
4029 return ThisArg;
4030 return Args[Idx - IsMemberFunction];
4031 };
4032 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4033 unsigned ArgIdx) {
4034 if (!Attr)
4035 return;
4036
4037 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4038 for (int CapturingParamIdx : Attr->params()) {
4039 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4040 // initialization codepath.
4041 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4042 isa<CXXConstructorDecl>(Val: FD))
4043 continue;
4044 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4045 CapturingEntity CE{.Entity: Capturing};
4046 // Ensure that 'Captured' outlives the 'Capturing' entity.
4047 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4048 }
4049 };
4050 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4051 HandleCaptureByAttr(FD->getParamDecl(i: I)->getAttr<LifetimeCaptureByAttr>(),
4052 I + IsMemberFunction);
4053 // Check when the implicit object param is captured.
4054 if (IsMemberFunction) {
4055 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4056 if (!TSI)
4057 return;
4058 AttributedTypeLoc ATL;
4059 for (TypeLoc TL = TSI->getTypeLoc();
4060 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4061 TL = ATL.getModifiedLoc())
4062 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4063 }
4064}
4065
4066void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4067 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4068 bool IsMemberFunction, SourceLocation Loc,
4069 SourceRange Range, VariadicCallType CallType) {
4070 // FIXME: We should check as much as we can in the template definition.
4071 if (CurContext->isDependentContext())
4072 return;
4073
4074 // Printf and scanf checking.
4075 llvm::SmallBitVector CheckedVarArgs;
4076 if (FDecl) {
4077 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4078 // Only create vector if there are format attributes.
4079 CheckedVarArgs.resize(N: Args.size());
4080 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4081 CheckedVarArgs);
4082 }
4083
4084 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4085 CheckedVarArgs.resize(N: Args.size());
4086 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4087 CheckedVarArgs);
4088 }
4089 }
4090
4091 // Refuse POD arguments that weren't caught by the format string
4092 // checks above.
4093 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4094 if (CallType != VariadicCallType::DoesNotApply &&
4095 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4096 unsigned NumParams = Proto ? Proto->getNumParams()
4097 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4098 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4099 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4100 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4101 : 0;
4102
4103 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4104 // Args[ArgIdx] can be null in malformed code.
4105 if (const Expr *Arg = Args[ArgIdx]) {
4106 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4107 checkVariadicArgument(E: Arg, CT: CallType);
4108 }
4109 }
4110 }
4111 if (FD)
4112 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4113 if (FDecl || Proto) {
4114 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4115
4116 // Type safety checking.
4117 if (FDecl) {
4118 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4119 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4120 }
4121 }
4122
4123 // Check that passed arguments match the alignment of original arguments.
4124 // Try to get the missing prototype from the declaration.
4125 if (!Proto && FDecl) {
4126 const auto *FT = FDecl->getFunctionType();
4127 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4128 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4129 }
4130 if (Proto) {
4131 // For variadic functions, we may have more args than parameters.
4132 // For some K&R functions, we may have less args than parameters.
4133 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4134 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4135 bool IsScalableArg = false;
4136 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4137 // Args[ArgIdx] can be null in malformed code.
4138 if (const Expr *Arg = Args[ArgIdx]) {
4139 if (Arg->containsErrors())
4140 continue;
4141
4142 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4143 FDecl->hasLinkage() &&
4144 FDecl->getFormalLinkage() != Linkage::Internal &&
4145 CallType == VariadicCallType::DoesNotApply)
4146 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4147
4148 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4149 if (ParamTy->isSizelessVectorType())
4150 IsScalableArg = true;
4151 QualType ArgTy = Arg->getType();
4152 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4153 ArgTy, ParamTy);
4154 }
4155 }
4156
4157 // If the callee has an AArch64 SME attribute to indicate that it is an
4158 // __arm_streaming function, then the caller requires SME to be available.
4159 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4160 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4161 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4162 llvm::StringMap<bool> CallerFeatureMap;
4163 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4164 if (!CallerFeatureMap.contains(Key: "sme"))
4165 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4166 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4167 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4168 }
4169 }
4170
4171 // If the call requires a streaming-mode change and has scalable vector
4172 // arguments or return values, then warn the user that the streaming and
4173 // non-streaming vector lengths may be different.
4174 // When both streaming and non-streaming vector lengths are defined and
4175 // mismatched, produce an error.
4176 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4177 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4178 (IsScalableArg || IsScalableRet)) {
4179 bool IsCalleeStreaming =
4180 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4181 bool IsCalleeStreamingCompatible =
4182 ExtInfo.AArch64SMEAttributes &
4183 FunctionType::SME_PStateSMCompatibleMask;
4184 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4185 if (!IsCalleeStreamingCompatible &&
4186 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4187 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4188 const LangOptions &LO = getLangOpts();
4189 unsigned VL = LO.VScaleMin * 128;
4190 unsigned SVL = LO.VScaleStreamingMin * 128;
4191 bool IsVLMismatch = VL && SVL && VL != SVL;
4192
4193 auto EmitDiag = [&](bool IsArg) {
4194 if (IsVLMismatch) {
4195 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4196 // Emit warning for streaming-compatible callers
4197 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4198 << IsArg << IsCalleeStreaming << SVL << VL;
4199 else
4200 // Emit error otherwise
4201 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4202 << IsArg << SVL << VL;
4203 } else
4204 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4205 << IsArg;
4206 };
4207
4208 if (IsScalableArg)
4209 EmitDiag(true);
4210 if (IsScalableRet)
4211 EmitDiag(false);
4212 }
4213 }
4214
4215 FunctionType::ArmStateValue CalleeArmZAState =
4216 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4217 FunctionType::ArmStateValue CalleeArmZT0State =
4218 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4219 if (CalleeArmZAState != FunctionType::ARM_None ||
4220 CalleeArmZT0State != FunctionType::ARM_None) {
4221 bool CallerHasZAState = false;
4222 bool CallerHasZT0State = false;
4223 if (CallerFD) {
4224 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4225 if (Attr && Attr->isNewZA())
4226 CallerHasZAState = true;
4227 if (Attr && Attr->isNewZT0())
4228 CallerHasZT0State = true;
4229 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4230 CallerHasZAState |=
4231 FunctionType::getArmZAState(
4232 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4233 FunctionType::ARM_None;
4234 CallerHasZT0State |=
4235 FunctionType::getArmZT0State(
4236 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4237 FunctionType::ARM_None;
4238 }
4239 }
4240
4241 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4242 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4243
4244 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4245 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4246
4247 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4248 CalleeArmZT0State != FunctionType::ARM_None) {
4249 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4250 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4251 }
4252 }
4253 }
4254
4255 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4256 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4257 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4258 if (!Arg->isValueDependent()) {
4259 Expr::EvalResult Align;
4260 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4261 const llvm::APSInt &I = Align.Val.getInt();
4262 if (!I.isPowerOf2())
4263 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4264 << Arg->getSourceRange();
4265
4266 if (I > Sema::MaximumAlignment)
4267 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4268 << Arg->getSourceRange() << Sema::MaximumAlignment;
4269 }
4270 }
4271 }
4272
4273 if (FD)
4274 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4275}
4276
4277void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4278 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4279 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4280 }
4281}
4282
4283void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4284 ArrayRef<const Expr *> Args,
4285 const FunctionProtoType *Proto,
4286 SourceLocation Loc) {
4287 VariadicCallType CallType = Proto->isVariadic()
4288 ? VariadicCallType::Constructor
4289 : VariadicCallType::DoesNotApply;
4290
4291 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4292 CheckArgAlignment(
4293 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4294 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4295
4296 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4297 Loc, Range: SourceRange(), CallType);
4298}
4299
4300bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4301 const FunctionProtoType *Proto) {
4302 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4303 isa<CXXMethodDecl>(Val: FDecl);
4304 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4305 IsMemberOperatorCall;
4306 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4307 Fn: TheCall->getCallee());
4308 Expr** Args = TheCall->getArgs();
4309 unsigned NumArgs = TheCall->getNumArgs();
4310
4311 Expr *ImplicitThis = nullptr;
4312 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4313 // If this is a call to a member operator, hide the first
4314 // argument from checkCall.
4315 // FIXME: Our choice of AST representation here is less than ideal.
4316 ImplicitThis = Args[0];
4317 ++Args;
4318 --NumArgs;
4319 } else if (IsMemberFunction && !FDecl->isStatic() &&
4320 !FDecl->hasCXXExplicitFunctionObjectParameter())
4321 ImplicitThis =
4322 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4323
4324 if (ImplicitThis) {
4325 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4326 // used.
4327 QualType ThisType = ImplicitThis->getType();
4328 if (!ThisType->isPointerType()) {
4329 assert(!ThisType->isReferenceType());
4330 ThisType = Context.getPointerType(T: ThisType);
4331 }
4332
4333 QualType ThisTypeFromDecl = Context.getPointerType(
4334 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4335
4336 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4337 ParamTy: ThisTypeFromDecl);
4338 }
4339
4340 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4341 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4342 Range: TheCall->getCallee()->getSourceRange(), CallType);
4343
4344 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4345 // None of the checks below are needed for functions that don't have
4346 // simple names (e.g., C++ conversion functions).
4347 if (!FnInfo)
4348 return false;
4349
4350 // Enforce TCB except for builtin calls, which are always allowed.
4351 if (FDecl->getBuiltinID() == 0)
4352 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4353
4354 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4355 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4356 CheckInfNaNFunction(Call: TheCall, FDecl);
4357
4358 if (getLangOpts().ObjC)
4359 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4360
4361 unsigned CMId = FDecl->getMemoryFunctionKind();
4362
4363 // Handle memory setting and copying functions.
4364 switch (CMId) {
4365 case 0:
4366 return false;
4367 case Builtin::BIstrlcpy: // fallthrough
4368 case Builtin::BIstrlcat:
4369 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4370 break;
4371 case Builtin::BIstrncat:
4372 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4373 break;
4374 case Builtin::BIfree:
4375 CheckFreeArguments(E: TheCall);
4376 break;
4377 default:
4378 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4379 }
4380
4381 return false;
4382}
4383
4384bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4385 const FunctionProtoType *Proto) {
4386 QualType Ty;
4387 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4388 Ty = V->getType().getNonReferenceType();
4389 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4390 Ty = F->getType().getNonReferenceType();
4391 else
4392 return false;
4393
4394 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4395 !Ty->isFunctionProtoType())
4396 return false;
4397
4398 VariadicCallType CallType;
4399 if (!Proto || !Proto->isVariadic()) {
4400 CallType = VariadicCallType::DoesNotApply;
4401 } else if (Ty->isBlockPointerType()) {
4402 CallType = VariadicCallType::Block;
4403 } else { // Ty->isFunctionPointerType()
4404 CallType = VariadicCallType::Function;
4405 }
4406
4407 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4408 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4409 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4410 Range: TheCall->getCallee()->getSourceRange(), CallType);
4411
4412 return false;
4413}
4414
4415bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4416 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4417 Fn: TheCall->getCallee());
4418 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4419 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4420 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4421 Range: TheCall->getCallee()->getSourceRange(), CallType);
4422
4423 return false;
4424}
4425
4426static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4427 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4428 return false;
4429
4430 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4431 switch (Op) {
4432 case AtomicExpr::AO__c11_atomic_init:
4433 case AtomicExpr::AO__opencl_atomic_init:
4434 llvm_unreachable("There is no ordering argument for an init");
4435
4436 case AtomicExpr::AO__c11_atomic_load:
4437 case AtomicExpr::AO__opencl_atomic_load:
4438 case AtomicExpr::AO__hip_atomic_load:
4439 case AtomicExpr::AO__atomic_load_n:
4440 case AtomicExpr::AO__atomic_load:
4441 case AtomicExpr::AO__scoped_atomic_load_n:
4442 case AtomicExpr::AO__scoped_atomic_load:
4443 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4444 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4445
4446 case AtomicExpr::AO__c11_atomic_store:
4447 case AtomicExpr::AO__opencl_atomic_store:
4448 case AtomicExpr::AO__hip_atomic_store:
4449 case AtomicExpr::AO__atomic_store:
4450 case AtomicExpr::AO__atomic_store_n:
4451 case AtomicExpr::AO__scoped_atomic_store:
4452 case AtomicExpr::AO__scoped_atomic_store_n:
4453 case AtomicExpr::AO__atomic_clear:
4454 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4455 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4456 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4457
4458 default:
4459 return true;
4460 }
4461}
4462
4463ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4464 AtomicExpr::AtomicOp Op) {
4465 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4466 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4467 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4468 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4469 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4470 Op);
4471}
4472
4473ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4474 SourceLocation RParenLoc, MultiExprArg Args,
4475 AtomicExpr::AtomicOp Op,
4476 AtomicArgumentOrder ArgOrder) {
4477 // All the non-OpenCL operations take one of the following forms.
4478 // The OpenCL operations take the __c11 forms with one extra argument for
4479 // synchronization scope.
4480 enum {
4481 // C __c11_atomic_init(A *, C)
4482 Init,
4483
4484 // C __c11_atomic_load(A *, int)
4485 Load,
4486
4487 // void __atomic_load(A *, CP, int)
4488 LoadCopy,
4489
4490 // void __atomic_store(A *, CP, int)
4491 Copy,
4492
4493 // C __c11_atomic_add(A *, M, int)
4494 Arithmetic,
4495
4496 // C __atomic_exchange_n(A *, CP, int)
4497 Xchg,
4498
4499 // void __atomic_exchange(A *, C *, CP, int)
4500 GNUXchg,
4501
4502 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4503 C11CmpXchg,
4504
4505 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4506 GNUCmpXchg,
4507
4508 // bool __atomic_test_and_set(A *, int)
4509 TestAndSetByte,
4510
4511 // void __atomic_clear(A *, int)
4512 ClearByte,
4513 } Form = Init;
4514
4515 const unsigned NumForm = ClearByte + 1;
4516 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4517 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4518 // where:
4519 // C is an appropriate type,
4520 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4521 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4522 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4523 // the int parameters are for orderings.
4524
4525 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4526 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4527 "need to update code for modified forms");
4528 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4529 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4530 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4531 "need to update code for modified C11 atomics");
4532 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4533 Op <= AtomicExpr::AO__opencl_atomic_store;
4534 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4535 Op <= AtomicExpr::AO__hip_atomic_store;
4536 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4537 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4538 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4539 Op <= AtomicExpr::AO__c11_atomic_store) ||
4540 IsOpenCL;
4541 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4542 Op == AtomicExpr::AO__atomic_store_n ||
4543 Op == AtomicExpr::AO__atomic_exchange_n ||
4544 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4545 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4546 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4547 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4548 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4549 // Bit mask for extra allowed value types other than integers for atomic
4550 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4551 // allow floating point.
4552 enum ArithOpExtraValueType {
4553 AOEVT_None = 0,
4554 AOEVT_Pointer = 1,
4555 AOEVT_FP = 2,
4556 };
4557 unsigned ArithAllows = AOEVT_None;
4558
4559 switch (Op) {
4560 case AtomicExpr::AO__c11_atomic_init:
4561 case AtomicExpr::AO__opencl_atomic_init:
4562 Form = Init;
4563 break;
4564
4565 case AtomicExpr::AO__c11_atomic_load:
4566 case AtomicExpr::AO__opencl_atomic_load:
4567 case AtomicExpr::AO__hip_atomic_load:
4568 case AtomicExpr::AO__atomic_load_n:
4569 case AtomicExpr::AO__scoped_atomic_load_n:
4570 Form = Load;
4571 break;
4572
4573 case AtomicExpr::AO__atomic_load:
4574 case AtomicExpr::AO__scoped_atomic_load:
4575 Form = LoadCopy;
4576 break;
4577
4578 case AtomicExpr::AO__c11_atomic_store:
4579 case AtomicExpr::AO__opencl_atomic_store:
4580 case AtomicExpr::AO__hip_atomic_store:
4581 case AtomicExpr::AO__atomic_store:
4582 case AtomicExpr::AO__atomic_store_n:
4583 case AtomicExpr::AO__scoped_atomic_store:
4584 case AtomicExpr::AO__scoped_atomic_store_n:
4585 Form = Copy;
4586 break;
4587 case AtomicExpr::AO__atomic_fetch_add:
4588 case AtomicExpr::AO__atomic_fetch_sub:
4589 case AtomicExpr::AO__atomic_add_fetch:
4590 case AtomicExpr::AO__atomic_sub_fetch:
4591 case AtomicExpr::AO__scoped_atomic_fetch_add:
4592 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4593 case AtomicExpr::AO__scoped_atomic_add_fetch:
4594 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4595 case AtomicExpr::AO__c11_atomic_fetch_add:
4596 case AtomicExpr::AO__c11_atomic_fetch_sub:
4597 case AtomicExpr::AO__opencl_atomic_fetch_add:
4598 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4599 case AtomicExpr::AO__hip_atomic_fetch_add:
4600 case AtomicExpr::AO__hip_atomic_fetch_sub:
4601 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4602 Form = Arithmetic;
4603 break;
4604 case AtomicExpr::AO__atomic_fetch_max:
4605 case AtomicExpr::AO__atomic_fetch_min:
4606 case AtomicExpr::AO__atomic_max_fetch:
4607 case AtomicExpr::AO__atomic_min_fetch:
4608 case AtomicExpr::AO__scoped_atomic_fetch_max:
4609 case AtomicExpr::AO__scoped_atomic_fetch_min:
4610 case AtomicExpr::AO__scoped_atomic_max_fetch:
4611 case AtomicExpr::AO__scoped_atomic_min_fetch:
4612 case AtomicExpr::AO__c11_atomic_fetch_max:
4613 case AtomicExpr::AO__c11_atomic_fetch_min:
4614 case AtomicExpr::AO__opencl_atomic_fetch_max:
4615 case AtomicExpr::AO__opencl_atomic_fetch_min:
4616 case AtomicExpr::AO__hip_atomic_fetch_max:
4617 case AtomicExpr::AO__hip_atomic_fetch_min:
4618 ArithAllows = AOEVT_FP;
4619 Form = Arithmetic;
4620 break;
4621 case AtomicExpr::AO__c11_atomic_fetch_and:
4622 case AtomicExpr::AO__c11_atomic_fetch_or:
4623 case AtomicExpr::AO__c11_atomic_fetch_xor:
4624 case AtomicExpr::AO__hip_atomic_fetch_and:
4625 case AtomicExpr::AO__hip_atomic_fetch_or:
4626 case AtomicExpr::AO__hip_atomic_fetch_xor:
4627 case AtomicExpr::AO__c11_atomic_fetch_nand:
4628 case AtomicExpr::AO__opencl_atomic_fetch_and:
4629 case AtomicExpr::AO__opencl_atomic_fetch_or:
4630 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4631 case AtomicExpr::AO__atomic_fetch_and:
4632 case AtomicExpr::AO__atomic_fetch_or:
4633 case AtomicExpr::AO__atomic_fetch_xor:
4634 case AtomicExpr::AO__atomic_fetch_nand:
4635 case AtomicExpr::AO__atomic_and_fetch:
4636 case AtomicExpr::AO__atomic_or_fetch:
4637 case AtomicExpr::AO__atomic_xor_fetch:
4638 case AtomicExpr::AO__atomic_nand_fetch:
4639 case AtomicExpr::AO__atomic_fetch_uinc:
4640 case AtomicExpr::AO__atomic_fetch_udec:
4641 case AtomicExpr::AO__scoped_atomic_fetch_and:
4642 case AtomicExpr::AO__scoped_atomic_fetch_or:
4643 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4644 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4645 case AtomicExpr::AO__scoped_atomic_and_fetch:
4646 case AtomicExpr::AO__scoped_atomic_or_fetch:
4647 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4648 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4649 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4650 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4651 Form = Arithmetic;
4652 break;
4653
4654 case AtomicExpr::AO__c11_atomic_exchange:
4655 case AtomicExpr::AO__hip_atomic_exchange:
4656 case AtomicExpr::AO__opencl_atomic_exchange:
4657 case AtomicExpr::AO__atomic_exchange_n:
4658 case AtomicExpr::AO__scoped_atomic_exchange_n:
4659 Form = Xchg;
4660 break;
4661
4662 case AtomicExpr::AO__atomic_exchange:
4663 case AtomicExpr::AO__scoped_atomic_exchange:
4664 Form = GNUXchg;
4665 break;
4666
4667 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4668 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4669 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4670 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4671 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4672 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4673 Form = C11CmpXchg;
4674 break;
4675
4676 case AtomicExpr::AO__atomic_compare_exchange:
4677 case AtomicExpr::AO__atomic_compare_exchange_n:
4678 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4679 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4680 Form = GNUCmpXchg;
4681 break;
4682
4683 case AtomicExpr::AO__atomic_test_and_set:
4684 Form = TestAndSetByte;
4685 break;
4686
4687 case AtomicExpr::AO__atomic_clear:
4688 Form = ClearByte;
4689 break;
4690 }
4691
4692 unsigned AdjustedNumArgs = NumArgs[Form];
4693 if ((IsOpenCL || IsHIP || IsScoped) &&
4694 Op != AtomicExpr::AO__opencl_atomic_init)
4695 ++AdjustedNumArgs;
4696 // Check we have the right number of arguments.
4697 if (Args.size() < AdjustedNumArgs) {
4698 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
4699 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4700 << /*is non object*/ 0 << ExprRange;
4701 return ExprError();
4702 } else if (Args.size() > AdjustedNumArgs) {
4703 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
4704 DiagID: diag::err_typecheck_call_too_many_args)
4705 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4706 << /*is non object*/ 0 << ExprRange;
4707 return ExprError();
4708 }
4709
4710 // Inspect the first argument of the atomic operation.
4711 Expr *Ptr = Args[0];
4712 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
4713 if (ConvertedPtr.isInvalid())
4714 return ExprError();
4715
4716 Ptr = ConvertedPtr.get();
4717 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4718 if (!pointerType) {
4719 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4720 << Ptr->getType() << 0 << Ptr->getSourceRange();
4721 return ExprError();
4722 }
4723
4724 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4725 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4726 QualType ValType = AtomTy; // 'C'
4727 if (IsC11) {
4728 if (!AtomTy->isAtomicType()) {
4729 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
4730 << Ptr->getType() << Ptr->getSourceRange();
4731 return ExprError();
4732 }
4733 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4734 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4735 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
4736 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4737 << Ptr->getSourceRange();
4738 return ExprError();
4739 }
4740 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4741 } else if (Form != Load && Form != LoadCopy) {
4742 if (ValType.isConstQualified()) {
4743 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
4744 << Ptr->getType() << Ptr->getSourceRange();
4745 return ExprError();
4746 }
4747 }
4748
4749 if (Form != TestAndSetByte && Form != ClearByte) {
4750 // Pointer to object of size zero is not allowed.
4751 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
4752 DiagID: diag::err_incomplete_type))
4753 return ExprError();
4754
4755 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
4756 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4757 << Ptr->getType() << 1 << Ptr->getSourceRange();
4758 return ExprError();
4759 }
4760 } else {
4761 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4762 // non-const pointer type, including void* and pointers to incomplete
4763 // structs, but only access the first byte.
4764 AtomTy = Context.CharTy;
4765 AtomTy = AtomTy.withCVRQualifiers(
4766 CVR: pointerType->getPointeeType().getCVRQualifiers());
4767 QualType PointerQT = Context.getPointerType(T: AtomTy);
4768 pointerType = PointerQT->getAs<PointerType>();
4769 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
4770 ValType = AtomTy;
4771 }
4772
4773 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4774 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4775 Diag(Loc: ExprRange.getBegin(),
4776 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
4777 << 0 << Ptr->getType() << Ptr->getSourceRange();
4778 return ExprError();
4779 }
4780
4781 // For an arithmetic operation, the implied arithmetic must be well-formed.
4782 if (Form == Arithmetic) {
4783 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4784 // trivial type errors.
4785 auto IsAllowedValueType = [&](QualType ValType,
4786 unsigned AllowedType) -> bool {
4787 if (ValType->isIntegerType())
4788 return true;
4789 if (ValType->isPointerType())
4790 return AllowedType & AOEVT_Pointer;
4791 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4792 return false;
4793 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4794 if (ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
4795 &Context.getTargetInfo().getLongDoubleFormat() ==
4796 &llvm::APFloat::x87DoubleExtended())
4797 return false;
4798 return true;
4799 };
4800 if (!IsAllowedValueType(ValType, ArithAllows)) {
4801 auto DID = ArithAllows & AOEVT_FP
4802 ? (ArithAllows & AOEVT_Pointer
4803 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4804 : diag::err_atomic_op_needs_atomic_int_or_fp)
4805 : diag::err_atomic_op_needs_atomic_int;
4806 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
4807 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4808 return ExprError();
4809 }
4810 if (IsC11 && ValType->isPointerType() &&
4811 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
4812 DiagID: diag::err_incomplete_type)) {
4813 return ExprError();
4814 }
4815 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4816 // For __atomic_*_n operations, the value type must be a scalar integral or
4817 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4818 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic_int_or_ptr)
4819 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4820 return ExprError();
4821 }
4822
4823 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4824 !AtomTy->isScalarType()) {
4825 // For GNU atomics, require a trivially-copyable type. This is not part of
4826 // the GNU atomics specification but we enforce it for consistency with
4827 // other atomics which generally all require a trivially-copyable type. This
4828 // is because atomics just copy bits.
4829 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
4830 << Ptr->getType() << Ptr->getSourceRange();
4831 return ExprError();
4832 }
4833
4834 switch (ValType.getObjCLifetime()) {
4835 case Qualifiers::OCL_None:
4836 case Qualifiers::OCL_ExplicitNone:
4837 // okay
4838 break;
4839
4840 case Qualifiers::OCL_Weak:
4841 case Qualifiers::OCL_Strong:
4842 case Qualifiers::OCL_Autoreleasing:
4843 // FIXME: Can this happen? By this point, ValType should be known
4844 // to be trivially copyable.
4845 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
4846 << ValType << Ptr->getSourceRange();
4847 return ExprError();
4848 }
4849
4850 // All atomic operations have an overload which takes a pointer to a volatile
4851 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4852 // into the result or the other operands. Similarly atomic_load takes a
4853 // pointer to a const 'A'.
4854 ValType.removeLocalVolatile();
4855 ValType.removeLocalConst();
4856 QualType ResultType = ValType;
4857 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4858 Form == ClearByte)
4859 ResultType = Context.VoidTy;
4860 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4861 ResultType = Context.BoolTy;
4862
4863 // The type of a parameter passed 'by value'. In the GNU atomics, such
4864 // arguments are actually passed as pointers.
4865 QualType ByValType = ValType; // 'CP'
4866 bool IsPassedByAddress = false;
4867 if (!IsC11 && !IsHIP && !IsN) {
4868 ByValType = Ptr->getType();
4869 IsPassedByAddress = true;
4870 }
4871
4872 SmallVector<Expr *, 5> APIOrderedArgs;
4873 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4874 APIOrderedArgs.push_back(Elt: Args[0]);
4875 switch (Form) {
4876 case Init:
4877 case Load:
4878 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
4879 break;
4880 case LoadCopy:
4881 case Copy:
4882 case Arithmetic:
4883 case Xchg:
4884 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4885 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4886 break;
4887 case GNUXchg:
4888 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4889 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
4890 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4891 break;
4892 case C11CmpXchg:
4893 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4894 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
4895 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4896 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
4897 break;
4898 case GNUCmpXchg:
4899 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4900 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
4901 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
4902 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4903 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
4904 break;
4905 case TestAndSetByte:
4906 case ClearByte:
4907 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4908 break;
4909 }
4910 } else
4911 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
4912
4913 // The first argument's non-CV pointer type is used to deduce the type of
4914 // subsequent arguments, except for:
4915 // - weak flag (always converted to bool)
4916 // - memory order (always converted to int)
4917 // - scope (always converted to int)
4918 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4919 QualType Ty;
4920 if (i < NumVals[Form] + 1) {
4921 switch (i) {
4922 case 0:
4923 // The first argument is always a pointer. It has a fixed type.
4924 // It is always dereferenced, a nullptr is undefined.
4925 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
4926 // Nothing else to do: we already know all we want about this pointer.
4927 continue;
4928 case 1:
4929 // The second argument is the non-atomic operand. For arithmetic, this
4930 // is always passed by value, and for a compare_exchange it is always
4931 // passed by address. For the rest, GNU uses by-address and C11 uses
4932 // by-value.
4933 assert(Form != Load);
4934 if (Form == Arithmetic && ValType->isPointerType())
4935 Ty = Context.getPointerDiffType();
4936 else if (Form == Init || Form == Arithmetic)
4937 Ty = ValType;
4938 else if (Form == Copy || Form == Xchg) {
4939 if (IsPassedByAddress) {
4940 // The value pointer is always dereferenced, a nullptr is undefined.
4941 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
4942 CallSiteLoc: ExprRange.getBegin());
4943 }
4944 Ty = ByValType;
4945 } else {
4946 Expr *ValArg = APIOrderedArgs[i];
4947 // The value pointer is always dereferenced, a nullptr is undefined.
4948 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
4949 LangAS AS = LangAS::Default;
4950 // Keep address space of non-atomic pointer type.
4951 if (const PointerType *PtrTy =
4952 ValArg->getType()->getAs<PointerType>()) {
4953 AS = PtrTy->getPointeeType().getAddressSpace();
4954 }
4955 Ty = Context.getPointerType(
4956 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
4957 }
4958 break;
4959 case 2:
4960 // The third argument to compare_exchange / GNU exchange is the desired
4961 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4962 if (IsPassedByAddress)
4963 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
4964 Ty = ByValType;
4965 break;
4966 case 3:
4967 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4968 Ty = Context.BoolTy;
4969 break;
4970 }
4971 } else {
4972 // The order(s) and scope are always converted to int.
4973 Ty = Context.IntTy;
4974 }
4975
4976 InitializedEntity Entity =
4977 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
4978 ExprResult Arg = APIOrderedArgs[i];
4979 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
4980 if (Arg.isInvalid())
4981 return true;
4982 APIOrderedArgs[i] = Arg.get();
4983 }
4984
4985 // Permute the arguments into a 'consistent' order.
4986 SmallVector<Expr*, 5> SubExprs;
4987 SubExprs.push_back(Elt: Ptr);
4988 switch (Form) {
4989 case Init:
4990 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4991 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
4992 break;
4993 case Load:
4994 case TestAndSetByte:
4995 case ClearByte:
4996 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
4997 break;
4998 case LoadCopy:
4999 case Copy:
5000 case Arithmetic:
5001 case Xchg:
5002 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5003 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5004 break;
5005 case GNUXchg:
5006 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5007 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5008 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5009 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5010 break;
5011 case C11CmpXchg:
5012 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5013 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5014 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5015 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5016 break;
5017 case GNUCmpXchg:
5018 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5019 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5020 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5021 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5022 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5023 break;
5024 }
5025
5026 // If the memory orders are constants, check they are valid.
5027 if (SubExprs.size() >= 2 && Form != Init) {
5028 std::optional<llvm::APSInt> Success =
5029 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5030 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5031 Diag(Loc: SubExprs[1]->getBeginLoc(),
5032 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5033 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5034 << SubExprs[1]->getSourceRange();
5035 }
5036 if (SubExprs.size() >= 5) {
5037 if (std::optional<llvm::APSInt> Failure =
5038 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5039 if (!llvm::is_contained(
5040 Set: {llvm::AtomicOrderingCABI::relaxed,
5041 llvm::AtomicOrderingCABI::consume,
5042 llvm::AtomicOrderingCABI::acquire,
5043 llvm::AtomicOrderingCABI::seq_cst},
5044 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5045 Diag(Loc: SubExprs[3]->getBeginLoc(),
5046 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5047 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5048 }
5049 }
5050 }
5051 }
5052
5053 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5054 auto *Scope = Args[Args.size() - 1];
5055 if (std::optional<llvm::APSInt> Result =
5056 Scope->getIntegerConstantExpr(Ctx: Context)) {
5057 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5058 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5059 << Scope->getSourceRange();
5060 }
5061 SubExprs.push_back(Elt: Scope);
5062 }
5063
5064 AtomicExpr *AE = new (Context)
5065 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5066
5067 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5068 Op == AtomicExpr::AO__c11_atomic_store ||
5069 Op == AtomicExpr::AO__opencl_atomic_load ||
5070 Op == AtomicExpr::AO__hip_atomic_load ||
5071 Op == AtomicExpr::AO__opencl_atomic_store ||
5072 Op == AtomicExpr::AO__hip_atomic_store) &&
5073 Context.AtomicUsesUnsupportedLibcall(E: AE))
5074 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5075 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5076 Op == AtomicExpr::AO__opencl_atomic_load ||
5077 Op == AtomicExpr::AO__hip_atomic_load)
5078 ? 0
5079 : 1);
5080
5081 if (ValType->isBitIntType()) {
5082 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5083 return ExprError();
5084 }
5085
5086 return AE;
5087}
5088
5089/// checkBuiltinArgument - Given a call to a builtin function, perform
5090/// normal type-checking on the given argument, updating the call in
5091/// place. This is useful when a builtin function requires custom
5092/// type-checking for some of its arguments but not necessarily all of
5093/// them.
5094///
5095/// Returns true on error.
5096static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5097 FunctionDecl *Fn = E->getDirectCallee();
5098 assert(Fn && "builtin call without direct callee!");
5099
5100 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5101 InitializedEntity Entity =
5102 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5103
5104 ExprResult Arg = E->getArg(Arg: ArgIndex);
5105 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5106 if (Arg.isInvalid())
5107 return true;
5108
5109 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5110 return false;
5111}
5112
5113ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5114 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5115 Expr *Callee = TheCall->getCallee();
5116 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5117 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5118
5119 // Ensure that we have at least one argument to do type inference from.
5120 if (TheCall->getNumArgs() < 1) {
5121 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5122 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5123 << Callee->getSourceRange();
5124 return ExprError();
5125 }
5126
5127 // Inspect the first argument of the atomic builtin. This should always be
5128 // a pointer type, whose element is an integral scalar or pointer type.
5129 // Because it is a pointer type, we don't have to worry about any implicit
5130 // casts here.
5131 // FIXME: We don't allow floating point scalars as input.
5132 Expr *FirstArg = TheCall->getArg(Arg: 0);
5133 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5134 if (FirstArgResult.isInvalid())
5135 return ExprError();
5136 FirstArg = FirstArgResult.get();
5137 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5138
5139 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5140 if (!pointerType) {
5141 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5142 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5143 return ExprError();
5144 }
5145
5146 QualType ValType = pointerType->getPointeeType();
5147 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5148 !ValType->isBlockPointerType()) {
5149 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5150 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5151 return ExprError();
5152 }
5153 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5154 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5155 Diag(Loc: FirstArg->getBeginLoc(),
5156 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5157 << 1 << ValType << FirstArg->getSourceRange();
5158 return ExprError();
5159 }
5160
5161 if (ValType.isConstQualified()) {
5162 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5163 << FirstArg->getType() << FirstArg->getSourceRange();
5164 return ExprError();
5165 }
5166
5167 switch (ValType.getObjCLifetime()) {
5168 case Qualifiers::OCL_None:
5169 case Qualifiers::OCL_ExplicitNone:
5170 // okay
5171 break;
5172
5173 case Qualifiers::OCL_Weak:
5174 case Qualifiers::OCL_Strong:
5175 case Qualifiers::OCL_Autoreleasing:
5176 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5177 << ValType << FirstArg->getSourceRange();
5178 return ExprError();
5179 }
5180
5181 // Strip any qualifiers off ValType.
5182 ValType = ValType.getUnqualifiedType();
5183
5184 // The majority of builtins return a value, but a few have special return
5185 // types, so allow them to override appropriately below.
5186 QualType ResultType = ValType;
5187
5188 // We need to figure out which concrete builtin this maps onto. For example,
5189 // __sync_fetch_and_add with a 2 byte object turns into
5190 // __sync_fetch_and_add_2.
5191#define BUILTIN_ROW(x) \
5192 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5193 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5194
5195 static const unsigned BuiltinIndices[][5] = {
5196 BUILTIN_ROW(__sync_fetch_and_add),
5197 BUILTIN_ROW(__sync_fetch_and_sub),
5198 BUILTIN_ROW(__sync_fetch_and_or),
5199 BUILTIN_ROW(__sync_fetch_and_and),
5200 BUILTIN_ROW(__sync_fetch_and_xor),
5201 BUILTIN_ROW(__sync_fetch_and_nand),
5202
5203 BUILTIN_ROW(__sync_add_and_fetch),
5204 BUILTIN_ROW(__sync_sub_and_fetch),
5205 BUILTIN_ROW(__sync_and_and_fetch),
5206 BUILTIN_ROW(__sync_or_and_fetch),
5207 BUILTIN_ROW(__sync_xor_and_fetch),
5208 BUILTIN_ROW(__sync_nand_and_fetch),
5209
5210 BUILTIN_ROW(__sync_val_compare_and_swap),
5211 BUILTIN_ROW(__sync_bool_compare_and_swap),
5212 BUILTIN_ROW(__sync_lock_test_and_set),
5213 BUILTIN_ROW(__sync_lock_release),
5214 BUILTIN_ROW(__sync_swap)
5215 };
5216#undef BUILTIN_ROW
5217
5218 // Determine the index of the size.
5219 unsigned SizeIndex;
5220 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5221 case 1: SizeIndex = 0; break;
5222 case 2: SizeIndex = 1; break;
5223 case 4: SizeIndex = 2; break;
5224 case 8: SizeIndex = 3; break;
5225 case 16: SizeIndex = 4; break;
5226 default:
5227 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5228 << FirstArg->getType() << FirstArg->getSourceRange();
5229 return ExprError();
5230 }
5231
5232 // Each of these builtins has one pointer argument, followed by some number of
5233 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5234 // that we ignore. Find out which row of BuiltinIndices to read from as well
5235 // as the number of fixed args.
5236 unsigned BuiltinID = FDecl->getBuiltinID();
5237 unsigned BuiltinIndex, NumFixed = 1;
5238 bool WarnAboutSemanticsChange = false;
5239 switch (BuiltinID) {
5240 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5241 case Builtin::BI__sync_fetch_and_add:
5242 case Builtin::BI__sync_fetch_and_add_1:
5243 case Builtin::BI__sync_fetch_and_add_2:
5244 case Builtin::BI__sync_fetch_and_add_4:
5245 case Builtin::BI__sync_fetch_and_add_8:
5246 case Builtin::BI__sync_fetch_and_add_16:
5247 BuiltinIndex = 0;
5248 break;
5249
5250 case Builtin::BI__sync_fetch_and_sub:
5251 case Builtin::BI__sync_fetch_and_sub_1:
5252 case Builtin::BI__sync_fetch_and_sub_2:
5253 case Builtin::BI__sync_fetch_and_sub_4:
5254 case Builtin::BI__sync_fetch_and_sub_8:
5255 case Builtin::BI__sync_fetch_and_sub_16:
5256 BuiltinIndex = 1;
5257 break;
5258
5259 case Builtin::BI__sync_fetch_and_or:
5260 case Builtin::BI__sync_fetch_and_or_1:
5261 case Builtin::BI__sync_fetch_and_or_2:
5262 case Builtin::BI__sync_fetch_and_or_4:
5263 case Builtin::BI__sync_fetch_and_or_8:
5264 case Builtin::BI__sync_fetch_and_or_16:
5265 BuiltinIndex = 2;
5266 break;
5267
5268 case Builtin::BI__sync_fetch_and_and:
5269 case Builtin::BI__sync_fetch_and_and_1:
5270 case Builtin::BI__sync_fetch_and_and_2:
5271 case Builtin::BI__sync_fetch_and_and_4:
5272 case Builtin::BI__sync_fetch_and_and_8:
5273 case Builtin::BI__sync_fetch_and_and_16:
5274 BuiltinIndex = 3;
5275 break;
5276
5277 case Builtin::BI__sync_fetch_and_xor:
5278 case Builtin::BI__sync_fetch_and_xor_1:
5279 case Builtin::BI__sync_fetch_and_xor_2:
5280 case Builtin::BI__sync_fetch_and_xor_4:
5281 case Builtin::BI__sync_fetch_and_xor_8:
5282 case Builtin::BI__sync_fetch_and_xor_16:
5283 BuiltinIndex = 4;
5284 break;
5285
5286 case Builtin::BI__sync_fetch_and_nand:
5287 case Builtin::BI__sync_fetch_and_nand_1:
5288 case Builtin::BI__sync_fetch_and_nand_2:
5289 case Builtin::BI__sync_fetch_and_nand_4:
5290 case Builtin::BI__sync_fetch_and_nand_8:
5291 case Builtin::BI__sync_fetch_and_nand_16:
5292 BuiltinIndex = 5;
5293 WarnAboutSemanticsChange = true;
5294 break;
5295
5296 case Builtin::BI__sync_add_and_fetch:
5297 case Builtin::BI__sync_add_and_fetch_1:
5298 case Builtin::BI__sync_add_and_fetch_2:
5299 case Builtin::BI__sync_add_and_fetch_4:
5300 case Builtin::BI__sync_add_and_fetch_8:
5301 case Builtin::BI__sync_add_and_fetch_16:
5302 BuiltinIndex = 6;
5303 break;
5304
5305 case Builtin::BI__sync_sub_and_fetch:
5306 case Builtin::BI__sync_sub_and_fetch_1:
5307 case Builtin::BI__sync_sub_and_fetch_2:
5308 case Builtin::BI__sync_sub_and_fetch_4:
5309 case Builtin::BI__sync_sub_and_fetch_8:
5310 case Builtin::BI__sync_sub_and_fetch_16:
5311 BuiltinIndex = 7;
5312 break;
5313
5314 case Builtin::BI__sync_and_and_fetch:
5315 case Builtin::BI__sync_and_and_fetch_1:
5316 case Builtin::BI__sync_and_and_fetch_2:
5317 case Builtin::BI__sync_and_and_fetch_4:
5318 case Builtin::BI__sync_and_and_fetch_8:
5319 case Builtin::BI__sync_and_and_fetch_16:
5320 BuiltinIndex = 8;
5321 break;
5322
5323 case Builtin::BI__sync_or_and_fetch:
5324 case Builtin::BI__sync_or_and_fetch_1:
5325 case Builtin::BI__sync_or_and_fetch_2:
5326 case Builtin::BI__sync_or_and_fetch_4:
5327 case Builtin::BI__sync_or_and_fetch_8:
5328 case Builtin::BI__sync_or_and_fetch_16:
5329 BuiltinIndex = 9;
5330 break;
5331
5332 case Builtin::BI__sync_xor_and_fetch:
5333 case Builtin::BI__sync_xor_and_fetch_1:
5334 case Builtin::BI__sync_xor_and_fetch_2:
5335 case Builtin::BI__sync_xor_and_fetch_4:
5336 case Builtin::BI__sync_xor_and_fetch_8:
5337 case Builtin::BI__sync_xor_and_fetch_16:
5338 BuiltinIndex = 10;
5339 break;
5340
5341 case Builtin::BI__sync_nand_and_fetch:
5342 case Builtin::BI__sync_nand_and_fetch_1:
5343 case Builtin::BI__sync_nand_and_fetch_2:
5344 case Builtin::BI__sync_nand_and_fetch_4:
5345 case Builtin::BI__sync_nand_and_fetch_8:
5346 case Builtin::BI__sync_nand_and_fetch_16:
5347 BuiltinIndex = 11;
5348 WarnAboutSemanticsChange = true;
5349 break;
5350
5351 case Builtin::BI__sync_val_compare_and_swap:
5352 case Builtin::BI__sync_val_compare_and_swap_1:
5353 case Builtin::BI__sync_val_compare_and_swap_2:
5354 case Builtin::BI__sync_val_compare_and_swap_4:
5355 case Builtin::BI__sync_val_compare_and_swap_8:
5356 case Builtin::BI__sync_val_compare_and_swap_16:
5357 BuiltinIndex = 12;
5358 NumFixed = 2;
5359 break;
5360
5361 case Builtin::BI__sync_bool_compare_and_swap:
5362 case Builtin::BI__sync_bool_compare_and_swap_1:
5363 case Builtin::BI__sync_bool_compare_and_swap_2:
5364 case Builtin::BI__sync_bool_compare_and_swap_4:
5365 case Builtin::BI__sync_bool_compare_and_swap_8:
5366 case Builtin::BI__sync_bool_compare_and_swap_16:
5367 BuiltinIndex = 13;
5368 NumFixed = 2;
5369 ResultType = Context.BoolTy;
5370 break;
5371
5372 case Builtin::BI__sync_lock_test_and_set:
5373 case Builtin::BI__sync_lock_test_and_set_1:
5374 case Builtin::BI__sync_lock_test_and_set_2:
5375 case Builtin::BI__sync_lock_test_and_set_4:
5376 case Builtin::BI__sync_lock_test_and_set_8:
5377 case Builtin::BI__sync_lock_test_and_set_16:
5378 BuiltinIndex = 14;
5379 break;
5380
5381 case Builtin::BI__sync_lock_release:
5382 case Builtin::BI__sync_lock_release_1:
5383 case Builtin::BI__sync_lock_release_2:
5384 case Builtin::BI__sync_lock_release_4:
5385 case Builtin::BI__sync_lock_release_8:
5386 case Builtin::BI__sync_lock_release_16:
5387 BuiltinIndex = 15;
5388 NumFixed = 0;
5389 ResultType = Context.VoidTy;
5390 break;
5391
5392 case Builtin::BI__sync_swap:
5393 case Builtin::BI__sync_swap_1:
5394 case Builtin::BI__sync_swap_2:
5395 case Builtin::BI__sync_swap_4:
5396 case Builtin::BI__sync_swap_8:
5397 case Builtin::BI__sync_swap_16:
5398 BuiltinIndex = 16;
5399 break;
5400 }
5401
5402 // Now that we know how many fixed arguments we expect, first check that we
5403 // have at least that many.
5404 if (TheCall->getNumArgs() < 1+NumFixed) {
5405 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5406 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5407 << Callee->getSourceRange();
5408 return ExprError();
5409 }
5410
5411 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5412 << Callee->getSourceRange();
5413
5414 if (WarnAboutSemanticsChange) {
5415 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5416 << Callee->getSourceRange();
5417 }
5418
5419 // Get the decl for the concrete builtin from this, we can tell what the
5420 // concrete integer type we should convert to is.
5421 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5422 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5423 FunctionDecl *NewBuiltinDecl;
5424 if (NewBuiltinID == BuiltinID)
5425 NewBuiltinDecl = FDecl;
5426 else {
5427 // Perform builtin lookup to avoid redeclaring it.
5428 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5429 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5430 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5431 assert(Res.getFoundDecl());
5432 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5433 if (!NewBuiltinDecl)
5434 return ExprError();
5435 }
5436
5437 // The first argument --- the pointer --- has a fixed type; we
5438 // deduce the types of the rest of the arguments accordingly. Walk
5439 // the remaining arguments, converting them to the deduced value type.
5440 for (unsigned i = 0; i != NumFixed; ++i) {
5441 ExprResult Arg = TheCall->getArg(Arg: i+1);
5442
5443 // GCC does an implicit conversion to the pointer or integer ValType. This
5444 // can fail in some cases (1i -> int**), check for this error case now.
5445 // Initialize the argument.
5446 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5447 Type: ValType, /*consume*/ Consumed: false);
5448 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5449 if (Arg.isInvalid())
5450 return ExprError();
5451
5452 // Okay, we have something that *can* be converted to the right type. Check
5453 // to see if there is a potentially weird extension going on here. This can
5454 // happen when you do an atomic operation on something like an char* and
5455 // pass in 42. The 42 gets converted to char. This is even more strange
5456 // for things like 45.123 -> char, etc.
5457 // FIXME: Do this check.
5458 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
5459 }
5460
5461 // Create a new DeclRefExpr to refer to the new decl.
5462 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5463 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
5464 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
5465 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
5466
5467 // Set the callee in the CallExpr.
5468 // FIXME: This loses syntactic information.
5469 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
5470 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
5471 CK: CK_BuiltinFnToFnPtr);
5472 TheCall->setCallee(PromotedCall.get());
5473
5474 // Change the result type of the call to match the original value type. This
5475 // is arbitrary, but the codegen for these builtins ins design to handle it
5476 // gracefully.
5477 TheCall->setType(ResultType);
5478
5479 // Prohibit problematic uses of bit-precise integer types with atomic
5480 // builtins. The arguments would have already been converted to the first
5481 // argument's type, so only need to check the first argument.
5482 const auto *BitIntValType = ValType->getAs<BitIntType>();
5483 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
5484 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
5485 return ExprError();
5486 }
5487
5488 return TheCallResult;
5489}
5490
5491ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5492 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5493 DeclRefExpr *DRE =
5494 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5495 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5496 unsigned BuiltinID = FDecl->getBuiltinID();
5497 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5498 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5499 "Unexpected nontemporal load/store builtin!");
5500 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5501 unsigned numArgs = isStore ? 2 : 1;
5502
5503 // Ensure that we have the proper number of arguments.
5504 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
5505 return ExprError();
5506
5507 // Inspect the last argument of the nontemporal builtin. This should always
5508 // be a pointer type, from which we imply the type of the memory access.
5509 // Because it is a pointer type, we don't have to worry about any implicit
5510 // casts here.
5511 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
5512 ExprResult PointerArgResult =
5513 DefaultFunctionArrayLvalueConversion(E: PointerArg);
5514
5515 if (PointerArgResult.isInvalid())
5516 return ExprError();
5517 PointerArg = PointerArgResult.get();
5518 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
5519
5520 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5521 if (!pointerType) {
5522 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
5523 << PointerArg->getType() << PointerArg->getSourceRange();
5524 return ExprError();
5525 }
5526
5527 QualType ValType = pointerType->getPointeeType();
5528
5529 // Strip any qualifiers off ValType.
5530 ValType = ValType.getUnqualifiedType();
5531 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5532 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5533 !ValType->isVectorType()) {
5534 Diag(Loc: DRE->getBeginLoc(),
5535 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5536 << PointerArg->getType() << PointerArg->getSourceRange();
5537 return ExprError();
5538 }
5539
5540 if (!isStore) {
5541 TheCall->setType(ValType);
5542 return TheCallResult;
5543 }
5544
5545 ExprResult ValArg = TheCall->getArg(Arg: 0);
5546 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5547 Context, Type: ValType, /*consume*/ Consumed: false);
5548 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
5549 if (ValArg.isInvalid())
5550 return ExprError();
5551
5552 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
5553 TheCall->setType(Context.VoidTy);
5554 return TheCallResult;
5555}
5556
5557/// CheckObjCString - Checks that the format string argument to the os_log()
5558/// and os_trace() functions is correct, and converts it to const char *.
5559ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5560 Arg = Arg->IgnoreParenCasts();
5561 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
5562 if (!Literal) {
5563 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
5564 Literal = ObjcLiteral->getString();
5565 }
5566 }
5567
5568 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5569 return ExprError(
5570 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
5571 << Arg->getSourceRange());
5572 }
5573
5574 ExprResult Result(Literal);
5575 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
5576 InitializedEntity Entity =
5577 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
5578 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
5579 return Result;
5580}
5581
5582/// Check that the user is calling the appropriate va_start builtin for the
5583/// target and calling convention.
5584static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5585 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5586 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5587 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5588 TT.getArch() == llvm::Triple::aarch64_32);
5589 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5590 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5591 if (IsX64 || IsAArch64) {
5592 CallingConv CC = CC_C;
5593 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5594 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5595 if (IsMSVAStart) {
5596 // Don't allow this in System V ABI functions.
5597 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5598 return S.Diag(Loc: Fn->getBeginLoc(),
5599 DiagID: diag::err_ms_va_start_used_in_sysv_function);
5600 } else {
5601 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5602 // On x64 Windows, don't allow this in System V ABI functions.
5603 // (Yes, that means there's no corresponding way to support variadic
5604 // System V ABI functions on Windows.)
5605 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5606 (!IsWindowsOrUEFI && CC == CC_Win64))
5607 return S.Diag(Loc: Fn->getBeginLoc(),
5608 DiagID: diag::err_va_start_used_in_wrong_abi_function)
5609 << !IsWindowsOrUEFI;
5610 }
5611 return false;
5612 }
5613
5614 if (IsMSVAStart)
5615 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
5616 return false;
5617}
5618
5619static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5620 ParmVarDecl **LastParam = nullptr) {
5621 // Determine whether the current function, block, or obj-c method is variadic
5622 // and get its parameter list.
5623 bool IsVariadic = false;
5624 ArrayRef<ParmVarDecl *> Params;
5625 DeclContext *Caller = S.CurContext;
5626 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
5627 IsVariadic = Block->isVariadic();
5628 Params = Block->parameters();
5629 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
5630 IsVariadic = FD->isVariadic();
5631 Params = FD->parameters();
5632 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
5633 IsVariadic = MD->isVariadic();
5634 // FIXME: This isn't correct for methods (results in bogus warning).
5635 Params = MD->parameters();
5636 } else if (isa<CapturedDecl>(Val: Caller)) {
5637 // We don't support va_start in a CapturedDecl.
5638 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
5639 return true;
5640 } else {
5641 // This must be some other declcontext that parses exprs.
5642 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
5643 return true;
5644 }
5645
5646 if (!IsVariadic) {
5647 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
5648 return true;
5649 }
5650
5651 if (LastParam)
5652 *LastParam = Params.empty() ? nullptr : Params.back();
5653
5654 return false;
5655}
5656
5657bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5658 Expr *Fn = TheCall->getCallee();
5659 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
5660 return true;
5661
5662 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5663 // This builtin requires one argument (the va_list), allows two arguments,
5664 // but diagnoses more than two arguments. e.g.,
5665 // __builtin_c23_va_start(); // error
5666 // __builtin_c23_va_start(list); // ok
5667 // __builtin_c23_va_start(list, param); // ok
5668 // __builtin_c23_va_start(list, anything, anything); // error
5669 // This differs from the GCC behavior in that they accept the last case
5670 // with a warning, but it doesn't seem like a useful behavior to allow.
5671 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
5672 return true;
5673 } else {
5674 // In C23 mode, va_start only needs one argument. However, the builtin still
5675 // requires two arguments (which matches the behavior of the GCC builtin),
5676 // <stdarg.h> passes `0` as the second argument in C23 mode.
5677 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5678 return true;
5679 }
5680
5681 // Type-check the first argument normally.
5682 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
5683 return true;
5684
5685 // Check that the current function is variadic, and get its last parameter.
5686 ParmVarDecl *LastParam;
5687 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
5688 return true;
5689
5690 // Verify that the second argument to the builtin is the last non-variadic
5691 // argument of the current function or method. In C23 mode, if the call is
5692 // not to __builtin_c23_va_start, and the second argument is an integer
5693 // constant expression with value 0, then we don't bother with this check.
5694 // For __builtin_c23_va_start, we only perform the check for the second
5695 // argument being the last argument to the current function if there is a
5696 // second argument present.
5697 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5698 TheCall->getNumArgs() < 2) {
5699 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5700 return false;
5701 }
5702
5703 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
5704 if (std::optional<llvm::APSInt> Val =
5705 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
5706 Val && LangOpts.C23 && *Val == 0 &&
5707 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5708 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5709 return false;
5710 }
5711
5712 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5713 // next block.
5714 QualType Type;
5715 SourceLocation ParamLoc;
5716 bool IsCRegister = false;
5717 bool SecondArgIsLastNonVariadicArgument = false;
5718 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
5719 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
5720 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5721
5722 Type = PV->getType();
5723 ParamLoc = PV->getLocation();
5724 IsCRegister =
5725 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5726 }
5727 }
5728
5729 if (!SecondArgIsLastNonVariadicArgument)
5730 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
5731 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5732 else if (IsCRegister || Type->isReferenceType() ||
5733 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
5734 // Promotable integers are UB, but enumerations need a bit of
5735 // extra checking to see what their promotable type actually is.
5736 if (!Context.isPromotableIntegerType(T: Type))
5737 return false;
5738 const auto *ED = Type->getAsEnumDecl();
5739 if (!ED)
5740 return true;
5741 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
5742 }()) {
5743 unsigned Reason = 0;
5744 if (Type->isReferenceType()) Reason = 1;
5745 else if (IsCRegister) Reason = 2;
5746 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
5747 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
5748 }
5749
5750 return false;
5751}
5752
5753bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5754 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5755 const LangOptions &LO = getLangOpts();
5756
5757 if (LO.CPlusPlus)
5758 return Arg->getType()
5759 .getCanonicalType()
5760 .getTypePtr()
5761 ->getPointeeType()
5762 .withoutLocalFastQualifiers() == Context.CharTy;
5763
5764 // In C, allow aliasing through `char *`, this is required for AArch64 at
5765 // least.
5766 return true;
5767 };
5768
5769 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5770 // const char *named_addr);
5771
5772 Expr *Func = Call->getCallee();
5773
5774 if (Call->getNumArgs() < 3)
5775 return Diag(Loc: Call->getEndLoc(),
5776 DiagID: diag::err_typecheck_call_too_few_args_at_least)
5777 << 0 /*function call*/ << 3 << Call->getNumArgs()
5778 << /*is non object*/ 0;
5779
5780 // Type-check the first argument normally.
5781 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
5782 return true;
5783
5784 // Check that the current function is variadic.
5785 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
5786 return true;
5787
5788 // __va_start on Windows does not validate the parameter qualifiers
5789
5790 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
5791 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5792
5793 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
5794 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5795
5796 const QualType &ConstCharPtrTy =
5797 Context.getPointerType(T: Context.CharTy.withConst());
5798 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5799 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5800 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5801 << 0 /* qualifier difference */
5802 << 3 /* parameter mismatch */
5803 << 2 << Arg1->getType() << ConstCharPtrTy;
5804
5805 const QualType SizeTy = Context.getSizeType();
5806 if (!Context.hasSameType(
5807 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
5808 T2: SizeTy))
5809 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5810 << Arg2->getType() << SizeTy << 1 /* different class */
5811 << 0 /* qualifier difference */
5812 << 3 /* parameter mismatch */
5813 << 3 << Arg2->getType() << SizeTy;
5814
5815 return false;
5816}
5817
5818bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5819 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5820 return true;
5821
5822 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5823 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
5824 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5825 << 1 << 0 << TheCall->getSourceRange();
5826
5827 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
5828 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
5829
5830 // Do standard promotions between the two arguments, returning their common
5831 // type.
5832 QualType Res = UsualArithmeticConversions(
5833 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
5834 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5835 return true;
5836
5837 // Make sure any conversions are pushed back into the call; this is
5838 // type safe since unordered compare builtins are declared as "_Bool
5839 // foo(...)".
5840 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
5841 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
5842
5843 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5844 return false;
5845
5846 // If the common type isn't a real floating type, then the arguments were
5847 // invalid for this operation.
5848 if (Res.isNull() || !Res->isRealFloatingType())
5849 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
5850 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
5851 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5852 << SourceRange(OrigArg0.get()->getBeginLoc(),
5853 OrigArg1.get()->getEndLoc());
5854
5855 return false;
5856}
5857
5858bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5859 unsigned BuiltinID) {
5860 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
5861 return true;
5862
5863 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
5864 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5865 BuiltinID == Builtin::BI__builtin_isinf ||
5866 BuiltinID == Builtin::BI__builtin_isinf_sign))
5867 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5868 << 0 << 0 << TheCall->getSourceRange();
5869
5870 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5871 BuiltinID == Builtin::BI__builtin_isunordered))
5872 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5873 << 1 << 0 << TheCall->getSourceRange();
5874
5875 bool IsFPClass = NumArgs == 2;
5876
5877 // Find out position of floating-point argument.
5878 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5879
5880 // We can count on all parameters preceding the floating-point just being int.
5881 // Try all of those.
5882 for (unsigned i = 0; i < FPArgNo; ++i) {
5883 Expr *Arg = TheCall->getArg(Arg: i);
5884
5885 if (Arg->isTypeDependent())
5886 return false;
5887
5888 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
5889 Action: AssignmentAction::Passing);
5890
5891 if (Res.isInvalid())
5892 return true;
5893 TheCall->setArg(Arg: i, ArgExpr: Res.get());
5894 }
5895
5896 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
5897
5898 if (OrigArg->isTypeDependent())
5899 return false;
5900
5901 // Usual Unary Conversions will convert half to float, which we want for
5902 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5903 // type how it is, but do normal L->Rvalue conversions.
5904 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5905 ExprResult Res = UsualUnaryConversions(E: OrigArg);
5906
5907 if (!Res.isUsable())
5908 return true;
5909 OrigArg = Res.get();
5910 } else {
5911 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
5912
5913 if (!Res.isUsable())
5914 return true;
5915 OrigArg = Res.get();
5916 }
5917 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
5918
5919 QualType VectorResultTy;
5920 QualType ElementTy = OrigArg->getType();
5921 // TODO: When all classification function are implemented with is_fpclass,
5922 // vector argument can be supported in all of them.
5923 if (ElementTy->isVectorType() && IsFPClass) {
5924 VectorResultTy = GetSignedVectorType(V: ElementTy);
5925 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5926 }
5927
5928 // This operation requires a non-_Complex floating-point number.
5929 if (!ElementTy->isRealFloatingType())
5930 return Diag(Loc: OrigArg->getBeginLoc(),
5931 DiagID: diag::err_typecheck_call_invalid_unary_fp)
5932 << OrigArg->getType() << OrigArg->getSourceRange();
5933
5934 // __builtin_isfpclass has integer parameter that specify test mask. It is
5935 // passed in (...), so it should be analyzed completely here.
5936 if (IsFPClass)
5937 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
5938 return true;
5939
5940 // TODO: enable this code to all classification functions.
5941 if (IsFPClass) {
5942 QualType ResultTy;
5943 if (!VectorResultTy.isNull())
5944 ResultTy = VectorResultTy;
5945 else
5946 ResultTy = Context.IntTy;
5947 TheCall->setType(ResultTy);
5948 }
5949
5950 return false;
5951}
5952
5953bool Sema::BuiltinComplex(CallExpr *TheCall) {
5954 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5955 return true;
5956
5957 bool Dependent = false;
5958 for (unsigned I = 0; I != 2; ++I) {
5959 Expr *Arg = TheCall->getArg(Arg: I);
5960 QualType T = Arg->getType();
5961 if (T->isDependentType()) {
5962 Dependent = true;
5963 continue;
5964 }
5965
5966 // Despite supporting _Complex int, GCC requires a real floating point type
5967 // for the operands of __builtin_complex.
5968 if (!T->isRealFloatingType()) {
5969 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
5970 << Arg->getType() << Arg->getSourceRange();
5971 }
5972
5973 ExprResult Converted = DefaultLvalueConversion(E: Arg);
5974 if (Converted.isInvalid())
5975 return true;
5976 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
5977 }
5978
5979 if (Dependent) {
5980 TheCall->setType(Context.DependentTy);
5981 return false;
5982 }
5983
5984 Expr *Real = TheCall->getArg(Arg: 0);
5985 Expr *Imag = TheCall->getArg(Arg: 1);
5986 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
5987 return Diag(Loc: Real->getBeginLoc(),
5988 DiagID: diag::err_typecheck_call_different_arg_types)
5989 << Real->getType() << Imag->getType()
5990 << Real->getSourceRange() << Imag->getSourceRange();
5991 }
5992
5993 TheCall->setType(Context.getComplexType(T: Real->getType()));
5994 return false;
5995}
5996
5997/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5998// This is declared to take (...), so we have to check everything.
5999ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6000 unsigned NumArgs = TheCall->getNumArgs();
6001 if (NumArgs < 2)
6002 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6003 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6004 << 0 /*function call*/ << 2 << NumArgs
6005 << /*is non object*/ 0 << TheCall->getSourceRange());
6006
6007 // Determine which of the following types of shufflevector we're checking:
6008 // 1) unary, vector mask: (lhs, mask)
6009 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6010 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6011 unsigned NumElements = 0;
6012
6013 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6014 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6015 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6016 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6017
6018 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6019 return ExprError(
6020 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6021 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6022 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6023 TheCall->getArg(Arg: 1)->getEndLoc()));
6024
6025 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6026 unsigned NumResElements = NumArgs - 2;
6027
6028 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6029 // with mask. If so, verify that RHS is an integer vector type with the
6030 // same number of elts as lhs.
6031 if (NumArgs == 2) {
6032 if (!RHSType->hasIntegerRepresentation() ||
6033 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6034 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6035 DiagID: diag::err_vec_builtin_incompatible_vector)
6036 << TheCall->getDirectCallee()
6037 << /*isMoreThanTwoArgs*/ false
6038 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6039 TheCall->getArg(Arg: 1)->getEndLoc()));
6040 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6041 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6042 DiagID: diag::err_vec_builtin_incompatible_vector)
6043 << TheCall->getDirectCallee()
6044 << /*isMoreThanTwoArgs*/ false
6045 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6046 TheCall->getArg(Arg: 1)->getEndLoc()));
6047 } else if (NumElements != NumResElements) {
6048 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6049 ResType = ResType->isExtVectorType()
6050 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6051 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6052 VecKind: VectorKind::Generic);
6053 }
6054 }
6055
6056 for (unsigned I = 2; I != NumArgs; ++I) {
6057 Expr *Arg = TheCall->getArg(Arg: I);
6058 if (Arg->isTypeDependent() || Arg->isValueDependent())
6059 continue;
6060
6061 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6062 if (!Result)
6063 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6064 DiagID: diag::err_shufflevector_nonconstant_argument)
6065 << Arg->getSourceRange());
6066
6067 // Allow -1 which will be translated to undef in the IR.
6068 if (Result->isSigned() && Result->isAllOnes())
6069 ;
6070 else if (Result->getActiveBits() > 64 ||
6071 Result->getZExtValue() >= NumElements * 2)
6072 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6073 DiagID: diag::err_shufflevector_argument_too_large)
6074 << Arg->getSourceRange());
6075
6076 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6077 }
6078
6079 auto *Result = new (Context) ShuffleVectorExpr(
6080 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6081 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6082
6083 // All moved to Result.
6084 TheCall->shrinkNumArgs(NewNumArgs: 0);
6085 return Result;
6086}
6087
6088ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6089 SourceLocation BuiltinLoc,
6090 SourceLocation RParenLoc) {
6091 ExprValueKind VK = VK_PRValue;
6092 ExprObjectKind OK = OK_Ordinary;
6093 QualType DstTy = TInfo->getType();
6094 QualType SrcTy = E->getType();
6095
6096 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6097 return ExprError(Diag(Loc: BuiltinLoc,
6098 DiagID: diag::err_convertvector_non_vector)
6099 << E->getSourceRange());
6100 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6101 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6102 << "second"
6103 << "__builtin_convertvector");
6104
6105 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6106 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6107 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6108 if (SrcElts != DstElts)
6109 return ExprError(Diag(Loc: BuiltinLoc,
6110 DiagID: diag::err_convertvector_incompatible_vector)
6111 << E->getSourceRange());
6112 }
6113
6114 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6115 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6116}
6117
6118bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6119 unsigned NumArgs = TheCall->getNumArgs();
6120
6121 if (NumArgs > 3)
6122 return Diag(Loc: TheCall->getEndLoc(),
6123 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6124 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6125 << TheCall->getSourceRange();
6126
6127 // Argument 0 is checked for us and the remaining arguments must be
6128 // constant integers.
6129 for (unsigned i = 1; i != NumArgs; ++i)
6130 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6131 return true;
6132
6133 return false;
6134}
6135
6136bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6137 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6138 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6139 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6140 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6141 return true;
6142 Expr *Arg = TheCall->getArg(Arg: 0);
6143 if (Arg->isInstantiationDependent())
6144 return false;
6145
6146 QualType ArgTy = Arg->getType();
6147 if (!ArgTy->hasFloatingRepresentation())
6148 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6149 << ArgTy;
6150 if (Arg->isLValue()) {
6151 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6152 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6153 }
6154 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6155 return false;
6156}
6157
6158bool Sema::BuiltinAssume(CallExpr *TheCall) {
6159 Expr *Arg = TheCall->getArg(Arg: 0);
6160 if (Arg->isInstantiationDependent()) return false;
6161
6162 if (Arg->HasSideEffects(Ctx: Context))
6163 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6164 << Arg->getSourceRange()
6165 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6166
6167 return false;
6168}
6169
6170bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6171 // The alignment must be a constant integer.
6172 Expr *Arg = TheCall->getArg(Arg: 1);
6173
6174 // We can't check the value of a dependent argument.
6175 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6176 if (const auto *UE =
6177 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6178 if (UE->getKind() == UETT_AlignOf ||
6179 UE->getKind() == UETT_PreferredAlignOf)
6180 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6181 << Arg->getSourceRange();
6182
6183 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6184
6185 if (!Result.isPowerOf2())
6186 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6187 << Arg->getSourceRange();
6188
6189 if (Result < Context.getCharWidth())
6190 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6191 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6192
6193 if (Result > std::numeric_limits<int32_t>::max())
6194 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6195 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6196 }
6197
6198 return false;
6199}
6200
6201bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6202 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6203 return true;
6204
6205 unsigned NumArgs = TheCall->getNumArgs();
6206 Expr *FirstArg = TheCall->getArg(Arg: 0);
6207
6208 {
6209 ExprResult FirstArgResult =
6210 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6211 if (!FirstArgResult.get()->getType()->isPointerType()) {
6212 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6213 << TheCall->getSourceRange();
6214 return true;
6215 }
6216 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6217 }
6218
6219 // The alignment must be a constant integer.
6220 Expr *SecondArg = TheCall->getArg(Arg: 1);
6221
6222 // We can't check the value of a dependent argument.
6223 if (!SecondArg->isValueDependent()) {
6224 llvm::APSInt Result;
6225 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6226 return true;
6227
6228 if (!Result.isPowerOf2())
6229 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6230 << SecondArg->getSourceRange();
6231
6232 if (Result > Sema::MaximumAlignment)
6233 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6234 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6235
6236 TheCall->setArg(Arg: 1,
6237 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6238 }
6239
6240 if (NumArgs > 2) {
6241 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6242 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6243 return true;
6244 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6245 }
6246
6247 return false;
6248}
6249
6250bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6251 unsigned BuiltinID =
6252 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6253 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6254
6255 unsigned NumArgs = TheCall->getNumArgs();
6256 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6257 if (NumArgs < NumRequiredArgs) {
6258 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6259 << 0 /* function call */ << NumRequiredArgs << NumArgs
6260 << /*is non object*/ 0 << TheCall->getSourceRange();
6261 }
6262 if (NumArgs >= NumRequiredArgs + 0x100) {
6263 return Diag(Loc: TheCall->getEndLoc(),
6264 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6265 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6266 << /*is non object*/ 0 << TheCall->getSourceRange();
6267 }
6268 unsigned i = 0;
6269
6270 // For formatting call, check buffer arg.
6271 if (!IsSizeCall) {
6272 ExprResult Arg(TheCall->getArg(Arg: i));
6273 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6274 Context, Type: Context.VoidPtrTy, Consumed: false);
6275 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6276 if (Arg.isInvalid())
6277 return true;
6278 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6279 i++;
6280 }
6281
6282 // Check string literal arg.
6283 unsigned FormatIdx = i;
6284 {
6285 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6286 if (Arg.isInvalid())
6287 return true;
6288 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6289 i++;
6290 }
6291
6292 // Make sure variadic args are scalar.
6293 unsigned FirstDataArg = i;
6294 while (i < NumArgs) {
6295 ExprResult Arg = DefaultVariadicArgumentPromotion(
6296 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6297 if (Arg.isInvalid())
6298 return true;
6299 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6300 if (ArgSize.getQuantity() >= 0x100) {
6301 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6302 << i << (int)ArgSize.getQuantity() << 0xff
6303 << TheCall->getSourceRange();
6304 }
6305 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6306 i++;
6307 }
6308
6309 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6310 // call to avoid duplicate diagnostics.
6311 if (!IsSizeCall) {
6312 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6313 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6314 bool Success = CheckFormatArguments(
6315 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6316 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6317 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6318 if (!Success)
6319 return true;
6320 }
6321
6322 if (IsSizeCall) {
6323 TheCall->setType(Context.getSizeType());
6324 } else {
6325 TheCall->setType(Context.VoidPtrTy);
6326 }
6327 return false;
6328}
6329
6330bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6331 llvm::APSInt &Result) {
6332 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6333
6334 if (Arg->isTypeDependent() || Arg->isValueDependent())
6335 return false;
6336
6337 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6338 if (!R) {
6339 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6340 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6341 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6342 << FDecl->getDeclName() << Arg->getSourceRange();
6343 }
6344 Result = *R;
6345
6346 return false;
6347}
6348
6349bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6350 int High, bool RangeIsError) {
6351 if (isConstantEvaluatedContext())
6352 return false;
6353 llvm::APSInt Result;
6354
6355 // We can't check the value of a dependent argument.
6356 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6357 if (Arg->isTypeDependent() || Arg->isValueDependent())
6358 return false;
6359
6360 // Check constant-ness first.
6361 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6362 return true;
6363
6364 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6365 if (RangeIsError)
6366 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6367 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6368 else
6369 // Defer the warning until we know if the code will be emitted so that
6370 // dead code can ignore this.
6371 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6372 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6373 << toString(I: Result, Radix: 10) << Low << High
6374 << Arg->getSourceRange());
6375 }
6376
6377 return false;
6378}
6379
6380bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6381 unsigned Num) {
6382 llvm::APSInt Result;
6383
6384 // We can't check the value of a dependent argument.
6385 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6386 if (Arg->isTypeDependent() || Arg->isValueDependent())
6387 return false;
6388
6389 // Check constant-ness first.
6390 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6391 return true;
6392
6393 if (Result.getSExtValue() % Num != 0)
6394 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6395 << Num << Arg->getSourceRange();
6396
6397 return false;
6398}
6399
6400bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6401 llvm::APSInt Result;
6402
6403 // We can't check the value of a dependent argument.
6404 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6405 if (Arg->isTypeDependent() || Arg->isValueDependent())
6406 return false;
6407
6408 // Check constant-ness first.
6409 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6410 return true;
6411
6412 if (Result.isPowerOf2())
6413 return false;
6414
6415 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6416 << Arg->getSourceRange();
6417}
6418
6419static bool IsShiftedByte(llvm::APSInt Value) {
6420 if (Value.isNegative())
6421 return false;
6422
6423 // Check if it's a shifted byte, by shifting it down
6424 while (true) {
6425 // If the value fits in the bottom byte, the check passes.
6426 if (Value < 0x100)
6427 return true;
6428
6429 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6430 // fails.
6431 if ((Value & 0xFF) != 0)
6432 return false;
6433
6434 // If the bottom 8 bits are all 0, but something above that is nonzero,
6435 // then shifting the value right by 8 bits won't affect whether it's a
6436 // shifted byte or not. So do that, and go round again.
6437 Value >>= 8;
6438 }
6439}
6440
6441bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6442 unsigned ArgBits) {
6443 llvm::APSInt Result;
6444
6445 // We can't check the value of a dependent argument.
6446 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6447 if (Arg->isTypeDependent() || Arg->isValueDependent())
6448 return false;
6449
6450 // Check constant-ness first.
6451 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6452 return true;
6453
6454 // Truncate to the given size.
6455 Result = Result.getLoBits(numBits: ArgBits);
6456 Result.setIsUnsigned(true);
6457
6458 if (IsShiftedByte(Value: Result))
6459 return false;
6460
6461 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
6462 << Arg->getSourceRange();
6463}
6464
6465bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6466 unsigned ArgNum,
6467 unsigned ArgBits) {
6468 llvm::APSInt Result;
6469
6470 // We can't check the value of a dependent argument.
6471 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6472 if (Arg->isTypeDependent() || Arg->isValueDependent())
6473 return false;
6474
6475 // Check constant-ness first.
6476 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6477 return true;
6478
6479 // Truncate to the given size.
6480 Result = Result.getLoBits(numBits: ArgBits);
6481 Result.setIsUnsigned(true);
6482
6483 // Check to see if it's in either of the required forms.
6484 if (IsShiftedByte(Value: Result) ||
6485 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6486 return false;
6487
6488 return Diag(Loc: TheCall->getBeginLoc(),
6489 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
6490 << Arg->getSourceRange();
6491}
6492
6493bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6494 if (!Context.getTargetInfo().hasSjLjLowering())
6495 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
6496 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6497
6498 Expr *Arg = TheCall->getArg(Arg: 1);
6499 llvm::APSInt Result;
6500
6501 // TODO: This is less than ideal. Overload this to take a value.
6502 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6503 return true;
6504
6505 if (Result != 1)
6506 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
6507 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6508
6509 return false;
6510}
6511
6512bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6513 if (!Context.getTargetInfo().hasSjLjLowering())
6514 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
6515 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6516 return false;
6517}
6518
6519bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6520 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6521 return true;
6522
6523 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
6524 if (ArgRes.isInvalid())
6525 return true;
6526
6527 // For simplicity, we support only limited expressions for the argument.
6528 // Specifically a flexible array member or a pointer with counted_by:
6529 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6530 // complex casting, which really shouldn't be a huge problem.
6531 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6532 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6533 return Diag(Loc: Arg->getBeginLoc(),
6534 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6535 << Arg->getSourceRange();
6536
6537 if (Arg->HasSideEffects(Ctx: Context))
6538 return Diag(Loc: Arg->getBeginLoc(),
6539 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
6540 << Arg->getSourceRange();
6541
6542 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
6543 const auto *CATy =
6544 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6545
6546 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6547 // Member has counted_by attribute - return pointer to count field
6548 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
6549 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6550 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
6551 return false;
6552 }
6553 }
6554
6555 // FAMs and pointers without counted_by return void*
6556 QualType MemberTy = ME->getMemberDecl()->getType();
6557 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6558 return Diag(Loc: Arg->getBeginLoc(),
6559 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6560 << Arg->getSourceRange();
6561 } else {
6562 return Diag(Loc: Arg->getBeginLoc(),
6563 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6564 << Arg->getSourceRange();
6565 }
6566
6567 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
6568 return false;
6569}
6570
6571/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6572/// It allows leaking and modification of bounds safety information.
6573bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6574 BuiltinCountedByRefKind K) {
6575 const CallExpr *CE =
6576 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
6577 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6578 return false;
6579
6580 switch (K) {
6581 case BuiltinCountedByRefKind::Assignment:
6582 case BuiltinCountedByRefKind::Initializer:
6583 Diag(Loc: E->getExprLoc(),
6584 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6585 << 0 << E->getSourceRange();
6586 break;
6587 case BuiltinCountedByRefKind::FunctionArg:
6588 Diag(Loc: E->getExprLoc(),
6589 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6590 << 1 << E->getSourceRange();
6591 break;
6592 case BuiltinCountedByRefKind::ReturnArg:
6593 Diag(Loc: E->getExprLoc(),
6594 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6595 << 2 << E->getSourceRange();
6596 break;
6597 case BuiltinCountedByRefKind::ArraySubscript:
6598 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6599 << 0 << E->getSourceRange();
6600 break;
6601 case BuiltinCountedByRefKind::BinaryExpr:
6602 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6603 << 1 << E->getSourceRange();
6604 break;
6605 }
6606
6607 return true;
6608}
6609
6610namespace {
6611
6612class UncoveredArgHandler {
6613 enum { Unknown = -1, AllCovered = -2 };
6614
6615 signed FirstUncoveredArg = Unknown;
6616 SmallVector<const Expr *, 4> DiagnosticExprs;
6617
6618public:
6619 UncoveredArgHandler() = default;
6620
6621 bool hasUncoveredArg() const {
6622 return (FirstUncoveredArg >= 0);
6623 }
6624
6625 unsigned getUncoveredArg() const {
6626 assert(hasUncoveredArg() && "no uncovered argument");
6627 return FirstUncoveredArg;
6628 }
6629
6630 void setAllCovered() {
6631 // A string has been found with all arguments covered, so clear out
6632 // the diagnostics.
6633 DiagnosticExprs.clear();
6634 FirstUncoveredArg = AllCovered;
6635 }
6636
6637 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6638 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6639
6640 // Don't update if a previous string covers all arguments.
6641 if (FirstUncoveredArg == AllCovered)
6642 return;
6643
6644 // UncoveredArgHandler tracks the highest uncovered argument index
6645 // and with it all the strings that match this index.
6646 if (NewFirstUncoveredArg == FirstUncoveredArg)
6647 DiagnosticExprs.push_back(Elt: StrExpr);
6648 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6649 DiagnosticExprs.clear();
6650 DiagnosticExprs.push_back(Elt: StrExpr);
6651 FirstUncoveredArg = NewFirstUncoveredArg;
6652 }
6653 }
6654
6655 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6656};
6657
6658enum StringLiteralCheckType {
6659 SLCT_NotALiteral,
6660 SLCT_UncheckedLiteral,
6661 SLCT_CheckedLiteral
6662};
6663
6664} // namespace
6665
6666static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6667 BinaryOperatorKind BinOpKind,
6668 bool AddendIsRight) {
6669 unsigned BitWidth = Offset.getBitWidth();
6670 unsigned AddendBitWidth = Addend.getBitWidth();
6671 // There might be negative interim results.
6672 if (Addend.isUnsigned()) {
6673 Addend = Addend.zext(width: ++AddendBitWidth);
6674 Addend.setIsSigned(true);
6675 }
6676 // Adjust the bit width of the APSInts.
6677 if (AddendBitWidth > BitWidth) {
6678 Offset = Offset.sext(width: AddendBitWidth);
6679 BitWidth = AddendBitWidth;
6680 } else if (BitWidth > AddendBitWidth) {
6681 Addend = Addend.sext(width: BitWidth);
6682 }
6683
6684 bool Ov = false;
6685 llvm::APSInt ResOffset = Offset;
6686 if (BinOpKind == BO_Add)
6687 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
6688 else {
6689 assert(AddendIsRight && BinOpKind == BO_Sub &&
6690 "operator must be add or sub with addend on the right");
6691 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
6692 }
6693
6694 // We add an offset to a pointer here so we should support an offset as big as
6695 // possible.
6696 if (Ov) {
6697 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6698 "index (intermediate) result too big");
6699 Offset = Offset.sext(width: 2 * BitWidth);
6700 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6701 return;
6702 }
6703
6704 Offset = ResOffset;
6705}
6706
6707namespace {
6708
6709// This is a wrapper class around StringLiteral to support offsetted string
6710// literals as format strings. It takes the offset into account when returning
6711// the string and its length or the source locations to display notes correctly.
6712class FormatStringLiteral {
6713 const StringLiteral *FExpr;
6714 int64_t Offset;
6715
6716public:
6717 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6718 : FExpr(fexpr), Offset(Offset) {}
6719
6720 const StringLiteral *getFormatString() const { return FExpr; }
6721
6722 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
6723
6724 unsigned getByteLength() const {
6725 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6726 }
6727
6728 unsigned getLength() const { return FExpr->getLength() - Offset; }
6729 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6730
6731 StringLiteralKind getKind() const { return FExpr->getKind(); }
6732
6733 QualType getType() const { return FExpr->getType(); }
6734
6735 bool isAscii() const { return FExpr->isOrdinary(); }
6736 bool isWide() const { return FExpr->isWide(); }
6737 bool isUTF8() const { return FExpr->isUTF8(); }
6738 bool isUTF16() const { return FExpr->isUTF16(); }
6739 bool isUTF32() const { return FExpr->isUTF32(); }
6740 bool isPascal() const { return FExpr->isPascal(); }
6741
6742 SourceLocation getLocationOfByte(
6743 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6744 const TargetInfo &Target, unsigned *StartToken = nullptr,
6745 unsigned *StartTokenByteOffset = nullptr) const {
6746 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
6747 StartToken, StartTokenByteOffset);
6748 }
6749
6750 SourceLocation getBeginLoc() const LLVM_READONLY {
6751 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6752 }
6753
6754 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6755};
6756
6757} // namespace
6758
6759static void CheckFormatString(
6760 Sema &S, const FormatStringLiteral *FExpr,
6761 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6762 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
6763 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6764 bool inFunctionCall, VariadicCallType CallType,
6765 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6766 bool IgnoreStringsWithoutSpecifiers);
6767
6768static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6769 const Expr *E);
6770
6771// Determine if an expression is a string literal or constant string.
6772// If this function returns false on the arguments to a function expecting a
6773// format string, we will usually need to emit a warning.
6774// True string literals are then checked by CheckFormatString.
6775static StringLiteralCheckType
6776checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6777 const Expr *E, ArrayRef<const Expr *> Args,
6778 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6779 unsigned firstDataArg, FormatStringType Type,
6780 VariadicCallType CallType, bool InFunctionCall,
6781 llvm::SmallBitVector &CheckedVarArgs,
6782 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6783 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6784 bool IgnoreStringsWithoutSpecifiers = false) {
6785 if (S.isConstantEvaluatedContext())
6786 return SLCT_NotALiteral;
6787tryAgain:
6788 assert(Offset.isSigned() && "invalid offset");
6789
6790 if (E->isTypeDependent() || E->isValueDependent())
6791 return SLCT_NotALiteral;
6792
6793 E = E->IgnoreParenCasts();
6794
6795 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
6796 // Technically -Wformat-nonliteral does not warn about this case.
6797 // The behavior of printf and friends in this case is implementation
6798 // dependent. Ideally if the format string cannot be null then
6799 // it should have a 'nonnull' attribute in the function prototype.
6800 return SLCT_UncheckedLiteral;
6801
6802 switch (E->getStmtClass()) {
6803 case Stmt::InitListExprClass:
6804 // Handle expressions like {"foobar"}.
6805 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
6806 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
6807 format_idx, firstDataArg, Type, CallType,
6808 /*InFunctionCall*/ false, CheckedVarArgs,
6809 UncoveredArg, Offset, CallerFormatParamIdx,
6810 IgnoreStringsWithoutSpecifiers);
6811 }
6812 return SLCT_NotALiteral;
6813 case Stmt::BinaryConditionalOperatorClass:
6814 case Stmt::ConditionalOperatorClass: {
6815 // The expression is a literal if both sub-expressions were, and it was
6816 // completely checked only if both sub-expressions were checked.
6817 const AbstractConditionalOperator *C =
6818 cast<AbstractConditionalOperator>(Val: E);
6819
6820 // Determine whether it is necessary to check both sub-expressions, for
6821 // example, because the condition expression is a constant that can be
6822 // evaluated at compile time.
6823 bool CheckLeft = true, CheckRight = true;
6824
6825 bool Cond;
6826 if (C->getCond()->EvaluateAsBooleanCondition(
6827 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
6828 if (Cond)
6829 CheckRight = false;
6830 else
6831 CheckLeft = false;
6832 }
6833
6834 // We need to maintain the offsets for the right and the left hand side
6835 // separately to check if every possible indexed expression is a valid
6836 // string literal. They might have different offsets for different string
6837 // literals in the end.
6838 StringLiteralCheckType Left;
6839 if (!CheckLeft)
6840 Left = SLCT_UncheckedLiteral;
6841 else {
6842 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
6843 Args, APK, format_idx, firstDataArg, Type,
6844 CallType, InFunctionCall, CheckedVarArgs,
6845 UncoveredArg, Offset, CallerFormatParamIdx,
6846 IgnoreStringsWithoutSpecifiers);
6847 if (Left == SLCT_NotALiteral || !CheckRight) {
6848 return Left;
6849 }
6850 }
6851
6852 StringLiteralCheckType Right = checkFormatStringExpr(
6853 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
6854 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6855 UncoveredArg, Offset, CallerFormatParamIdx,
6856 IgnoreStringsWithoutSpecifiers);
6857
6858 return (CheckLeft && Left < Right) ? Left : Right;
6859 }
6860
6861 case Stmt::ImplicitCastExprClass:
6862 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
6863 goto tryAgain;
6864
6865 case Stmt::OpaqueValueExprClass:
6866 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
6867 E = src;
6868 goto tryAgain;
6869 }
6870 return SLCT_NotALiteral;
6871
6872 case Stmt::PredefinedExprClass:
6873 // While __func__, etc., are technically not string literals, they
6874 // cannot contain format specifiers and thus are not a security
6875 // liability.
6876 return SLCT_UncheckedLiteral;
6877
6878 case Stmt::DeclRefExprClass: {
6879 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
6880
6881 // As an exception, do not flag errors for variables binding to
6882 // const string literals.
6883 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
6884 bool isConstant = false;
6885 QualType T = DR->getType();
6886
6887 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6888 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
6889 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6890 isConstant = T.isConstant(Ctx: S.Context) &&
6891 PT->getPointeeType().isConstant(Ctx: S.Context);
6892 } else if (T->isObjCObjectPointerType()) {
6893 // In ObjC, there is usually no "const ObjectPointer" type,
6894 // so don't check if the pointee type is constant.
6895 isConstant = T.isConstant(Ctx: S.Context);
6896 }
6897
6898 if (isConstant) {
6899 if (const Expr *Init = VD->getAnyInitializer()) {
6900 // Look through initializers like const char c[] = { "foo" }
6901 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
6902 if (InitList->isStringLiteralInit())
6903 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
6904 }
6905 return checkFormatStringExpr(
6906 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
6907 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
6908 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
6909 }
6910 }
6911
6912 // When the format argument is an argument of this function, and this
6913 // function also has the format attribute, there are several interactions
6914 // for which there shouldn't be a warning. For instance, when calling
6915 // v*printf from a function that has the printf format attribute, we
6916 // should not emit a warning about using `fmt`, even though it's not
6917 // constant, because the arguments have already been checked for the
6918 // caller of `logmessage`:
6919 //
6920 // __attribute__((format(printf, 1, 2)))
6921 // void logmessage(char const *fmt, ...) {
6922 // va_list ap;
6923 // va_start(ap, fmt);
6924 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6925 // ...
6926 // }
6927 //
6928 // Another interaction that we need to support is using a format string
6929 // specified by the format_matches attribute:
6930 //
6931 // __attribute__((format_matches(printf, 1, "%s %d")))
6932 // void logmessage(char const *fmt, const char *a, int b) {
6933 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6934 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6935 // ...
6936 // }
6937 //
6938 // Yet another interaction that we need to support is calling a variadic
6939 // format function from a format function that has fixed arguments. For
6940 // instance:
6941 //
6942 // __attribute__((format(printf, 1, 2)))
6943 // void logstring(char const *fmt, char const *str) {
6944 // printf(fmt, str); /* do not emit a warning about "fmt" */
6945 // }
6946 //
6947 // Same (and perhaps more relatably) for the variadic template case:
6948 //
6949 // template<typename... Args>
6950 // __attribute__((format(printf, 1, 2)))
6951 // void log(const char *fmt, Args&&... args) {
6952 // printf(fmt, forward<Args>(args)...);
6953 // /* do not emit a warning about "fmt" */
6954 // }
6955 //
6956 // Due to implementation difficulty, we only check the format, not the
6957 // format arguments, in all cases.
6958 //
6959 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
6960 if (CallerFormatParamIdx)
6961 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
6962 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
6963 for (const auto *PVFormatMatches :
6964 D->specific_attrs<FormatMatchesAttr>()) {
6965 Sema::FormatStringInfo CalleeFSI;
6966 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
6967 FirstArg: 0, FSI: &CalleeFSI))
6968 continue;
6969 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6970 // If using the wrong type of format string, emit a diagnostic
6971 // here and stop checking to avoid irrelevant diagnostics.
6972 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
6973 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
6974 DiagID: diag::warn_format_string_type_incompatible)
6975 << PVFormatMatches->getType()->getName()
6976 << S.GetFormatStringTypeName(FST: Type);
6977 if (!InFunctionCall) {
6978 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
6979 DiagID: diag::note_format_string_defined);
6980 }
6981 return SLCT_UncheckedLiteral;
6982 }
6983 return checkFormatStringExpr(
6984 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
6985 Args, APK, format_idx, firstDataArg, Type, CallType,
6986 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6987 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6988 }
6989 }
6990
6991 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6992 Sema::FormatStringInfo CallerFSI;
6993 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
6994 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
6995 continue;
6996 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6997 // We also check if the formats are compatible.
6998 // We can't pass a 'scanf' string to a 'printf' function.
6999 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7000 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7001 DiagID: diag::warn_format_string_type_incompatible)
7002 << PVFormat->getType()->getName()
7003 << S.GetFormatStringTypeName(FST: Type);
7004 if (!InFunctionCall) {
7005 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7006 }
7007 return SLCT_UncheckedLiteral;
7008 }
7009 // Lastly, check that argument passing kinds transition in a
7010 // way that makes sense:
7011 // from a caller with FAPK_VAList, allow FAPK_VAList
7012 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7013 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7014 // from a caller with FAPK_Variadic, allow FAPK_VAList
7015 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7016 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7017 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7018 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7019 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7020 return SLCT_UncheckedLiteral;
7021 }
7022 }
7023 }
7024 }
7025 }
7026 }
7027
7028 return SLCT_NotALiteral;
7029 }
7030
7031 case Stmt::CallExprClass:
7032 case Stmt::CXXMemberCallExprClass: {
7033 const CallExpr *CE = cast<CallExpr>(Val: E);
7034 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7035 bool IsFirst = true;
7036 StringLiteralCheckType CommonResult;
7037 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7038 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7039 StringLiteralCheckType Result = checkFormatStringExpr(
7040 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7041 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7042 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7043 if (IsFirst) {
7044 CommonResult = Result;
7045 IsFirst = false;
7046 }
7047 }
7048 if (!IsFirst)
7049 return CommonResult;
7050
7051 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7052 unsigned BuiltinID = FD->getBuiltinID();
7053 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7054 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7055 const Expr *Arg = CE->getArg(Arg: 0);
7056 return checkFormatStringExpr(
7057 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7058 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7059 UncoveredArg, Offset, CallerFormatParamIdx,
7060 IgnoreStringsWithoutSpecifiers);
7061 }
7062 }
7063 }
7064 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7065 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7066 format_idx, firstDataArg, Type, CallType,
7067 /*InFunctionCall*/ false, CheckedVarArgs,
7068 UncoveredArg, Offset, CallerFormatParamIdx,
7069 IgnoreStringsWithoutSpecifiers);
7070 return SLCT_NotALiteral;
7071 }
7072 case Stmt::ObjCMessageExprClass: {
7073 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7074 if (const auto *MD = ME->getMethodDecl()) {
7075 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7076 // As a special case heuristic, if we're using the method -[NSBundle
7077 // localizedStringForKey:value:table:], ignore any key strings that lack
7078 // format specifiers. The idea is that if the key doesn't have any
7079 // format specifiers then its probably just a key to map to the
7080 // localized strings. If it does have format specifiers though, then its
7081 // likely that the text of the key is the format string in the
7082 // programmer's language, and should be checked.
7083 const ObjCInterfaceDecl *IFace;
7084 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7085 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7086 MD->getSelector().isKeywordSelector(
7087 Names: {"localizedStringForKey", "value", "table"})) {
7088 IgnoreStringsWithoutSpecifiers = true;
7089 }
7090
7091 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7092 return checkFormatStringExpr(
7093 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7094 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7095 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7096 }
7097 }
7098
7099 return SLCT_NotALiteral;
7100 }
7101 case Stmt::ObjCStringLiteralClass:
7102 case Stmt::StringLiteralClass: {
7103 const StringLiteral *StrE = nullptr;
7104
7105 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7106 StrE = ObjCFExpr->getString();
7107 else
7108 StrE = cast<StringLiteral>(Val: E);
7109
7110 if (StrE) {
7111 if (Offset.isNegative() || Offset > StrE->getLength()) {
7112 // TODO: It would be better to have an explicit warning for out of
7113 // bounds literals.
7114 return SLCT_NotALiteral;
7115 }
7116 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7117 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7118 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7119 CallType, CheckedVarArgs, UncoveredArg,
7120 IgnoreStringsWithoutSpecifiers);
7121 return SLCT_CheckedLiteral;
7122 }
7123
7124 return SLCT_NotALiteral;
7125 }
7126 case Stmt::BinaryOperatorClass: {
7127 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7128
7129 // A string literal + an int offset is still a string literal.
7130 if (BinOp->isAdditiveOp()) {
7131 Expr::EvalResult LResult, RResult;
7132
7133 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7134 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7135 InConstantContext: S.isConstantEvaluatedContext());
7136 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7137 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7138 InConstantContext: S.isConstantEvaluatedContext());
7139
7140 if (LIsInt != RIsInt) {
7141 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7142
7143 if (LIsInt) {
7144 if (BinOpKind == BO_Add) {
7145 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7146 E = BinOp->getRHS();
7147 goto tryAgain;
7148 }
7149 } else {
7150 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7151 E = BinOp->getLHS();
7152 goto tryAgain;
7153 }
7154 }
7155 }
7156
7157 return SLCT_NotALiteral;
7158 }
7159 case Stmt::UnaryOperatorClass: {
7160 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7161 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7162 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7163 Expr::EvalResult IndexResult;
7164 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7165 AllowSideEffects: Expr::SE_NoSideEffects,
7166 InConstantContext: S.isConstantEvaluatedContext())) {
7167 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7168 /*RHS is int*/ AddendIsRight: true);
7169 E = ASE->getBase();
7170 goto tryAgain;
7171 }
7172 }
7173
7174 return SLCT_NotALiteral;
7175 }
7176
7177 default:
7178 return SLCT_NotALiteral;
7179 }
7180}
7181
7182// If this expression can be evaluated at compile-time,
7183// check if the result is a StringLiteral and return it
7184// otherwise return nullptr
7185static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7186 const Expr *E) {
7187 Expr::EvalResult Result;
7188 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7189 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7190 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7191 return LVE;
7192 }
7193 return nullptr;
7194}
7195
7196StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7197 switch (FST) {
7198 case FormatStringType::Scanf:
7199 return "scanf";
7200 case FormatStringType::Printf:
7201 return "printf";
7202 case FormatStringType::NSString:
7203 return "NSString";
7204 case FormatStringType::Strftime:
7205 return "strftime";
7206 case FormatStringType::Strfmon:
7207 return "strfmon";
7208 case FormatStringType::Kprintf:
7209 return "kprintf";
7210 case FormatStringType::FreeBSDKPrintf:
7211 return "freebsd_kprintf";
7212 case FormatStringType::OSLog:
7213 return "os_log";
7214 default:
7215 return "<unknown>";
7216 }
7217}
7218
7219FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7220 return llvm::StringSwitch<FormatStringType>(Flavor)
7221 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7222 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7223 Value: FormatStringType::Printf)
7224 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7225 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7226 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7227 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7228 Value: FormatStringType::Kprintf)
7229 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7230 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7231 .Case(S: "os_log", Value: FormatStringType::OSLog)
7232 .Default(Value: FormatStringType::Unknown);
7233}
7234
7235FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7236 return GetFormatStringType(Flavor: Format->getType()->getName());
7237}
7238
7239FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7240 return GetFormatStringType(Flavor: Format->getType()->getName());
7241}
7242
7243bool Sema::CheckFormatArguments(const FormatAttr *Format,
7244 ArrayRef<const Expr *> Args, bool IsCXXMember,
7245 VariadicCallType CallType, SourceLocation Loc,
7246 SourceRange Range,
7247 llvm::SmallBitVector &CheckedVarArgs) {
7248 FormatStringInfo FSI;
7249 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7250 HasImplicitThisParam: IsCXXMember,
7251 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7252 return CheckFormatArguments(
7253 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7254 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7255 return false;
7256}
7257
7258bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7259 ArrayRef<const Expr *> Args, bool IsCXXMember,
7260 VariadicCallType CallType, SourceLocation Loc,
7261 SourceRange Range,
7262 llvm::SmallBitVector &CheckedVarArgs) {
7263 FormatStringInfo FSI;
7264 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7265 FSI: &FSI)) {
7266 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7267 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7268 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7269 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7270 CallType, Loc, range: Range, CheckedVarArgs);
7271 }
7272 return false;
7273}
7274
7275static bool CheckMissingFormatAttribute(
7276 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7277 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7278 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7279 SourceLocation Loc) {
7280 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7281 return false;
7282
7283 DeclContext *DC = S->CurContext;
7284 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7285 return false;
7286 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7287
7288 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7289
7290 // Find the offset to convert between attribute and parameter indexes.
7291 unsigned CallerArgumentIndexOffset =
7292 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7293
7294 unsigned FirstArgumentIndex = -1;
7295 switch (APK) {
7296 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7297 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7298 // As an extension, clang allows the format attribute on non-variadic
7299 // functions.
7300 // Caller must have fixed arguments to pass them to a fixed or variadic
7301 // function. Try to match caller and callee arguments. If successful, then
7302 // emit a diag with the caller idx, otherwise we can't determine the callee
7303 // arguments.
7304 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7305 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7306 // There aren't enough arguments in the caller to pass to callee.
7307 return false;
7308 }
7309 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7310 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7311 const auto *Arg =
7312 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7313 if (!Arg)
7314 return false;
7315 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7316 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7317 return false;
7318 }
7319 FirstArgumentIndex =
7320 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7321 break;
7322 }
7323 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7324 // Caller arguments are either variadic or a va_list.
7325 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7326 ? (NumCallerParams + CallerArgumentIndexOffset)
7327 : 0;
7328 break;
7329 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7330 // The callee has a format_matches attribute. We will emit that instead.
7331 if (!ReferenceFormatString)
7332 return false;
7333 break;
7334 }
7335
7336 // Emit the diagnostic and fixit.
7337 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7338 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7339 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7340 do {
7341 std::string Attr, Fixit;
7342 llvm::raw_string_ostream AttrOS(Attr);
7343 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7344 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7345 << FirstArgumentIndex << ")";
7346 } else {
7347 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7348 << ", \"";
7349 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7350 AttrOS << "\")";
7351 }
7352 AttrOS.flush();
7353 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7354 if (ND)
7355 DB << ND;
7356 else
7357 DB << "block";
7358
7359 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7360 if (isa<BlockDecl>(Val: Caller))
7361 break;
7362
7363 SourceLocation SL;
7364 llvm::raw_string_ostream IS(Fixit);
7365 // The attribute goes at the start of the declaration in C/C++ functions
7366 // and methods, but after the declaration for Objective-C methods.
7367 if (isa<ObjCMethodDecl>(Val: Caller)) {
7368 IS << ' ';
7369 SL = Caller->getEndLoc();
7370 }
7371 const LangOptions &LO = S->getLangOpts();
7372 if (LO.C23 || LO.CPlusPlus11)
7373 IS << "[[gnu::" << Attr << "]]";
7374 else if (LO.ObjC || LO.GNUMode)
7375 IS << "__attribute__((" << Attr << "))";
7376 else
7377 break;
7378 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7379 IS << ' ';
7380 SL = Caller->getBeginLoc();
7381 }
7382 IS.flush();
7383
7384 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7385 } while (false);
7386
7387 // Add implicit format or format_matches attribute.
7388 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7389 Caller->addAttr(A: FormatAttr::CreateImplicit(
7390 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7391 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7392 } else {
7393 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7394 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7395 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7396 }
7397
7398 {
7399 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7400 if (ND)
7401 DB << ND;
7402 else
7403 DB << "block";
7404 }
7405 return true;
7406}
7407
7408bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7409 Sema::FormatArgumentPassingKind APK,
7410 StringLiteral *ReferenceFormatString,
7411 unsigned format_idx, unsigned firstDataArg,
7412 FormatStringType Type,
7413 VariadicCallType CallType, SourceLocation Loc,
7414 SourceRange Range,
7415 llvm::SmallBitVector &CheckedVarArgs) {
7416 // CHECK: printf/scanf-like function is called with no format string.
7417 if (format_idx >= Args.size()) {
7418 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7419 return false;
7420 }
7421
7422 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7423
7424 // CHECK: format string is not a string literal.
7425 //
7426 // Dynamically generated format strings are difficult to
7427 // automatically vet at compile time. Requiring that format strings
7428 // are string literals: (1) permits the checking of format strings by
7429 // the compiler and thereby (2) can practically remove the source of
7430 // many format string exploits.
7431
7432 // Format string can be either ObjC string (e.g. @"%d") or
7433 // C string (e.g. "%d")
7434 // ObjC string uses the same format specifiers as C string, so we can use
7435 // the same format string checking logic for both ObjC and C strings.
7436 UncoveredArgHandler UncoveredArg;
7437 std::optional<unsigned> CallerParamIdx;
7438 StringLiteralCheckType CT = checkFormatStringExpr(
7439 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
7440 firstDataArg, Type, CallType,
7441 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
7442 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
7443
7444 // Generate a diagnostic where an uncovered argument is detected.
7445 if (UncoveredArg.hasUncoveredArg()) {
7446 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7447 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7448 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
7449 }
7450
7451 if (CT != SLCT_NotALiteral)
7452 // Literal format string found, check done!
7453 return CT == SLCT_CheckedLiteral;
7454
7455 // Do not emit diag when the string param is a macro expansion and the
7456 // format is either NSString or CFString. This is a hack to prevent
7457 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7458 // which are usually used in place of NS and CF string literals.
7459 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7460 if (Type == FormatStringType::NSString &&
7461 SourceMgr.isInSystemMacro(loc: FormatLoc))
7462 return false;
7463
7464 if (CallerParamIdx && CheckMissingFormatAttribute(
7465 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
7466 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
7467 return false;
7468
7469 // Strftime is particular as it always uses a single 'time' argument,
7470 // so it is safe to pass a non-literal string.
7471 if (Type == FormatStringType::Strftime)
7472 return false;
7473
7474 // If there are no arguments specified, warn with -Wformat-security, otherwise
7475 // warn only with -Wformat-nonliteral.
7476 if (Args.size() == firstDataArg) {
7477 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
7478 << OrigFormatExpr->getSourceRange();
7479 switch (Type) {
7480 default:
7481 break;
7482 case FormatStringType::Kprintf:
7483 case FormatStringType::FreeBSDKPrintf:
7484 case FormatStringType::Printf:
7485 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7486 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
7487 break;
7488 case FormatStringType::NSString:
7489 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7490 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
7491 break;
7492 }
7493 } else {
7494 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
7495 << OrigFormatExpr->getSourceRange();
7496 }
7497 return false;
7498}
7499
7500namespace {
7501
7502class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7503protected:
7504 Sema &S;
7505 const FormatStringLiteral *FExpr;
7506 const Expr *OrigFormatExpr;
7507 const FormatStringType FSType;
7508 const unsigned FirstDataArg;
7509 const unsigned NumDataArgs;
7510 const char *Beg; // Start of format string.
7511 const Sema::FormatArgumentPassingKind ArgPassingKind;
7512 ArrayRef<const Expr *> Args;
7513 unsigned FormatIdx;
7514 llvm::SmallBitVector CoveredArgs;
7515 bool usesPositionalArgs = false;
7516 bool atFirstArg = true;
7517 bool inFunctionCall;
7518 VariadicCallType CallType;
7519 llvm::SmallBitVector &CheckedVarArgs;
7520 UncoveredArgHandler &UncoveredArg;
7521
7522public:
7523 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7524 const Expr *origFormatExpr, const FormatStringType type,
7525 unsigned firstDataArg, unsigned numDataArgs,
7526 const char *beg, Sema::FormatArgumentPassingKind APK,
7527 ArrayRef<const Expr *> Args, unsigned formatIdx,
7528 bool inFunctionCall, VariadicCallType callType,
7529 llvm::SmallBitVector &CheckedVarArgs,
7530 UncoveredArgHandler &UncoveredArg)
7531 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7532 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7533 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7534 inFunctionCall(inFunctionCall), CallType(callType),
7535 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7536 CoveredArgs.resize(N: numDataArgs);
7537 CoveredArgs.reset();
7538 }
7539
7540 bool HasFormatArguments() const {
7541 return ArgPassingKind == Sema::FAPK_Fixed ||
7542 ArgPassingKind == Sema::FAPK_Variadic;
7543 }
7544
7545 void DoneProcessing();
7546
7547 void HandleIncompleteSpecifier(const char *startSpecifier,
7548 unsigned specifierLen) override;
7549
7550 void HandleInvalidLengthModifier(
7551 const analyze_format_string::FormatSpecifier &FS,
7552 const analyze_format_string::ConversionSpecifier &CS,
7553 const char *startSpecifier, unsigned specifierLen,
7554 unsigned DiagID);
7555
7556 void HandleNonStandardLengthModifier(
7557 const analyze_format_string::FormatSpecifier &FS,
7558 const char *startSpecifier, unsigned specifierLen);
7559
7560 void HandleNonStandardConversionSpecifier(
7561 const analyze_format_string::ConversionSpecifier &CS,
7562 const char *startSpecifier, unsigned specifierLen);
7563
7564 void HandlePosition(const char *startPos, unsigned posLen) override;
7565
7566 void HandleInvalidPosition(const char *startSpecifier,
7567 unsigned specifierLen,
7568 analyze_format_string::PositionContext p) override;
7569
7570 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7571
7572 void HandleNullChar(const char *nullCharacter) override;
7573
7574 template <typename Range>
7575 static void
7576 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7577 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7578 bool IsStringLocation, Range StringRange,
7579 ArrayRef<FixItHint> Fixit = {});
7580
7581protected:
7582 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7583 const char *startSpec,
7584 unsigned specifierLen,
7585 const char *csStart, unsigned csLen);
7586
7587 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7588 const char *startSpec,
7589 unsigned specifierLen);
7590
7591 SourceRange getFormatStringRange();
7592 CharSourceRange getSpecifierRange(const char *startSpecifier,
7593 unsigned specifierLen);
7594 SourceLocation getLocationOfByte(const char *x);
7595
7596 const Expr *getDataArg(unsigned i) const;
7597
7598 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7599 const analyze_format_string::ConversionSpecifier &CS,
7600 const char *startSpecifier, unsigned specifierLen,
7601 unsigned argIndex);
7602
7603 template <typename Range>
7604 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7605 bool IsStringLocation, Range StringRange,
7606 ArrayRef<FixItHint> Fixit = {});
7607};
7608
7609} // namespace
7610
7611SourceRange CheckFormatHandler::getFormatStringRange() {
7612 return OrigFormatExpr->getSourceRange();
7613}
7614
7615CharSourceRange CheckFormatHandler::
7616getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7617 SourceLocation Start = getLocationOfByte(x: startSpecifier);
7618 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
7619
7620 // Advance the end SourceLocation by one due to half-open ranges.
7621 End = End.getLocWithOffset(Offset: 1);
7622
7623 return CharSourceRange::getCharRange(B: Start, E: End);
7624}
7625
7626SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7627 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
7628 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
7629}
7630
7631void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7632 unsigned specifierLen){
7633 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
7634 Loc: getLocationOfByte(x: startSpecifier),
7635 /*IsStringLocation*/true,
7636 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7637}
7638
7639void CheckFormatHandler::HandleInvalidLengthModifier(
7640 const analyze_format_string::FormatSpecifier &FS,
7641 const analyze_format_string::ConversionSpecifier &CS,
7642 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7643 using namespace analyze_format_string;
7644
7645 const LengthModifier &LM = FS.getLengthModifier();
7646 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7647
7648 // See if we know how to fix this length modifier.
7649 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7650 if (FixedLM) {
7651 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7652 Loc: getLocationOfByte(x: LM.getStart()),
7653 /*IsStringLocation*/true,
7654 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7655
7656 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7657 << FixedLM->toString()
7658 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7659
7660 } else {
7661 FixItHint Hint;
7662 if (DiagID == diag::warn_format_nonsensical_length)
7663 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
7664
7665 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7666 Loc: getLocationOfByte(x: LM.getStart()),
7667 /*IsStringLocation*/true,
7668 StringRange: getSpecifierRange(startSpecifier, specifierLen),
7669 FixIt: Hint);
7670 }
7671}
7672
7673void CheckFormatHandler::HandleNonStandardLengthModifier(
7674 const analyze_format_string::FormatSpecifier &FS,
7675 const char *startSpecifier, unsigned specifierLen) {
7676 using namespace analyze_format_string;
7677
7678 const LengthModifier &LM = FS.getLengthModifier();
7679 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7680
7681 // See if we know how to fix this length modifier.
7682 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7683 if (FixedLM) {
7684 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7685 << LM.toString() << 0,
7686 Loc: getLocationOfByte(x: LM.getStart()),
7687 /*IsStringLocation*/true,
7688 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7689
7690 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7691 << FixedLM->toString()
7692 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7693
7694 } else {
7695 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7696 << LM.toString() << 0,
7697 Loc: getLocationOfByte(x: LM.getStart()),
7698 /*IsStringLocation*/true,
7699 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7700 }
7701}
7702
7703void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7704 const analyze_format_string::ConversionSpecifier &CS,
7705 const char *startSpecifier, unsigned specifierLen) {
7706 using namespace analyze_format_string;
7707
7708 // See if we know how to fix this conversion specifier.
7709 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7710 if (FixedCS) {
7711 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7712 << CS.toString() << /*conversion specifier*/1,
7713 Loc: getLocationOfByte(x: CS.getStart()),
7714 /*IsStringLocation*/true,
7715 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7716
7717 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
7718 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
7719 << FixedCS->toString()
7720 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
7721 } else {
7722 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7723 << CS.toString() << /*conversion specifier*/1,
7724 Loc: getLocationOfByte(x: CS.getStart()),
7725 /*IsStringLocation*/true,
7726 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7727 }
7728}
7729
7730void CheckFormatHandler::HandlePosition(const char *startPos,
7731 unsigned posLen) {
7732 if (!S.getDiagnostics().isIgnored(
7733 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
7734 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
7735 Loc: getLocationOfByte(x: startPos),
7736 /*IsStringLocation*/ true,
7737 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7738}
7739
7740void CheckFormatHandler::HandleInvalidPosition(
7741 const char *startSpecifier, unsigned specifierLen,
7742 analyze_format_string::PositionContext p) {
7743 if (!S.getDiagnostics().isIgnored(
7744 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
7745 EmitFormatDiagnostic(
7746 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7747 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
7748 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7749}
7750
7751void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7752 unsigned posLen) {
7753 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
7754 Loc: SourceLocation()))
7755 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
7756 Loc: getLocationOfByte(x: startPos),
7757 /*IsStringLocation*/ true,
7758 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7759}
7760
7761void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7762 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
7763 // The presence of a null character is likely an error.
7764 EmitFormatDiagnostic(
7765 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
7766 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/true,
7767 StringRange: getFormatStringRange());
7768 }
7769}
7770
7771// Note that this may return NULL if there was an error parsing or building
7772// one of the argument expressions.
7773const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7774 return Args[FirstDataArg + i];
7775}
7776
7777void CheckFormatHandler::DoneProcessing() {
7778 // Does the number of data arguments exceed the number of
7779 // format conversions in the format string?
7780 if (HasFormatArguments()) {
7781 // Find any arguments that weren't covered.
7782 CoveredArgs.flip();
7783 signed notCoveredArg = CoveredArgs.find_first();
7784 if (notCoveredArg >= 0) {
7785 assert((unsigned)notCoveredArg < NumDataArgs);
7786 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
7787 } else {
7788 UncoveredArg.setAllCovered();
7789 }
7790 }
7791}
7792
7793void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7794 const Expr *ArgExpr) {
7795 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7796 "Invalid state");
7797
7798 if (!ArgExpr)
7799 return;
7800
7801 SourceLocation Loc = ArgExpr->getBeginLoc();
7802
7803 if (S.getSourceManager().isInSystemMacro(loc: Loc))
7804 return;
7805
7806 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
7807 for (auto E : DiagnosticExprs)
7808 PDiag << E->getSourceRange();
7809
7810 CheckFormatHandler::EmitFormatDiagnostic(
7811 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0],
7812 PDiag, Loc, /*IsStringLocation*/false,
7813 StringRange: DiagnosticExprs[0]->getSourceRange());
7814}
7815
7816bool
7817CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7818 SourceLocation Loc,
7819 const char *startSpec,
7820 unsigned specifierLen,
7821 const char *csStart,
7822 unsigned csLen) {
7823 bool keepGoing = true;
7824 if (argIndex < NumDataArgs) {
7825 // Consider the argument coverered, even though the specifier doesn't
7826 // make sense.
7827 CoveredArgs.set(argIndex);
7828 }
7829 else {
7830 // If argIndex exceeds the number of data arguments we
7831 // don't issue a warning because that is just a cascade of warnings (and
7832 // they may have intended '%%' anyway). We don't want to continue processing
7833 // the format string after this point, however, as we will like just get
7834 // gibberish when trying to match arguments.
7835 keepGoing = false;
7836 }
7837
7838 StringRef Specifier(csStart, csLen);
7839
7840 // If the specifier in non-printable, it could be the first byte of a UTF-8
7841 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7842 // hex value.
7843 std::string CodePointStr;
7844 if (!llvm::sys::locale::isPrint(c: *csStart)) {
7845 llvm::UTF32 CodePoint;
7846 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7847 const llvm::UTF8 *E =
7848 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7849 llvm::ConversionResult Result =
7850 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
7851
7852 if (Result != llvm::conversionOK) {
7853 unsigned char FirstChar = *csStart;
7854 CodePoint = (llvm::UTF32)FirstChar;
7855 }
7856
7857 llvm::raw_string_ostream OS(CodePointStr);
7858 if (CodePoint < 256)
7859 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
7860 else if (CodePoint <= 0xFFFF)
7861 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
7862 else
7863 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
7864 Specifier = CodePointStr;
7865 }
7866
7867 EmitFormatDiagnostic(
7868 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
7869 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7870
7871 return keepGoing;
7872}
7873
7874void
7875CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7876 const char *startSpec,
7877 unsigned specifierLen) {
7878 EmitFormatDiagnostic(
7879 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args),
7880 Loc, /*isStringLoc*/IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7881}
7882
7883bool
7884CheckFormatHandler::CheckNumArgs(
7885 const analyze_format_string::FormatSpecifier &FS,
7886 const analyze_format_string::ConversionSpecifier &CS,
7887 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7888
7889 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7890 PartialDiagnostic PDiag = FS.usesPositionalArg()
7891 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
7892 << (argIndex+1) << NumDataArgs)
7893 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
7894 EmitFormatDiagnostic(
7895 PDiag, Loc: getLocationOfByte(x: CS.getStart()), /*IsStringLocation*/true,
7896 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7897
7898 // Since more arguments than conversion tokens are given, by extension
7899 // all arguments are covered, so mark this as so.
7900 UncoveredArg.setAllCovered();
7901 return false;
7902 }
7903 return true;
7904}
7905
7906template<typename Range>
7907void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7908 SourceLocation Loc,
7909 bool IsStringLocation,
7910 Range StringRange,
7911 ArrayRef<FixItHint> FixIt) {
7912 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7913 Loc, IsStringLocation, StringRange, FixIt);
7914}
7915
7916/// If the format string is not within the function call, emit a note
7917/// so that the function call and string are in diagnostic messages.
7918///
7919/// \param InFunctionCall if true, the format string is within the function
7920/// call and only one diagnostic message will be produced. Otherwise, an
7921/// extra note will be emitted pointing to location of the format string.
7922///
7923/// \param ArgumentExpr the expression that is passed as the format string
7924/// argument in the function call. Used for getting locations when two
7925/// diagnostics are emitted.
7926///
7927/// \param PDiag the callee should already have provided any strings for the
7928/// diagnostic message. This function only adds locations and fixits
7929/// to diagnostics.
7930///
7931/// \param Loc primary location for diagnostic. If two diagnostics are
7932/// required, one will be at Loc and a new SourceLocation will be created for
7933/// the other one.
7934///
7935/// \param IsStringLocation if true, Loc points to the format string should be
7936/// used for the note. Otherwise, Loc points to the argument list and will
7937/// be used with PDiag.
7938///
7939/// \param StringRange some or all of the string to highlight. This is
7940/// templated so it can accept either a CharSourceRange or a SourceRange.
7941///
7942/// \param FixIt optional fix it hint for the format string.
7943template <typename Range>
7944void CheckFormatHandler::EmitFormatDiagnostic(
7945 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7946 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7947 Range StringRange, ArrayRef<FixItHint> FixIt) {
7948 if (InFunctionCall) {
7949 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
7950 D << StringRange;
7951 D << FixIt;
7952 } else {
7953 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
7954 << ArgumentExpr->getSourceRange();
7955
7956 const Sema::SemaDiagnosticBuilder &Note =
7957 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7958 diag::note_format_string_defined);
7959
7960 Note << StringRange;
7961 Note << FixIt;
7962 }
7963}
7964
7965//===--- CHECK: Printf format string checking -----------------------------===//
7966
7967namespace {
7968
7969class CheckPrintfHandler : public CheckFormatHandler {
7970public:
7971 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7972 const Expr *origFormatExpr, const FormatStringType type,
7973 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7974 const char *beg, Sema::FormatArgumentPassingKind APK,
7975 ArrayRef<const Expr *> Args, unsigned formatIdx,
7976 bool inFunctionCall, VariadicCallType CallType,
7977 llvm::SmallBitVector &CheckedVarArgs,
7978 UncoveredArgHandler &UncoveredArg)
7979 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7980 numDataArgs, beg, APK, Args, formatIdx,
7981 inFunctionCall, CallType, CheckedVarArgs,
7982 UncoveredArg) {}
7983
7984 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7985
7986 /// Returns true if '%@' specifiers are allowed in the format string.
7987 bool allowsObjCArg() const {
7988 return FSType == FormatStringType::NSString ||
7989 FSType == FormatStringType::OSLog ||
7990 FSType == FormatStringType::OSTrace;
7991 }
7992
7993 bool HandleInvalidPrintfConversionSpecifier(
7994 const analyze_printf::PrintfSpecifier &FS,
7995 const char *startSpecifier,
7996 unsigned specifierLen) override;
7997
7998 void handleInvalidMaskType(StringRef MaskType) override;
7999
8000 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8001 const char *startSpecifier, unsigned specifierLen,
8002 const TargetInfo &Target) override;
8003 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8004 const char *StartSpecifier,
8005 unsigned SpecifierLen,
8006 const Expr *E);
8007
8008 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8009 const char *startSpecifier, unsigned specifierLen);
8010 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8011 const analyze_printf::OptionalAmount &Amt,
8012 unsigned type,
8013 const char *startSpecifier, unsigned specifierLen);
8014 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8015 const analyze_printf::OptionalFlag &flag,
8016 const char *startSpecifier, unsigned specifierLen);
8017 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8018 const analyze_printf::OptionalFlag &ignoredFlag,
8019 const analyze_printf::OptionalFlag &flag,
8020 const char *startSpecifier, unsigned specifierLen);
8021 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8022 const Expr *E);
8023
8024 void HandleEmptyObjCModifierFlag(const char *startFlag,
8025 unsigned flagLen) override;
8026
8027 void HandleInvalidObjCModifierFlag(const char *startFlag,
8028 unsigned flagLen) override;
8029
8030 void
8031 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8032 const char *flagsEnd,
8033 const char *conversionPosition) override;
8034};
8035
8036/// Keeps around the information needed to verify that two specifiers are
8037/// compatible.
8038class EquatableFormatArgument {
8039public:
8040 enum SpecifierSensitivity : unsigned {
8041 SS_None,
8042 SS_Private,
8043 SS_Public,
8044 SS_Sensitive
8045 };
8046
8047 enum FormatArgumentRole : unsigned {
8048 FAR_Data,
8049 FAR_FieldWidth,
8050 FAR_Precision,
8051 FAR_Auxiliary, // FreeBSD kernel %b and %D
8052 };
8053
8054private:
8055 analyze_format_string::ArgType ArgType;
8056 analyze_format_string::LengthModifier::Kind LengthMod;
8057 StringRef SpecifierLetter;
8058 CharSourceRange Range;
8059 SourceLocation ElementLoc;
8060 FormatArgumentRole Role : 2;
8061 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8062 unsigned Position : 14;
8063 unsigned ModifierFor : 14; // not set for FAR_Data
8064
8065 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8066 bool InFunctionCall) const;
8067
8068public:
8069 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8070 analyze_format_string::LengthModifier::Kind LengthMod,
8071 StringRef SpecifierLetter,
8072 analyze_format_string::ArgType ArgType,
8073 FormatArgumentRole Role,
8074 SpecifierSensitivity Sensitivity, unsigned Position,
8075 unsigned ModifierFor)
8076 : ArgType(ArgType), LengthMod(LengthMod),
8077 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8078 Role(Role), Sensitivity(Sensitivity), Position(Position),
8079 ModifierFor(ModifierFor) {}
8080
8081 unsigned getPosition() const { return Position; }
8082 SourceLocation getSourceLocation() const { return ElementLoc; }
8083 CharSourceRange getSourceRange() const { return Range; }
8084 analyze_format_string::LengthModifier getLengthModifier() const {
8085 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8086 }
8087 void setModifierFor(unsigned V) { ModifierFor = V; }
8088
8089 std::string buildFormatSpecifier() const {
8090 std::string result;
8091 llvm::raw_string_ostream(result)
8092 << getLengthModifier().toString() << SpecifierLetter;
8093 return result;
8094 }
8095
8096 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8097 const Expr *FmtExpr, bool InFunctionCall) const;
8098};
8099
8100/// Turns format strings into lists of EquatableSpecifier objects.
8101class DecomposePrintfHandler : public CheckPrintfHandler {
8102 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8103 bool HadError;
8104
8105 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8106 const Expr *origFormatExpr,
8107 const FormatStringType type, unsigned firstDataArg,
8108 unsigned numDataArgs, bool isObjC, const char *beg,
8109 Sema::FormatArgumentPassingKind APK,
8110 ArrayRef<const Expr *> Args, unsigned formatIdx,
8111 bool inFunctionCall, VariadicCallType CallType,
8112 llvm::SmallBitVector &CheckedVarArgs,
8113 UncoveredArgHandler &UncoveredArg,
8114 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8115 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8116 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8117 inFunctionCall, CallType, CheckedVarArgs,
8118 UncoveredArg),
8119 Specs(Specs), HadError(false) {}
8120
8121public:
8122 static bool
8123 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8124 FormatStringType type, bool IsObjC, bool InFunctionCall,
8125 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8126
8127 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8128 const char *startSpecifier,
8129 unsigned specifierLen,
8130 const TargetInfo &Target) override;
8131};
8132
8133} // namespace
8134
8135bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8136 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8137 unsigned specifierLen) {
8138 const analyze_printf::PrintfConversionSpecifier &CS =
8139 FS.getConversionSpecifier();
8140
8141 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
8142 Loc: getLocationOfByte(x: CS.getStart()),
8143 startSpec: startSpecifier, specifierLen,
8144 csStart: CS.getStart(), csLen: CS.getLength());
8145}
8146
8147void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8148 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8149}
8150
8151// Error out if struct or complex type argments are passed to os_log.
8152static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8153 QualType T) {
8154 if (FSType != FormatStringType::OSLog)
8155 return false;
8156 return T->isRecordType() || T->isComplexType();
8157}
8158
8159bool CheckPrintfHandler::HandleAmount(
8160 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8161 const char *startSpecifier, unsigned specifierLen) {
8162 if (Amt.hasDataArgument()) {
8163 if (HasFormatArguments()) {
8164 unsigned argIndex = Amt.getArgIndex();
8165 if (argIndex >= NumDataArgs) {
8166 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8167 << k,
8168 Loc: getLocationOfByte(x: Amt.getStart()),
8169 /*IsStringLocation*/ true,
8170 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8171 // Don't do any more checking. We will just emit
8172 // spurious errors.
8173 return false;
8174 }
8175
8176 // Type check the data argument. It should be an 'int'.
8177 // Although not in conformance with C99, we also allow the argument to be
8178 // an 'unsigned int' as that is a reasonably safe case. GCC also
8179 // doesn't emit a warning for that case.
8180 CoveredArgs.set(argIndex);
8181 const Expr *Arg = getDataArg(i: argIndex);
8182 if (!Arg)
8183 return false;
8184
8185 QualType T = Arg->getType();
8186
8187 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8188 assert(AT.isValid());
8189
8190 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8191 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8192 ? diag::err_printf_asterisk_wrong_type
8193 : diag::warn_printf_asterisk_wrong_type;
8194 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8195 << k << AT.getRepresentativeTypeName(C&: S.Context)
8196 << T << Arg->getSourceRange(),
8197 Loc: getLocationOfByte(x: Amt.getStart()),
8198 /*IsStringLocation*/ true,
8199 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8200 // Don't do any more checking. We will just emit
8201 // spurious errors.
8202 return false;
8203 }
8204 }
8205 }
8206 return true;
8207}
8208
8209void CheckPrintfHandler::HandleInvalidAmount(
8210 const analyze_printf::PrintfSpecifier &FS,
8211 const analyze_printf::OptionalAmount &Amt,
8212 unsigned type,
8213 const char *startSpecifier,
8214 unsigned specifierLen) {
8215 const analyze_printf::PrintfConversionSpecifier &CS =
8216 FS.getConversionSpecifier();
8217
8218 FixItHint fixit =
8219 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8220 ? FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(),
8221 specifierLen: Amt.getConstantLength()))
8222 : FixItHint();
8223
8224 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8225 << type << CS.toString(),
8226 Loc: getLocationOfByte(x: Amt.getStart()),
8227 /*IsStringLocation*/true,
8228 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8229 FixIt: fixit);
8230}
8231
8232void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8233 const analyze_printf::OptionalFlag &flag,
8234 const char *startSpecifier,
8235 unsigned specifierLen) {
8236 // Warn about pointless flag with a fixit removal.
8237 const analyze_printf::PrintfConversionSpecifier &CS =
8238 FS.getConversionSpecifier();
8239 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8240 << flag.toString() << CS.toString(),
8241 Loc: getLocationOfByte(x: flag.getPosition()),
8242 /*IsStringLocation*/true,
8243 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8244 FixIt: FixItHint::CreateRemoval(
8245 RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8246}
8247
8248void CheckPrintfHandler::HandleIgnoredFlag(
8249 const analyze_printf::PrintfSpecifier &FS,
8250 const analyze_printf::OptionalFlag &ignoredFlag,
8251 const analyze_printf::OptionalFlag &flag,
8252 const char *startSpecifier,
8253 unsigned specifierLen) {
8254 // Warn about ignored flag with a fixit removal.
8255 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8256 << ignoredFlag.toString() << flag.toString(),
8257 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8258 /*IsStringLocation*/true,
8259 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8260 FixIt: FixItHint::CreateRemoval(
8261 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8262}
8263
8264void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8265 unsigned flagLen) {
8266 // Warn about an empty flag.
8267 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag),
8268 Loc: getLocationOfByte(x: startFlag),
8269 /*IsStringLocation*/true,
8270 StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8271}
8272
8273void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8274 unsigned flagLen) {
8275 // Warn about an invalid flag.
8276 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8277 StringRef flag(startFlag, flagLen);
8278 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8279 Loc: getLocationOfByte(x: startFlag),
8280 /*IsStringLocation*/true,
8281 StringRange: Range, FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8282}
8283
8284void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8285 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8286 // Warn about using '[...]' without a '@' conversion.
8287 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8288 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8289 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8290 Loc: getLocationOfByte(x: conversionPosition),
8291 /*IsStringLocation*/ true, StringRange: Range,
8292 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8293}
8294
8295void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8296 const Expr *FmtExpr,
8297 bool InFunctionCall) const {
8298 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8299 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8300}
8301
8302bool EquatableFormatArgument::VerifyCompatible(
8303 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8304 bool InFunctionCall) const {
8305 using MK = analyze_format_string::ArgType::MatchKind;
8306 if (Role != Other.Role) {
8307 // diagnose and stop
8308 EmitDiagnostic(
8309 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8310 FmtExpr, InFunctionCall);
8311 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8312 return false;
8313 }
8314
8315 if (Role != FAR_Data) {
8316 if (ModifierFor != Other.ModifierFor) {
8317 // diagnose and stop
8318 EmitDiagnostic(S,
8319 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8320 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8321 FmtExpr, InFunctionCall);
8322 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8323 return false;
8324 }
8325 return true;
8326 }
8327
8328 bool HadError = false;
8329 if (Sensitivity != Other.Sensitivity) {
8330 // diagnose and continue
8331 EmitDiagnostic(S,
8332 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8333 << Sensitivity << Other.Sensitivity,
8334 FmtExpr, InFunctionCall);
8335 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8336 << 0 << Other.Range;
8337 }
8338
8339 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8340 case MK::Match:
8341 break;
8342
8343 case MK::MatchPromotion:
8344 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8345 // MatchPromotion is treated as a failure by format_matches.
8346 case MK::NoMatch:
8347 case MK::NoMatchTypeConfusion:
8348 case MK::NoMatchPromotionTypeConfusion:
8349 EmitDiagnostic(S,
8350 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8351 << buildFormatSpecifier()
8352 << Other.buildFormatSpecifier(),
8353 FmtExpr, InFunctionCall);
8354 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8355 << 0 << Other.Range;
8356 break;
8357
8358 case MK::NoMatchPedantic:
8359 EmitDiagnostic(S,
8360 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8361 << buildFormatSpecifier()
8362 << Other.buildFormatSpecifier(),
8363 FmtExpr, InFunctionCall);
8364 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8365 << 0 << Other.Range;
8366 break;
8367
8368 case MK::NoMatchSignedness:
8369 EmitDiagnostic(S,
8370 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8371 << buildFormatSpecifier()
8372 << Other.buildFormatSpecifier(),
8373 FmtExpr, InFunctionCall);
8374 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8375 << 0 << Other.Range;
8376 break;
8377 }
8378 return !HadError;
8379}
8380
8381bool DecomposePrintfHandler::GetSpecifiers(
8382 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8383 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8384 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8385 StringRef Data = FSL->getString();
8386 const char *Str = Data.data();
8387 llvm::SmallBitVector BV;
8388 UncoveredArgHandler UA;
8389 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8390 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8391 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8392 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8393 UA, Args);
8394
8395 if (!analyze_format_string::ParsePrintfString(
8396 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8397 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8398 H.DoneProcessing();
8399 if (H.HadError)
8400 return false;
8401
8402 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8403 const EquatableFormatArgument &B) {
8404 return A.getPosition() < B.getPosition();
8405 });
8406 return true;
8407}
8408
8409bool DecomposePrintfHandler::HandlePrintfSpecifier(
8410 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8411 unsigned specifierLen, const TargetInfo &Target) {
8412 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8413 specifierLen, Target)) {
8414 HadError = true;
8415 return false;
8416 }
8417
8418 // Do not add any specifiers to the list for %%. This is possibly incorrect
8419 // if using a precision/width with a data argument, but that combination is
8420 // meaningless and we wouldn't know which format to attach the
8421 // precision/width to.
8422 const auto &CS = FS.getConversionSpecifier();
8423 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8424 return true;
8425
8426 // have to patch these to have the right ModifierFor if they are used
8427 const unsigned Unset = ~0;
8428 unsigned FieldWidthIndex = Unset;
8429 unsigned PrecisionIndex = Unset;
8430
8431 // field width?
8432 const auto &FieldWidth = FS.getFieldWidth();
8433 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8434 FieldWidthIndex = Specs.size();
8435 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8436 Args: getLocationOfByte(x: FieldWidth.getStart()),
8437 Args: analyze_format_string::LengthModifier::None, Args: "*",
8438 Args: FieldWidth.getArgType(Ctx&: S.Context),
8439 Args: EquatableFormatArgument::FAR_FieldWidth,
8440 Args: EquatableFormatArgument::SS_None,
8441 Args: FieldWidth.usesPositionalArg()
8442 ? FieldWidth.getPositionalArgIndex() - 1
8443 : FieldWidthIndex,
8444 Args: 0);
8445 }
8446 // precision?
8447 const auto &Precision = FS.getPrecision();
8448 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8449 PrecisionIndex = Specs.size();
8450 Specs.emplace_back(
8451 Args: getSpecifierRange(startSpecifier, specifierLen),
8452 Args: getLocationOfByte(x: Precision.getStart()),
8453 Args: analyze_format_string::LengthModifier::None, Args: ".*",
8454 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
8455 Args: EquatableFormatArgument::SS_None,
8456 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8457 : PrecisionIndex,
8458 Args: 0);
8459 }
8460
8461 // this specifier
8462 unsigned SpecIndex =
8463 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8464 if (FieldWidthIndex != Unset)
8465 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8466 if (PrecisionIndex != Unset)
8467 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8468
8469 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8470 if (FS.isPrivate())
8471 Sensitivity = EquatableFormatArgument::SS_Private;
8472 else if (FS.isPublic())
8473 Sensitivity = EquatableFormatArgument::SS_Public;
8474 else if (FS.isSensitive())
8475 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8476 else
8477 Sensitivity = EquatableFormatArgument::SS_None;
8478
8479 Specs.emplace_back(
8480 Args: getSpecifierRange(startSpecifier, specifierLen),
8481 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier().getKind(),
8482 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
8483 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
8484
8485 // auxiliary argument?
8486 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
8487 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
8488 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8489 Args: getLocationOfByte(x: CS.getStart()),
8490 Args: analyze_format_string::LengthModifier::None,
8491 Args: CS.getCharacters(),
8492 Args: analyze_format_string::ArgType::CStrTy,
8493 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
8494 Args: SpecIndex + 1, Args&: SpecIndex);
8495 }
8496 return true;
8497}
8498
8499// Determines if the specified is a C++ class or struct containing
8500// a member with the specified name and kind (e.g. a CXXMethodDecl named
8501// "c_str()").
8502template<typename MemberKind>
8503static llvm::SmallPtrSet<MemberKind*, 1>
8504CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8505 auto *RD = Ty->getAsCXXRecordDecl();
8506 llvm::SmallPtrSet<MemberKind*, 1> Results;
8507
8508 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8509 return Results;
8510
8511 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8512 Sema::LookupMemberName);
8513 R.suppressDiagnostics();
8514
8515 // We just need to include all members of the right kind turned up by the
8516 // filter, at this point.
8517 if (S.LookupQualifiedName(R, LookupCtx: RD))
8518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8519 NamedDecl *decl = (*I)->getUnderlyingDecl();
8520 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8521 Results.insert(FK);
8522 }
8523 return Results;
8524}
8525
8526/// Check if we could call '.c_str()' on an object.
8527///
8528/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8529/// allow the call, or if it would be ambiguous).
8530bool Sema::hasCStrMethod(const Expr *E) {
8531 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8532
8533 MethodSet Results =
8534 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
8535 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8536 MI != ME; ++MI)
8537 if ((*MI)->getMinRequiredArguments() == 0)
8538 return true;
8539 return false;
8540}
8541
8542// Check if a (w)string was passed when a (w)char* was needed, and offer a
8543// better diagnostic if so. AT is assumed to be valid.
8544// Returns true when a c_str() conversion method is found.
8545bool CheckPrintfHandler::checkForCStrMembers(
8546 const analyze_printf::ArgType &AT, const Expr *E) {
8547 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8548
8549 MethodSet Results =
8550 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
8551
8552 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8553 MI != ME; ++MI) {
8554 const CXXMethodDecl *Method = *MI;
8555 if (Method->getMinRequiredArguments() == 0 &&
8556 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
8557 // FIXME: Suggest parens if the expression needs them.
8558 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
8559 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
8560 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
8561 return true;
8562 }
8563 }
8564
8565 return false;
8566}
8567
8568bool CheckPrintfHandler::HandlePrintfSpecifier(
8569 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8570 unsigned specifierLen, const TargetInfo &Target) {
8571 using namespace analyze_format_string;
8572 using namespace analyze_printf;
8573
8574 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8575
8576 if (FS.consumesDataArgument()) {
8577 if (atFirstArg) {
8578 atFirstArg = false;
8579 usesPositionalArgs = FS.usesPositionalArg();
8580 }
8581 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8582 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
8583 startSpec: startSpecifier, specifierLen);
8584 return false;
8585 }
8586 }
8587
8588 // First check if the field width, precision, and conversion specifier
8589 // have matching data arguments.
8590 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0,
8591 startSpecifier, specifierLen)) {
8592 return false;
8593 }
8594
8595 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1,
8596 startSpecifier, specifierLen)) {
8597 return false;
8598 }
8599
8600 if (!CS.consumesDataArgument()) {
8601 // FIXME: Technically specifying a precision or field width here
8602 // makes no sense. Worth issuing a warning at some point.
8603 return true;
8604 }
8605
8606 // Consume the argument.
8607 unsigned argIndex = FS.getArgIndex();
8608 if (argIndex < NumDataArgs) {
8609 // The check to see if the argIndex is valid will come later.
8610 // We set the bit here because we may exit early from this
8611 // function if we encounter some other error.
8612 CoveredArgs.set(argIndex);
8613 }
8614
8615 // FreeBSD kernel extensions.
8616 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8617 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8618 // We need at least two arguments.
8619 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
8620 return false;
8621
8622 if (HasFormatArguments()) {
8623 // Claim the second argument.
8624 CoveredArgs.set(argIndex + 1);
8625
8626 // Type check the first argument (int for %b, pointer for %D)
8627 const Expr *Ex = getDataArg(i: argIndex);
8628 const analyze_printf::ArgType &AT =
8629 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8630 ? ArgType(S.Context.IntTy)
8631 : ArgType::CPointerTy;
8632 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
8633 EmitFormatDiagnostic(
8634 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8635 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8636 << false << Ex->getSourceRange(),
8637 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8638 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8639
8640 // Type check the second argument (char * for both %b and %D)
8641 Ex = getDataArg(i: argIndex + 1);
8642 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8643 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
8644 EmitFormatDiagnostic(
8645 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8646 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8647 << false << Ex->getSourceRange(),
8648 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8649 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8650 }
8651 return true;
8652 }
8653
8654 // Check for using an Objective-C specific conversion specifier
8655 // in a non-ObjC literal.
8656 if (!allowsObjCArg() && CS.isObjCArg()) {
8657 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8658 specifierLen);
8659 }
8660
8661 // %P can only be used with os_log.
8662 if (FSType != FormatStringType::OSLog &&
8663 CS.getKind() == ConversionSpecifier::PArg) {
8664 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8665 specifierLen);
8666 }
8667
8668 // %n is not allowed with os_log.
8669 if (FSType == FormatStringType::OSLog &&
8670 CS.getKind() == ConversionSpecifier::nArg) {
8671 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
8672 Loc: getLocationOfByte(x: CS.getStart()),
8673 /*IsStringLocation*/ false,
8674 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8675
8676 return true;
8677 }
8678
8679 // Only scalars are allowed for os_trace.
8680 if (FSType == FormatStringType::OSTrace &&
8681 (CS.getKind() == ConversionSpecifier::PArg ||
8682 CS.getKind() == ConversionSpecifier::sArg ||
8683 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8684 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8685 specifierLen);
8686 }
8687
8688 // Check for use of public/private annotation outside of os_log().
8689 if (FSType != FormatStringType::OSLog) {
8690 if (FS.isPublic().isSet()) {
8691 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8692 << "public",
8693 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
8694 /*IsStringLocation*/ false,
8695 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8696 }
8697 if (FS.isPrivate().isSet()) {
8698 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8699 << "private",
8700 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
8701 /*IsStringLocation*/ false,
8702 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8703 }
8704 }
8705
8706 const llvm::Triple &Triple = Target.getTriple();
8707 if (CS.getKind() == ConversionSpecifier::nArg &&
8708 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8709 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
8710 Loc: getLocationOfByte(x: CS.getStart()),
8711 /*IsStringLocation*/ false,
8712 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8713 }
8714
8715 // Check for invalid use of field width
8716 if (!FS.hasValidFieldWidth()) {
8717 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
8718 startSpecifier, specifierLen);
8719 }
8720
8721 // Check for invalid use of precision
8722 if (!FS.hasValidPrecision()) {
8723 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
8724 startSpecifier, specifierLen);
8725 }
8726
8727 // Precision is mandatory for %P specifier.
8728 if (CS.getKind() == ConversionSpecifier::PArg &&
8729 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8730 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
8731 Loc: getLocationOfByte(x: startSpecifier),
8732 /*IsStringLocation*/ false,
8733 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8734 }
8735
8736 // Check each flag does not conflict with any other component.
8737 if (!FS.hasValidThousandsGroupingPrefix())
8738 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8739 if (!FS.hasValidLeadingZeros())
8740 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
8741 if (!FS.hasValidPlusPrefix())
8742 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
8743 if (!FS.hasValidSpacePrefix())
8744 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
8745 if (!FS.hasValidAlternativeForm())
8746 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
8747 if (!FS.hasValidLeftJustified())
8748 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
8749
8750 // Check that flags are not ignored by another flag
8751 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8752 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
8753 startSpecifier, specifierLen);
8754 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8755 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
8756 startSpecifier, specifierLen);
8757
8758 // Check the length modifier is valid with the given conversion specifier.
8759 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
8760 LO: S.getLangOpts()))
8761 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8762 DiagID: diag::warn_format_nonsensical_length);
8763 else if (!FS.hasStandardLengthModifier())
8764 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8765 else if (!FS.hasStandardLengthConversionCombination())
8766 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8767 DiagID: diag::warn_format_non_standard_conversion_spec);
8768
8769 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
8770 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8771
8772 // The remaining checks depend on the data arguments.
8773 if (!HasFormatArguments())
8774 return true;
8775
8776 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8777 return false;
8778
8779 const Expr *Arg = getDataArg(i: argIndex);
8780 if (!Arg)
8781 return true;
8782
8783 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
8784}
8785
8786static bool requiresParensToAddCast(const Expr *E) {
8787 // FIXME: We should have a general way to reason about operator
8788 // precedence and whether parens are actually needed here.
8789 // Take care of a few common cases where they aren't.
8790 const Expr *Inside = E->IgnoreImpCasts();
8791 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
8792 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8793
8794 switch (Inside->getStmtClass()) {
8795 case Stmt::ArraySubscriptExprClass:
8796 case Stmt::CallExprClass:
8797 case Stmt::CharacterLiteralClass:
8798 case Stmt::CXXBoolLiteralExprClass:
8799 case Stmt::DeclRefExprClass:
8800 case Stmt::FloatingLiteralClass:
8801 case Stmt::IntegerLiteralClass:
8802 case Stmt::MemberExprClass:
8803 case Stmt::ObjCArrayLiteralClass:
8804 case Stmt::ObjCBoolLiteralExprClass:
8805 case Stmt::ObjCBoxedExprClass:
8806 case Stmt::ObjCDictionaryLiteralClass:
8807 case Stmt::ObjCEncodeExprClass:
8808 case Stmt::ObjCIvarRefExprClass:
8809 case Stmt::ObjCMessageExprClass:
8810 case Stmt::ObjCPropertyRefExprClass:
8811 case Stmt::ObjCStringLiteralClass:
8812 case Stmt::ObjCSubscriptRefExprClass:
8813 case Stmt::ParenExprClass:
8814 case Stmt::StringLiteralClass:
8815 case Stmt::UnaryOperatorClass:
8816 return false;
8817 default:
8818 return true;
8819 }
8820}
8821
8822static std::pair<QualType, StringRef>
8823shouldNotPrintDirectly(const ASTContext &Context,
8824 QualType IntendedTy,
8825 const Expr *E) {
8826 // Use a 'while' to peel off layers of typedefs.
8827 QualType TyTy = IntendedTy;
8828 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8829 StringRef Name = UserTy->getDecl()->getName();
8830 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8831 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
8832 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
8833 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
8834 .Case(S: "SInt32", Value: Context.IntTy)
8835 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
8836 .Default(Value: QualType());
8837
8838 if (!CastTy.isNull())
8839 return std::make_pair(x&: CastTy, y&: Name);
8840
8841 TyTy = UserTy->desugar();
8842 }
8843
8844 // Strip parens if necessary.
8845 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
8846 return shouldNotPrintDirectly(Context,
8847 IntendedTy: PE->getSubExpr()->getType(),
8848 E: PE->getSubExpr());
8849
8850 // If this is a conditional expression, then its result type is constructed
8851 // via usual arithmetic conversions and thus there might be no necessary
8852 // typedef sugar there. Recurse to operands to check for NSInteger &
8853 // Co. usage condition.
8854 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
8855 QualType TrueTy, FalseTy;
8856 StringRef TrueName, FalseName;
8857
8858 std::tie(args&: TrueTy, args&: TrueName) =
8859 shouldNotPrintDirectly(Context,
8860 IntendedTy: CO->getTrueExpr()->getType(),
8861 E: CO->getTrueExpr());
8862 std::tie(args&: FalseTy, args&: FalseName) =
8863 shouldNotPrintDirectly(Context,
8864 IntendedTy: CO->getFalseExpr()->getType(),
8865 E: CO->getFalseExpr());
8866
8867 if (TrueTy == FalseTy)
8868 return std::make_pair(x&: TrueTy, y&: TrueName);
8869 else if (TrueTy.isNull())
8870 return std::make_pair(x&: FalseTy, y&: FalseName);
8871 else if (FalseTy.isNull())
8872 return std::make_pair(x&: TrueTy, y&: TrueName);
8873 }
8874
8875 return std::make_pair(x: QualType(), y: StringRef());
8876}
8877
8878/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8879/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8880/// type do not count.
8881static bool
8882isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8883 QualType From = ICE->getSubExpr()->getType();
8884 QualType To = ICE->getType();
8885 // It's an integer promotion if the destination type is the promoted
8886 // source type.
8887 if (ICE->getCastKind() == CK_IntegralCast &&
8888 S.Context.isPromotableIntegerType(T: From) &&
8889 S.Context.getPromotedIntegerType(PromotableType: From) == To)
8890 return true;
8891 // Look through vector types, since we do default argument promotion for
8892 // those in OpenCL.
8893 if (const auto *VecTy = From->getAs<ExtVectorType>())
8894 From = VecTy->getElementType();
8895 if (const auto *VecTy = To->getAs<ExtVectorType>())
8896 To = VecTy->getElementType();
8897 // It's a floating promotion if the source type is a lower rank.
8898 return ICE->getCastKind() == CK_FloatingCast &&
8899 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
8900}
8901
8902static analyze_format_string::ArgType::MatchKind
8903handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
8904 DiagnosticsEngine &Diags, SourceLocation Loc) {
8905 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
8906 if (Diags.isIgnored(
8907 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
8908 Loc) ||
8909 Diags.isIgnored(
8910 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8911 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8912 return analyze_format_string::ArgType::Match;
8913 }
8914 }
8915 return Match;
8916}
8917
8918bool
8919CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8920 const char *StartSpecifier,
8921 unsigned SpecifierLen,
8922 const Expr *E) {
8923 using namespace analyze_format_string;
8924 using namespace analyze_printf;
8925
8926 // Now type check the data expression that matches the
8927 // format specifier.
8928 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
8929 if (!AT.isValid())
8930 return true;
8931
8932 QualType ExprTy = E->getType();
8933 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
8934 ExprTy = TET->getUnderlyingExpr()->getType();
8935 }
8936
8937 // When using the format attribute in C++, you can receive a function or an
8938 // array that will necessarily decay to a pointer when passed to the final
8939 // format consumer. Apply decay before type comparison.
8940 if (ExprTy->canDecayToPointerType())
8941 ExprTy = S.Context.getDecayedType(T: ExprTy);
8942
8943 // Diagnose attempts to print a boolean value as a character. Unlike other
8944 // -Wformat diagnostics, this is fine from a type perspective, but it still
8945 // doesn't make sense.
8946 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8947 E->isKnownToHaveBooleanValue()) {
8948 const CharSourceRange &CSR =
8949 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
8950 SmallString<4> FSString;
8951 llvm::raw_svector_ostream os(FSString);
8952 FS.toString(os);
8953 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
8954 << FSString,
8955 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
8956 return true;
8957 }
8958
8959 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8960 // dumping raw class data (like is-a pointer), not actual data.
8961 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
8962 ExprTy->isObjCObjectPointerType()) {
8963 const CharSourceRange &CSR =
8964 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
8965 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
8966 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
8967 return true;
8968 }
8969
8970 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8971 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
8972 ArgType::MatchKind OrigMatch = Match;
8973
8974 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
8975 if (Match == ArgType::Match)
8976 return true;
8977
8978 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8979 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8980
8981 // Look through argument promotions for our error message's reported type.
8982 // This includes the integral and floating promotions, but excludes array
8983 // and function pointer decay (seeing that an argument intended to be a
8984 // string has type 'char [6]' is probably more confusing than 'char *') and
8985 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8986 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
8987 if (isArithmeticArgumentPromotion(S, ICE)) {
8988 E = ICE->getSubExpr();
8989 ExprTy = E->getType();
8990
8991 // Check if we didn't match because of an implicit cast from a 'char'
8992 // or 'short' to an 'int'. This is done because printf is a varargs
8993 // function.
8994 if (ICE->getType() == S.Context.IntTy ||
8995 ICE->getType() == S.Context.UnsignedIntTy) {
8996 // All further checking is done on the subexpression
8997 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
8998 if (OrigMatch == ArgType::NoMatchSignedness &&
8999 ImplicitMatch != ArgType::NoMatchSignedness)
9000 // If the original match was a signedness match this match on the
9001 // implicit cast type also need to be signedness match otherwise we
9002 // might introduce new unexpected warnings from -Wformat-signedness.
9003 return true;
9004 ImplicitMatch = handleFormatSignedness(
9005 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9006 if (ImplicitMatch == ArgType::Match)
9007 return true;
9008 }
9009 }
9010 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9011 // Special case for 'a', which has type 'int' in C.
9012 // Note, however, that we do /not/ want to treat multibyte constants like
9013 // 'MooV' as characters! This form is deprecated but still exists. In
9014 // addition, don't treat expressions as of type 'char' if one byte length
9015 // modifier is provided.
9016 if (ExprTy == S.Context.IntTy &&
9017 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9018 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9019 ExprTy = S.Context.CharTy;
9020 // To improve check results, we consider a character literal in C
9021 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9022 // more likely a type confusion situation, so we will suggest to
9023 // use '%hhd' instead by discarding the MatchPromotion.
9024 if (Match == ArgType::MatchPromotion)
9025 Match = ArgType::NoMatch;
9026 }
9027 }
9028 if (Match == ArgType::MatchPromotion) {
9029 // WG14 N2562 only clarified promotions in *printf
9030 // For NSLog in ObjC, just preserve -Wformat behavior
9031 if (!S.getLangOpts().ObjC &&
9032 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9033 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9034 return true;
9035 Match = ArgType::NoMatch;
9036 }
9037 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9038 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9039 Match = ImplicitMatch;
9040 assert(Match != ArgType::MatchPromotion);
9041
9042 // Look through unscoped enums to their underlying type.
9043 bool IsEnum = false;
9044 bool IsScopedEnum = false;
9045 QualType IntendedTy = ExprTy;
9046 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9047 IntendedTy = ED->getIntegerType();
9048 if (!ED->isScoped()) {
9049 ExprTy = IntendedTy;
9050 // This controls whether we're talking about the underlying type or not,
9051 // which we only want to do when it's an unscoped enum.
9052 IsEnum = true;
9053 } else {
9054 IsScopedEnum = true;
9055 }
9056 }
9057
9058 // %C in an Objective-C context prints a unichar, not a wchar_t.
9059 // If the argument is an integer of some kind, believe the %C and suggest
9060 // a cast instead of changing the conversion specifier.
9061 if (isObjCContext() &&
9062 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9063 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9064 !ExprTy->isCharType()) {
9065 // 'unichar' is defined as a typedef of unsigned short, but we should
9066 // prefer using the typedef if it is visible.
9067 IntendedTy = S.Context.UnsignedShortTy;
9068
9069 // While we are here, check if the value is an IntegerLiteral that happens
9070 // to be within the valid range.
9071 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9072 const llvm::APInt &V = IL->getValue();
9073 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9074 return true;
9075 }
9076
9077 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9078 Sema::LookupOrdinaryName);
9079 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9080 NamedDecl *ND = Result.getFoundDecl();
9081 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9082 if (TD->getUnderlyingType() == IntendedTy)
9083 IntendedTy =
9084 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9085 /*Qualifier=*/std::nullopt, Decl: TD);
9086 }
9087 }
9088 }
9089
9090 // Special-case some of Darwin's platform-independence types by suggesting
9091 // casts to primitive types that are known to be large enough.
9092 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9093 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9094 QualType CastTy;
9095 std::tie(args&: CastTy, args&: CastTyName) = shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9096 if (!CastTy.isNull()) {
9097 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9098 // (long in ASTContext). Only complain to pedants or when they're the
9099 // underlying type of a scoped enum (which always needs a cast).
9100 if (!IsScopedEnum &&
9101 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9102 (AT.isSizeT() || AT.isPtrdiffT()) &&
9103 AT.matchesType(C&: S.Context, argTy: CastTy))
9104 Match = ArgType::NoMatchPedantic;
9105 IntendedTy = CastTy;
9106 ShouldNotPrintDirectly = true;
9107 }
9108 }
9109
9110 // We may be able to offer a FixItHint if it is a supported type.
9111 PrintfSpecifier fixedFS = FS;
9112 bool Success =
9113 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9114
9115 if (Success) {
9116 // Get the fix string from the fixed format specifier
9117 SmallString<16> buf;
9118 llvm::raw_svector_ostream os(buf);
9119 fixedFS.toString(os);
9120
9121 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9122
9123 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9124 unsigned Diag;
9125 switch (Match) {
9126 case ArgType::Match:
9127 case ArgType::MatchPromotion:
9128 case ArgType::NoMatchPromotionTypeConfusion:
9129 llvm_unreachable("expected non-matching");
9130 case ArgType::NoMatchSignedness:
9131 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9132 break;
9133 case ArgType::NoMatchPedantic:
9134 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9135 break;
9136 case ArgType::NoMatchTypeConfusion:
9137 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9138 break;
9139 case ArgType::NoMatch:
9140 Diag = diag::warn_format_conversion_argument_type_mismatch;
9141 break;
9142 }
9143
9144 // In this case, the specifier is wrong and should be changed to match
9145 // the argument.
9146 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9147 << AT.getRepresentativeTypeName(C&: S.Context)
9148 << IntendedTy << IsEnum << E->getSourceRange(),
9149 Loc: E->getBeginLoc(),
9150 /*IsStringLocation*/ false, StringRange: SpecRange,
9151 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9152 } else {
9153 // The canonical type for formatting this value is different from the
9154 // actual type of the expression. (This occurs, for example, with Darwin's
9155 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9156 // should be printed as 'long' for 64-bit compatibility.)
9157 // Rather than emitting a normal format/argument mismatch, we want to
9158 // add a cast to the recommended type (and correct the format string
9159 // if necessary). We should also do so for scoped enumerations.
9160 SmallString<16> CastBuf;
9161 llvm::raw_svector_ostream CastFix(CastBuf);
9162 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9163 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9164 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9165
9166 SmallVector<FixItHint,4> Hints;
9167 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9168 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9169 Loc: E->getExprLoc());
9170 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9171 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9172
9173 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9174 // If there's already a cast present, just replace it.
9175 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9176 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9177
9178 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9179 // If the expression has high enough precedence,
9180 // just write the C-style cast.
9181 Hints.push_back(
9182 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9183 } else {
9184 // Otherwise, add parens around the expression as well as the cast.
9185 CastFix << "(";
9186 Hints.push_back(
9187 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9188
9189 // We don't use getLocForEndOfToken because it returns invalid source
9190 // locations for macro expansions (by design).
9191 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9192 SourceLocation After = EndLoc.getLocWithOffset(
9193 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9194 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9195 }
9196
9197 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9198 // The expression has a type that should not be printed directly.
9199 // We extract the name from the typedef because we don't want to show
9200 // the underlying type in the diagnostic.
9201 StringRef Name;
9202 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9203 Name = TypedefTy->getDecl()->getName();
9204 else
9205 Name = CastTyName;
9206 unsigned Diag = Match == ArgType::NoMatchPedantic
9207 ? diag::warn_format_argument_needs_cast_pedantic
9208 : diag::warn_format_argument_needs_cast;
9209 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9210 << E->getSourceRange(),
9211 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9212 StringRange: SpecRange, FixIt: Hints);
9213 } else {
9214 // In this case, the expression could be printed using a different
9215 // specifier, but we've decided that the specifier is probably correct
9216 // and we should cast instead. Just use the normal warning message.
9217
9218 unsigned Diag =
9219 IsScopedEnum
9220 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9221 : diag::warn_format_conversion_argument_type_mismatch;
9222
9223 EmitFormatDiagnostic(
9224 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9225 << IsEnum << E->getSourceRange(),
9226 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9227 }
9228 }
9229 } else {
9230 const CharSourceRange &CSR = getSpecifierRange(startSpecifier: StartSpecifier,
9231 specifierLen: SpecifierLen);
9232 // Since the warning for passing non-POD types to variadic functions
9233 // was deferred until now, we emit a warning for non-POD
9234 // arguments here.
9235 bool EmitTypeMismatch = false;
9236 switch (S.isValidVarArgType(Ty: ExprTy)) {
9237 case VarArgKind::Valid:
9238 case VarArgKind::ValidInCXX11: {
9239 unsigned Diag;
9240 switch (Match) {
9241 case ArgType::Match:
9242 case ArgType::MatchPromotion:
9243 case ArgType::NoMatchPromotionTypeConfusion:
9244 llvm_unreachable("expected non-matching");
9245 case ArgType::NoMatchSignedness:
9246 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9247 break;
9248 case ArgType::NoMatchPedantic:
9249 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9250 break;
9251 case ArgType::NoMatchTypeConfusion:
9252 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9253 break;
9254 case ArgType::NoMatch:
9255 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)
9256 ? diag::err_format_conversion_argument_type_mismatch
9257 : diag::warn_format_conversion_argument_type_mismatch;
9258 break;
9259 }
9260
9261 EmitFormatDiagnostic(
9262 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9263 << IsEnum << CSR << E->getSourceRange(),
9264 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9265 break;
9266 }
9267 case VarArgKind::Undefined:
9268 case VarArgKind::MSVCUndefined:
9269 if (CallType == VariadicCallType::DoesNotApply) {
9270 EmitTypeMismatch = true;
9271 } else {
9272 EmitFormatDiagnostic(
9273 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9274 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9275 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9276 << E->getSourceRange(),
9277 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9278 checkForCStrMembers(AT, E);
9279 }
9280 break;
9281
9282 case VarArgKind::Invalid:
9283 if (CallType == VariadicCallType::DoesNotApply)
9284 EmitTypeMismatch = true;
9285 else if (ExprTy->isObjCObjectType())
9286 EmitFormatDiagnostic(
9287 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9288 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9289 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9290 << E->getSourceRange(),
9291 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9292 else
9293 // FIXME: If this is an initializer list, suggest removing the braces
9294 // or inserting a cast to the target type.
9295 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9296 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9297 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9298 break;
9299 }
9300
9301 if (EmitTypeMismatch) {
9302 // The function is not variadic, so we do not generate warnings about
9303 // being allowed to pass that object as a variadic argument. Instead,
9304 // since there are inherently no printf specifiers for types which cannot
9305 // be passed as variadic arguments, emit a plain old specifier mismatch
9306 // argument.
9307 EmitFormatDiagnostic(
9308 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9309 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9310 << E->getSourceRange(),
9311 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9312 }
9313
9314 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9315 "format string specifier index out of range");
9316 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9317 }
9318
9319 return true;
9320}
9321
9322//===--- CHECK: Scanf format string checking ------------------------------===//
9323
9324namespace {
9325
9326class CheckScanfHandler : public CheckFormatHandler {
9327public:
9328 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9329 const Expr *origFormatExpr, FormatStringType type,
9330 unsigned firstDataArg, unsigned numDataArgs,
9331 const char *beg, Sema::FormatArgumentPassingKind APK,
9332 ArrayRef<const Expr *> Args, unsigned formatIdx,
9333 bool inFunctionCall, VariadicCallType CallType,
9334 llvm::SmallBitVector &CheckedVarArgs,
9335 UncoveredArgHandler &UncoveredArg)
9336 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9337 numDataArgs, beg, APK, Args, formatIdx,
9338 inFunctionCall, CallType, CheckedVarArgs,
9339 UncoveredArg) {}
9340
9341 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9342 const char *startSpecifier,
9343 unsigned specifierLen) override;
9344
9345 bool HandleInvalidScanfConversionSpecifier(
9346 const analyze_scanf::ScanfSpecifier &FS,
9347 const char *startSpecifier,
9348 unsigned specifierLen) override;
9349
9350 void HandleIncompleteScanList(const char *start, const char *end) override;
9351};
9352
9353} // namespace
9354
9355void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9356 const char *end) {
9357 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9358 Loc: getLocationOfByte(x: end), /*IsStringLocation*/true,
9359 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9360}
9361
9362bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9363 const analyze_scanf::ScanfSpecifier &FS,
9364 const char *startSpecifier,
9365 unsigned specifierLen) {
9366 const analyze_scanf::ScanfConversionSpecifier &CS =
9367 FS.getConversionSpecifier();
9368
9369 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
9370 Loc: getLocationOfByte(x: CS.getStart()),
9371 startSpec: startSpecifier, specifierLen,
9372 csStart: CS.getStart(), csLen: CS.getLength());
9373}
9374
9375bool CheckScanfHandler::HandleScanfSpecifier(
9376 const analyze_scanf::ScanfSpecifier &FS,
9377 const char *startSpecifier,
9378 unsigned specifierLen) {
9379 using namespace analyze_scanf;
9380 using namespace analyze_format_string;
9381
9382 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9383
9384 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9385 // be used to decide if we are using positional arguments consistently.
9386 if (FS.consumesDataArgument()) {
9387 if (atFirstArg) {
9388 atFirstArg = false;
9389 usesPositionalArgs = FS.usesPositionalArg();
9390 }
9391 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9392 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9393 startSpec: startSpecifier, specifierLen);
9394 return false;
9395 }
9396 }
9397
9398 // Check if the field with is non-zero.
9399 const OptionalAmount &Amt = FS.getFieldWidth();
9400 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9401 if (Amt.getConstantAmount() == 0) {
9402 const CharSourceRange &R = getSpecifierRange(startSpecifier: Amt.getStart(),
9403 specifierLen: Amt.getConstantLength());
9404 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9405 Loc: getLocationOfByte(x: Amt.getStart()),
9406 /*IsStringLocation*/true, StringRange: R,
9407 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9408 }
9409 }
9410
9411 if (!FS.consumesDataArgument()) {
9412 // FIXME: Technically specifying a precision or field width here
9413 // makes no sense. Worth issuing a warning at some point.
9414 return true;
9415 }
9416
9417 // Consume the argument.
9418 unsigned argIndex = FS.getArgIndex();
9419 if (argIndex < NumDataArgs) {
9420 // The check to see if the argIndex is valid will come later.
9421 // We set the bit here because we may exit early from this
9422 // function if we encounter some other error.
9423 CoveredArgs.set(argIndex);
9424 }
9425
9426 // Check the length modifier is valid with the given conversion specifier.
9427 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9428 LO: S.getLangOpts()))
9429 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9430 DiagID: diag::warn_format_nonsensical_length);
9431 else if (!FS.hasStandardLengthModifier())
9432 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9433 else if (!FS.hasStandardLengthConversionCombination())
9434 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9435 DiagID: diag::warn_format_non_standard_conversion_spec);
9436
9437 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9438 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9439
9440 // The remaining checks depend on the data arguments.
9441 if (!HasFormatArguments())
9442 return true;
9443
9444 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9445 return false;
9446
9447 // Check that the argument type matches the format specifier.
9448 const Expr *Ex = getDataArg(i: argIndex);
9449 if (!Ex)
9450 return true;
9451
9452 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
9453
9454 if (!AT.isValid()) {
9455 return true;
9456 }
9457
9458 analyze_format_string::ArgType::MatchKind Match =
9459 AT.matchesType(C&: S.Context, argTy: Ex->getType());
9460 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
9461 if (Match == analyze_format_string::ArgType::Match)
9462 return true;
9463 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9464 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
9465
9466 ScanfSpecifier fixedFS = FS;
9467 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
9468 LangOpt: S.getLangOpts(), Ctx&: S.Context);
9469
9470 unsigned Diag =
9471 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9472 : Signedness
9473 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9474 : diag::warn_format_conversion_argument_type_mismatch;
9475
9476 if (Success) {
9477 // Get the fix string from the fixed format specifier.
9478 SmallString<128> buf;
9479 llvm::raw_svector_ostream os(buf);
9480 fixedFS.toString(os);
9481
9482 EmitFormatDiagnostic(
9483 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
9484 << Ex->getType() << false << Ex->getSourceRange(),
9485 Loc: Ex->getBeginLoc(),
9486 /*IsStringLocation*/ false,
9487 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9488 FixIt: FixItHint::CreateReplacement(
9489 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
9490 } else {
9491 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9492 << AT.getRepresentativeTypeName(C&: S.Context)
9493 << Ex->getType() << false << Ex->getSourceRange(),
9494 Loc: Ex->getBeginLoc(),
9495 /*IsStringLocation*/ false,
9496 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9497 }
9498
9499 return true;
9500}
9501
9502static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9503 ArrayRef<EquatableFormatArgument> RefArgs,
9504 const StringLiteral *Fmt,
9505 ArrayRef<EquatableFormatArgument> FmtArgs,
9506 const Expr *FmtExpr, bool InFunctionCall) {
9507 bool HadError = false;
9508 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9509 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9510 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9511 // In positional-style format strings, the same specifier can appear
9512 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9513 // are sorted by getPosition(), and we process each range of equal
9514 // getPosition() values as one group.
9515 // RefArgs are taken from a string literal that was given to
9516 // attribute(format_matches), and if we got this far, we have already
9517 // verified that if it has positional specifiers that appear in multiple
9518 // locations, then they are all mutually compatible. What's left for us to
9519 // do is verify that all specifiers with the same position in FmtArgs are
9520 // compatible with the RefArgs specifiers. We check each specifier from
9521 // FmtArgs against the first member of the RefArgs group.
9522 for (; FmtIter < FmtEnd; ++FmtIter) {
9523 // Clang does not diagnose missing format specifiers in positional-style
9524 // strings (TODO: which it probably should do, as it is UB to skip over a
9525 // format argument). Skip specifiers if needed.
9526 if (FmtIter->getPosition() < RefIter->getPosition())
9527 continue;
9528
9529 // Delimits a new getPosition() value.
9530 if (FmtIter->getPosition() > RefIter->getPosition())
9531 break;
9532
9533 HadError |=
9534 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
9535 }
9536
9537 // Jump RefIter to the start of the next group.
9538 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
9539 return Arg.getPosition() != RefIter->getPosition();
9540 });
9541 }
9542
9543 if (FmtIter < FmtEnd) {
9544 CheckFormatHandler::EmitFormatDiagnostic(
9545 S, InFunctionCall, ArgumentExpr: FmtExpr,
9546 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
9547 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
9548 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
9549 } else if (RefIter < RefEnd) {
9550 CheckFormatHandler::EmitFormatDiagnostic(
9551 S, InFunctionCall, ArgumentExpr: FmtExpr,
9552 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
9553 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
9554 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
9555 << 1 << RefIter->getSourceRange();
9556 }
9557 return !HadError;
9558}
9559
9560static void CheckFormatString(
9561 Sema &S, const FormatStringLiteral *FExpr,
9562 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9563 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
9564 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9565 bool inFunctionCall, VariadicCallType CallType,
9566 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9567 bool IgnoreStringsWithoutSpecifiers) {
9568 // CHECK: is the format string a wide literal?
9569 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9570 CheckFormatHandler::EmitFormatDiagnostic(
9571 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9572 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
9573 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9574 return;
9575 }
9576
9577 // Str - The format string. NOTE: this is NOT null-terminated!
9578 StringRef StrRef = FExpr->getString();
9579 const char *Str = StrRef.data();
9580 // Account for cases where the string literal is truncated in a declaration.
9581 const ConstantArrayType *T =
9582 S.Context.getAsConstantArrayType(T: FExpr->getType());
9583 assert(T && "String literal not of constant array type!");
9584 size_t TypeSize = T->getZExtSize();
9585 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9586 const unsigned numDataArgs = Args.size() - firstDataArg;
9587
9588 if (IgnoreStringsWithoutSpecifiers &&
9589 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9590 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9591 return;
9592
9593 // Emit a warning if the string literal is truncated and does not contain an
9594 // embedded null character.
9595 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
9596 CheckFormatHandler::EmitFormatDiagnostic(
9597 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9598 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
9599 Loc: FExpr->getBeginLoc(),
9600 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
9601 return;
9602 }
9603
9604 // CHECK: empty format string?
9605 if (StrLen == 0 && numDataArgs > 0) {
9606 CheckFormatHandler::EmitFormatDiagnostic(
9607 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9608 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
9609 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9610 return;
9611 }
9612
9613 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
9614 Type == FormatStringType::Kprintf ||
9615 Type == FormatStringType::FreeBSDKPrintf ||
9616 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
9617 bool IsObjC =
9618 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9619 if (ReferenceFormatString == nullptr) {
9620 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9621 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9622 inFunctionCall, CallType, CheckedVarArgs,
9623 UncoveredArg);
9624
9625 if (!analyze_format_string::ParsePrintfString(
9626 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9627 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
9628 Type == FormatStringType::FreeBSDKPrintf))
9629 H.DoneProcessing();
9630 } else {
9631 S.CheckFormatStringsCompatible(
9632 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
9633 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
9634 }
9635 } else if (Type == FormatStringType::Scanf) {
9636 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9637 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9638 CallType, CheckedVarArgs, UncoveredArg);
9639
9640 if (!analyze_format_string::ParseScanfString(
9641 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9642 H.DoneProcessing();
9643 } // TODO: handle other formats
9644}
9645
9646bool Sema::CheckFormatStringsCompatible(
9647 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9648 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9649 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9650 Type != FormatStringType::Kprintf &&
9651 Type != FormatStringType::FreeBSDKPrintf &&
9652 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9653 return true;
9654
9655 bool IsObjC =
9656 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9657 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
9658 FormatStringLiteral RefLit = AuthoritativeFormatString;
9659 FormatStringLiteral TestLit = TestedFormatString;
9660 const Expr *Arg;
9661 bool DiagAtStringLiteral;
9662 if (FunctionCallArg) {
9663 Arg = FunctionCallArg;
9664 DiagAtStringLiteral = false;
9665 } else {
9666 Arg = TestedFormatString;
9667 DiagAtStringLiteral = true;
9668 }
9669 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
9670 FmtExpr: AuthoritativeFormatString, Type,
9671 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
9672 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
9673 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
9674 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
9675 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
9676 InFunctionCall: DiagAtStringLiteral);
9677 }
9678 return false;
9679}
9680
9681bool Sema::ValidateFormatString(FormatStringType Type,
9682 const StringLiteral *Str) {
9683 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9684 Type != FormatStringType::Kprintf &&
9685 Type != FormatStringType::FreeBSDKPrintf &&
9686 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9687 return true;
9688
9689 FormatStringLiteral RefLit = Str;
9690 llvm::SmallVector<EquatableFormatArgument, 9> Args;
9691 bool IsObjC =
9692 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9693 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
9694 InFunctionCall: true, Args))
9695 return false;
9696
9697 // Group arguments by getPosition() value, and check that each member of the
9698 // group is compatible with the first member. This verifies that when
9699 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9700 // are mutually compatible. As an optimization, don't test the first member
9701 // against itself.
9702 bool HadError = false;
9703 auto Iter = Args.begin();
9704 auto End = Args.end();
9705 while (Iter != End) {
9706 const auto &FirstInGroup = *Iter;
9707 for (++Iter;
9708 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9709 ++Iter) {
9710 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
9711 }
9712 }
9713 return !HadError;
9714}
9715
9716bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9717 // Str - The format string. NOTE: this is NOT null-terminated!
9718 StringRef StrRef = FExpr->getString();
9719 const char *Str = StrRef.data();
9720 // Account for cases where the string literal is truncated in a declaration.
9721 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
9722 assert(T && "String literal not of constant array type!");
9723 size_t TypeSize = T->getZExtSize();
9724 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9725 return analyze_format_string::ParseFormatStringHasSArg(beg: Str, end: Str + StrLen,
9726 LO: getLangOpts(),
9727 Target: Context.getTargetInfo());
9728}
9729
9730//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9731
9732// Returns the related absolute value function that is larger, of 0 if one
9733// does not exist.
9734static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9735 switch (AbsFunction) {
9736 default:
9737 return 0;
9738
9739 case Builtin::BI__builtin_abs:
9740 return Builtin::BI__builtin_labs;
9741 case Builtin::BI__builtin_labs:
9742 return Builtin::BI__builtin_llabs;
9743 case Builtin::BI__builtin_llabs:
9744 return 0;
9745
9746 case Builtin::BI__builtin_fabsf:
9747 return Builtin::BI__builtin_fabs;
9748 case Builtin::BI__builtin_fabs:
9749 return Builtin::BI__builtin_fabsl;
9750 case Builtin::BI__builtin_fabsl:
9751 return 0;
9752
9753 case Builtin::BI__builtin_cabsf:
9754 return Builtin::BI__builtin_cabs;
9755 case Builtin::BI__builtin_cabs:
9756 return Builtin::BI__builtin_cabsl;
9757 case Builtin::BI__builtin_cabsl:
9758 return 0;
9759
9760 case Builtin::BIabs:
9761 return Builtin::BIlabs;
9762 case Builtin::BIlabs:
9763 return Builtin::BIllabs;
9764 case Builtin::BIllabs:
9765 return 0;
9766
9767 case Builtin::BIfabsf:
9768 return Builtin::BIfabs;
9769 case Builtin::BIfabs:
9770 return Builtin::BIfabsl;
9771 case Builtin::BIfabsl:
9772 return 0;
9773
9774 case Builtin::BIcabsf:
9775 return Builtin::BIcabs;
9776 case Builtin::BIcabs:
9777 return Builtin::BIcabsl;
9778 case Builtin::BIcabsl:
9779 return 0;
9780 }
9781}
9782
9783// Returns the argument type of the absolute value function.
9784static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9785 unsigned AbsType) {
9786 if (AbsType == 0)
9787 return QualType();
9788
9789 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9790 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
9791 if (Error != ASTContext::GE_None)
9792 return QualType();
9793
9794 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9795 if (!FT)
9796 return QualType();
9797
9798 if (FT->getNumParams() != 1)
9799 return QualType();
9800
9801 return FT->getParamType(i: 0);
9802}
9803
9804// Returns the best absolute value function, or zero, based on type and
9805// current absolute value function.
9806static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9807 unsigned AbsFunctionKind) {
9808 unsigned BestKind = 0;
9809 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
9810 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9811 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
9812 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
9813 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
9814 if (BestKind == 0)
9815 BestKind = Kind;
9816 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
9817 BestKind = Kind;
9818 break;
9819 }
9820 }
9821 }
9822 return BestKind;
9823}
9824
9825enum AbsoluteValueKind {
9826 AVK_Integer,
9827 AVK_Floating,
9828 AVK_Complex
9829};
9830
9831static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9832 if (T->isIntegralOrEnumerationType())
9833 return AVK_Integer;
9834 if (T->isRealFloatingType())
9835 return AVK_Floating;
9836 if (T->isAnyComplexType())
9837 return AVK_Complex;
9838
9839 llvm_unreachable("Type not integer, floating, or complex");
9840}
9841
9842// Changes the absolute value function to a different type. Preserves whether
9843// the function is a builtin.
9844static unsigned changeAbsFunction(unsigned AbsKind,
9845 AbsoluteValueKind ValueKind) {
9846 switch (ValueKind) {
9847 case AVK_Integer:
9848 switch (AbsKind) {
9849 default:
9850 return 0;
9851 case Builtin::BI__builtin_fabsf:
9852 case Builtin::BI__builtin_fabs:
9853 case Builtin::BI__builtin_fabsl:
9854 case Builtin::BI__builtin_cabsf:
9855 case Builtin::BI__builtin_cabs:
9856 case Builtin::BI__builtin_cabsl:
9857 return Builtin::BI__builtin_abs;
9858 case Builtin::BIfabsf:
9859 case Builtin::BIfabs:
9860 case Builtin::BIfabsl:
9861 case Builtin::BIcabsf:
9862 case Builtin::BIcabs:
9863 case Builtin::BIcabsl:
9864 return Builtin::BIabs;
9865 }
9866 case AVK_Floating:
9867 switch (AbsKind) {
9868 default:
9869 return 0;
9870 case Builtin::BI__builtin_abs:
9871 case Builtin::BI__builtin_labs:
9872 case Builtin::BI__builtin_llabs:
9873 case Builtin::BI__builtin_cabsf:
9874 case Builtin::BI__builtin_cabs:
9875 case Builtin::BI__builtin_cabsl:
9876 return Builtin::BI__builtin_fabsf;
9877 case Builtin::BIabs:
9878 case Builtin::BIlabs:
9879 case Builtin::BIllabs:
9880 case Builtin::BIcabsf:
9881 case Builtin::BIcabs:
9882 case Builtin::BIcabsl:
9883 return Builtin::BIfabsf;
9884 }
9885 case AVK_Complex:
9886 switch (AbsKind) {
9887 default:
9888 return 0;
9889 case Builtin::BI__builtin_abs:
9890 case Builtin::BI__builtin_labs:
9891 case Builtin::BI__builtin_llabs:
9892 case Builtin::BI__builtin_fabsf:
9893 case Builtin::BI__builtin_fabs:
9894 case Builtin::BI__builtin_fabsl:
9895 return Builtin::BI__builtin_cabsf;
9896 case Builtin::BIabs:
9897 case Builtin::BIlabs:
9898 case Builtin::BIllabs:
9899 case Builtin::BIfabsf:
9900 case Builtin::BIfabs:
9901 case Builtin::BIfabsl:
9902 return Builtin::BIcabsf;
9903 }
9904 }
9905 llvm_unreachable("Unable to convert function");
9906}
9907
9908static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9909 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9910 if (!FnInfo)
9911 return 0;
9912
9913 switch (FDecl->getBuiltinID()) {
9914 default:
9915 return 0;
9916 case Builtin::BI__builtin_abs:
9917 case Builtin::BI__builtin_fabs:
9918 case Builtin::BI__builtin_fabsf:
9919 case Builtin::BI__builtin_fabsl:
9920 case Builtin::BI__builtin_labs:
9921 case Builtin::BI__builtin_llabs:
9922 case Builtin::BI__builtin_cabs:
9923 case Builtin::BI__builtin_cabsf:
9924 case Builtin::BI__builtin_cabsl:
9925 case Builtin::BIabs:
9926 case Builtin::BIlabs:
9927 case Builtin::BIllabs:
9928 case Builtin::BIfabs:
9929 case Builtin::BIfabsf:
9930 case Builtin::BIfabsl:
9931 case Builtin::BIcabs:
9932 case Builtin::BIcabsf:
9933 case Builtin::BIcabsl:
9934 return FDecl->getBuiltinID();
9935 }
9936 llvm_unreachable("Unknown Builtin type");
9937}
9938
9939// If the replacement is valid, emit a note with replacement function.
9940// Additionally, suggest including the proper header if not already included.
9941static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9942 unsigned AbsKind, QualType ArgType) {
9943 bool EmitHeaderHint = true;
9944 const char *HeaderName = nullptr;
9945 std::string FunctionName;
9946 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9947 FunctionName = "std::abs";
9948 if (ArgType->isIntegralOrEnumerationType()) {
9949 HeaderName = "cstdlib";
9950 } else if (ArgType->isRealFloatingType()) {
9951 HeaderName = "cmath";
9952 } else {
9953 llvm_unreachable("Invalid Type");
9954 }
9955
9956 // Lookup all std::abs
9957 if (NamespaceDecl *Std = S.getStdNamespace()) {
9958 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
9959 R.suppressDiagnostics();
9960 S.LookupQualifiedName(R, LookupCtx: Std);
9961
9962 for (const auto *I : R) {
9963 const FunctionDecl *FDecl = nullptr;
9964 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
9965 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
9966 } else {
9967 FDecl = dyn_cast<FunctionDecl>(Val: I);
9968 }
9969 if (!FDecl)
9970 continue;
9971
9972 // Found std::abs(), check that they are the right ones.
9973 if (FDecl->getNumParams() != 1)
9974 continue;
9975
9976 // Check that the parameter type can handle the argument.
9977 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
9978 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
9979 S.Context.getTypeSize(T: ArgType) <=
9980 S.Context.getTypeSize(T: ParamType)) {
9981 // Found a function, don't need the header hint.
9982 EmitHeaderHint = false;
9983 break;
9984 }
9985 }
9986 }
9987 } else {
9988 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
9989 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
9990
9991 if (HeaderName) {
9992 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
9993 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9994 R.suppressDiagnostics();
9995 S.LookupName(R, S: S.getCurScope());
9996
9997 if (R.isSingleResult()) {
9998 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
9999 if (FD && FD->getBuiltinID() == AbsKind) {
10000 EmitHeaderHint = false;
10001 } else {
10002 return;
10003 }
10004 } else if (!R.empty()) {
10005 return;
10006 }
10007 }
10008 }
10009
10010 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10011 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10012
10013 if (!HeaderName)
10014 return;
10015
10016 if (!EmitHeaderHint)
10017 return;
10018
10019 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10020 << FunctionName;
10021}
10022
10023template <std::size_t StrLen>
10024static bool IsStdFunction(const FunctionDecl *FDecl,
10025 const char (&Str)[StrLen]) {
10026 if (!FDecl)
10027 return false;
10028 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10029 return false;
10030 if (!FDecl->isInStdNamespace())
10031 return false;
10032
10033 return true;
10034}
10035
10036enum class MathCheck { NaN, Inf };
10037static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10038 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10039 return llvm::is_contained(Set: names, Element: calleeName);
10040 };
10041
10042 switch (Check) {
10043 case MathCheck::NaN:
10044 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10045 "__builtin_nanf16", "__builtin_nanf128"});
10046 case MathCheck::Inf:
10047 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10048 "__builtin_inff16", "__builtin_inff128"});
10049 }
10050 llvm_unreachable("unknown MathCheck");
10051}
10052
10053static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10054 if (FDecl->getName() != "infinity")
10055 return false;
10056
10057 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10058 const CXXRecordDecl *RDecl = MDecl->getParent();
10059 if (RDecl->getName() != "numeric_limits")
10060 return false;
10061
10062 if (const NamespaceDecl *NSDecl =
10063 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10064 return NSDecl->isStdNamespace();
10065 }
10066
10067 return false;
10068}
10069
10070void Sema::CheckInfNaNFunction(const CallExpr *Call,
10071 const FunctionDecl *FDecl) {
10072 if (!FDecl->getIdentifier())
10073 return;
10074
10075 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10076 if (FPO.getNoHonorNaNs() &&
10077 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10078 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10079 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10080 << 1 << 0 << Call->getSourceRange();
10081 return;
10082 }
10083
10084 if (FPO.getNoHonorInfs() &&
10085 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10086 IsInfinityFunction(FDecl) ||
10087 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10088 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10089 << 0 << 0 << Call->getSourceRange();
10090 }
10091}
10092
10093void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10094 const FunctionDecl *FDecl) {
10095 if (Call->getNumArgs() != 1)
10096 return;
10097
10098 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10099 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10100 if (AbsKind == 0 && !IsStdAbs)
10101 return;
10102
10103 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10104 QualType ParamType = Call->getArg(Arg: 0)->getType();
10105
10106 // Unsigned types cannot be negative. Suggest removing the absolute value
10107 // function call.
10108 if (ArgType->isUnsignedIntegerType()) {
10109 std::string FunctionName =
10110 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10111 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10112 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10113 << FunctionName
10114 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10115 return;
10116 }
10117
10118 // Taking the absolute value of a pointer is very suspicious, they probably
10119 // wanted to index into an array, dereference a pointer, call a function, etc.
10120 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10121 unsigned DiagType = 0;
10122 if (ArgType->isFunctionType())
10123 DiagType = 1;
10124 else if (ArgType->isArrayType())
10125 DiagType = 2;
10126
10127 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10128 return;
10129 }
10130
10131 // std::abs has overloads which prevent most of the absolute value problems
10132 // from occurring.
10133 if (IsStdAbs)
10134 return;
10135
10136 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10137 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10138
10139 // The argument and parameter are the same kind. Check if they are the right
10140 // size.
10141 if (ArgValueKind == ParamValueKind) {
10142 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10143 return;
10144
10145 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10146 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10147 << FDecl << ArgType << ParamType;
10148
10149 if (NewAbsKind == 0)
10150 return;
10151
10152 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10153 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10154 return;
10155 }
10156
10157 // ArgValueKind != ParamValueKind
10158 // The wrong type of absolute value function was used. Attempt to find the
10159 // proper one.
10160 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10161 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10162 if (NewAbsKind == 0)
10163 return;
10164
10165 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10166 << FDecl << ParamValueKind << ArgValueKind;
10167
10168 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10169 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10170}
10171
10172//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10173void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10174 const FunctionDecl *FDecl) {
10175 if (!Call || !FDecl) return;
10176
10177 // Ignore template specializations and macros.
10178 if (inTemplateInstantiation()) return;
10179 if (Call->getExprLoc().isMacroID()) return;
10180
10181 // Only care about the one template argument, two function parameter std::max
10182 if (Call->getNumArgs() != 2) return;
10183 if (!IsStdFunction(FDecl, Str: "max")) return;
10184 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10185 if (!ArgList) return;
10186 if (ArgList->size() != 1) return;
10187
10188 // Check that template type argument is unsigned integer.
10189 const auto& TA = ArgList->get(Idx: 0);
10190 if (TA.getKind() != TemplateArgument::Type) return;
10191 QualType ArgType = TA.getAsType();
10192 if (!ArgType->isUnsignedIntegerType()) return;
10193
10194 // See if either argument is a literal zero.
10195 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10196 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10197 if (!MTE) return false;
10198 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10199 if (!Num) return false;
10200 if (Num->getValue() != 0) return false;
10201 return true;
10202 };
10203
10204 const Expr *FirstArg = Call->getArg(Arg: 0);
10205 const Expr *SecondArg = Call->getArg(Arg: 1);
10206 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10207 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10208
10209 // Only warn when exactly one argument is zero.
10210 if (IsFirstArgZero == IsSecondArgZero) return;
10211
10212 SourceRange FirstRange = FirstArg->getSourceRange();
10213 SourceRange SecondRange = SecondArg->getSourceRange();
10214
10215 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10216
10217 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10218 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10219
10220 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10221 SourceRange RemovalRange;
10222 if (IsFirstArgZero) {
10223 RemovalRange = SourceRange(FirstRange.getBegin(),
10224 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10225 } else {
10226 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10227 SecondRange.getEnd());
10228 }
10229
10230 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10231 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10232 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10233}
10234
10235//===--- CHECK: Standard memory functions ---------------------------------===//
10236
10237/// Takes the expression passed to the size_t parameter of functions
10238/// such as memcmp, strncat, etc and warns if it's a comparison.
10239///
10240/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10241static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10242 const IdentifierInfo *FnName,
10243 SourceLocation FnLoc,
10244 SourceLocation RParenLoc) {
10245 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10246 if (!Size)
10247 return false;
10248
10249 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10250 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10251 return false;
10252
10253 SourceRange SizeRange = Size->getSourceRange();
10254 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10255 << SizeRange << FnName;
10256 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10257 << FnName
10258 << FixItHint::CreateInsertion(
10259 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10260 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10261 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10262 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10263 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10264 Code: ")");
10265
10266 return true;
10267}
10268
10269/// Determine whether the given type is or contains a dynamic class type
10270/// (e.g., whether it has a vtable).
10271static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10272 bool &IsContained) {
10273 // Look through array types while ignoring qualifiers.
10274 const Type *Ty = T->getBaseElementTypeUnsafe();
10275 IsContained = false;
10276
10277 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10278 RD = RD ? RD->getDefinition() : nullptr;
10279 if (!RD || RD->isInvalidDecl())
10280 return nullptr;
10281
10282 if (RD->isDynamicClass())
10283 return RD;
10284
10285 // Check all the fields. If any bases were dynamic, the class is dynamic.
10286 // It's impossible for a class to transitively contain itself by value, so
10287 // infinite recursion is impossible.
10288 for (auto *FD : RD->fields()) {
10289 bool SubContained;
10290 if (const CXXRecordDecl *ContainedRD =
10291 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10292 IsContained = true;
10293 return ContainedRD;
10294 }
10295 }
10296
10297 return nullptr;
10298}
10299
10300static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10301 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10302 if (Unary->getKind() == UETT_SizeOf)
10303 return Unary;
10304 return nullptr;
10305}
10306
10307/// If E is a sizeof expression, returns its argument expression,
10308/// otherwise returns NULL.
10309static const Expr *getSizeOfExprArg(const Expr *E) {
10310 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10311 if (!SizeOf->isArgumentType())
10312 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10313 return nullptr;
10314}
10315
10316/// If E is a sizeof expression, returns its argument type.
10317static QualType getSizeOfArgType(const Expr *E) {
10318 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10319 return SizeOf->getTypeOfArgument();
10320 return QualType();
10321}
10322
10323namespace {
10324
10325struct SearchNonTrivialToInitializeField
10326 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10327 using Super =
10328 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10329
10330 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10331
10332 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10333 SourceLocation SL) {
10334 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10335 asDerived().visitArray(PDIK, AT, SL);
10336 return;
10337 }
10338
10339 Super::visitWithKind(PDIK, FT, Args&: SL);
10340 }
10341
10342 void visitARCStrong(QualType FT, SourceLocation SL) {
10343 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10344 }
10345 void visitARCWeak(QualType FT, SourceLocation SL) {
10346 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10347 }
10348 void visitStruct(QualType FT, SourceLocation SL) {
10349 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10350 visit(FT: FD->getType(), Args: FD->getLocation());
10351 }
10352 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10353 const ArrayType *AT, SourceLocation SL) {
10354 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10355 }
10356 void visitTrivial(QualType FT, SourceLocation SL) {}
10357
10358 static void diag(QualType RT, const Expr *E, Sema &S) {
10359 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10360 }
10361
10362 ASTContext &getContext() { return S.getASTContext(); }
10363
10364 const Expr *E;
10365 Sema &S;
10366};
10367
10368struct SearchNonTrivialToCopyField
10369 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10370 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10371
10372 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10373
10374 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10375 SourceLocation SL) {
10376 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10377 asDerived().visitArray(PCK, AT, SL);
10378 return;
10379 }
10380
10381 Super::visitWithKind(PCK, FT, Args&: SL);
10382 }
10383
10384 void visitARCStrong(QualType FT, SourceLocation SL) {
10385 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10386 }
10387 void visitARCWeak(QualType FT, SourceLocation SL) {
10388 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10389 }
10390 void visitPtrAuth(QualType FT, SourceLocation SL) {
10391 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10392 }
10393 void visitStruct(QualType FT, SourceLocation SL) {
10394 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10395 visit(FT: FD->getType(), Args: FD->getLocation());
10396 }
10397 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10398 SourceLocation SL) {
10399 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10400 }
10401 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10402 SourceLocation SL) {}
10403 void visitTrivial(QualType FT, SourceLocation SL) {}
10404 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10405
10406 static void diag(QualType RT, const Expr *E, Sema &S) {
10407 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10408 }
10409
10410 ASTContext &getContext() { return S.getASTContext(); }
10411
10412 const Expr *E;
10413 Sema &S;
10414};
10415
10416}
10417
10418/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10419static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10420 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10421
10422 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
10423 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10424 return false;
10425
10426 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
10427 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
10428 }
10429
10430 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
10431}
10432
10433/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10434///
10435/// \code
10436/// #define MACRO 0
10437/// foo(MACRO);
10438/// foo(0);
10439/// \endcode
10440///
10441/// This should return true for the first call to foo, but not for the second
10442/// (regardless of whether foo is a macro or function).
10443static bool isArgumentExpandedFromMacro(SourceManager &SM,
10444 SourceLocation CallLoc,
10445 SourceLocation ArgLoc) {
10446 if (!CallLoc.isMacroID())
10447 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
10448
10449 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
10450 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
10451}
10452
10453/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10454/// last two arguments transposed.
10455static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10456 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10457 return;
10458
10459 const Expr *SizeArg =
10460 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10461
10462 auto isLiteralZero = [](const Expr *E) {
10463 return (isa<IntegerLiteral>(Val: E) &&
10464 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
10465 (isa<CharacterLiteral>(Val: E) &&
10466 cast<CharacterLiteral>(Val: E)->getValue() == 0);
10467 };
10468
10469 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10470 SourceLocation CallLoc = Call->getRParenLoc();
10471 SourceManager &SM = S.getSourceManager();
10472 if (isLiteralZero(SizeArg) &&
10473 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
10474
10475 SourceLocation DiagLoc = SizeArg->getExprLoc();
10476
10477 // Some platforms #define bzero to __builtin_memset. See if this is the
10478 // case, and if so, emit a better diagnostic.
10479 if (BId == Builtin::BIbzero ||
10480 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10481 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
10482 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
10483 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
10484 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
10485 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
10486 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
10487 }
10488 return;
10489 }
10490
10491 // If the second argument to a memset is a sizeof expression and the third
10492 // isn't, this is also likely an error. This should catch
10493 // 'memset(buf, sizeof(buf), 0xff)'.
10494 if (BId == Builtin::BImemset &&
10495 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
10496 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
10497 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
10498 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
10499 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
10500 return;
10501 }
10502}
10503
10504void Sema::CheckMemaccessArguments(const CallExpr *Call,
10505 unsigned BId,
10506 IdentifierInfo *FnName) {
10507 assert(BId != 0);
10508
10509 // It is possible to have a non-standard definition of memset. Validate
10510 // we have enough arguments, and if not, abort further checking.
10511 unsigned ExpectedNumArgs =
10512 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10513 if (Call->getNumArgs() < ExpectedNumArgs)
10514 return;
10515
10516 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10517 BId == Builtin::BIstrndup ? 1 : 2);
10518 unsigned LenArg =
10519 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10520 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
10521
10522 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
10523 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10524 return;
10525
10526 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10527 CheckMemaccessSize(S&: *this, BId, Call);
10528
10529 // We have special checking when the length is a sizeof expression.
10530 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
10531 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
10532 llvm::FoldingSetNodeID SizeOfArgID;
10533
10534 // Although widely used, 'bzero' is not a standard function. Be more strict
10535 // with the argument types before allowing diagnostics and only allow the
10536 // form bzero(ptr, sizeof(...)).
10537 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10538 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10539 return;
10540
10541 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10542 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
10543 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
10544
10545 QualType DestTy = Dest->getType();
10546 QualType PointeeTy;
10547 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10548 PointeeTy = DestPtrTy->getPointeeType();
10549
10550 // Never warn about void type pointers. This can be used to suppress
10551 // false positives.
10552 if (PointeeTy->isVoidType())
10553 continue;
10554
10555 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10556 // actually comparing the expressions for equality. Because computing the
10557 // expression IDs can be expensive, we only do this if the diagnostic is
10558 // enabled.
10559 if (SizeOfArg &&
10560 !Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
10561 Loc: SizeOfArg->getExprLoc())) {
10562 // We only compute IDs for expressions if the warning is enabled, and
10563 // cache the sizeof arg's ID.
10564 if (SizeOfArgID == llvm::FoldingSetNodeID())
10565 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
10566 llvm::FoldingSetNodeID DestID;
10567 Dest->Profile(ID&: DestID, Context, Canonical: true);
10568 if (DestID == SizeOfArgID) {
10569 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10570 // over sizeof(src) as well.
10571 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10572 StringRef ReadableName = FnName->getName();
10573
10574 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest))
10575 if (UnaryOp->getOpcode() == UO_AddrOf)
10576 ActionIdx = 1; // If its an address-of operator, just remove it.
10577 if (!PointeeTy->isIncompleteType() &&
10578 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
10579 ActionIdx = 2; // If the pointee's size is sizeof(char),
10580 // suggest an explicit length.
10581
10582 // If the function is defined as a builtin macro, do not show macro
10583 // expansion.
10584 SourceLocation SL = SizeOfArg->getExprLoc();
10585 SourceRange DSR = Dest->getSourceRange();
10586 SourceRange SSR = SizeOfArg->getSourceRange();
10587 SourceManager &SM = getSourceManager();
10588
10589 if (SM.isMacroArgExpansion(Loc: SL)) {
10590 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
10591 SL = SM.getSpellingLoc(Loc: SL);
10592 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
10593 SM.getSpellingLoc(Loc: DSR.getEnd()));
10594 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
10595 SM.getSpellingLoc(Loc: SSR.getEnd()));
10596 }
10597
10598 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10599 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
10600 << ReadableName
10601 << PointeeTy
10602 << DestTy
10603 << DSR
10604 << SSR);
10605 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10606 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
10607 << ActionIdx
10608 << SSR);
10609
10610 break;
10611 }
10612 }
10613
10614 // Also check for cases where the sizeof argument is the exact same
10615 // type as the memory argument, and where it points to a user-defined
10616 // record type.
10617 if (SizeOfArgTy != QualType()) {
10618 if (PointeeTy->isRecordType() &&
10619 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
10620 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
10621 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
10622 << FnName << SizeOfArgTy << ArgIdx
10623 << PointeeTy << Dest->getSourceRange()
10624 << LenExpr->getSourceRange());
10625 break;
10626 }
10627 }
10628 } else if (DestTy->isArrayType()) {
10629 PointeeTy = DestTy;
10630 }
10631
10632 if (PointeeTy == QualType())
10633 continue;
10634
10635 // Always complain about dynamic classes.
10636 bool IsContained;
10637 if (const CXXRecordDecl *ContainedRD =
10638 getContainedDynamicClass(T: PointeeTy, IsContained)) {
10639
10640 unsigned OperationType = 0;
10641 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10642 // "overwritten" if we're warning about the destination for any call
10643 // but memcmp; otherwise a verb appropriate to the call.
10644 if (ArgIdx != 0 || IsCmp) {
10645 if (BId == Builtin::BImemcpy)
10646 OperationType = 1;
10647 else if(BId == Builtin::BImemmove)
10648 OperationType = 2;
10649 else if (IsCmp)
10650 OperationType = 3;
10651 }
10652
10653 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10654 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
10655 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10656 << IsContained << ContainedRD << OperationType
10657 << Call->getCallee()->getSourceRange());
10658 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10659 BId != Builtin::BImemset)
10660 DiagRuntimeBehavior(
10661 Loc: Dest->getExprLoc(), Statement: Dest,
10662 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
10663 << ArgIdx << FnName << PointeeTy
10664 << Call->getCallee()->getSourceRange());
10665 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10666
10667 // FIXME: Do not consider incomplete types even though they may be
10668 // completed later. GCC does not diagnose such code, but we may want to
10669 // consider diagnosing it in the future, perhaps under a different, but
10670 // related, diagnostic group.
10671 bool NonTriviallyCopyableCXXRecord =
10672 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10673 !PointeeTy.isTriviallyCopyableType(Context);
10674
10675 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10676 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
10677 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10678 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10679 << ArgIdx << FnName << PointeeTy << 0);
10680 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
10681 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10682 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10683 // FIXME: Limiting this warning to dest argument until we decide
10684 // whether it's valid for source argument too.
10685 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10686 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10687 << FnName << PointeeTy);
10688 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10689 RD->isNonTrivialToPrimitiveCopy()) {
10690 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10691 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10692 << ArgIdx << FnName << PointeeTy << 1);
10693 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
10694 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10695 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10696 // FIXME: Limiting this warning to dest argument until we decide
10697 // whether it's valid for source argument too.
10698 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10699 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10700 << FnName << PointeeTy);
10701 } else {
10702 continue;
10703 }
10704 } else
10705 continue;
10706
10707 DiagRuntimeBehavior(
10708 Loc: Dest->getExprLoc(), Statement: Dest,
10709 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
10710 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
10711 break;
10712 }
10713}
10714
10715// A little helper routine: ignore addition and subtraction of integer literals.
10716// This intentionally does not ignore all integer constant expressions because
10717// we don't want to remove sizeof().
10718static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10719 Ex = Ex->IgnoreParenCasts();
10720
10721 while (true) {
10722 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
10723 if (!BO || !BO->isAdditiveOp())
10724 break;
10725
10726 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10727 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10728
10729 if (isa<IntegerLiteral>(Val: RHS))
10730 Ex = LHS;
10731 else if (isa<IntegerLiteral>(Val: LHS))
10732 Ex = RHS;
10733 else
10734 break;
10735 }
10736
10737 return Ex;
10738}
10739
10740static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10741 ASTContext &Context) {
10742 // Only handle constant-sized or VLAs, but not flexible members.
10743 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
10744 // Only issue the FIXIT for arrays of size > 1.
10745 if (CAT->getZExtSize() <= 1)
10746 return false;
10747 } else if (!Ty->isVariableArrayType()) {
10748 return false;
10749 }
10750 return true;
10751}
10752
10753void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10754 IdentifierInfo *FnName) {
10755
10756 // Don't crash if the user has the wrong number of arguments
10757 unsigned NumArgs = Call->getNumArgs();
10758 if ((NumArgs != 3) && (NumArgs != 4))
10759 return;
10760
10761 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
10762 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
10763 const Expr *CompareWithSrc = nullptr;
10764
10765 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
10766 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10767 return;
10768
10769 // Look for 'strlcpy(dst, x, sizeof(x))'
10770 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
10771 CompareWithSrc = Ex;
10772 else {
10773 // Look for 'strlcpy(dst, x, strlen(x))'
10774 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
10775 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10776 SizeCall->getNumArgs() == 1)
10777 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
10778 }
10779 }
10780
10781 if (!CompareWithSrc)
10782 return;
10783
10784 // Determine if the argument to sizeof/strlen is equal to the source
10785 // argument. In principle there's all kinds of things you could do
10786 // here, for instance creating an == expression and evaluating it with
10787 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10788 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
10789 if (!SrcArgDRE)
10790 return;
10791
10792 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
10793 if (!CompareWithSrcDRE ||
10794 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10795 return;
10796
10797 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
10798 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
10799 << OriginalSizeArg->getSourceRange() << FnName;
10800
10801 // Output a FIXIT hint if the destination is an array (rather than a
10802 // pointer to an array). This could be enhanced to handle some
10803 // pointers if we know the actual size, like if DstArg is 'array+2'
10804 // we could say 'sizeof(array)-2'.
10805 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
10806 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
10807 return;
10808
10809 SmallString<128> sizeString;
10810 llvm::raw_svector_ostream OS(sizeString);
10811 OS << "sizeof(";
10812 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10813 OS << ")";
10814
10815 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
10816 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
10817 Code: OS.str());
10818}
10819
10820/// Check if two expressions refer to the same declaration.
10821static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10822 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
10823 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
10824 return D1->getDecl() == D2->getDecl();
10825 return false;
10826}
10827
10828static const Expr *getStrlenExprArg(const Expr *E) {
10829 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
10830 const FunctionDecl *FD = CE->getDirectCallee();
10831 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10832 return nullptr;
10833 return CE->getArg(Arg: 0)->IgnoreParenCasts();
10834 }
10835 return nullptr;
10836}
10837
10838void Sema::CheckStrncatArguments(const CallExpr *CE,
10839 const IdentifierInfo *FnName) {
10840 // Don't crash if the user has the wrong number of arguments.
10841 if (CE->getNumArgs() < 3)
10842 return;
10843 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
10844 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
10845 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
10846
10847 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
10848 RParenLoc: CE->getRParenLoc()))
10849 return;
10850
10851 // Identify common expressions, which are wrongly used as the size argument
10852 // to strncat and may lead to buffer overflows.
10853 unsigned PatternType = 0;
10854 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
10855 // - sizeof(dst)
10856 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
10857 PatternType = 1;
10858 // - sizeof(src)
10859 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
10860 PatternType = 2;
10861 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
10862 if (BE->getOpcode() == BO_Sub) {
10863 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10864 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10865 // - sizeof(dst) - strlen(dst)
10866 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
10867 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
10868 PatternType = 1;
10869 // - sizeof(src) - (anything)
10870 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
10871 PatternType = 2;
10872 }
10873 }
10874
10875 if (PatternType == 0)
10876 return;
10877
10878 // Generate the diagnostic.
10879 SourceLocation SL = LenArg->getBeginLoc();
10880 SourceRange SR = LenArg->getSourceRange();
10881 SourceManager &SM = getSourceManager();
10882
10883 // If the function is defined as a builtin macro, do not show macro expansion.
10884 if (SM.isMacroArgExpansion(Loc: SL)) {
10885 SL = SM.getSpellingLoc(Loc: SL);
10886 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
10887 SM.getSpellingLoc(Loc: SR.getEnd()));
10888 }
10889
10890 // Check if the destination is an array (rather than a pointer to an array).
10891 QualType DstTy = DstArg->getType();
10892 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
10893 Context);
10894 if (!isKnownSizeArray) {
10895 if (PatternType == 1)
10896 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
10897 else
10898 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
10899 return;
10900 }
10901
10902 if (PatternType == 1)
10903 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
10904 else
10905 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
10906
10907 SmallString<128> sizeString;
10908 llvm::raw_svector_ostream OS(sizeString);
10909 OS << "sizeof(";
10910 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10911 OS << ") - ";
10912 OS << "strlen(";
10913 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10914 OS << ") - 1";
10915
10916 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
10917 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
10918}
10919
10920namespace {
10921void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10922 const UnaryOperator *UnaryExpr, const Decl *D) {
10923 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
10924 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
10925 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
10926 return;
10927 }
10928}
10929
10930void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10931 const UnaryOperator *UnaryExpr) {
10932 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
10933 const Decl *D = Lvalue->getDecl();
10934 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10935 if (!DD->getType()->isReferenceType())
10936 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10937 }
10938 }
10939
10940 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
10941 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10942 D: Lvalue->getMemberDecl());
10943}
10944
10945void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10946 const UnaryOperator *UnaryExpr) {
10947 const auto *Lambda = dyn_cast<LambdaExpr>(
10948 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10949 if (!Lambda)
10950 return;
10951
10952 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
10953 << CalleeName << 2 /*object: lambda expression*/;
10954}
10955
10956void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10957 const DeclRefExpr *Lvalue) {
10958 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
10959 if (Var == nullptr)
10960 return;
10961
10962 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
10963 << CalleeName << 0 /*object: */ << Var;
10964}
10965
10966void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10967 const CastExpr *Cast) {
10968 SmallString<128> SizeString;
10969 llvm::raw_svector_ostream OS(SizeString);
10970
10971 clang::CastKind Kind = Cast->getCastKind();
10972 if (Kind == clang::CK_BitCast &&
10973 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10974 return;
10975 if (Kind == clang::CK_IntegralToPointer &&
10976 !isa<IntegerLiteral>(
10977 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10978 return;
10979
10980 switch (Cast->getCastKind()) {
10981 case clang::CK_BitCast:
10982 case clang::CK_IntegralToPointer:
10983 case clang::CK_FunctionToPointerDecay:
10984 OS << '\'';
10985 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
10986 OS << '\'';
10987 break;
10988 default:
10989 return;
10990 }
10991
10992 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
10993 << CalleeName << 0 /*object: */ << OS.str();
10994}
10995} // namespace
10996
10997void Sema::CheckFreeArguments(const CallExpr *E) {
10998 const std::string CalleeName =
10999 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11000
11001 { // Prefer something that doesn't involve a cast to make things simpler.
11002 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11003 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11004 switch (UnaryExpr->getOpcode()) {
11005 case UnaryOperator::Opcode::UO_AddrOf:
11006 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11007 case UnaryOperator::Opcode::UO_Plus:
11008 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11009 default:
11010 break;
11011 }
11012
11013 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11014 if (Lvalue->getType()->isArrayType())
11015 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11016
11017 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11018 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11019 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11020 return;
11021 }
11022
11023 if (isa<BlockExpr>(Val: Arg)) {
11024 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11025 << CalleeName << 1 /*object: block*/;
11026 return;
11027 }
11028 }
11029 // Maybe the cast was important, check after the other cases.
11030 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11031 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11032}
11033
11034void
11035Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11036 SourceLocation ReturnLoc,
11037 bool isObjCMethod,
11038 const AttrVec *Attrs,
11039 const FunctionDecl *FD) {
11040 // Check if the return value is null but should not be.
11041 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11042 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11043 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11044 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11045 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11046
11047 // C++11 [basic.stc.dynamic.allocation]p4:
11048 // If an allocation function declared with a non-throwing
11049 // exception-specification fails to allocate storage, it shall return
11050 // a null pointer. Any other allocation function that fails to allocate
11051 // storage shall indicate failure only by throwing an exception [...]
11052 if (FD) {
11053 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11054 if (Op == OO_New || Op == OO_Array_New) {
11055 const FunctionProtoType *Proto
11056 = FD->getType()->castAs<FunctionProtoType>();
11057 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11058 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11059 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11060 << FD << getLangOpts().CPlusPlus11;
11061 }
11062 }
11063
11064 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11065 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11066 }
11067
11068 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11069 // here prevent the user from using a PPC MMA type as trailing return type.
11070 if (Context.getTargetInfo().getTriple().isPPC64())
11071 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11072}
11073
11074void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11075 const Expr *RHS, BinaryOperatorKind Opcode) {
11076 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11077 return;
11078
11079 // Match and capture subexpressions such as "(float) X == 0.1".
11080 const FloatingLiteral *FPLiteral;
11081 const CastExpr *FPCast;
11082 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11083 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11084 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11085 return FPLiteral && FPCast;
11086 };
11087
11088 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11089 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11090 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11091 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11092 TargetTy->isFloatingPoint()) {
11093 bool Lossy;
11094 llvm::APFloat TargetC = FPLiteral->getValue();
11095 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11096 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11097 if (Lossy) {
11098 // If the literal cannot be represented in the source type, then a
11099 // check for == is always false and check for != is always true.
11100 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11101 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11102 << LHS->getSourceRange() << RHS->getSourceRange();
11103 return;
11104 }
11105 }
11106 }
11107
11108 // Match a more general floating-point equality comparison (-Wfloat-equal).
11109 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11110 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11111
11112 // Special case: check for x == x (which is OK).
11113 // Do not emit warnings for such cases.
11114 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11115 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11116 if (DRL->getDecl() == DRR->getDecl())
11117 return;
11118
11119 // Special case: check for comparisons against literals that can be exactly
11120 // represented by APFloat. In such cases, do not emit a warning. This
11121 // is a heuristic: often comparison against such literals are used to
11122 // detect if a value in a variable has not changed. This clearly can
11123 // lead to false negatives.
11124 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11125 if (FLL->isExact())
11126 return;
11127 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11128 if (FLR->isExact())
11129 return;
11130
11131 // Check for comparisons with builtin types.
11132 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11133 CL && CL->getBuiltinCallee())
11134 return;
11135
11136 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11137 CR && CR->getBuiltinCallee())
11138 return;
11139
11140 // Emit the diagnostic.
11141 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11142 << LHS->getSourceRange() << RHS->getSourceRange();
11143}
11144
11145//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11146//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11147
11148namespace {
11149
11150/// Structure recording the 'active' range of an integer-valued
11151/// expression.
11152struct IntRange {
11153 /// The number of bits active in the int. Note that this includes exactly one
11154 /// sign bit if !NonNegative.
11155 unsigned Width;
11156
11157 /// True if the int is known not to have negative values. If so, all leading
11158 /// bits before Width are known zero, otherwise they are known to be the
11159 /// same as the MSB within Width.
11160 bool NonNegative;
11161
11162 IntRange(unsigned Width, bool NonNegative)
11163 : Width(Width), NonNegative(NonNegative) {}
11164
11165 /// Number of bits excluding the sign bit.
11166 unsigned valueBits() const {
11167 return NonNegative ? Width : Width - 1;
11168 }
11169
11170 /// Returns the range of the bool type.
11171 static IntRange forBoolType() {
11172 return IntRange(1, true);
11173 }
11174
11175 /// Returns the range of an opaque value of the given integral type.
11176 static IntRange forValueOfType(ASTContext &C, QualType T) {
11177 return forValueOfCanonicalType(C,
11178 T: T->getCanonicalTypeInternal().getTypePtr());
11179 }
11180
11181 /// Returns the range of an opaque value of a canonical integral type.
11182 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11183 assert(T->isCanonicalUnqualified());
11184
11185 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11186 T = VT->getElementType().getTypePtr();
11187 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11188 T = CT->getElementType().getTypePtr();
11189 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11190 T = AT->getValueType().getTypePtr();
11191
11192 if (!C.getLangOpts().CPlusPlus) {
11193 // For enum types in C code, use the underlying datatype.
11194 if (const auto *ED = T->getAsEnumDecl())
11195 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11196 } else if (auto *Enum = T->getAsEnumDecl()) {
11197 // For enum types in C++, use the known bit width of the enumerators.
11198 // In C++11, enums can have a fixed underlying type. Use this type to
11199 // compute the range.
11200 if (Enum->isFixed()) {
11201 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11202 !Enum->getIntegerType()->isSignedIntegerType());
11203 }
11204
11205 unsigned NumPositive = Enum->getNumPositiveBits();
11206 unsigned NumNegative = Enum->getNumNegativeBits();
11207
11208 if (NumNegative == 0)
11209 return IntRange(NumPositive, true/*NonNegative*/);
11210 else
11211 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11212 false/*NonNegative*/);
11213 }
11214
11215 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11216 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11217
11218 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11219 assert(BT->isInteger());
11220
11221 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11222 }
11223
11224 /// Returns the "target" range of a canonical integral type, i.e.
11225 /// the range of values expressible in the type.
11226 ///
11227 /// This matches forValueOfCanonicalType except that enums have the
11228 /// full range of their type, not the range of their enumerators.
11229 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11230 assert(T->isCanonicalUnqualified());
11231
11232 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11233 T = VT->getElementType().getTypePtr();
11234 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11235 T = CT->getElementType().getTypePtr();
11236 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11237 T = AT->getValueType().getTypePtr();
11238 if (const auto *ED = T->getAsEnumDecl())
11239 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11240
11241 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11242 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11243
11244 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11245 assert(BT->isInteger());
11246
11247 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11248 }
11249
11250 /// Returns the supremum of two ranges: i.e. their conservative merge.
11251 static IntRange join(IntRange L, IntRange R) {
11252 bool Unsigned = L.NonNegative && R.NonNegative;
11253 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11254 L.NonNegative && R.NonNegative);
11255 }
11256
11257 /// Return the range of a bitwise-AND of the two ranges.
11258 static IntRange bit_and(IntRange L, IntRange R) {
11259 unsigned Bits = std::max(a: L.Width, b: R.Width);
11260 bool NonNegative = false;
11261 if (L.NonNegative) {
11262 Bits = std::min(a: Bits, b: L.Width);
11263 NonNegative = true;
11264 }
11265 if (R.NonNegative) {
11266 Bits = std::min(a: Bits, b: R.Width);
11267 NonNegative = true;
11268 }
11269 return IntRange(Bits, NonNegative);
11270 }
11271
11272 /// Return the range of a sum of the two ranges.
11273 static IntRange sum(IntRange L, IntRange R) {
11274 bool Unsigned = L.NonNegative && R.NonNegative;
11275 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11276 Unsigned);
11277 }
11278
11279 /// Return the range of a difference of the two ranges.
11280 static IntRange difference(IntRange L, IntRange R) {
11281 // We need a 1-bit-wider range if:
11282 // 1) LHS can be negative: least value can be reduced.
11283 // 2) RHS can be negative: greatest value can be increased.
11284 bool CanWiden = !L.NonNegative || !R.NonNegative;
11285 bool Unsigned = L.NonNegative && R.Width == 0;
11286 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11287 !Unsigned,
11288 Unsigned);
11289 }
11290
11291 /// Return the range of a product of the two ranges.
11292 static IntRange product(IntRange L, IntRange R) {
11293 // If both LHS and RHS can be negative, we can form
11294 // -2^L * -2^R = 2^(L + R)
11295 // which requires L + R + 1 value bits to represent.
11296 bool CanWiden = !L.NonNegative && !R.NonNegative;
11297 bool Unsigned = L.NonNegative && R.NonNegative;
11298 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11299 Unsigned);
11300 }
11301
11302 /// Return the range of a remainder operation between the two ranges.
11303 static IntRange rem(IntRange L, IntRange R) {
11304 // The result of a remainder can't be larger than the result of
11305 // either side. The sign of the result is the sign of the LHS.
11306 bool Unsigned = L.NonNegative;
11307 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11308 Unsigned);
11309 }
11310};
11311
11312} // namespace
11313
11314static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11315 if (value.isSigned() && value.isNegative())
11316 return IntRange(value.getSignificantBits(), false);
11317
11318 if (value.getBitWidth() > MaxWidth)
11319 value = value.trunc(width: MaxWidth);
11320
11321 // isNonNegative() just checks the sign bit without considering
11322 // signedness.
11323 return IntRange(value.getActiveBits(), true);
11324}
11325
11326static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11327 if (result.isInt())
11328 return GetValueRange(value&: result.getInt(), MaxWidth);
11329
11330 if (result.isVector()) {
11331 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11332 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11333 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11334 R = IntRange::join(L: R, R: El);
11335 }
11336 return R;
11337 }
11338
11339 if (result.isComplexInt()) {
11340 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11341 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11342 return IntRange::join(L: R, R: I);
11343 }
11344
11345 // This can happen with lossless casts to intptr_t of "based" lvalues.
11346 // Assume it might use arbitrary bits.
11347 // FIXME: The only reason we need to pass the type in here is to get
11348 // the sign right on this one case. It would be nice if APValue
11349 // preserved this.
11350 assert(result.isLValue() || result.isAddrLabelDiff());
11351 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11352}
11353
11354static QualType GetExprType(const Expr *E) {
11355 QualType Ty = E->getType();
11356 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11357 Ty = AtomicRHS->getValueType();
11358 return Ty;
11359}
11360
11361/// Attempts to estimate an approximate range for the given integer expression.
11362/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11363/// reliable estimation cannot be determined.
11364///
11365/// \param MaxWidth The width to which the value will be truncated.
11366/// \param InConstantContext If \c true, interpret the expression within a
11367/// constant context.
11368/// \param Approximate If \c true, provide a likely range of values by assuming
11369/// that arithmetic on narrower types remains within those types.
11370/// If \c false, return a range that includes all possible values
11371/// resulting from the expression.
11372/// \returns A range of values that the expression might take, or
11373/// std::nullopt if a reliable estimation cannot be determined.
11374static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11375 unsigned MaxWidth,
11376 bool InConstantContext,
11377 bool Approximate) {
11378 E = E->IgnoreParens();
11379
11380 // Try a full evaluation first.
11381 Expr::EvalResult result;
11382 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11383 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11384
11385 // I think we only want to look through implicit casts here; if the
11386 // user has an explicit widening cast, we should treat the value as
11387 // being of the new, wider type.
11388 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11389 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11390 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
11391 Approximate);
11392
11393 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
11394
11395 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11396 CE->getCastKind() == CK_BooleanToSignedIntegral;
11397
11398 // Assume that non-integer casts can span the full range of the type.
11399 if (!isIntegerCast)
11400 return OutputTypeRange;
11401
11402 std::optional<IntRange> SubRange = TryGetExprRange(
11403 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
11404 InConstantContext, Approximate);
11405 if (!SubRange)
11406 return std::nullopt;
11407
11408 // Bail out if the subexpr's range is as wide as the cast type.
11409 if (SubRange->Width >= OutputTypeRange.Width)
11410 return OutputTypeRange;
11411
11412 // Otherwise, we take the smaller width, and we're non-negative if
11413 // either the output type or the subexpr is.
11414 return IntRange(SubRange->Width,
11415 SubRange->NonNegative || OutputTypeRange.NonNegative);
11416 }
11417
11418 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
11419 // If we can fold the condition, just take that operand.
11420 bool CondResult;
11421 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
11422 return TryGetExprRange(
11423 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11424 InConstantContext, Approximate);
11425
11426 // Otherwise, conservatively merge.
11427 // TryGetExprRange requires an integer expression, but a throw expression
11428 // results in a void type.
11429 Expr *TrueExpr = CO->getTrueExpr();
11430 if (TrueExpr->getType()->isVoidType())
11431 return std::nullopt;
11432
11433 std::optional<IntRange> L =
11434 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
11435 if (!L)
11436 return std::nullopt;
11437
11438 Expr *FalseExpr = CO->getFalseExpr();
11439 if (FalseExpr->getType()->isVoidType())
11440 return std::nullopt;
11441
11442 std::optional<IntRange> R =
11443 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
11444 if (!R)
11445 return std::nullopt;
11446
11447 return IntRange::join(L: *L, R: *R);
11448 }
11449
11450 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
11451 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11452
11453 switch (BO->getOpcode()) {
11454 case BO_Cmp:
11455 llvm_unreachable("builtin <=> should have class type");
11456
11457 // Boolean-valued operations are single-bit and positive.
11458 case BO_LAnd:
11459 case BO_LOr:
11460 case BO_LT:
11461 case BO_GT:
11462 case BO_LE:
11463 case BO_GE:
11464 case BO_EQ:
11465 case BO_NE:
11466 return IntRange::forBoolType();
11467
11468 // The type of the assignments is the type of the LHS, so the RHS
11469 // is not necessarily the same type.
11470 case BO_MulAssign:
11471 case BO_DivAssign:
11472 case BO_RemAssign:
11473 case BO_AddAssign:
11474 case BO_SubAssign:
11475 case BO_XorAssign:
11476 case BO_OrAssign:
11477 // TODO: bitfields?
11478 return IntRange::forValueOfType(C, T: GetExprType(E));
11479
11480 // Simple assignments just pass through the RHS, which will have
11481 // been coerced to the LHS type.
11482 case BO_Assign:
11483 // TODO: bitfields?
11484 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11485 Approximate);
11486
11487 // Operations with opaque sources are black-listed.
11488 case BO_PtrMemD:
11489 case BO_PtrMemI:
11490 return IntRange::forValueOfType(C, T: GetExprType(E));
11491
11492 // Bitwise-and uses the *infinum* of the two source ranges.
11493 case BO_And:
11494 case BO_AndAssign:
11495 Combine = IntRange::bit_and;
11496 break;
11497
11498 // Left shift gets black-listed based on a judgement call.
11499 case BO_Shl:
11500 // ...except that we want to treat '1 << (blah)' as logically
11501 // positive. It's an important idiom.
11502 if (IntegerLiteral *I
11503 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
11504 if (I->getValue() == 1) {
11505 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
11506 return IntRange(R.Width, /*NonNegative*/ true);
11507 }
11508 }
11509 [[fallthrough]];
11510
11511 case BO_ShlAssign:
11512 return IntRange::forValueOfType(C, T: GetExprType(E));
11513
11514 // Right shift by a constant can narrow its left argument.
11515 case BO_Shr:
11516 case BO_ShrAssign: {
11517 std::optional<IntRange> L = TryGetExprRange(
11518 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11519 if (!L)
11520 return std::nullopt;
11521
11522 // If the shift amount is a positive constant, drop the width by
11523 // that much.
11524 if (std::optional<llvm::APSInt> shift =
11525 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11526 if (shift->isNonNegative()) {
11527 if (shift->uge(RHS: L->Width))
11528 L->Width = (L->NonNegative ? 0 : 1);
11529 else
11530 L->Width -= shift->getZExtValue();
11531 }
11532 }
11533
11534 return L;
11535 }
11536
11537 // Comma acts as its right operand.
11538 case BO_Comma:
11539 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11540 Approximate);
11541
11542 case BO_Add:
11543 if (!Approximate)
11544 Combine = IntRange::sum;
11545 break;
11546
11547 case BO_Sub:
11548 if (BO->getLHS()->getType()->isPointerType())
11549 return IntRange::forValueOfType(C, T: GetExprType(E));
11550 if (!Approximate)
11551 Combine = IntRange::difference;
11552 break;
11553
11554 case BO_Mul:
11555 if (!Approximate)
11556 Combine = IntRange::product;
11557 break;
11558
11559 // The width of a division result is mostly determined by the size
11560 // of the LHS.
11561 case BO_Div: {
11562 // Don't 'pre-truncate' the operands.
11563 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
11564 std::optional<IntRange> L = TryGetExprRange(
11565 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11566 if (!L)
11567 return std::nullopt;
11568
11569 // If the divisor is constant, use that.
11570 if (std::optional<llvm::APSInt> divisor =
11571 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11572 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11573 if (log2 >= L->Width)
11574 L->Width = (L->NonNegative ? 0 : 1);
11575 else
11576 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
11577 return L;
11578 }
11579
11580 // Otherwise, just use the LHS's width.
11581 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11582 // could be -1.
11583 std::optional<IntRange> R = TryGetExprRange(
11584 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11585 if (!R)
11586 return std::nullopt;
11587
11588 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11589 }
11590
11591 case BO_Rem:
11592 Combine = IntRange::rem;
11593 break;
11594
11595 // The default behavior is okay for these.
11596 case BO_Xor:
11597 case BO_Or:
11598 break;
11599 }
11600
11601 // Combine the two ranges, but limit the result to the type in which we
11602 // performed the computation.
11603 QualType T = GetExprType(E);
11604 unsigned opWidth = C.getIntWidth(T);
11605 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
11606 InConstantContext, Approximate);
11607 if (!L)
11608 return std::nullopt;
11609
11610 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
11611 InConstantContext, Approximate);
11612 if (!R)
11613 return std::nullopt;
11614
11615 IntRange C = Combine(*L, *R);
11616 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11617 C.Width = std::min(a: C.Width, b: MaxWidth);
11618 return C;
11619 }
11620
11621 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
11622 switch (UO->getOpcode()) {
11623 // Boolean-valued operations are white-listed.
11624 case UO_LNot:
11625 return IntRange::forBoolType();
11626
11627 // Operations with opaque sources are black-listed.
11628 case UO_Deref:
11629 case UO_AddrOf: // should be impossible
11630 return IntRange::forValueOfType(C, T: GetExprType(E));
11631
11632 case UO_Minus: {
11633 if (E->getType()->isUnsignedIntegerType()) {
11634 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11635 Approximate);
11636 }
11637
11638 std::optional<IntRange> SubRange = TryGetExprRange(
11639 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11640
11641 if (!SubRange)
11642 return std::nullopt;
11643
11644 // If the range was previously non-negative, we need an extra bit for the
11645 // sign bit. Otherwise, we need an extra bit because the negation of the
11646 // most-negative value is one bit wider than that value.
11647 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
11648 }
11649
11650 case UO_Not: {
11651 if (E->getType()->isUnsignedIntegerType()) {
11652 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11653 Approximate);
11654 }
11655
11656 std::optional<IntRange> SubRange = TryGetExprRange(
11657 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11658
11659 if (!SubRange)
11660 return std::nullopt;
11661
11662 // The width increments by 1 if the sub-expression cannot be negative
11663 // since it now can be.
11664 return IntRange(
11665 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
11666 false);
11667 }
11668
11669 default:
11670 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11671 Approximate);
11672 }
11673 }
11674
11675 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
11676 return TryGetExprRange(C, E: OVE->getSourceExpr(), MaxWidth, InConstantContext,
11677 Approximate);
11678
11679 if (const auto *BitField = E->getSourceBitField())
11680 return IntRange(BitField->getBitWidthValue(),
11681 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11682
11683 if (GetExprType(E)->isVoidType())
11684 return std::nullopt;
11685
11686 return IntRange::forValueOfType(C, T: GetExprType(E));
11687}
11688
11689static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11690 bool InConstantContext,
11691 bool Approximate) {
11692 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
11693 Approximate);
11694}
11695
11696/// Checks whether the given value, which currently has the given
11697/// source semantics, has the same value when coerced through the
11698/// target semantics.
11699static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11700 const llvm::fltSemantics &Src,
11701 const llvm::fltSemantics &Tgt) {
11702 llvm::APFloat truncated = value;
11703
11704 bool ignored;
11705 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11706 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11707
11708 return truncated.bitwiseIsEqual(RHS: value);
11709}
11710
11711/// Checks whether the given value, which currently has the given
11712/// source semantics, has the same value when coerced through the
11713/// target semantics.
11714///
11715/// The value might be a vector of floats (or a complex number).
11716static bool IsSameFloatAfterCast(const APValue &value,
11717 const llvm::fltSemantics &Src,
11718 const llvm::fltSemantics &Tgt) {
11719 if (value.isFloat())
11720 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
11721
11722 if (value.isVector()) {
11723 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11724 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
11725 return false;
11726 return true;
11727 }
11728
11729 assert(value.isComplexFloat());
11730 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
11731 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
11732}
11733
11734static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11735 bool IsListInit = false);
11736
11737static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11738 // Suppress cases where we are comparing against an enum constant.
11739 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
11740 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
11741 return true;
11742
11743 // Suppress cases where the value is expanded from a macro, unless that macro
11744 // is how a language represents a boolean literal. This is the case in both C
11745 // and Objective-C.
11746 SourceLocation BeginLoc = E->getBeginLoc();
11747 if (BeginLoc.isMacroID()) {
11748 StringRef MacroName = Lexer::getImmediateMacroName(
11749 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
11750 return MacroName != "YES" && MacroName != "NO" &&
11751 MacroName != "true" && MacroName != "false";
11752 }
11753
11754 return false;
11755}
11756
11757static bool isKnownToHaveUnsignedValue(const Expr *E) {
11758 return E->getType()->isIntegerType() &&
11759 (!E->getType()->isSignedIntegerType() ||
11760 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11761}
11762
11763namespace {
11764/// The promoted range of values of a type. In general this has the
11765/// following structure:
11766///
11767/// |-----------| . . . |-----------|
11768/// ^ ^ ^ ^
11769/// Min HoleMin HoleMax Max
11770///
11771/// ... where there is only a hole if a signed type is promoted to unsigned
11772/// (in which case Min and Max are the smallest and largest representable
11773/// values).
11774struct PromotedRange {
11775 // Min, or HoleMax if there is a hole.
11776 llvm::APSInt PromotedMin;
11777 // Max, or HoleMin if there is a hole.
11778 llvm::APSInt PromotedMax;
11779
11780 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11781 if (R.Width == 0)
11782 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11783 else if (R.Width >= BitWidth && !Unsigned) {
11784 // Promotion made the type *narrower*. This happens when promoting
11785 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11786 // Treat all values of 'signed int' as being in range for now.
11787 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
11788 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
11789 } else {
11790 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
11791 .extOrTrunc(width: BitWidth);
11792 PromotedMin.setIsUnsigned(Unsigned);
11793
11794 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
11795 .extOrTrunc(width: BitWidth);
11796 PromotedMax.setIsUnsigned(Unsigned);
11797 }
11798 }
11799
11800 // Determine whether this range is contiguous (has no hole).
11801 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11802
11803 // Where a constant value is within the range.
11804 enum ComparisonResult {
11805 LT = 0x1,
11806 LE = 0x2,
11807 GT = 0x4,
11808 GE = 0x8,
11809 EQ = 0x10,
11810 NE = 0x20,
11811 InRangeFlag = 0x40,
11812
11813 Less = LE | LT | NE,
11814 Min = LE | InRangeFlag,
11815 InRange = InRangeFlag,
11816 Max = GE | InRangeFlag,
11817 Greater = GE | GT | NE,
11818
11819 OnlyValue = LE | GE | EQ | InRangeFlag,
11820 InHole = NE
11821 };
11822
11823 ComparisonResult compare(const llvm::APSInt &Value) const {
11824 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11825 Value.isUnsigned() == PromotedMin.isUnsigned());
11826 if (!isContiguous()) {
11827 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11828 if (Value.isMinValue()) return Min;
11829 if (Value.isMaxValue()) return Max;
11830 if (Value >= PromotedMin) return InRange;
11831 if (Value <= PromotedMax) return InRange;
11832 return InHole;
11833 }
11834
11835 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
11836 case -1: return Less;
11837 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11838 case 1:
11839 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
11840 case -1: return InRange;
11841 case 0: return Max;
11842 case 1: return Greater;
11843 }
11844 }
11845
11846 llvm_unreachable("impossible compare result");
11847 }
11848
11849 static std::optional<StringRef>
11850 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11851 if (Op == BO_Cmp) {
11852 ComparisonResult LTFlag = LT, GTFlag = GT;
11853 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
11854
11855 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11856 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11857 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11858 return std::nullopt;
11859 }
11860
11861 ComparisonResult TrueFlag, FalseFlag;
11862 if (Op == BO_EQ) {
11863 TrueFlag = EQ;
11864 FalseFlag = NE;
11865 } else if (Op == BO_NE) {
11866 TrueFlag = NE;
11867 FalseFlag = EQ;
11868 } else {
11869 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11870 TrueFlag = LT;
11871 FalseFlag = GE;
11872 } else {
11873 TrueFlag = GT;
11874 FalseFlag = LE;
11875 }
11876 if (Op == BO_GE || Op == BO_LE)
11877 std::swap(a&: TrueFlag, b&: FalseFlag);
11878 }
11879 if (R & TrueFlag)
11880 return StringRef("true");
11881 if (R & FalseFlag)
11882 return StringRef("false");
11883 return std::nullopt;
11884 }
11885};
11886}
11887
11888static bool HasEnumType(const Expr *E) {
11889 // Strip off implicit integral promotions.
11890 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11891 if (ICE->getCastKind() != CK_IntegralCast &&
11892 ICE->getCastKind() != CK_NoOp)
11893 break;
11894 E = ICE->getSubExpr();
11895 }
11896
11897 return E->getType()->isEnumeralType();
11898}
11899
11900static int classifyConstantValue(Expr *Constant) {
11901 // The values of this enumeration are used in the diagnostics
11902 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11903 enum ConstantValueKind {
11904 Miscellaneous = 0,
11905 LiteralTrue,
11906 LiteralFalse
11907 };
11908 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
11909 return BL->getValue() ? ConstantValueKind::LiteralTrue
11910 : ConstantValueKind::LiteralFalse;
11911 return ConstantValueKind::Miscellaneous;
11912}
11913
11914static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11915 Expr *Constant, Expr *Other,
11916 const llvm::APSInt &Value,
11917 bool RhsConstant) {
11918 if (S.inTemplateInstantiation())
11919 return false;
11920
11921 Expr *OriginalOther = Other;
11922
11923 Constant = Constant->IgnoreParenImpCasts();
11924 Other = Other->IgnoreParenImpCasts();
11925
11926 // Suppress warnings on tautological comparisons between values of the same
11927 // enumeration type. There are only two ways we could warn on this:
11928 // - If the constant is outside the range of representable values of
11929 // the enumeration. In such a case, we should warn about the cast
11930 // to enumeration type, not about the comparison.
11931 // - If the constant is the maximum / minimum in-range value. For an
11932 // enumeratin type, such comparisons can be meaningful and useful.
11933 if (Constant->getType()->isEnumeralType() &&
11934 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
11935 return false;
11936
11937 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11938 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
11939 if (!OtherValueRange)
11940 return false;
11941
11942 QualType OtherT = Other->getType();
11943 if (const auto *AT = OtherT->getAs<AtomicType>())
11944 OtherT = AT->getValueType();
11945 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
11946
11947 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11948 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11949 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11950 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
11951 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
11952
11953 // Whether we're treating Other as being a bool because of the form of
11954 // expression despite it having another type (typically 'int' in C).
11955 bool OtherIsBooleanDespiteType =
11956 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11957 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11958 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11959
11960 // Check if all values in the range of possible values of this expression
11961 // lead to the same comparison outcome.
11962 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11963 Value.isUnsigned());
11964 auto Cmp = OtherPromotedValueRange.compare(Value);
11965 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
11966 if (!Result)
11967 return false;
11968
11969 // Also consider the range determined by the type alone. This allows us to
11970 // classify the warning under the proper diagnostic group.
11971 bool TautologicalTypeCompare = false;
11972 {
11973 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11974 Value.isUnsigned());
11975 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11976 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
11977 ConstantOnRHS: RhsConstant)) {
11978 TautologicalTypeCompare = true;
11979 Cmp = TypeCmp;
11980 Result = TypeResult;
11981 }
11982 }
11983
11984 // Don't warn if the non-constant operand actually always evaluates to the
11985 // same value.
11986 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11987 return false;
11988
11989 // Suppress the diagnostic for an in-range comparison if the constant comes
11990 // from a macro or enumerator. We don't want to diagnose
11991 //
11992 // some_long_value <= INT_MAX
11993 //
11994 // when sizeof(int) == sizeof(long).
11995 bool InRange = Cmp & PromotedRange::InRangeFlag;
11996 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
11997 return false;
11998
11999 // A comparison of an unsigned bit-field against 0 is really a type problem,
12000 // even though at the type level the bit-field might promote to 'signed int'.
12001 if (Other->refersToBitField() && InRange && Value == 0 &&
12002 Other->getType()->isUnsignedIntegerOrEnumerationType())
12003 TautologicalTypeCompare = true;
12004
12005 // If this is a comparison to an enum constant, include that
12006 // constant in the diagnostic.
12007 const EnumConstantDecl *ED = nullptr;
12008 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12009 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12010
12011 // Should be enough for uint128 (39 decimal digits)
12012 SmallString<64> PrettySourceValue;
12013 llvm::raw_svector_ostream OS(PrettySourceValue);
12014 if (ED) {
12015 OS << '\'' << *ED << "' (" << Value << ")";
12016 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12017 Val: Constant->IgnoreParenImpCasts())) {
12018 OS << (BL->getValue() ? "YES" : "NO");
12019 } else {
12020 OS << Value;
12021 }
12022
12023 if (!TautologicalTypeCompare) {
12024 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12025 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12026 << E->getOpcodeStr() << OS.str() << *Result
12027 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12028 return true;
12029 }
12030
12031 if (IsObjCSignedCharBool) {
12032 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12033 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12034 << OS.str() << *Result);
12035 return true;
12036 }
12037
12038 // FIXME: We use a somewhat different formatting for the in-range cases and
12039 // cases involving boolean values for historical reasons. We should pick a
12040 // consistent way of presenting these diagnostics.
12041 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12042
12043 S.DiagRuntimeBehavior(
12044 Loc: E->getOperatorLoc(), Statement: E,
12045 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12046 : diag::warn_tautological_bool_compare)
12047 << OS.str() << classifyConstantValue(Constant) << OtherT
12048 << OtherIsBooleanDespiteType << *Result
12049 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12050 } else {
12051 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12052 unsigned Diag =
12053 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12054 ? (HasEnumType(E: OriginalOther)
12055 ? diag::warn_unsigned_enum_always_true_comparison
12056 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12057 : diag::warn_unsigned_always_true_comparison)
12058 : diag::warn_tautological_constant_compare;
12059
12060 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12061 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12062 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12063 }
12064
12065 return true;
12066}
12067
12068/// Analyze the operands of the given comparison. Implements the
12069/// fallback case from AnalyzeComparison.
12070static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12071 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12072 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12073}
12074
12075/// Implements -Wsign-compare.
12076///
12077/// \param E the binary operator to check for warnings
12078static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12079 // The type the comparison is being performed in.
12080 QualType T = E->getLHS()->getType();
12081
12082 // Only analyze comparison operators where both sides have been converted to
12083 // the same type.
12084 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12085 return AnalyzeImpConvsInComparison(S, E);
12086
12087 // Don't analyze value-dependent comparisons directly.
12088 if (E->isValueDependent())
12089 return AnalyzeImpConvsInComparison(S, E);
12090
12091 Expr *LHS = E->getLHS();
12092 Expr *RHS = E->getRHS();
12093
12094 if (T->isIntegralType(Ctx: S.Context)) {
12095 std::optional<llvm::APSInt> RHSValue =
12096 RHS->getIntegerConstantExpr(Ctx: S.Context);
12097 std::optional<llvm::APSInt> LHSValue =
12098 LHS->getIntegerConstantExpr(Ctx: S.Context);
12099
12100 // We don't care about expressions whose result is a constant.
12101 if (RHSValue && LHSValue)
12102 return AnalyzeImpConvsInComparison(S, E);
12103
12104 // We only care about expressions where just one side is literal
12105 if ((bool)RHSValue ^ (bool)LHSValue) {
12106 // Is the constant on the RHS or LHS?
12107 const bool RhsConstant = (bool)RHSValue;
12108 Expr *Const = RhsConstant ? RHS : LHS;
12109 Expr *Other = RhsConstant ? LHS : RHS;
12110 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12111
12112 // Check whether an integer constant comparison results in a value
12113 // of 'true' or 'false'.
12114 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12115 return AnalyzeImpConvsInComparison(S, E);
12116 }
12117 }
12118
12119 if (!T->hasUnsignedIntegerRepresentation()) {
12120 // We don't do anything special if this isn't an unsigned integral
12121 // comparison: we're only interested in integral comparisons, and
12122 // signed comparisons only happen in cases we don't care to warn about.
12123 return AnalyzeImpConvsInComparison(S, E);
12124 }
12125
12126 LHS = LHS->IgnoreParenImpCasts();
12127 RHS = RHS->IgnoreParenImpCasts();
12128
12129 if (!S.getLangOpts().CPlusPlus) {
12130 // Avoid warning about comparison of integers with different signs when
12131 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12132 // the type of `E`.
12133 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12134 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12135 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12136 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12137 }
12138
12139 // Check to see if one of the (unmodified) operands is of different
12140 // signedness.
12141 Expr *signedOperand, *unsignedOperand;
12142 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12143 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12144 "unsigned comparison between two signed integer expressions?");
12145 signedOperand = LHS;
12146 unsignedOperand = RHS;
12147 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12148 signedOperand = RHS;
12149 unsignedOperand = LHS;
12150 } else {
12151 return AnalyzeImpConvsInComparison(S, E);
12152 }
12153
12154 // Otherwise, calculate the effective range of the signed operand.
12155 std::optional<IntRange> signedRange =
12156 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12157 /*Approximate=*/true);
12158 if (!signedRange)
12159 return;
12160
12161 // Go ahead and analyze implicit conversions in the operands. Note
12162 // that we skip the implicit conversions on both sides.
12163 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12164 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12165
12166 // If the signed range is non-negative, -Wsign-compare won't fire.
12167 if (signedRange->NonNegative)
12168 return;
12169
12170 // For (in)equality comparisons, if the unsigned operand is a
12171 // constant which cannot collide with a overflowed signed operand,
12172 // then reinterpreting the signed operand as unsigned will not
12173 // change the result of the comparison.
12174 if (E->isEqualityOp()) {
12175 unsigned comparisonWidth = S.Context.getIntWidth(T);
12176 std::optional<IntRange> unsignedRange = TryGetExprRange(
12177 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12178 /*Approximate=*/true);
12179 if (!unsignedRange)
12180 return;
12181
12182 // We should never be unable to prove that the unsigned operand is
12183 // non-negative.
12184 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12185
12186 if (unsignedRange->Width < comparisonWidth)
12187 return;
12188 }
12189
12190 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12191 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12192 << LHS->getType() << RHS->getType()
12193 << LHS->getSourceRange() << RHS->getSourceRange());
12194}
12195
12196/// Analyzes an attempt to assign the given value to a bitfield.
12197///
12198/// Returns true if there was something fishy about the attempt.
12199static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12200 SourceLocation InitLoc) {
12201 assert(Bitfield->isBitField());
12202 if (Bitfield->isInvalidDecl())
12203 return false;
12204
12205 // White-list bool bitfields.
12206 QualType BitfieldType = Bitfield->getType();
12207 if (BitfieldType->isBooleanType())
12208 return false;
12209
12210 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12211 // If the underlying enum type was not explicitly specified as an unsigned
12212 // type and the enum contain only positive values, MSVC++ will cause an
12213 // inconsistency by storing this as a signed type.
12214 if (S.getLangOpts().CPlusPlus11 &&
12215 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12216 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12217 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12218 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12219 << BitfieldEnumDecl;
12220 }
12221 }
12222
12223 // Ignore value- or type-dependent expressions.
12224 if (Bitfield->getBitWidth()->isValueDependent() ||
12225 Bitfield->getBitWidth()->isTypeDependent() ||
12226 Init->isValueDependent() ||
12227 Init->isTypeDependent())
12228 return false;
12229
12230 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12231 unsigned FieldWidth = Bitfield->getBitWidthValue();
12232
12233 Expr::EvalResult Result;
12234 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12235 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12236 // The RHS is not constant. If the RHS has an enum type, make sure the
12237 // bitfield is wide enough to hold all the values of the enum without
12238 // truncation.
12239 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12240 const PreferredTypeAttr *PTAttr = nullptr;
12241 if (!ED) {
12242 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12243 if (PTAttr)
12244 ED = PTAttr->getType()->getAsEnumDecl();
12245 }
12246 if (ED) {
12247 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12248
12249 // Enum types are implicitly signed on Windows, so check if there are any
12250 // negative enumerators to see if the enum was intended to be signed or
12251 // not.
12252 bool SignedEnum = ED->getNumNegativeBits() > 0;
12253
12254 // Check for surprising sign changes when assigning enum values to a
12255 // bitfield of different signedness. If the bitfield is signed and we
12256 // have exactly the right number of bits to store this unsigned enum,
12257 // suggest changing the enum to an unsigned type. This typically happens
12258 // on Windows where unfixed enums always use an underlying type of 'int'.
12259 unsigned DiagID = 0;
12260 if (SignedEnum && !SignedBitfield) {
12261 DiagID =
12262 PTAttr == nullptr
12263 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12264 : diag::
12265 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12266 } else if (SignedBitfield && !SignedEnum &&
12267 ED->getNumPositiveBits() == FieldWidth) {
12268 DiagID =
12269 PTAttr == nullptr
12270 ? diag::warn_signed_bitfield_enum_conversion
12271 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12272 }
12273 if (DiagID) {
12274 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12275 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12276 SourceRange TypeRange =
12277 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12278 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12279 << SignedEnum << TypeRange;
12280 if (PTAttr)
12281 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12282 << ED;
12283 }
12284
12285 // Compute the required bitwidth. If the enum has negative values, we need
12286 // one more bit than the normal number of positive bits to represent the
12287 // sign bit.
12288 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12289 b: ED->getNumNegativeBits())
12290 : ED->getNumPositiveBits();
12291
12292 // Check the bitwidth.
12293 if (BitsNeeded > FieldWidth) {
12294 Expr *WidthExpr = Bitfield->getBitWidth();
12295 auto DiagID =
12296 PTAttr == nullptr
12297 ? diag::warn_bitfield_too_small_for_enum
12298 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12299 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12300 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12301 << BitsNeeded << ED << WidthExpr->getSourceRange();
12302 if (PTAttr)
12303 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12304 << ED;
12305 }
12306 }
12307
12308 return false;
12309 }
12310
12311 llvm::APSInt Value = Result.Val.getInt();
12312
12313 unsigned OriginalWidth = Value.getBitWidth();
12314
12315 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12316 // false positives where the user is demonstrating they intend to use the
12317 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12318 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12319 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12320 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12321 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12322 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12323 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12324 return false;
12325 }
12326
12327 if (!Value.isSigned() || Value.isNegative())
12328 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12329 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12330 OriginalWidth = Value.getSignificantBits();
12331
12332 if (OriginalWidth <= FieldWidth)
12333 return false;
12334
12335 // Compute the value which the bitfield will contain.
12336 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12337 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12338
12339 // Check whether the stored value is equal to the original value.
12340 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12341 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12342 return false;
12343
12344 std::string PrettyValue = toString(I: Value, Radix: 10);
12345 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12346
12347 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12348 ? diag::warn_impcast_single_bit_bitield_precision_constant
12349 : diag::warn_impcast_bitfield_precision_constant)
12350 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12351 << Init->getSourceRange();
12352
12353 return true;
12354}
12355
12356/// Analyze the given simple or compound assignment for warning-worthy
12357/// operations.
12358static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12359 // Just recurse on the LHS.
12360 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12361
12362 // We want to recurse on the RHS as normal unless we're assigning to
12363 // a bitfield.
12364 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12365 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12366 InitLoc: E->getOperatorLoc())) {
12367 // Recurse, ignoring any implicit conversions on the RHS.
12368 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12369 CC: E->getOperatorLoc());
12370 }
12371 }
12372
12373 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12374
12375 // Diagnose implicitly sequentially-consistent atomic assignment.
12376 if (E->getLHS()->getType()->isAtomicType())
12377 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12378}
12379
12380/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12381static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12382 QualType T, SourceLocation CContext, unsigned diag,
12383 bool PruneControlFlow = false) {
12384 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12385 // address space annotations isn't really useful. The warnings aren't because
12386 // you're converting a `private int` to `unsigned int`, it is because you're
12387 // conerting `int` to `unsigned int`.
12388 if (SourceType.hasAddressSpace())
12389 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
12390 if (T.hasAddressSpace())
12391 T = S.getASTContext().removeAddrSpaceQualType(T);
12392 if (PruneControlFlow) {
12393 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12394 PD: S.PDiag(DiagID: diag)
12395 << SourceType << T << E->getSourceRange()
12396 << SourceRange(CContext));
12397 return;
12398 }
12399 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
12400 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12401}
12402
12403/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12404static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12405 SourceLocation CContext, unsigned diag,
12406 bool PruneControlFlow = false) {
12407 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
12408}
12409
12410/// Diagnose an implicit cast from a floating point value to an integer value.
12411static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12412 SourceLocation CContext) {
12413 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
12414 bool PruneWarnings = S.inTemplateInstantiation();
12415
12416 const Expr *InnerE = E->IgnoreParenImpCasts();
12417 // We also want to warn on, e.g., "int i = -1.234"
12418 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
12419 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12420 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12421
12422 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
12423
12424 llvm::APFloat Value(0.0);
12425 bool IsConstant =
12426 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
12427 if (!IsConstant) {
12428 if (S.ObjC().isSignedCharBool(Ty: T)) {
12429 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12430 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
12431 << E->getType());
12432 }
12433
12434 return DiagnoseImpCast(S, E, T, CContext,
12435 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12436 }
12437
12438 bool isExact = false;
12439
12440 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12441 T->hasUnsignedIntegerRepresentation());
12442 llvm::APFloat::opStatus Result = Value.convertToInteger(
12443 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
12444
12445 // FIXME: Force the precision of the source value down so we don't print
12446 // digits which are usually useless (we don't really care here if we
12447 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12448 // would automatically print the shortest representation, but it's a bit
12449 // tricky to implement.
12450 SmallString<16> PrettySourceValue;
12451 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12452 precision = (precision * 59 + 195) / 196;
12453 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
12454
12455 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
12456 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12457 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12458 << PrettySourceValue);
12459 }
12460
12461 if (Result == llvm::APFloat::opOK && isExact) {
12462 if (IsLiteral) return;
12463 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
12464 PruneControlFlow: PruneWarnings);
12465 }
12466
12467 // Conversion of a floating-point value to a non-bool integer where the
12468 // integral part cannot be represented by the integer type is undefined.
12469 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12470 return DiagnoseImpCast(
12471 S, E, T, CContext,
12472 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12473 : diag::warn_impcast_float_to_integer_out_of_range,
12474 PruneControlFlow: PruneWarnings);
12475
12476 unsigned DiagID = 0;
12477 if (IsLiteral) {
12478 // Warn on floating point literal to integer.
12479 DiagID = diag::warn_impcast_literal_float_to_integer;
12480 } else if (IntegerValue == 0) {
12481 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12482 return DiagnoseImpCast(S, E, T, CContext,
12483 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12484 }
12485 // Warn on non-zero to zero conversion.
12486 DiagID = diag::warn_impcast_float_to_integer_zero;
12487 } else {
12488 if (IntegerValue.isUnsigned()) {
12489 if (!IntegerValue.isMaxValue()) {
12490 return DiagnoseImpCast(S, E, T, CContext,
12491 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12492 }
12493 } else { // IntegerValue.isSigned()
12494 if (!IntegerValue.isMaxSignedValue() &&
12495 !IntegerValue.isMinSignedValue()) {
12496 return DiagnoseImpCast(S, E, T, CContext,
12497 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12498 }
12499 }
12500 // Warn on evaluatable floating point expression to integer conversion.
12501 DiagID = diag::warn_impcast_float_to_integer;
12502 }
12503
12504 SmallString<16> PrettyTargetValue;
12505 if (IsBool)
12506 PrettyTargetValue = Value.isZero() ? "false" : "true";
12507 else
12508 IntegerValue.toString(Str&: PrettyTargetValue);
12509
12510 if (PruneWarnings) {
12511 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12512 PD: S.PDiag(DiagID)
12513 << E->getType() << T.getUnqualifiedType()
12514 << PrettySourceValue << PrettyTargetValue
12515 << E->getSourceRange() << SourceRange(CContext));
12516 } else {
12517 S.Diag(Loc: E->getExprLoc(), DiagID)
12518 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12519 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12520 }
12521}
12522
12523/// Analyze the given compound assignment for the possible losing of
12524/// floating-point precision.
12525static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12526 assert(isa<CompoundAssignOperator>(E) &&
12527 "Must be compound assignment operation");
12528 // Recurse on the LHS and RHS in here
12529 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12530 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12531
12532 if (E->getLHS()->getType()->isAtomicType())
12533 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12534
12535 // Now check the outermost expression
12536 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12537 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
12538 ->getComputationResultType()
12539 ->getAs<BuiltinType>();
12540
12541 // The below checks assume source is floating point.
12542 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12543
12544 // If source is floating point but target is an integer.
12545 if (ResultBT->isInteger())
12546 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
12547 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
12548
12549 if (!ResultBT->isFloatingPoint())
12550 return;
12551
12552 // If both source and target are floating points, warn about losing precision.
12553 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12554 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
12555 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
12556 // warn about dropping FP rank.
12557 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
12558 diag: diag::warn_impcast_float_result_precision);
12559}
12560
12561static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12562 IntRange Range) {
12563 if (!Range.Width) return "0";
12564
12565 llvm::APSInt ValueInRange = Value;
12566 ValueInRange.setIsSigned(!Range.NonNegative);
12567 ValueInRange = ValueInRange.trunc(width: Range.Width);
12568 return toString(I: ValueInRange, Radix: 10);
12569}
12570
12571static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12572 bool ToBool) {
12573 if (!isa<ImplicitCastExpr>(Val: Ex))
12574 return false;
12575
12576 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12577 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
12578 const Type *Source =
12579 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
12580 if (Target->isDependentType())
12581 return false;
12582
12583 const auto *FloatCandidateBT =
12584 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
12585 const Type *BoolCandidateType = ToBool ? Target : Source;
12586
12587 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
12588 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12589}
12590
12591static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12592 SourceLocation CC) {
12593 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12594 const Expr *CurrA = TheCall->getArg(Arg: I);
12595 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
12596 continue;
12597
12598 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12599 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
12600 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12601 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
12602 if (IsSwapped) {
12603 // Warn on this floating-point to bool conversion.
12604 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
12605 T: CurrA->getType(), CContext: CC,
12606 diag: diag::warn_impcast_floating_point_to_bool);
12607 }
12608 }
12609}
12610
12611static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12612 SourceLocation CC) {
12613 // Don't warn on functions which have return type nullptr_t.
12614 if (isa<CallExpr>(Val: E))
12615 return;
12616
12617 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12618 const Expr *NewE = E->IgnoreParenImpCasts();
12619 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
12620 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12621 if (!IsGNUNullExpr && !HasNullPtrType)
12622 return;
12623
12624 // Return if target type is a safe conversion.
12625 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12626 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12627 return;
12628
12629 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
12630 Loc: E->getExprLoc()))
12631 return;
12632
12633 SourceLocation Loc = E->getSourceRange().getBegin();
12634
12635 // Venture through the macro stacks to get to the source of macro arguments.
12636 // The new location is a better location than the complete location that was
12637 // passed in.
12638 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12639 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
12640
12641 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12642 if (IsGNUNullExpr && Loc.isMacroID()) {
12643 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12644 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
12645 if (MacroName == "NULL")
12646 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12647 }
12648
12649 // Only warn if the null and context location are in the same macro expansion.
12650 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
12651 return;
12652
12653 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
12654 << HasNullPtrType << T << SourceRange(CC)
12655 << FixItHint::CreateReplacement(RemoveRange: Loc,
12656 Code: S.getFixItZeroLiteralForType(T, Loc));
12657}
12658
12659// Helper function to filter out cases for constant width constant conversion.
12660// Don't warn on char array initialization or for non-decimal values.
12661static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12662 SourceLocation CC) {
12663 // If initializing from a constant, and the constant starts with '0',
12664 // then it is a binary, octal, or hexadecimal. Allow these constants
12665 // to fill all the bits, even if there is a sign change.
12666 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
12667 const char FirstLiteralCharacter =
12668 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
12669 if (FirstLiteralCharacter == '0')
12670 return false;
12671 }
12672
12673 // If the CC location points to a '{', and the type is char, then assume
12674 // assume it is an array initialization.
12675 if (CC.isValid() && T->isCharType()) {
12676 const char FirstContextCharacter =
12677 S.getSourceManager().getCharacterData(SL: CC)[0];
12678 if (FirstContextCharacter == '{')
12679 return false;
12680 }
12681
12682 return true;
12683}
12684
12685static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12686 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
12687 if (!IL) {
12688 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12689 if (UO->getOpcode() == UO_Minus)
12690 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
12691 }
12692 }
12693
12694 return IL;
12695}
12696
12697static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12698 E = E->IgnoreParenImpCasts();
12699 SourceLocation ExprLoc = E->getExprLoc();
12700
12701 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12702 BinaryOperator::Opcode Opc = BO->getOpcode();
12703 Expr::EvalResult Result;
12704 // Do not diagnose unsigned shifts.
12705 if (Opc == BO_Shl) {
12706 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
12707 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
12708 if (LHS && LHS->getValue() == 0)
12709 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
12710 else if (!E->isValueDependent() && LHS && RHS &&
12711 RHS->getValue().isNonNegative() &&
12712 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
12713 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
12714 << (Result.Val.getInt() != 0);
12715 else if (E->getType()->isSignedIntegerType())
12716 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
12717 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
12718 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
12719 Code: ") != 0");
12720 }
12721 }
12722
12723 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12724 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
12725 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
12726 if (!LHS || !RHS)
12727 return;
12728 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12729 (RHS->getValue() == 0 || RHS->getValue() == 1))
12730 // Do not diagnose common idioms.
12731 return;
12732 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12733 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
12734 }
12735}
12736
12737static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
12738 const Type *Target, Expr *E,
12739 QualType T,
12740 SourceLocation CC) {
12741 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12742 Source != Target);
12743
12744 // Lone surrogates have a distinct representation in UTF-32.
12745 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12746 // so don't warn on such conversion.
12747 if (Source->isChar16Type() && Target->isChar32Type())
12748 return;
12749
12750 Expr::EvalResult Result;
12751 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
12752 InConstantContext: S.isConstantEvaluatedContext())) {
12753 llvm::APSInt Value(32);
12754 Value = Result.Val.getInt();
12755 bool IsASCII = Value <= 0x7F;
12756 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12757 bool ConversionPreservesSemantics =
12758 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12759
12760 if (!ConversionPreservesSemantics) {
12761 auto IsSingleCodeUnitCP = [](const QualType &T,
12762 const llvm::APSInt &Value) {
12763 if (T->isChar8Type())
12764 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12765 if (T->isChar16Type())
12766 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12767 assert(T->isChar32Type());
12768 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12769 };
12770
12771 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
12772 << E->getType() << T
12773 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12774 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
12775 }
12776 } else {
12777 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
12778 S.getASTContext().getIntWidth(T);
12779 DiagnoseImpCast(S, E, T, CContext: CC,
12780 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
12781 : diag::warn_impcast_unicode_char_type);
12782 }
12783}
12784
12785bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
12786 From = Context.getCanonicalType(T: From);
12787 To = Context.getCanonicalType(T: To);
12788 QualType MaybePointee = From->getPointeeType();
12789 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12790 From = MaybePointee;
12791 MaybePointee = To->getPointeeType();
12792 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12793 To = MaybePointee;
12794
12795 if (const auto *FromFn = From->getAs<FunctionType>()) {
12796 if (const auto *ToFn = To->getAs<FunctionType>()) {
12797 if (FromFn->getCFIUncheckedCalleeAttr() &&
12798 !ToFn->getCFIUncheckedCalleeAttr())
12799 return true;
12800 }
12801 }
12802 return false;
12803}
12804
12805void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
12806 bool *ICContext, bool IsListInit) {
12807 if (E->isTypeDependent() || E->isValueDependent()) return;
12808
12809 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
12810 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12811 if (Source == Target) return;
12812 if (Target->isDependentType()) return;
12813
12814 // If the conversion context location is invalid don't complain. We also
12815 // don't want to emit a warning if the issue occurs from the expansion of
12816 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12817 // delay this check as long as possible. Once we detect we are in that
12818 // scenario, we just return.
12819 if (CC.isInvalid())
12820 return;
12821
12822 if (Source->isAtomicType())
12823 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12824
12825 // Diagnose implicit casts to bool.
12826 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
12827 if (isa<StringLiteral>(Val: E))
12828 // Warn on string literal to bool. Checks for string literals in logical
12829 // and expressions, for instance, assert(0 && "error here"), are
12830 // prevented by a check in AnalyzeImplicitConversions().
12831 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12832 diag: diag::warn_impcast_string_literal_to_bool);
12833 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
12834 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
12835 // This covers the literal expressions that evaluate to Objective-C
12836 // objects.
12837 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12838 diag: diag::warn_impcast_objective_c_literal_to_bool);
12839 }
12840 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12841 // Warn on pointer to bool conversion that is always true.
12842 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
12843 Range: SourceRange(CC));
12844 }
12845 }
12846
12847 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12848 // is a typedef for signed char (macOS), then that constant value has to be 1
12849 // or 0.
12850 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
12851 Expr::EvalResult Result;
12852 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
12853 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12854 ObjC().adornBoolConversionDiagWithTernaryFixit(
12855 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12856 << toString(I: Result.Val.getInt(), Radix: 10));
12857 }
12858 return;
12859 }
12860 }
12861
12862 // Check implicit casts from Objective-C collection literals to specialized
12863 // collection types, e.g., NSArray<NSString *> *.
12864 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
12865 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
12866 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
12867 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
12868
12869 // Strip vector types.
12870 if (isa<VectorType>(Val: Source)) {
12871 if (Target->isSveVLSBuiltinType() &&
12872 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
12873 SecondType: QualType(Source, 0)) ||
12874 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
12875 SecondType: QualType(Source, 0))))
12876 return;
12877
12878 if (Target->isRVVVLSBuiltinType() &&
12879 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
12880 SecondType: QualType(Source, 0)) ||
12881 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
12882 SecondType: QualType(Source, 0))))
12883 return;
12884
12885 if (!isa<VectorType>(Val: Target)) {
12886 if (SourceMgr.isInSystemMacro(loc: CC))
12887 return;
12888 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
12889 }
12890 if (getLangOpts().HLSL &&
12891 Target->castAs<VectorType>()->getNumElements() <
12892 Source->castAs<VectorType>()->getNumElements()) {
12893 // Diagnose vector truncation but don't return. We may also want to
12894 // diagnose an element conversion.
12895 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12896 diag: diag::warn_hlsl_impcast_vector_truncation);
12897 }
12898
12899 // If the vector cast is cast between two vectors of the same size, it is
12900 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12901 if (!getLangOpts().HLSL &&
12902 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
12903 return;
12904
12905 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
12906 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
12907 }
12908 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
12909 Target = VecTy->getElementType().getTypePtr();
12910
12911 if (isa<ConstantMatrixType>(Val: Source)) {
12912 if (Target->isScalarType())
12913 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
12914
12915 if (getLangOpts().HLSL &&
12916 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
12917 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
12918 // Diagnose Matrix truncation but don't return. We may also want to
12919 // diagnose an element conversion.
12920 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12921 diag: diag::warn_hlsl_impcast_matrix_truncation);
12922 }
12923 }
12924 // Strip complex types.
12925 if (isa<ComplexType>(Val: Source)) {
12926 if (!isa<ComplexType>(Val: Target)) {
12927 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
12928 return;
12929
12930 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12931 diag: getLangOpts().CPlusPlus
12932 ? diag::err_impcast_complex_scalar
12933 : diag::warn_impcast_complex_scalar);
12934 }
12935
12936 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
12937 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
12938 }
12939
12940 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
12941 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
12942
12943 // Strip SVE vector types
12944 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12945 // Need the original target type for vector type checks
12946 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12947 // Handle conversion from scalable to fixed when msve-vector-bits is
12948 // specified
12949 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
12950 SecondType: QualType(Source, 0)) ||
12951 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
12952 SecondType: QualType(Source, 0)))
12953 return;
12954
12955 // If the vector cast is cast between two vectors of the same size, it is
12956 // a bitcast, not a conversion.
12957 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
12958 return;
12959
12960 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
12961 }
12962
12963 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12964 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
12965
12966 // If the source is floating point...
12967 if (SourceBT && SourceBT->isFloatingPoint()) {
12968 // ...and the target is floating point...
12969 if (TargetBT && TargetBT->isFloatingPoint()) {
12970 // ...then warn if we're dropping FP rank.
12971
12972 int Order = getASTContext().getFloatingTypeSemanticOrder(
12973 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
12974 if (Order > 0) {
12975 // Don't warn about float constants that are precisely
12976 // representable in the target type.
12977 Expr::EvalResult result;
12978 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
12979 // Value might be a float, a float vector, or a float complex.
12980 if (IsSameFloatAfterCast(
12981 value: result.Val,
12982 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
12983 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
12984 return;
12985 }
12986
12987 if (SourceMgr.isInSystemMacro(loc: CC))
12988 return;
12989
12990 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
12991 }
12992 // ... or possibly if we're increasing rank, too
12993 else if (Order < 0) {
12994 if (SourceMgr.isInSystemMacro(loc: CC))
12995 return;
12996
12997 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
12998 }
12999 return;
13000 }
13001
13002 // If the target is integral, always warn.
13003 if (TargetBT && TargetBT->isInteger()) {
13004 if (SourceMgr.isInSystemMacro(loc: CC))
13005 return;
13006
13007 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13008 }
13009
13010 // Detect the case where a call result is converted from floating-point to
13011 // to bool, and the final argument to the call is converted from bool, to
13012 // discover this typo:
13013 //
13014 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13015 //
13016 // FIXME: This is an incredibly special case; is there some more general
13017 // way to detect this class of misplaced-parentheses bug?
13018 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13019 // Check last argument of function call to see if it is an
13020 // implicit cast from a type matching the type the result
13021 // is being cast to.
13022 CallExpr *CEx = cast<CallExpr>(Val: E);
13023 if (unsigned NumArgs = CEx->getNumArgs()) {
13024 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13025 Expr *InnerE = LastA->IgnoreParenImpCasts();
13026 if (isa<ImplicitCastExpr>(Val: LastA) &&
13027 InnerE->getType()->isBooleanType()) {
13028 // Warn on this floating-point to bool conversion
13029 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13030 diag: diag::warn_impcast_floating_point_to_bool);
13031 }
13032 }
13033 }
13034 return;
13035 }
13036
13037 // Valid casts involving fixed point types should be accounted for here.
13038 if (Source->isFixedPointType()) {
13039 if (Target->isUnsaturatedFixedPointType()) {
13040 Expr::EvalResult Result;
13041 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13042 InConstantContext: isConstantEvaluatedContext())) {
13043 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13044 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13045 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13046 if (Value > MaxVal || Value < MinVal) {
13047 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13048 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13049 << Value.toString() << T
13050 << E->getSourceRange()
13051 << clang::SourceRange(CC));
13052 return;
13053 }
13054 }
13055 } else if (Target->isIntegerType()) {
13056 Expr::EvalResult Result;
13057 if (!isConstantEvaluatedContext() &&
13058 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13059 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13060
13061 bool Overflowed;
13062 llvm::APSInt IntResult = FXResult.convertToInt(
13063 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13064 Overflow: &Overflowed);
13065
13066 if (Overflowed) {
13067 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13068 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13069 << FXResult.toString() << T
13070 << E->getSourceRange()
13071 << clang::SourceRange(CC));
13072 return;
13073 }
13074 }
13075 }
13076 } else if (Target->isUnsaturatedFixedPointType()) {
13077 if (Source->isIntegerType()) {
13078 Expr::EvalResult Result;
13079 if (!isConstantEvaluatedContext() &&
13080 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13081 llvm::APSInt Value = Result.Val.getInt();
13082
13083 bool Overflowed;
13084 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13085 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13086
13087 if (Overflowed) {
13088 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13089 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13090 << toString(I: Value, /*Radix=*/10) << T
13091 << E->getSourceRange()
13092 << clang::SourceRange(CC));
13093 return;
13094 }
13095 }
13096 }
13097 }
13098
13099 // If we are casting an integer type to a floating point type without
13100 // initialization-list syntax, we might lose accuracy if the floating
13101 // point type has a narrower significand than the integer type.
13102 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13103 TargetBT->isFloatingType() && !IsListInit) {
13104 // Determine the number of precision bits in the source integer type.
13105 std::optional<IntRange> SourceRange =
13106 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13107 /*Approximate=*/true);
13108 if (!SourceRange)
13109 return;
13110 unsigned int SourcePrecision = SourceRange->Width;
13111
13112 // Determine the number of precision bits in the
13113 // target floating point type.
13114 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13115 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13116
13117 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13118 SourcePrecision > TargetPrecision) {
13119
13120 if (std::optional<llvm::APSInt> SourceInt =
13121 E->getIntegerConstantExpr(Ctx: Context)) {
13122 // If the source integer is a constant, convert it to the target
13123 // floating point type. Issue a warning if the value changes
13124 // during the whole conversion.
13125 llvm::APFloat TargetFloatValue(
13126 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13127 llvm::APFloat::opStatus ConversionStatus =
13128 TargetFloatValue.convertFromAPInt(
13129 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13130 RM: llvm::APFloat::rmNearestTiesToEven);
13131
13132 if (ConversionStatus != llvm::APFloat::opOK) {
13133 SmallString<32> PrettySourceValue;
13134 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13135 SmallString<32> PrettyTargetValue;
13136 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13137
13138 DiagRuntimeBehavior(
13139 Loc: E->getExprLoc(), Statement: E,
13140 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13141 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13142 << E->getSourceRange() << clang::SourceRange(CC));
13143 }
13144 } else {
13145 // Otherwise, the implicit conversion may lose precision.
13146 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13147 diag: diag::warn_impcast_integer_float_precision);
13148 }
13149 }
13150 }
13151
13152 DiagnoseNullConversion(S&: *this, E, T, CC);
13153
13154 DiscardMisalignedMemberAddress(T: Target, E);
13155
13156 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13157 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13158 return;
13159 }
13160
13161 if (Target->isBooleanType())
13162 DiagnoseIntInBoolContext(S&: *this, E);
13163
13164 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13165 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13166 << QualType(Source, 0) << QualType(Target, 0);
13167 }
13168
13169 if (!Source->isIntegerType() || !Target->isIntegerType())
13170 return;
13171
13172 // TODO: remove this early return once the false positives for constant->bool
13173 // in templates, macros, etc, are reduced or removed.
13174 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13175 return;
13176
13177 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13178 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13179 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13180 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13181 << E->getType());
13182 }
13183 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13184 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13185 if (!LikelySourceRange)
13186 return;
13187
13188 IntRange SourceTypeRange =
13189 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13190 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13191
13192 if (LikelySourceRange->Width > TargetRange.Width) {
13193 // If the source is a constant, use a default-on diagnostic.
13194 // TODO: this should happen for bitfield stores, too.
13195 Expr::EvalResult Result;
13196 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13197 InConstantContext: isConstantEvaluatedContext())) {
13198 llvm::APSInt Value(32);
13199 Value = Result.Val.getInt();
13200
13201 if (SourceMgr.isInSystemMacro(loc: CC))
13202 return;
13203
13204 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13205 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13206
13207 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13208 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13209 << PrettySourceValue << PrettyTargetValue
13210 << E->getType() << T << E->getSourceRange()
13211 << SourceRange(CC));
13212 return;
13213 }
13214
13215 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13216 if (SourceMgr.isInSystemMacro(loc: CC))
13217 return;
13218
13219 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13220 if (UO->getOpcode() == UO_Minus)
13221 return DiagnoseImpCast(
13222 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13223 }
13224
13225 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13226 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13227 /* pruneControlFlow */ PruneControlFlow: true);
13228 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13229 diag: diag::warn_impcast_integer_precision);
13230 }
13231
13232 if (TargetRange.Width > SourceTypeRange.Width) {
13233 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13234 if (UO->getOpcode() == UO_Minus)
13235 if (Source->isUnsignedIntegerType()) {
13236 if (Target->isUnsignedIntegerType())
13237 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13238 diag: diag::warn_impcast_high_order_zero_bits);
13239 if (Target->isSignedIntegerType())
13240 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13241 diag: diag::warn_impcast_nonnegative_result);
13242 }
13243 }
13244
13245 if (TargetRange.Width == LikelySourceRange->Width &&
13246 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13247 Source->isSignedIntegerType()) {
13248 // Warn when doing a signed to signed conversion, warn if the positive
13249 // source value is exactly the width of the target type, which will
13250 // cause a negative value to be stored.
13251
13252 Expr::EvalResult Result;
13253 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13254 !SourceMgr.isInSystemMacro(loc: CC)) {
13255 llvm::APSInt Value = Result.Val.getInt();
13256 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13257 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13258 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13259
13260 Diag(Loc: E->getExprLoc(),
13261 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13262 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13263 << E->getSourceRange() << SourceRange(CC));
13264 return;
13265 }
13266 }
13267
13268 // Fall through for non-constants to give a sign conversion warning.
13269 }
13270
13271 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13272 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13273 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13274 LikelySourceRange->Width == TargetRange.Width))) {
13275 if (SourceMgr.isInSystemMacro(loc: CC))
13276 return;
13277
13278 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13279 TargetBT->isInteger() &&
13280 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13281 return;
13282 }
13283
13284 unsigned DiagID = diag::warn_impcast_integer_sign;
13285
13286 // Traditionally, gcc has warned about this under -Wsign-compare.
13287 // We also want to warn about it in -Wconversion.
13288 // So if -Wconversion is off, use a completely identical diagnostic
13289 // in the sign-compare group.
13290 // The conditional-checking code will
13291 if (ICContext) {
13292 DiagID = diag::warn_impcast_integer_sign_conditional;
13293 *ICContext = true;
13294 }
13295
13296 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13297 }
13298
13299 // If we're implicitly converting from an integer into an enumeration, that
13300 // is valid in C but invalid in C++.
13301 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13302 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13303 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13304 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13305
13306 // Diagnose conversions between different enumeration types.
13307 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13308 // type, to give us better diagnostics.
13309 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13310
13311 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13312 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13313 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13314 TargetEnum->getDecl()->hasNameForLinkage() &&
13315 SourceEnum != TargetEnum) {
13316 if (SourceMgr.isInSystemMacro(loc: CC))
13317 return;
13318
13319 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13320 diag: diag::warn_impcast_different_enum_types);
13321 }
13322}
13323
13324static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13325 SourceLocation CC, QualType T);
13326
13327static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13328 SourceLocation CC, bool &ICContext) {
13329 E = E->IgnoreParenImpCasts();
13330 // Diagnose incomplete type for second or third operand in C.
13331 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13332 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13333
13334 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13335 return CheckConditionalOperator(S, E: CO, CC, T);
13336
13337 AnalyzeImplicitConversions(S, E, CC);
13338 if (E->getType() != T)
13339 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
13340}
13341
13342static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13343 SourceLocation CC, QualType T) {
13344 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
13345
13346 Expr *TrueExpr = E->getTrueExpr();
13347 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
13348 TrueExpr = BCO->getCommon();
13349
13350 bool Suspicious = false;
13351 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
13352 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
13353
13354 if (T->isBooleanType())
13355 DiagnoseIntInBoolContext(S, E);
13356
13357 // If -Wconversion would have warned about either of the candidates
13358 // for a signedness conversion to the context type...
13359 if (!Suspicious) return;
13360
13361 // ...but it's currently ignored...
13362 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
13363 return;
13364
13365 // ...then check whether it would have warned about either of the
13366 // candidates for a signedness conversion to the condition type.
13367 if (E->getType() == T) return;
13368
13369 Suspicious = false;
13370 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
13371 ICContext: &Suspicious);
13372 if (!Suspicious)
13373 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
13374 T: E->getType(), CC, ICContext: &Suspicious);
13375}
13376
13377/// Check conversion of given expression to boolean.
13378/// Input argument E is a logical expression.
13379static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13380 // Run the bool-like conversion checks only for C since there bools are
13381 // still not used as the return type from "boolean" operators or as the input
13382 // type for conditional operators.
13383 if (S.getLangOpts().CPlusPlus)
13384 return;
13385 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13386 return;
13387 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
13388}
13389
13390namespace {
13391struct AnalyzeImplicitConversionsWorkItem {
13392 Expr *E;
13393 SourceLocation CC;
13394 bool IsListInit;
13395};
13396}
13397
13398static void CheckCommaOperand(
13399 Sema &S, Expr *E, QualType T, SourceLocation CC,
13400 bool ExtraCheckForImplicitConversion,
13401 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13402 E = E->IgnoreParenImpCasts();
13403 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
13404
13405 if (ExtraCheckForImplicitConversion && E->getType() != T)
13406 S.CheckImplicitConversion(E, T, CC);
13407}
13408
13409/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13410/// that should be visited are added to WorkList.
13411static void AnalyzeImplicitConversions(
13412 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13413 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13414 Expr *OrigE = Item.E;
13415 SourceLocation CC = Item.CC;
13416
13417 QualType T = OrigE->getType();
13418 Expr *E = OrigE->IgnoreParenImpCasts();
13419
13420 // Propagate whether we are in a C++ list initialization expression.
13421 // If so, we do not issue warnings for implicit int-float conversion
13422 // precision loss, because C++11 narrowing already handles it.
13423 //
13424 // HLSL's initialization lists are special, so they shouldn't observe the C++
13425 // behavior here.
13426 bool IsListInit =
13427 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
13428 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13429
13430 if (E->isTypeDependent() || E->isValueDependent())
13431 return;
13432
13433 Expr *SourceExpr = E;
13434 // Examine, but don't traverse into the source expression of an
13435 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13436 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13437 // evaluate it in the context of checking the specific conversion to T though.
13438 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
13439 if (auto *Src = OVE->getSourceExpr())
13440 SourceExpr = Src;
13441
13442 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
13443 if (UO->getOpcode() == UO_Not &&
13444 UO->getSubExpr()->isKnownToHaveBooleanValue())
13445 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
13446 << OrigE->getSourceRange() << T->isBooleanType()
13447 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
13448
13449 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
13450 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13451 BO->getLHS()->isKnownToHaveBooleanValue() &&
13452 BO->getRHS()->isKnownToHaveBooleanValue() &&
13453 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
13454 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
13455 SourceManager &SM = S.getSourceManager();
13456 const LangOptions &LO = S.getLangOpts();
13457 SourceLocation BLoc = BO->getOperatorLoc();
13458 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
13459 StringRef SR = clang::Lexer::getSourceText(
13460 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
13461 // To reduce false positives, only issue the diagnostic if the operator
13462 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13463 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13464 // in C, along with other macro spellings the user might invent.
13465 if (SR.str() == "&" || SR.str() == "|") {
13466
13467 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
13468 << (BO->getOpcode() == BO_And ? "&" : "|")
13469 << OrigE->getSourceRange()
13470 << FixItHint::CreateReplacement(
13471 RemoveRange: BO->getOperatorLoc(),
13472 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
13473 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
13474 }
13475 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13476 /// Analyze the given comma operator. The basic idea behind the analysis
13477 /// is to analyze the left and right operands slightly differently. The
13478 /// left operand needs to check whether the operand itself has an implicit
13479 /// conversion, but not whether the left operand induces an implicit
13480 /// conversion for the entire comma expression itself. This is similar to
13481 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13482 /// were directly used for the implicit conversion check.
13483 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
13484 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13485 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
13486 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13487 return;
13488 }
13489 }
13490
13491 // For conditional operators, we analyze the arguments as if they
13492 // were being fed directly into the output.
13493 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
13494 CheckConditionalOperator(S, E: CO, CC, T);
13495 return;
13496 }
13497
13498 // Check implicit argument conversions for function calls.
13499 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
13500 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
13501
13502 // Go ahead and check any implicit conversions we might have skipped.
13503 // The non-canonical typecheck is just an optimization;
13504 // CheckImplicitConversion will filter out dead implicit conversions.
13505 if (SourceExpr->getType() != T)
13506 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
13507
13508 // Now continue drilling into this expression.
13509
13510 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
13511 // The bound subexpressions in a PseudoObjectExpr are not reachable
13512 // as transitive children.
13513 // FIXME: Use a more uniform representation for this.
13514 for (auto *SE : POE->semantics())
13515 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
13516 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13517 }
13518
13519 // Skip past explicit casts.
13520 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
13521 E = CE->getSubExpr();
13522 // In the special case of a C++ function-style cast with braces,
13523 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13524 // initializer. This InitListExpr basically belongs to the cast itself, so
13525 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13526 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
13527 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
13528 if (InitListE->getNumInits() == 1) {
13529 E = InitListE->getInit(Init: 0);
13530 }
13531 }
13532 }
13533 E = E->IgnoreParenImpCasts();
13534 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13535 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13536 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
13537 return;
13538 }
13539
13540 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
13541 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
13542 // The base expression is only used to initialize the parameter for
13543 // arguments to `inout` parameters, so we only traverse down the base
13544 // expression for `inout` cases.
13545 if (OutArgE->isInOut())
13546 WorkList.push_back(
13547 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13548 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
13549 return;
13550 }
13551
13552 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13553 // Do a somewhat different check with comparison operators.
13554 if (BO->isComparisonOp())
13555 return AnalyzeComparison(S, E: BO);
13556
13557 // And with simple assignments.
13558 if (BO->getOpcode() == BO_Assign)
13559 return AnalyzeAssignment(S, E: BO);
13560 // And with compound assignments.
13561 if (BO->isAssignmentOp())
13562 return AnalyzeCompoundAssignment(S, E: BO);
13563 }
13564
13565 // These break the otherwise-useful invariant below. Fortunately,
13566 // we don't really need to recurse into them, because any internal
13567 // expressions should have been analyzed already when they were
13568 // built into statements.
13569 if (isa<StmtExpr>(Val: E)) return;
13570
13571 // Don't descend into unevaluated contexts.
13572 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
13573
13574 // Now just recurse over the expression's children.
13575 CC = E->getExprLoc();
13576 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
13577 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13578 for (Stmt *SubStmt : E->children()) {
13579 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
13580 if (!ChildExpr)
13581 continue;
13582
13583 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
13584 if (ChildExpr == CSE->getOperand())
13585 // Do not recurse over a CoroutineSuspendExpr's operand.
13586 // The operand is also a subexpression of getCommonExpr(), and
13587 // recursing into it directly would produce duplicate diagnostics.
13588 continue;
13589
13590 if (IsLogicalAndOperator &&
13591 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
13592 // Ignore checking string literals that are in logical and operators.
13593 // This is a common pattern for asserts.
13594 continue;
13595 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
13596 }
13597
13598 if (BO && BO->isLogicalOp()) {
13599 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13600 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13601 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13602
13603 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13604 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13605 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13606 }
13607
13608 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
13609 if (U->getOpcode() == UO_LNot) {
13610 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
13611 } else if (U->getOpcode() != UO_AddrOf) {
13612 if (U->getSubExpr()->getType()->isAtomicType())
13613 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
13614 DiagID: diag::warn_atomic_implicit_seq_cst);
13615 }
13616 }
13617}
13618
13619/// AnalyzeImplicitConversions - Find and report any interesting
13620/// implicit conversions in the given expression. There are a couple
13621/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13622static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13623 bool IsListInit/*= false*/) {
13624 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13625 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
13626 while (!WorkList.empty())
13627 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
13628}
13629
13630// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13631// Returns true when emitting a warning about taking the address of a reference.
13632static bool CheckForReference(Sema &SemaRef, const Expr *E,
13633 const PartialDiagnostic &PD) {
13634 E = E->IgnoreParenImpCasts();
13635
13636 const FunctionDecl *FD = nullptr;
13637
13638 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13639 if (!DRE->getDecl()->getType()->isReferenceType())
13640 return false;
13641 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13642 if (!M->getMemberDecl()->getType()->isReferenceType())
13643 return false;
13644 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
13645 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
13646 return false;
13647 FD = Call->getDirectCallee();
13648 } else {
13649 return false;
13650 }
13651
13652 SemaRef.Diag(Loc: E->getExprLoc(), PD);
13653
13654 // If possible, point to location of function.
13655 if (FD) {
13656 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
13657 }
13658
13659 return true;
13660}
13661
13662// Returns true if the SourceLocation is expanded from any macro body.
13663// Returns false if the SourceLocation is invalid, is from not in a macro
13664// expansion, or is from expanded from a top-level macro argument.
13665static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13666 if (Loc.isInvalid())
13667 return false;
13668
13669 while (Loc.isMacroID()) {
13670 if (SM.isMacroBodyExpansion(Loc))
13671 return true;
13672 Loc = SM.getImmediateMacroCallerLoc(Loc);
13673 }
13674
13675 return false;
13676}
13677
13678void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13679 Expr::NullPointerConstantKind NullKind,
13680 bool IsEqual, SourceRange Range) {
13681 if (!E)
13682 return;
13683
13684 // Don't warn inside macros.
13685 if (E->getExprLoc().isMacroID()) {
13686 const SourceManager &SM = getSourceManager();
13687 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
13688 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
13689 return;
13690 }
13691 E = E->IgnoreImpCasts();
13692
13693 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13694
13695 if (isa<CXXThisExpr>(Val: E)) {
13696 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13697 : diag::warn_this_bool_conversion;
13698 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13699 return;
13700 }
13701
13702 bool IsAddressOf = false;
13703
13704 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
13705 if (UO->getOpcode() != UO_AddrOf)
13706 return;
13707 IsAddressOf = true;
13708 E = UO->getSubExpr();
13709 }
13710
13711 if (IsAddressOf) {
13712 unsigned DiagID = IsCompare
13713 ? diag::warn_address_of_reference_null_compare
13714 : diag::warn_address_of_reference_bool_conversion;
13715 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13716 << IsEqual;
13717 if (CheckForReference(SemaRef&: *this, E, PD)) {
13718 return;
13719 }
13720 }
13721
13722 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13723 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
13724 std::string Str;
13725 llvm::raw_string_ostream S(Str);
13726 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13727 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13728 : diag::warn_cast_nonnull_to_bool;
13729 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
13730 << E->getSourceRange() << Range << IsEqual;
13731 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
13732 };
13733
13734 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13735 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
13736 if (auto *Callee = Call->getDirectCallee()) {
13737 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13738 ComplainAboutNonnullParamOrCall(A);
13739 return;
13740 }
13741 }
13742 }
13743
13744 // Complain if we are converting a lambda expression to a boolean value
13745 // outside of instantiation.
13746 if (!inTemplateInstantiation()) {
13747 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
13748 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13749 MRecordDecl && MRecordDecl->isLambda()) {
13750 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
13751 << /*LambdaPointerConversionOperatorType=*/3
13752 << MRecordDecl->getSourceRange() << Range << IsEqual;
13753 return;
13754 }
13755 }
13756 }
13757
13758 // Expect to find a single Decl. Skip anything more complicated.
13759 ValueDecl *D = nullptr;
13760 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
13761 D = R->getDecl();
13762 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13763 D = M->getMemberDecl();
13764 }
13765
13766 // Weak Decls can be null.
13767 if (!D || D->isWeak())
13768 return;
13769
13770 // Check for parameter decl with nonnull attribute
13771 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
13772 if (getCurFunction() &&
13773 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
13774 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13775 ComplainAboutNonnullParamOrCall(A);
13776 return;
13777 }
13778
13779 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
13780 // Skip function template not specialized yet.
13781 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13782 return;
13783 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
13784 assert(ParamIter != FD->param_end());
13785 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
13786
13787 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13788 if (!NonNull->args_size()) {
13789 ComplainAboutNonnullParamOrCall(NonNull);
13790 return;
13791 }
13792
13793 for (const ParamIdx &ArgNo : NonNull->args()) {
13794 if (ArgNo.getASTIndex() == ParamNo) {
13795 ComplainAboutNonnullParamOrCall(NonNull);
13796 return;
13797 }
13798 }
13799 }
13800 }
13801 }
13802 }
13803
13804 QualType T = D->getType();
13805 const bool IsArray = T->isArrayType();
13806 const bool IsFunction = T->isFunctionType();
13807
13808 // Address of function is used to silence the function warning.
13809 if (IsAddressOf && IsFunction) {
13810 return;
13811 }
13812
13813 // Found nothing.
13814 if (!IsAddressOf && !IsFunction && !IsArray)
13815 return;
13816
13817 // Pretty print the expression for the diagnostic.
13818 std::string Str;
13819 llvm::raw_string_ostream S(Str);
13820 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13821
13822 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13823 : diag::warn_impcast_pointer_to_bool;
13824 enum {
13825 AddressOf,
13826 FunctionPointer,
13827 ArrayPointer
13828 } DiagType;
13829 if (IsAddressOf)
13830 DiagType = AddressOf;
13831 else if (IsFunction)
13832 DiagType = FunctionPointer;
13833 else if (IsArray)
13834 DiagType = ArrayPointer;
13835 else
13836 llvm_unreachable("Could not determine diagnostic.");
13837 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13838 << Range << IsEqual;
13839
13840 if (!IsFunction)
13841 return;
13842
13843 // Suggest '&' to silence the function warning.
13844 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
13845 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
13846
13847 // Check to see if '()' fixit should be emitted.
13848 QualType ReturnType;
13849 UnresolvedSet<4> NonTemplateOverloads;
13850 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
13851 if (ReturnType.isNull())
13852 return;
13853
13854 if (IsCompare) {
13855 // There are two cases here. If there is null constant, the only suggest
13856 // for a pointer return type. If the null is 0, then suggest if the return
13857 // type is a pointer or an integer type.
13858 if (!ReturnType->isPointerType()) {
13859 if (NullKind == Expr::NPCK_ZeroExpression ||
13860 NullKind == Expr::NPCK_ZeroLiteral) {
13861 if (!ReturnType->isIntegerType())
13862 return;
13863 } else {
13864 return;
13865 }
13866 }
13867 } else { // !IsCompare
13868 // For function to bool, only suggest if the function pointer has bool
13869 // return type.
13870 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
13871 return;
13872 }
13873 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
13874 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
13875}
13876
13877void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13878 // Don't diagnose in unevaluated contexts.
13879 if (isUnevaluatedContext())
13880 return;
13881
13882 // Don't diagnose for value- or type-dependent expressions.
13883 if (E->isTypeDependent() || E->isValueDependent())
13884 return;
13885
13886 // Check for array bounds violations in cases where the check isn't triggered
13887 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13888 // ArraySubscriptExpr is on the RHS of a variable initialization.
13889 CheckArrayAccess(E);
13890
13891 // This is not the right CC for (e.g.) a variable initialization.
13892 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
13893}
13894
13895void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13896 ::CheckBoolLikeConversion(S&: *this, E, CC);
13897}
13898
13899void Sema::CheckForIntOverflow (const Expr *E) {
13900 // Use a work list to deal with nested struct initializers.
13901 SmallVector<const Expr *, 2> Exprs(1, E);
13902
13903 do {
13904 const Expr *OriginalE = Exprs.pop_back_val();
13905 const Expr *E = OriginalE->IgnoreParenCasts();
13906
13907 if (isa<BinaryOperator, UnaryOperator>(Val: E)) {
13908 E->EvaluateForOverflow(Ctx: Context);
13909 continue;
13910 }
13911
13912 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
13913 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
13914 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
13915 E->EvaluateForOverflow(Ctx: Context);
13916 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
13917 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
13918 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
13919 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
13920 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
13921 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
13922 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
13923 Exprs.push_back(Elt: Temporary->getSubExpr());
13924 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
13925 Exprs.push_back(Elt: Array->getIdx());
13926 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
13927 Exprs.push_back(Elt: Compound->getInitializer());
13928 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
13929 New && New->isArray()) {
13930 if (auto ArraySize = New->getArraySize())
13931 Exprs.push_back(Elt: *ArraySize);
13932 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
13933 Exprs.push_back(Elt: MTE->getSubExpr());
13934 } while (!Exprs.empty());
13935}
13936
13937namespace {
13938
13939/// Visitor for expressions which looks for unsequenced operations on the
13940/// same object.
13941class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13942 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13943
13944 /// A tree of sequenced regions within an expression. Two regions are
13945 /// unsequenced if one is an ancestor or a descendent of the other. When we
13946 /// finish processing an expression with sequencing, such as a comma
13947 /// expression, we fold its tree nodes into its parent, since they are
13948 /// unsequenced with respect to nodes we will visit later.
13949 class SequenceTree {
13950 struct Value {
13951 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13952 unsigned Parent : 31;
13953 LLVM_PREFERRED_TYPE(bool)
13954 unsigned Merged : 1;
13955 };
13956 SmallVector<Value, 8> Values;
13957
13958 public:
13959 /// A region within an expression which may be sequenced with respect
13960 /// to some other region.
13961 class Seq {
13962 friend class SequenceTree;
13963
13964 unsigned Index;
13965
13966 explicit Seq(unsigned N) : Index(N) {}
13967
13968 public:
13969 Seq() : Index(0) {}
13970 };
13971
13972 SequenceTree() { Values.push_back(Elt: Value(0)); }
13973 Seq root() const { return Seq(0); }
13974
13975 /// Create a new sequence of operations, which is an unsequenced
13976 /// subset of \p Parent. This sequence of operations is sequenced with
13977 /// respect to other children of \p Parent.
13978 Seq allocate(Seq Parent) {
13979 Values.push_back(Elt: Value(Parent.Index));
13980 return Seq(Values.size() - 1);
13981 }
13982
13983 /// Merge a sequence of operations into its parent.
13984 void merge(Seq S) {
13985 Values[S.Index].Merged = true;
13986 }
13987
13988 /// Determine whether two operations are unsequenced. This operation
13989 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13990 /// should have been merged into its parent as appropriate.
13991 bool isUnsequenced(Seq Cur, Seq Old) {
13992 unsigned C = representative(K: Cur.Index);
13993 unsigned Target = representative(K: Old.Index);
13994 while (C >= Target) {
13995 if (C == Target)
13996 return true;
13997 C = Values[C].Parent;
13998 }
13999 return false;
14000 }
14001
14002 private:
14003 /// Pick a representative for a sequence.
14004 unsigned representative(unsigned K) {
14005 if (Values[K].Merged)
14006 // Perform path compression as we go.
14007 return Values[K].Parent = representative(K: Values[K].Parent);
14008 return K;
14009 }
14010 };
14011
14012 /// An object for which we can track unsequenced uses.
14013 using Object = const NamedDecl *;
14014
14015 /// Different flavors of object usage which we track. We only track the
14016 /// least-sequenced usage of each kind.
14017 enum UsageKind {
14018 /// A read of an object. Multiple unsequenced reads are OK.
14019 UK_Use,
14020
14021 /// A modification of an object which is sequenced before the value
14022 /// computation of the expression, such as ++n in C++.
14023 UK_ModAsValue,
14024
14025 /// A modification of an object which is not sequenced before the value
14026 /// computation of the expression, such as n++.
14027 UK_ModAsSideEffect,
14028
14029 UK_Count = UK_ModAsSideEffect + 1
14030 };
14031
14032 /// Bundle together a sequencing region and the expression corresponding
14033 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14034 struct Usage {
14035 const Expr *UsageExpr = nullptr;
14036 SequenceTree::Seq Seq;
14037
14038 Usage() = default;
14039 };
14040
14041 struct UsageInfo {
14042 Usage Uses[UK_Count];
14043
14044 /// Have we issued a diagnostic for this object already?
14045 bool Diagnosed = false;
14046
14047 UsageInfo();
14048 };
14049 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14050
14051 Sema &SemaRef;
14052
14053 /// Sequenced regions within the expression.
14054 SequenceTree Tree;
14055
14056 /// Declaration modifications and references which we have seen.
14057 UsageInfoMap UsageMap;
14058
14059 /// The region we are currently within.
14060 SequenceTree::Seq Region;
14061
14062 /// Filled in with declarations which were modified as a side-effect
14063 /// (that is, post-increment operations).
14064 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14065
14066 /// Expressions to check later. We defer checking these to reduce
14067 /// stack usage.
14068 SmallVectorImpl<const Expr *> &WorkList;
14069
14070 /// RAII object wrapping the visitation of a sequenced subexpression of an
14071 /// expression. At the end of this process, the side-effects of the evaluation
14072 /// become sequenced with respect to the value computation of the result, so
14073 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14074 /// UK_ModAsValue.
14075 struct SequencedSubexpression {
14076 SequencedSubexpression(SequenceChecker &Self)
14077 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14078 Self.ModAsSideEffect = &ModAsSideEffect;
14079 }
14080
14081 ~SequencedSubexpression() {
14082 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14083 // Add a new usage with usage kind UK_ModAsValue, and then restore
14084 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14085 // the previous one was empty).
14086 UsageInfo &UI = Self.UsageMap[M.first];
14087 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14088 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14089 SideEffectUsage = M.second;
14090 }
14091 Self.ModAsSideEffect = OldModAsSideEffect;
14092 }
14093
14094 SequenceChecker &Self;
14095 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14096 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14097 };
14098
14099 /// RAII object wrapping the visitation of a subexpression which we might
14100 /// choose to evaluate as a constant. If any subexpression is evaluated and
14101 /// found to be non-constant, this allows us to suppress the evaluation of
14102 /// the outer expression.
14103 class EvaluationTracker {
14104 public:
14105 EvaluationTracker(SequenceChecker &Self)
14106 : Self(Self), Prev(Self.EvalTracker) {
14107 Self.EvalTracker = this;
14108 }
14109
14110 ~EvaluationTracker() {
14111 Self.EvalTracker = Prev;
14112 if (Prev)
14113 Prev->EvalOK &= EvalOK;
14114 }
14115
14116 bool evaluate(const Expr *E, bool &Result) {
14117 if (!EvalOK || E->isValueDependent())
14118 return false;
14119 EvalOK = E->EvaluateAsBooleanCondition(
14120 Result, Ctx: Self.SemaRef.Context,
14121 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14122 return EvalOK;
14123 }
14124
14125 private:
14126 SequenceChecker &Self;
14127 EvaluationTracker *Prev;
14128 bool EvalOK = true;
14129 } *EvalTracker = nullptr;
14130
14131 /// Find the object which is produced by the specified expression,
14132 /// if any.
14133 Object getObject(const Expr *E, bool Mod) const {
14134 E = E->IgnoreParenCasts();
14135 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14136 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14137 return getObject(E: UO->getSubExpr(), Mod);
14138 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14139 if (BO->getOpcode() == BO_Comma)
14140 return getObject(E: BO->getRHS(), Mod);
14141 if (Mod && BO->isAssignmentOp())
14142 return getObject(E: BO->getLHS(), Mod);
14143 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14144 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14145 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14146 return ME->getMemberDecl();
14147 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14148 // FIXME: If this is a reference, map through to its value.
14149 return DRE->getDecl();
14150 return nullptr;
14151 }
14152
14153 /// Note that an object \p O was modified or used by an expression
14154 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14155 /// the object \p O as obtained via the \p UsageMap.
14156 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14157 // Get the old usage for the given object and usage kind.
14158 Usage &U = UI.Uses[UK];
14159 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14160 // If we have a modification as side effect and are in a sequenced
14161 // subexpression, save the old Usage so that we can restore it later
14162 // in SequencedSubexpression::~SequencedSubexpression.
14163 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14164 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14165 // Then record the new usage with the current sequencing region.
14166 U.UsageExpr = UsageExpr;
14167 U.Seq = Region;
14168 }
14169 }
14170
14171 /// Check whether a modification or use of an object \p O in an expression
14172 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14173 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14174 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14175 /// usage and false we are checking for a mod-use unsequenced usage.
14176 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14177 UsageKind OtherKind, bool IsModMod) {
14178 if (UI.Diagnosed)
14179 return;
14180
14181 const Usage &U = UI.Uses[OtherKind];
14182 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14183 return;
14184
14185 const Expr *Mod = U.UsageExpr;
14186 const Expr *ModOrUse = UsageExpr;
14187 if (OtherKind == UK_Use)
14188 std::swap(a&: Mod, b&: ModOrUse);
14189
14190 SemaRef.DiagRuntimeBehavior(
14191 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14192 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14193 : diag::warn_unsequenced_mod_use)
14194 << O << SourceRange(ModOrUse->getExprLoc()));
14195 UI.Diagnosed = true;
14196 }
14197
14198 // A note on note{Pre, Post}{Use, Mod}:
14199 //
14200 // (It helps to follow the algorithm with an expression such as
14201 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14202 // operations before C++17 and both are well-defined in C++17).
14203 //
14204 // When visiting a node which uses/modify an object we first call notePreUse
14205 // or notePreMod before visiting its sub-expression(s). At this point the
14206 // children of the current node have not yet been visited and so the eventual
14207 // uses/modifications resulting from the children of the current node have not
14208 // been recorded yet.
14209 //
14210 // We then visit the children of the current node. After that notePostUse or
14211 // notePostMod is called. These will 1) detect an unsequenced modification
14212 // as side effect (as in "k++ + k") and 2) add a new usage with the
14213 // appropriate usage kind.
14214 //
14215 // We also have to be careful that some operation sequences modification as
14216 // side effect as well (for example: || or ,). To account for this we wrap
14217 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14218 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14219 // which record usages which are modifications as side effect, and then
14220 // downgrade them (or more accurately restore the previous usage which was a
14221 // modification as side effect) when exiting the scope of the sequenced
14222 // subexpression.
14223
14224 void notePreUse(Object O, const Expr *UseExpr) {
14225 UsageInfo &UI = UsageMap[O];
14226 // Uses conflict with other modifications.
14227 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14228 }
14229
14230 void notePostUse(Object O, const Expr *UseExpr) {
14231 UsageInfo &UI = UsageMap[O];
14232 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14233 /*IsModMod=*/false);
14234 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14235 }
14236
14237 void notePreMod(Object O, const Expr *ModExpr) {
14238 UsageInfo &UI = UsageMap[O];
14239 // Modifications conflict with other modifications and with uses.
14240 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14241 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14242 }
14243
14244 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14245 UsageInfo &UI = UsageMap[O];
14246 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14247 /*IsModMod=*/true);
14248 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14249 }
14250
14251public:
14252 SequenceChecker(Sema &S, const Expr *E,
14253 SmallVectorImpl<const Expr *> &WorkList)
14254 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14255 Visit(S: E);
14256 // Silence a -Wunused-private-field since WorkList is now unused.
14257 // TODO: Evaluate if it can be used, and if not remove it.
14258 (void)this->WorkList;
14259 }
14260
14261 void VisitStmt(const Stmt *S) {
14262 // Skip all statements which aren't expressions for now.
14263 }
14264
14265 void VisitExpr(const Expr *E) {
14266 // By default, just recurse to evaluated subexpressions.
14267 Base::VisitStmt(S: E);
14268 }
14269
14270 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14271 for (auto *Sub : CSE->children()) {
14272 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14273 if (!ChildExpr)
14274 continue;
14275
14276 if (ChildExpr == CSE->getOperand())
14277 // Do not recurse over a CoroutineSuspendExpr's operand.
14278 // The operand is also a subexpression of getCommonExpr(), and
14279 // recursing into it directly could confuse object management
14280 // for the sake of sequence tracking.
14281 continue;
14282
14283 Visit(S: Sub);
14284 }
14285 }
14286
14287 void VisitCastExpr(const CastExpr *E) {
14288 Object O = Object();
14289 if (E->getCastKind() == CK_LValueToRValue)
14290 O = getObject(E: E->getSubExpr(), Mod: false);
14291
14292 if (O)
14293 notePreUse(O, UseExpr: E);
14294 VisitExpr(E);
14295 if (O)
14296 notePostUse(O, UseExpr: E);
14297 }
14298
14299 void VisitSequencedExpressions(const Expr *SequencedBefore,
14300 const Expr *SequencedAfter) {
14301 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
14302 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
14303 SequenceTree::Seq OldRegion = Region;
14304
14305 {
14306 SequencedSubexpression SeqBefore(*this);
14307 Region = BeforeRegion;
14308 Visit(S: SequencedBefore);
14309 }
14310
14311 Region = AfterRegion;
14312 Visit(S: SequencedAfter);
14313
14314 Region = OldRegion;
14315
14316 Tree.merge(S: BeforeRegion);
14317 Tree.merge(S: AfterRegion);
14318 }
14319
14320 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14321 // C++17 [expr.sub]p1:
14322 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14323 // expression E1 is sequenced before the expression E2.
14324 if (SemaRef.getLangOpts().CPlusPlus17)
14325 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
14326 else {
14327 Visit(S: ASE->getLHS());
14328 Visit(S: ASE->getRHS());
14329 }
14330 }
14331
14332 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14333 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14334 void VisitBinPtrMem(const BinaryOperator *BO) {
14335 // C++17 [expr.mptr.oper]p4:
14336 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14337 // the expression E1 is sequenced before the expression E2.
14338 if (SemaRef.getLangOpts().CPlusPlus17)
14339 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14340 else {
14341 Visit(S: BO->getLHS());
14342 Visit(S: BO->getRHS());
14343 }
14344 }
14345
14346 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14347 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14348 void VisitBinShlShr(const BinaryOperator *BO) {
14349 // C++17 [expr.shift]p4:
14350 // The expression E1 is sequenced before the expression E2.
14351 if (SemaRef.getLangOpts().CPlusPlus17)
14352 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14353 else {
14354 Visit(S: BO->getLHS());
14355 Visit(S: BO->getRHS());
14356 }
14357 }
14358
14359 void VisitBinComma(const BinaryOperator *BO) {
14360 // C++11 [expr.comma]p1:
14361 // Every value computation and side effect associated with the left
14362 // expression is sequenced before every value computation and side
14363 // effect associated with the right expression.
14364 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14365 }
14366
14367 void VisitBinAssign(const BinaryOperator *BO) {
14368 SequenceTree::Seq RHSRegion;
14369 SequenceTree::Seq LHSRegion;
14370 if (SemaRef.getLangOpts().CPlusPlus17) {
14371 RHSRegion = Tree.allocate(Parent: Region);
14372 LHSRegion = Tree.allocate(Parent: Region);
14373 } else {
14374 RHSRegion = Region;
14375 LHSRegion = Region;
14376 }
14377 SequenceTree::Seq OldRegion = Region;
14378
14379 // C++11 [expr.ass]p1:
14380 // [...] the assignment is sequenced after the value computation
14381 // of the right and left operands, [...]
14382 //
14383 // so check it before inspecting the operands and update the
14384 // map afterwards.
14385 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
14386 if (O)
14387 notePreMod(O, ModExpr: BO);
14388
14389 if (SemaRef.getLangOpts().CPlusPlus17) {
14390 // C++17 [expr.ass]p1:
14391 // [...] The right operand is sequenced before the left operand. [...]
14392 {
14393 SequencedSubexpression SeqBefore(*this);
14394 Region = RHSRegion;
14395 Visit(S: BO->getRHS());
14396 }
14397
14398 Region = LHSRegion;
14399 Visit(S: BO->getLHS());
14400
14401 if (O && isa<CompoundAssignOperator>(Val: BO))
14402 notePostUse(O, UseExpr: BO);
14403
14404 } else {
14405 // C++11 does not specify any sequencing between the LHS and RHS.
14406 Region = LHSRegion;
14407 Visit(S: BO->getLHS());
14408
14409 if (O && isa<CompoundAssignOperator>(Val: BO))
14410 notePostUse(O, UseExpr: BO);
14411
14412 Region = RHSRegion;
14413 Visit(S: BO->getRHS());
14414 }
14415
14416 // C++11 [expr.ass]p1:
14417 // the assignment is sequenced [...] before the value computation of the
14418 // assignment expression.
14419 // C11 6.5.16/3 has no such rule.
14420 Region = OldRegion;
14421 if (O)
14422 notePostMod(O, ModExpr: BO,
14423 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14424 : UK_ModAsSideEffect);
14425 if (SemaRef.getLangOpts().CPlusPlus17) {
14426 Tree.merge(S: RHSRegion);
14427 Tree.merge(S: LHSRegion);
14428 }
14429 }
14430
14431 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14432 VisitBinAssign(BO: CAO);
14433 }
14434
14435 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14436 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14437 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14438 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14439 if (!O)
14440 return VisitExpr(E: UO);
14441
14442 notePreMod(O, ModExpr: UO);
14443 Visit(S: UO->getSubExpr());
14444 // C++11 [expr.pre.incr]p1:
14445 // the expression ++x is equivalent to x+=1
14446 notePostMod(O, ModExpr: UO,
14447 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14448 : UK_ModAsSideEffect);
14449 }
14450
14451 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14452 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14453 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14454 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14455 if (!O)
14456 return VisitExpr(E: UO);
14457
14458 notePreMod(O, ModExpr: UO);
14459 Visit(S: UO->getSubExpr());
14460 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
14461 }
14462
14463 void VisitBinLOr(const BinaryOperator *BO) {
14464 // C++11 [expr.log.or]p2:
14465 // If the second expression is evaluated, every value computation and
14466 // side effect associated with the first expression is sequenced before
14467 // every value computation and side effect associated with the
14468 // second expression.
14469 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14470 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14471 SequenceTree::Seq OldRegion = Region;
14472
14473 EvaluationTracker Eval(*this);
14474 {
14475 SequencedSubexpression Sequenced(*this);
14476 Region = LHSRegion;
14477 Visit(S: BO->getLHS());
14478 }
14479
14480 // C++11 [expr.log.or]p1:
14481 // [...] the second operand is not evaluated if the first operand
14482 // evaluates to true.
14483 bool EvalResult = false;
14484 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14485 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14486 if (ShouldVisitRHS) {
14487 Region = RHSRegion;
14488 Visit(S: BO->getRHS());
14489 }
14490
14491 Region = OldRegion;
14492 Tree.merge(S: LHSRegion);
14493 Tree.merge(S: RHSRegion);
14494 }
14495
14496 void VisitBinLAnd(const BinaryOperator *BO) {
14497 // C++11 [expr.log.and]p2:
14498 // If the second expression is evaluated, every value computation and
14499 // side effect associated with the first expression is sequenced before
14500 // every value computation and side effect associated with the
14501 // second expression.
14502 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14503 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14504 SequenceTree::Seq OldRegion = Region;
14505
14506 EvaluationTracker Eval(*this);
14507 {
14508 SequencedSubexpression Sequenced(*this);
14509 Region = LHSRegion;
14510 Visit(S: BO->getLHS());
14511 }
14512
14513 // C++11 [expr.log.and]p1:
14514 // [...] the second operand is not evaluated if the first operand is false.
14515 bool EvalResult = false;
14516 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14517 bool ShouldVisitRHS = !EvalOK || EvalResult;
14518 if (ShouldVisitRHS) {
14519 Region = RHSRegion;
14520 Visit(S: BO->getRHS());
14521 }
14522
14523 Region = OldRegion;
14524 Tree.merge(S: LHSRegion);
14525 Tree.merge(S: RHSRegion);
14526 }
14527
14528 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14529 // C++11 [expr.cond]p1:
14530 // [...] Every value computation and side effect associated with the first
14531 // expression is sequenced before every value computation and side effect
14532 // associated with the second or third expression.
14533 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
14534
14535 // No sequencing is specified between the true and false expression.
14536 // However since exactly one of both is going to be evaluated we can
14537 // consider them to be sequenced. This is needed to avoid warning on
14538 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14539 // both the true and false expressions because we can't evaluate x.
14540 // This will still allow us to detect an expression like (pre C++17)
14541 // "(x ? y += 1 : y += 2) = y".
14542 //
14543 // We don't wrap the visitation of the true and false expression with
14544 // SequencedSubexpression because we don't want to downgrade modifications
14545 // as side effect in the true and false expressions after the visition
14546 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14547 // not warn between the two "y++", but we should warn between the "y++"
14548 // and the "y".
14549 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
14550 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
14551 SequenceTree::Seq OldRegion = Region;
14552
14553 EvaluationTracker Eval(*this);
14554 {
14555 SequencedSubexpression Sequenced(*this);
14556 Region = ConditionRegion;
14557 Visit(S: CO->getCond());
14558 }
14559
14560 // C++11 [expr.cond]p1:
14561 // [...] The first expression is contextually converted to bool (Clause 4).
14562 // It is evaluated and if it is true, the result of the conditional
14563 // expression is the value of the second expression, otherwise that of the
14564 // third expression. Only one of the second and third expressions is
14565 // evaluated. [...]
14566 bool EvalResult = false;
14567 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
14568 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14569 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14570 if (ShouldVisitTrueExpr) {
14571 Region = TrueRegion;
14572 Visit(S: CO->getTrueExpr());
14573 }
14574 if (ShouldVisitFalseExpr) {
14575 Region = FalseRegion;
14576 Visit(S: CO->getFalseExpr());
14577 }
14578
14579 Region = OldRegion;
14580 Tree.merge(S: ConditionRegion);
14581 Tree.merge(S: TrueRegion);
14582 Tree.merge(S: FalseRegion);
14583 }
14584
14585 void VisitCallExpr(const CallExpr *CE) {
14586 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14587
14588 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
14589 return;
14590
14591 // C++11 [intro.execution]p15:
14592 // When calling a function [...], every value computation and side effect
14593 // associated with any argument expression, or with the postfix expression
14594 // designating the called function, is sequenced before execution of every
14595 // expression or statement in the body of the function [and thus before
14596 // the value computation of its result].
14597 SequencedSubexpression Sequenced(*this);
14598 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
14599 // C++17 [expr.call]p5
14600 // The postfix-expression is sequenced before each expression in the
14601 // expression-list and any default argument. [...]
14602 SequenceTree::Seq CalleeRegion;
14603 SequenceTree::Seq OtherRegion;
14604 if (SemaRef.getLangOpts().CPlusPlus17) {
14605 CalleeRegion = Tree.allocate(Parent: Region);
14606 OtherRegion = Tree.allocate(Parent: Region);
14607 } else {
14608 CalleeRegion = Region;
14609 OtherRegion = Region;
14610 }
14611 SequenceTree::Seq OldRegion = Region;
14612
14613 // Visit the callee expression first.
14614 Region = CalleeRegion;
14615 if (SemaRef.getLangOpts().CPlusPlus17) {
14616 SequencedSubexpression Sequenced(*this);
14617 Visit(S: CE->getCallee());
14618 } else {
14619 Visit(S: CE->getCallee());
14620 }
14621
14622 // Then visit the argument expressions.
14623 Region = OtherRegion;
14624 for (const Expr *Argument : CE->arguments())
14625 Visit(S: Argument);
14626
14627 Region = OldRegion;
14628 if (SemaRef.getLangOpts().CPlusPlus17) {
14629 Tree.merge(S: CalleeRegion);
14630 Tree.merge(S: OtherRegion);
14631 }
14632 });
14633 }
14634
14635 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14636 // C++17 [over.match.oper]p2:
14637 // [...] the operator notation is first transformed to the equivalent
14638 // function-call notation as summarized in Table 12 (where @ denotes one
14639 // of the operators covered in the specified subclause). However, the
14640 // operands are sequenced in the order prescribed for the built-in
14641 // operator (Clause 8).
14642 //
14643 // From the above only overloaded binary operators and overloaded call
14644 // operators have sequencing rules in C++17 that we need to handle
14645 // separately.
14646 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14647 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14648 return VisitCallExpr(CE: CXXOCE);
14649
14650 enum {
14651 NoSequencing,
14652 LHSBeforeRHS,
14653 RHSBeforeLHS,
14654 LHSBeforeRest
14655 } SequencingKind;
14656 switch (CXXOCE->getOperator()) {
14657 case OO_Equal:
14658 case OO_PlusEqual:
14659 case OO_MinusEqual:
14660 case OO_StarEqual:
14661 case OO_SlashEqual:
14662 case OO_PercentEqual:
14663 case OO_CaretEqual:
14664 case OO_AmpEqual:
14665 case OO_PipeEqual:
14666 case OO_LessLessEqual:
14667 case OO_GreaterGreaterEqual:
14668 SequencingKind = RHSBeforeLHS;
14669 break;
14670
14671 case OO_LessLess:
14672 case OO_GreaterGreater:
14673 case OO_AmpAmp:
14674 case OO_PipePipe:
14675 case OO_Comma:
14676 case OO_ArrowStar:
14677 case OO_Subscript:
14678 SequencingKind = LHSBeforeRHS;
14679 break;
14680
14681 case OO_Call:
14682 SequencingKind = LHSBeforeRest;
14683 break;
14684
14685 default:
14686 SequencingKind = NoSequencing;
14687 break;
14688 }
14689
14690 if (SequencingKind == NoSequencing)
14691 return VisitCallExpr(CE: CXXOCE);
14692
14693 // This is a call, so all subexpressions are sequenced before the result.
14694 SequencedSubexpression Sequenced(*this);
14695
14696 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
14697 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14698 "Should only get there with C++17 and above!");
14699 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14700 "Should only get there with an overloaded binary operator"
14701 " or an overloaded call operator!");
14702
14703 if (SequencingKind == LHSBeforeRest) {
14704 assert(CXXOCE->getOperator() == OO_Call &&
14705 "We should only have an overloaded call operator here!");
14706
14707 // This is very similar to VisitCallExpr, except that we only have the
14708 // C++17 case. The postfix-expression is the first argument of the
14709 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14710 // are in the following arguments.
14711 //
14712 // Note that we intentionally do not visit the callee expression since
14713 // it is just a decayed reference to a function.
14714 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
14715 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
14716 SequenceTree::Seq OldRegion = Region;
14717
14718 assert(CXXOCE->getNumArgs() >= 1 &&
14719 "An overloaded call operator must have at least one argument"
14720 " for the postfix-expression!");
14721 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14722 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14723 CXXOCE->getNumArgs() - 1);
14724
14725 // Visit the postfix-expression first.
14726 {
14727 Region = PostfixExprRegion;
14728 SequencedSubexpression Sequenced(*this);
14729 Visit(S: PostfixExpr);
14730 }
14731
14732 // Then visit the argument expressions.
14733 Region = ArgsRegion;
14734 for (const Expr *Arg : Args)
14735 Visit(S: Arg);
14736
14737 Region = OldRegion;
14738 Tree.merge(S: PostfixExprRegion);
14739 Tree.merge(S: ArgsRegion);
14740 } else {
14741 assert(CXXOCE->getNumArgs() == 2 &&
14742 "Should only have two arguments here!");
14743 assert((SequencingKind == LHSBeforeRHS ||
14744 SequencingKind == RHSBeforeLHS) &&
14745 "Unexpected sequencing kind!");
14746
14747 // We do not visit the callee expression since it is just a decayed
14748 // reference to a function.
14749 const Expr *E1 = CXXOCE->getArg(Arg: 0);
14750 const Expr *E2 = CXXOCE->getArg(Arg: 1);
14751 if (SequencingKind == RHSBeforeLHS)
14752 std::swap(a&: E1, b&: E2);
14753
14754 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
14755 }
14756 });
14757 }
14758
14759 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14760 // This is a call, so all subexpressions are sequenced before the result.
14761 SequencedSubexpression Sequenced(*this);
14762
14763 if (!CCE->isListInitialization())
14764 return VisitExpr(E: CCE);
14765
14766 // In C++11, list initializations are sequenced.
14767 SequenceExpressionsInOrder(
14768 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14769 }
14770
14771 void VisitInitListExpr(const InitListExpr *ILE) {
14772 if (!SemaRef.getLangOpts().CPlusPlus11)
14773 return VisitExpr(E: ILE);
14774
14775 // In C++11, list initializations are sequenced.
14776 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
14777 }
14778
14779 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14780 // C++20 parenthesized list initializations are sequenced. See C++20
14781 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14782 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
14783 }
14784
14785private:
14786 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14787 SmallVector<SequenceTree::Seq, 32> Elts;
14788 SequenceTree::Seq Parent = Region;
14789 for (const Expr *E : ExpressionList) {
14790 if (!E)
14791 continue;
14792 Region = Tree.allocate(Parent);
14793 Elts.push_back(Elt: Region);
14794 Visit(S: E);
14795 }
14796
14797 // Forget that the initializers are sequenced.
14798 Region = Parent;
14799 for (unsigned I = 0; I < Elts.size(); ++I)
14800 Tree.merge(S: Elts[I]);
14801 }
14802};
14803
14804SequenceChecker::UsageInfo::UsageInfo() = default;
14805
14806} // namespace
14807
14808void Sema::CheckUnsequencedOperations(const Expr *E) {
14809 SmallVector<const Expr *, 8> WorkList;
14810 WorkList.push_back(Elt: E);
14811 while (!WorkList.empty()) {
14812 const Expr *Item = WorkList.pop_back_val();
14813 SequenceChecker(*this, Item, WorkList);
14814 }
14815}
14816
14817void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14818 bool IsConstexpr) {
14819 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14820 IsConstexpr || isa<ConstantExpr>(Val: E));
14821 CheckImplicitConversions(E, CC: CheckLoc);
14822 if (!E->isInstantiationDependent())
14823 CheckUnsequencedOperations(E);
14824 if (!IsConstexpr && !E->isValueDependent())
14825 CheckForIntOverflow(E);
14826}
14827
14828void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14829 FieldDecl *BitField,
14830 Expr *Init) {
14831 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
14832}
14833
14834static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14835 SourceLocation Loc) {
14836 if (!PType->isVariablyModifiedType())
14837 return;
14838 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
14839 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
14840 return;
14841 }
14842 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
14843 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
14844 return;
14845 }
14846 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
14847 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
14848 return;
14849 }
14850
14851 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
14852 if (!AT)
14853 return;
14854
14855 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
14856 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
14857 return;
14858 }
14859
14860 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
14861}
14862
14863bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14864 bool CheckParameterNames) {
14865 bool HasInvalidParm = false;
14866 for (ParmVarDecl *Param : Parameters) {
14867 assert(Param && "null in a parameter list");
14868 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14869 // function declarator that is part of a function definition of
14870 // that function shall not have incomplete type.
14871 //
14872 // C++23 [dcl.fct.def.general]/p2
14873 // The type of a parameter [...] for a function definition
14874 // shall not be a (possibly cv-qualified) class type that is incomplete
14875 // or abstract within the function body unless the function is deleted.
14876 if (!Param->isInvalidDecl() &&
14877 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
14878 DiagID: diag::err_typecheck_decl_incomplete_type) ||
14879 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
14880 DiagID: diag::err_abstract_type_in_decl,
14881 Args: AbstractParamType))) {
14882 Param->setInvalidDecl();
14883 HasInvalidParm = true;
14884 }
14885
14886 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14887 // declaration of each parameter shall include an identifier.
14888 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14889 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14890 // Diagnose this as an extension in C17 and earlier.
14891 if (!getLangOpts().C23)
14892 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
14893 }
14894
14895 // C99 6.7.5.3p12:
14896 // If the function declarator is not part of a definition of that
14897 // function, parameters may have incomplete type and may use the [*]
14898 // notation in their sequences of declarator specifiers to specify
14899 // variable length array types.
14900 QualType PType = Param->getOriginalType();
14901 // FIXME: This diagnostic should point the '[*]' if source-location
14902 // information is added for it.
14903 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
14904
14905 // If the parameter is a c++ class type and it has to be destructed in the
14906 // callee function, declare the destructor so that it can be called by the
14907 // callee function. Do not perform any direct access check on the dtor here.
14908 if (!Param->isInvalidDecl()) {
14909 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14910 if (!ClassDecl->isInvalidDecl() &&
14911 !ClassDecl->hasIrrelevantDestructor() &&
14912 !ClassDecl->isDependentContext() &&
14913 ClassDecl->isParamDestroyedInCallee()) {
14914 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
14915 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
14916 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
14917 }
14918 }
14919 }
14920
14921 // Parameters with the pass_object_size attribute only need to be marked
14922 // constant at function definitions. Because we lack information about
14923 // whether we're on a declaration or definition when we're instantiating the
14924 // attribute, we need to check for constness here.
14925 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14926 if (!Param->getType().isConstQualified())
14927 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
14928 << Attr->getSpelling() << 1;
14929
14930 // Check for parameter names shadowing fields from the class.
14931 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14932 // The owning context for the parameter should be the function, but we
14933 // want to see if this function's declaration context is a record.
14934 DeclContext *DC = Param->getDeclContext();
14935 if (DC && DC->isFunctionOrMethod()) {
14936 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
14937 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
14938 RD, /*DeclIsField*/ false);
14939 }
14940 }
14941
14942 if (!Param->isInvalidDecl() &&
14943 Param->getOriginalType()->isWebAssemblyTableType()) {
14944 Param->setInvalidDecl();
14945 HasInvalidParm = true;
14946 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
14947 }
14948 }
14949
14950 return HasInvalidParm;
14951}
14952
14953std::optional<std::pair<
14954 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
14955 *E,
14956 ASTContext
14957 &Ctx);
14958
14959/// Compute the alignment and offset of the base class object given the
14960/// derived-to-base cast expression and the alignment and offset of the derived
14961/// class object.
14962static std::pair<CharUnits, CharUnits>
14963getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14964 CharUnits BaseAlignment, CharUnits Offset,
14965 ASTContext &Ctx) {
14966 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14967 ++PathI) {
14968 const CXXBaseSpecifier *Base = *PathI;
14969 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14970 if (Base->isVirtual()) {
14971 // The complete object may have a lower alignment than the non-virtual
14972 // alignment of the base, in which case the base may be misaligned. Choose
14973 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14974 // conservative lower bound of the complete object alignment.
14975 CharUnits NonVirtualAlignment =
14976 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
14977 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
14978 Offset = CharUnits::Zero();
14979 } else {
14980 const ASTRecordLayout &RL =
14981 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
14982 Offset += RL.getBaseClassOffset(Base: BaseDecl);
14983 }
14984 DerivedType = Base->getType();
14985 }
14986
14987 return std::make_pair(x&: BaseAlignment, y&: Offset);
14988}
14989
14990/// Compute the alignment and offset of a binary additive operator.
14991static std::optional<std::pair<CharUnits, CharUnits>>
14992getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14993 bool IsSub, ASTContext &Ctx) {
14994 QualType PointeeType = PtrE->getType()->getPointeeType();
14995
14996 if (!PointeeType->isConstantSizeType())
14997 return std::nullopt;
14998
14999 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15000
15001 if (!P)
15002 return std::nullopt;
15003
15004 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15005 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15006 CharUnits Offset = EltSize * IdxRes->getExtValue();
15007 if (IsSub)
15008 Offset = -Offset;
15009 return std::make_pair(x&: P->first, y: P->second + Offset);
15010 }
15011
15012 // If the integer expression isn't a constant expression, compute the lower
15013 // bound of the alignment using the alignment and offset of the pointer
15014 // expression and the element size.
15015 return std::make_pair(
15016 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15017 y: CharUnits::Zero());
15018}
15019
15020/// This helper function takes an lvalue expression and returns the alignment of
15021/// a VarDecl and a constant offset from the VarDecl.
15022std::optional<std::pair<
15023 CharUnits,
15024 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15025 ASTContext &Ctx) {
15026 E = E->IgnoreParens();
15027 switch (E->getStmtClass()) {
15028 default:
15029 break;
15030 case Stmt::CStyleCastExprClass:
15031 case Stmt::CXXStaticCastExprClass:
15032 case Stmt::ImplicitCastExprClass: {
15033 auto *CE = cast<CastExpr>(Val: E);
15034 const Expr *From = CE->getSubExpr();
15035 switch (CE->getCastKind()) {
15036 default:
15037 break;
15038 case CK_NoOp:
15039 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15040 case CK_UncheckedDerivedToBase:
15041 case CK_DerivedToBase: {
15042 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15043 if (!P)
15044 break;
15045 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15046 Offset: P->second, Ctx);
15047 }
15048 }
15049 break;
15050 }
15051 case Stmt::ArraySubscriptExprClass: {
15052 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15053 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15054 IsSub: false, Ctx);
15055 }
15056 case Stmt::DeclRefExprClass: {
15057 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15058 // FIXME: If VD is captured by copy or is an escaping __block variable,
15059 // use the alignment of VD's type.
15060 if (!VD->getType()->isReferenceType()) {
15061 // Dependent alignment cannot be resolved -> bail out.
15062 if (VD->hasDependentAlignment())
15063 break;
15064 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15065 }
15066 if (VD->hasInit())
15067 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15068 }
15069 break;
15070 }
15071 case Stmt::MemberExprClass: {
15072 auto *ME = cast<MemberExpr>(Val: E);
15073 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15074 if (!FD || FD->getType()->isReferenceType() ||
15075 FD->getParent()->isInvalidDecl())
15076 break;
15077 std::optional<std::pair<CharUnits, CharUnits>> P;
15078 if (ME->isArrow())
15079 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15080 else
15081 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15082 if (!P)
15083 break;
15084 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15085 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15086 return std::make_pair(x&: P->first,
15087 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15088 }
15089 case Stmt::UnaryOperatorClass: {
15090 auto *UO = cast<UnaryOperator>(Val: E);
15091 switch (UO->getOpcode()) {
15092 default:
15093 break;
15094 case UO_Deref:
15095 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15096 }
15097 break;
15098 }
15099 case Stmt::BinaryOperatorClass: {
15100 auto *BO = cast<BinaryOperator>(Val: E);
15101 auto Opcode = BO->getOpcode();
15102 switch (Opcode) {
15103 default:
15104 break;
15105 case BO_Comma:
15106 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15107 }
15108 break;
15109 }
15110 }
15111 return std::nullopt;
15112}
15113
15114/// This helper function takes a pointer expression and returns the alignment of
15115/// a VarDecl and a constant offset from the VarDecl.
15116std::optional<std::pair<
15117 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15118 *E,
15119 ASTContext
15120 &Ctx) {
15121 E = E->IgnoreParens();
15122 switch (E->getStmtClass()) {
15123 default:
15124 break;
15125 case Stmt::CStyleCastExprClass:
15126 case Stmt::CXXStaticCastExprClass:
15127 case Stmt::ImplicitCastExprClass: {
15128 auto *CE = cast<CastExpr>(Val: E);
15129 const Expr *From = CE->getSubExpr();
15130 switch (CE->getCastKind()) {
15131 default:
15132 break;
15133 case CK_NoOp:
15134 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15135 case CK_ArrayToPointerDecay:
15136 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15137 case CK_UncheckedDerivedToBase:
15138 case CK_DerivedToBase: {
15139 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15140 if (!P)
15141 break;
15142 return getDerivedToBaseAlignmentAndOffset(
15143 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15144 }
15145 }
15146 break;
15147 }
15148 case Stmt::CXXThisExprClass: {
15149 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15150 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15151 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15152 }
15153 case Stmt::UnaryOperatorClass: {
15154 auto *UO = cast<UnaryOperator>(Val: E);
15155 if (UO->getOpcode() == UO_AddrOf)
15156 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15157 break;
15158 }
15159 case Stmt::BinaryOperatorClass: {
15160 auto *BO = cast<BinaryOperator>(Val: E);
15161 auto Opcode = BO->getOpcode();
15162 switch (Opcode) {
15163 default:
15164 break;
15165 case BO_Add:
15166 case BO_Sub: {
15167 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15168 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15169 std::swap(a&: LHS, b&: RHS);
15170 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15171 Ctx);
15172 }
15173 case BO_Comma:
15174 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15175 }
15176 break;
15177 }
15178 }
15179 return std::nullopt;
15180}
15181
15182static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15183 // See if we can compute the alignment of a VarDecl and an offset from it.
15184 std::optional<std::pair<CharUnits, CharUnits>> P =
15185 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15186
15187 if (P)
15188 return P->first.alignmentAtOffset(offset: P->second);
15189
15190 // If that failed, return the type's alignment.
15191 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15192}
15193
15194void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15195 // This is actually a lot of work to potentially be doing on every
15196 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15197 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15198 return;
15199
15200 // Ignore dependent types.
15201 if (T->isDependentType() || Op->getType()->isDependentType())
15202 return;
15203
15204 // Require that the destination be a pointer type.
15205 const PointerType *DestPtr = T->getAs<PointerType>();
15206 if (!DestPtr) return;
15207
15208 // If the destination has alignment 1, we're done.
15209 QualType DestPointee = DestPtr->getPointeeType();
15210 if (DestPointee->isIncompleteType()) return;
15211 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15212 if (DestAlign.isOne()) return;
15213
15214 // Require that the source be a pointer type.
15215 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15216 if (!SrcPtr) return;
15217 QualType SrcPointee = SrcPtr->getPointeeType();
15218
15219 // Explicitly allow casts from cv void*. We already implicitly
15220 // allowed casts to cv void*, since they have alignment 1.
15221 // Also allow casts involving incomplete types, which implicitly
15222 // includes 'void'.
15223 if (SrcPointee->isIncompleteType()) return;
15224
15225 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15226
15227 if (SrcAlign >= DestAlign) return;
15228
15229 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15230 << Op->getType() << T
15231 << static_cast<unsigned>(SrcAlign.getQuantity())
15232 << static_cast<unsigned>(DestAlign.getQuantity())
15233 << TRange << Op->getSourceRange();
15234}
15235
15236void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15237 const ArraySubscriptExpr *ASE,
15238 bool AllowOnePastEnd, bool IndexNegated) {
15239 // Already diagnosed by the constant evaluator.
15240 if (isConstantEvaluatedContext())
15241 return;
15242
15243 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15244 if (IndexExpr->isValueDependent())
15245 return;
15246
15247 const Type *EffectiveType =
15248 BaseExpr->getType()->getPointeeOrArrayElementType();
15249 BaseExpr = BaseExpr->IgnoreParenCasts();
15250 const ConstantArrayType *ArrayTy =
15251 Context.getAsConstantArrayType(T: BaseExpr->getType());
15252
15253 LangOptions::StrictFlexArraysLevelKind
15254 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15255
15256 const Type *BaseType =
15257 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15258 bool IsUnboundedArray =
15259 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15260 Context, StrictFlexArraysLevel,
15261 /*IgnoreTemplateOrMacroSubstitution=*/true);
15262 if (EffectiveType->isDependentType() ||
15263 (!IsUnboundedArray && BaseType->isDependentType()))
15264 return;
15265
15266 Expr::EvalResult Result;
15267 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15268 return;
15269
15270 llvm::APSInt index = Result.Val.getInt();
15271 if (IndexNegated) {
15272 index.setIsUnsigned(false);
15273 index = -index;
15274 }
15275
15276 if (IsUnboundedArray) {
15277 if (EffectiveType->isFunctionType())
15278 return;
15279 if (index.isUnsigned() || !index.isNegative()) {
15280 const auto &ASTC = getASTContext();
15281 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15282 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15283 if (index.getBitWidth() < AddrBits)
15284 index = index.zext(width: AddrBits);
15285 std::optional<CharUnits> ElemCharUnits =
15286 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15287 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15288 // pointer) bounds-checking isn't meaningful.
15289 if (!ElemCharUnits || ElemCharUnits->isZero())
15290 return;
15291 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15292 // If index has more active bits than address space, we already know
15293 // we have a bounds violation to warn about. Otherwise, compute
15294 // address of (index + 1)th element, and warn about bounds violation
15295 // only if that address exceeds address space.
15296 if (index.getActiveBits() <= AddrBits) {
15297 bool Overflow;
15298 llvm::APInt Product(index);
15299 Product += 1;
15300 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
15301 if (!Overflow && Product.getActiveBits() <= AddrBits)
15302 return;
15303 }
15304
15305 // Need to compute max possible elements in address space, since that
15306 // is included in diag message.
15307 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
15308 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
15309 MaxElems += 1;
15310 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
15311 MaxElems = MaxElems.udiv(RHS: ElemBytes);
15312
15313 unsigned DiagID =
15314 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15315 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15316
15317 // Diag message shows element size in bits and in "bytes" (platform-
15318 // dependent CharUnits)
15319 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15320 PD: PDiag(DiagID) << index << AddrBits
15321 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
15322 << ElemBytes << MaxElems
15323 << MaxElems.getZExtValue()
15324 << IndexExpr->getSourceRange());
15325
15326 const NamedDecl *ND = nullptr;
15327 // Try harder to find a NamedDecl to point at in the note.
15328 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15329 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15330 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15331 ND = DRE->getDecl();
15332 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15333 ND = ME->getMemberDecl();
15334
15335 if (ND)
15336 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15337 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15338 }
15339 return;
15340 }
15341
15342 if (index.isUnsigned() || !index.isNegative()) {
15343 // It is possible that the type of the base expression after
15344 // IgnoreParenCasts is incomplete, even though the type of the base
15345 // expression before IgnoreParenCasts is complete (see PR39746 for an
15346 // example). In this case we have no information about whether the array
15347 // access exceeds the array bounds. However we can still diagnose an array
15348 // access which precedes the array bounds.
15349 if (BaseType->isIncompleteType())
15350 return;
15351
15352 llvm::APInt size = ArrayTy->getSize();
15353
15354 if (BaseType != EffectiveType) {
15355 // Make sure we're comparing apples to apples when comparing index to
15356 // size.
15357 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
15358 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
15359
15360 // Handle ptrarith_typesize being zero, such as when casting to void*.
15361 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15362 if (!ptrarith_typesize)
15363 ptrarith_typesize = Context.getCharWidth();
15364
15365 if (ptrarith_typesize != array_typesize) {
15366 // There's a cast to a different size type involved.
15367 uint64_t ratio = array_typesize / ptrarith_typesize;
15368
15369 // TODO: Be smarter about handling cases where array_typesize is not a
15370 // multiple of ptrarith_typesize.
15371 if (ptrarith_typesize * ratio == array_typesize)
15372 size *= llvm::APInt(size.getBitWidth(), ratio);
15373 }
15374 }
15375
15376 if (size.getBitWidth() > index.getBitWidth())
15377 index = index.zext(width: size.getBitWidth());
15378 else if (size.getBitWidth() < index.getBitWidth())
15379 size = size.zext(width: index.getBitWidth());
15380
15381 // For array subscripting the index must be less than size, but for pointer
15382 // arithmetic also allow the index (offset) to be equal to size since
15383 // computing the next address after the end of the array is legal and
15384 // commonly done e.g. in C++ iterators and range-based for loops.
15385 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
15386 return;
15387
15388 // Suppress the warning if the subscript expression (as identified by the
15389 // ']' location) and the index expression are both from macro expansions
15390 // within a system header.
15391 if (ASE) {
15392 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15393 Loc: ASE->getRBracketLoc());
15394 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
15395 SourceLocation IndexLoc =
15396 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
15397 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
15398 return;
15399 }
15400 }
15401
15402 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15403 : diag::warn_ptr_arith_exceeds_bounds;
15404 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15405 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15406
15407 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15408 PD: PDiag(DiagID)
15409 << index << ArrayTy->desugar() << CastMsg
15410 << CastMsgTy << IndexExpr->getSourceRange());
15411 } else {
15412 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15413 if (!ASE) {
15414 DiagID = diag::warn_ptr_arith_precedes_bounds;
15415 if (index.isNegative()) index = -index;
15416 }
15417
15418 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15419 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
15420 }
15421
15422 const NamedDecl *ND = nullptr;
15423 // Try harder to find a NamedDecl to point at in the note.
15424 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15425 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15426 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15427 ND = DRE->getDecl();
15428 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15429 ND = ME->getMemberDecl();
15430
15431 if (ND)
15432 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15433 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15434}
15435
15436void Sema::CheckArrayAccess(const Expr *expr) {
15437 int AllowOnePastEnd = 0;
15438 while (expr) {
15439 expr = expr->IgnoreParenImpCasts();
15440 switch (expr->getStmtClass()) {
15441 case Stmt::ArraySubscriptExprClass: {
15442 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
15443 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
15444 AllowOnePastEnd: AllowOnePastEnd > 0);
15445 expr = ASE->getBase();
15446 break;
15447 }
15448 case Stmt::MemberExprClass: {
15449 expr = cast<MemberExpr>(Val: expr)->getBase();
15450 break;
15451 }
15452 case Stmt::ArraySectionExprClass: {
15453 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
15454 // FIXME: We should probably be checking all of the elements to the
15455 // 'length' here as well.
15456 if (ASE->getLowerBound())
15457 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
15458 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
15459 return;
15460 }
15461 case Stmt::UnaryOperatorClass: {
15462 // Only unwrap the * and & unary operators
15463 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
15464 expr = UO->getSubExpr();
15465 switch (UO->getOpcode()) {
15466 case UO_AddrOf:
15467 AllowOnePastEnd++;
15468 break;
15469 case UO_Deref:
15470 AllowOnePastEnd--;
15471 break;
15472 default:
15473 return;
15474 }
15475 break;
15476 }
15477 case Stmt::ConditionalOperatorClass: {
15478 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
15479 if (const Expr *lhs = cond->getLHS())
15480 CheckArrayAccess(expr: lhs);
15481 if (const Expr *rhs = cond->getRHS())
15482 CheckArrayAccess(expr: rhs);
15483 return;
15484 }
15485 case Stmt::CXXOperatorCallExprClass: {
15486 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
15487 for (const auto *Arg : OCE->arguments())
15488 CheckArrayAccess(expr: Arg);
15489 return;
15490 }
15491 default:
15492 return;
15493 }
15494 }
15495}
15496
15497static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15498 Expr *RHS, bool isProperty) {
15499 // Check if RHS is an Objective-C object literal, which also can get
15500 // immediately zapped in a weak reference. Note that we explicitly
15501 // allow ObjCStringLiterals, since those are designed to never really die.
15502 RHS = RHS->IgnoreParenImpCasts();
15503
15504 // This enum needs to match with the 'select' in
15505 // warn_objc_arc_literal_assign (off-by-1).
15506 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
15507 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15508 return false;
15509
15510 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
15511 << (unsigned) Kind
15512 << (isProperty ? 0 : 1)
15513 << RHS->getSourceRange();
15514
15515 return true;
15516}
15517
15518static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15519 Qualifiers::ObjCLifetime LT,
15520 Expr *RHS, bool isProperty) {
15521 // Strip off any implicit cast added to get to the one ARC-specific.
15522 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15523 if (cast->getCastKind() == CK_ARCConsumeObject) {
15524 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
15525 << (LT == Qualifiers::OCL_ExplicitNone)
15526 << (isProperty ? 0 : 1)
15527 << RHS->getSourceRange();
15528 return true;
15529 }
15530 RHS = cast->getSubExpr();
15531 }
15532
15533 if (LT == Qualifiers::OCL_Weak &&
15534 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15535 return true;
15536
15537 return false;
15538}
15539
15540bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15541 QualType LHS, Expr *RHS) {
15542 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15543
15544 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15545 return false;
15546
15547 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
15548 return true;
15549
15550 return false;
15551}
15552
15553void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15554 Expr *LHS, Expr *RHS) {
15555 QualType LHSType;
15556 // PropertyRef on LHS type need be directly obtained from
15557 // its declaration as it has a PseudoType.
15558 ObjCPropertyRefExpr *PRE
15559 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
15560 if (PRE && !PRE->isImplicitProperty()) {
15561 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15562 if (PD)
15563 LHSType = PD->getType();
15564 }
15565
15566 if (LHSType.isNull())
15567 LHSType = LHS->getType();
15568
15569 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15570
15571 if (LT == Qualifiers::OCL_Weak) {
15572 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
15573 getCurFunction()->markSafeWeakUse(E: LHS);
15574 }
15575
15576 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
15577 return;
15578
15579 // FIXME. Check for other life times.
15580 if (LT != Qualifiers::OCL_None)
15581 return;
15582
15583 if (PRE) {
15584 if (PRE->isImplicitProperty())
15585 return;
15586 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15587 if (!PD)
15588 return;
15589
15590 unsigned Attributes = PD->getPropertyAttributes();
15591 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15592 // when 'assign' attribute was not explicitly specified
15593 // by user, ignore it and rely on property type itself
15594 // for lifetime info.
15595 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15596 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15597 LHSType->isObjCRetainableType())
15598 return;
15599
15600 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15601 if (cast->getCastKind() == CK_ARCConsumeObject) {
15602 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
15603 << RHS->getSourceRange();
15604 return;
15605 }
15606 RHS = cast->getSubExpr();
15607 }
15608 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15609 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
15610 return;
15611 }
15612 }
15613}
15614
15615//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15616
15617static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15618 SourceLocation StmtLoc,
15619 const NullStmt *Body) {
15620 // Do not warn if the body is a macro that expands to nothing, e.g:
15621 //
15622 // #define CALL(x)
15623 // if (condition)
15624 // CALL(0);
15625 if (Body->hasLeadingEmptyMacro())
15626 return false;
15627
15628 // Get line numbers of statement and body.
15629 bool StmtLineInvalid;
15630 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
15631 Invalid: &StmtLineInvalid);
15632 if (StmtLineInvalid)
15633 return false;
15634
15635 bool BodyLineInvalid;
15636 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
15637 Invalid: &BodyLineInvalid);
15638 if (BodyLineInvalid)
15639 return false;
15640
15641 // Warn if null statement and body are on the same line.
15642 if (StmtLine != BodyLine)
15643 return false;
15644
15645 return true;
15646}
15647
15648void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15649 const Stmt *Body,
15650 unsigned DiagID) {
15651 // Since this is a syntactic check, don't emit diagnostic for template
15652 // instantiations, this just adds noise.
15653 if (CurrentInstantiationScope)
15654 return;
15655
15656 // The body should be a null statement.
15657 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15658 if (!NBody)
15659 return;
15660
15661 // Do the usual checks.
15662 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15663 return;
15664
15665 Diag(Loc: NBody->getSemiLoc(), DiagID);
15666 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15667}
15668
15669void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15670 const Stmt *PossibleBody) {
15671 assert(!CurrentInstantiationScope); // Ensured by caller
15672
15673 SourceLocation StmtLoc;
15674 const Stmt *Body;
15675 unsigned DiagID;
15676 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
15677 StmtLoc = FS->getRParenLoc();
15678 Body = FS->getBody();
15679 DiagID = diag::warn_empty_for_body;
15680 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
15681 StmtLoc = WS->getRParenLoc();
15682 Body = WS->getBody();
15683 DiagID = diag::warn_empty_while_body;
15684 } else
15685 return; // Neither `for' nor `while'.
15686
15687 // The body should be a null statement.
15688 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15689 if (!NBody)
15690 return;
15691
15692 // Skip expensive checks if diagnostic is disabled.
15693 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
15694 return;
15695
15696 // Do the usual checks.
15697 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15698 return;
15699
15700 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15701 // noise level low, emit diagnostics only if for/while is followed by a
15702 // CompoundStmt, e.g.:
15703 // for (int i = 0; i < n; i++);
15704 // {
15705 // a(i);
15706 // }
15707 // or if for/while is followed by a statement with more indentation
15708 // than for/while itself:
15709 // for (int i = 0; i < n; i++);
15710 // a(i);
15711 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
15712 if (!ProbableTypo) {
15713 bool BodyColInvalid;
15714 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15715 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
15716 if (BodyColInvalid)
15717 return;
15718
15719 bool StmtColInvalid;
15720 unsigned StmtCol =
15721 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
15722 if (StmtColInvalid)
15723 return;
15724
15725 if (BodyCol > StmtCol)
15726 ProbableTypo = true;
15727 }
15728
15729 if (ProbableTypo) {
15730 Diag(Loc: NBody->getSemiLoc(), DiagID);
15731 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15732 }
15733}
15734
15735//===--- CHECK: Warn on self move with std::move. -------------------------===//
15736
15737void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15738 SourceLocation OpLoc) {
15739 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
15740 return;
15741
15742 if (inTemplateInstantiation())
15743 return;
15744
15745 // Strip parens and casts away.
15746 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15747 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15748
15749 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15750 // which we can treat as an inlined std::move
15751 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
15752 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15753 RHSExpr = CE->getArg(Arg: 0);
15754 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
15755 CXXSCE && CXXSCE->isXValue())
15756 RHSExpr = CXXSCE->getSubExpr();
15757 else
15758 return;
15759
15760 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15761 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15762
15763 // Two DeclRefExpr's, check that the decls are the same.
15764 if (LHSDeclRef && RHSDeclRef) {
15765 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15766 return;
15767 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15768 RHSDeclRef->getDecl()->getCanonicalDecl())
15769 return;
15770
15771 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15772 << LHSExpr->getType() << LHSExpr->getSourceRange()
15773 << RHSExpr->getSourceRange();
15774 if (const FieldDecl *F =
15775 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
15776 D << 1 << F
15777 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15778 else
15779 D << 0;
15780 return;
15781 }
15782
15783 // Member variables require a different approach to check for self moves.
15784 // MemberExpr's are the same if every nested MemberExpr refers to the same
15785 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15786 // the base Expr's are CXXThisExpr's.
15787 const Expr *LHSBase = LHSExpr;
15788 const Expr *RHSBase = RHSExpr;
15789 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
15790 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
15791 if (!LHSME || !RHSME)
15792 return;
15793
15794 while (LHSME && RHSME) {
15795 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15796 RHSME->getMemberDecl()->getCanonicalDecl())
15797 return;
15798
15799 LHSBase = LHSME->getBase();
15800 RHSBase = RHSME->getBase();
15801 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
15802 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
15803 }
15804
15805 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
15806 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
15807 if (LHSDeclRef && RHSDeclRef) {
15808 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15809 return;
15810 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15811 RHSDeclRef->getDecl()->getCanonicalDecl())
15812 return;
15813
15814 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15815 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15816 << RHSExpr->getSourceRange();
15817 return;
15818 }
15819
15820 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
15821 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15822 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15823 << RHSExpr->getSourceRange();
15824}
15825
15826//===--- Layout compatibility ----------------------------------------------//
15827
15828static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15829
15830/// Check if two enumeration types are layout-compatible.
15831static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15832 const EnumDecl *ED2) {
15833 // C++11 [dcl.enum] p8:
15834 // Two enumeration types are layout-compatible if they have the same
15835 // underlying type.
15836 return ED1->isComplete() && ED2->isComplete() &&
15837 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
15838}
15839
15840/// Check if two fields are layout-compatible.
15841/// Can be used on union members, which are exempt from alignment requirement
15842/// of common initial sequence.
15843static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15844 const FieldDecl *Field2,
15845 bool AreUnionMembers = false) {
15846#ifndef NDEBUG
15847 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15848 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15849 assert(((Field1Parent->isStructureOrClassType() &&
15850 Field2Parent->isStructureOrClassType()) ||
15851 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15852 "Can't evaluate layout compatibility between a struct field and a "
15853 "union field.");
15854 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15855 (AreUnionMembers && Field1Parent->isUnionType())) &&
15856 "AreUnionMembers should be 'true' for union fields (only).");
15857#endif
15858
15859 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
15860 return false;
15861
15862 if (Field1->isBitField() != Field2->isBitField())
15863 return false;
15864
15865 if (Field1->isBitField()) {
15866 // Make sure that the bit-fields are the same length.
15867 unsigned Bits1 = Field1->getBitWidthValue();
15868 unsigned Bits2 = Field2->getBitWidthValue();
15869
15870 if (Bits1 != Bits2)
15871 return false;
15872 }
15873
15874 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15875 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15876 return false;
15877
15878 if (!AreUnionMembers &&
15879 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15880 return false;
15881
15882 return true;
15883}
15884
15885/// Check if two standard-layout structs are layout-compatible.
15886/// (C++11 [class.mem] p17)
15887static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15888 const RecordDecl *RD2) {
15889 // Get to the class where the fields are declared
15890 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
15891 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15892
15893 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
15894 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15895
15896 // Check the fields.
15897 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
15898 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15899 return isLayoutCompatible(C, Field1: F1, Field2: F2);
15900 });
15901}
15902
15903/// Check if two standard-layout unions are layout-compatible.
15904/// (C++11 [class.mem] p18)
15905static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15906 const RecordDecl *RD2) {
15907 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15908 RD2->fields());
15909
15910 for (auto *Field1 : RD1->fields()) {
15911 auto I = UnmatchedFields.begin();
15912 auto E = UnmatchedFields.end();
15913
15914 for ( ; I != E; ++I) {
15915 if (isLayoutCompatible(C, Field1, Field2: *I, /*IsUnionMember=*/AreUnionMembers: true)) {
15916 bool Result = UnmatchedFields.erase(Ptr: *I);
15917 (void) Result;
15918 assert(Result);
15919 break;
15920 }
15921 }
15922 if (I == E)
15923 return false;
15924 }
15925
15926 return UnmatchedFields.empty();
15927}
15928
15929static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15930 const RecordDecl *RD2) {
15931 if (RD1->isUnion() != RD2->isUnion())
15932 return false;
15933
15934 if (RD1->isUnion())
15935 return isLayoutCompatibleUnion(C, RD1, RD2);
15936 else
15937 return isLayoutCompatibleStruct(C, RD1, RD2);
15938}
15939
15940/// Check if two types are layout-compatible in C++11 sense.
15941static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15942 if (T1.isNull() || T2.isNull())
15943 return false;
15944
15945 // C++20 [basic.types] p11:
15946 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15947 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15948 // or layout-compatible standard-layout class types (11.4).
15949 T1 = T1.getCanonicalType().getUnqualifiedType();
15950 T2 = T2.getCanonicalType().getUnqualifiedType();
15951
15952 if (C.hasSameType(T1, T2))
15953 return true;
15954
15955 const Type::TypeClass TC1 = T1->getTypeClass();
15956 const Type::TypeClass TC2 = T2->getTypeClass();
15957
15958 if (TC1 != TC2)
15959 return false;
15960
15961 if (TC1 == Type::Enum)
15962 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
15963 if (TC1 == Type::Record) {
15964 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15965 return false;
15966
15967 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
15968 RD2: T2->castAsRecordDecl());
15969 }
15970
15971 return false;
15972}
15973
15974bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
15975 return isLayoutCompatible(C: getASTContext(), T1, T2);
15976}
15977
15978//===-------------- Pointer interconvertibility ----------------------------//
15979
15980bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
15981 const TypeSourceInfo *Derived) {
15982 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15983 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15984
15985 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15986 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
15987 return true;
15988
15989 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
15990 return false;
15991
15992 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15993 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15994 return true;
15995
15996 return false;
15997}
15998
15999//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16000
16001/// Given a type tag expression find the type tag itself.
16002///
16003/// \param TypeExpr Type tag expression, as it appears in user's code.
16004///
16005/// \param VD Declaration of an identifier that appears in a type tag.
16006///
16007/// \param MagicValue Type tag magic value.
16008///
16009/// \param isConstantEvaluated whether the evalaution should be performed in
16010
16011/// constant context.
16012static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16013 const ValueDecl **VD, uint64_t *MagicValue,
16014 bool isConstantEvaluated) {
16015 while(true) {
16016 if (!TypeExpr)
16017 return false;
16018
16019 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16020
16021 switch (TypeExpr->getStmtClass()) {
16022 case Stmt::UnaryOperatorClass: {
16023 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16024 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16025 TypeExpr = UO->getSubExpr();
16026 continue;
16027 }
16028 return false;
16029 }
16030
16031 case Stmt::DeclRefExprClass: {
16032 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16033 *VD = DRE->getDecl();
16034 return true;
16035 }
16036
16037 case Stmt::IntegerLiteralClass: {
16038 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16039 llvm::APInt MagicValueAPInt = IL->getValue();
16040 if (MagicValueAPInt.getActiveBits() <= 64) {
16041 *MagicValue = MagicValueAPInt.getZExtValue();
16042 return true;
16043 } else
16044 return false;
16045 }
16046
16047 case Stmt::BinaryConditionalOperatorClass:
16048 case Stmt::ConditionalOperatorClass: {
16049 const AbstractConditionalOperator *ACO =
16050 cast<AbstractConditionalOperator>(Val: TypeExpr);
16051 bool Result;
16052 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16053 InConstantContext: isConstantEvaluated)) {
16054 if (Result)
16055 TypeExpr = ACO->getTrueExpr();
16056 else
16057 TypeExpr = ACO->getFalseExpr();
16058 continue;
16059 }
16060 return false;
16061 }
16062
16063 case Stmt::BinaryOperatorClass: {
16064 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16065 if (BO->getOpcode() == BO_Comma) {
16066 TypeExpr = BO->getRHS();
16067 continue;
16068 }
16069 return false;
16070 }
16071
16072 default:
16073 return false;
16074 }
16075 }
16076}
16077
16078/// Retrieve the C type corresponding to type tag TypeExpr.
16079///
16080/// \param TypeExpr Expression that specifies a type tag.
16081///
16082/// \param MagicValues Registered magic values.
16083///
16084/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16085/// kind.
16086///
16087/// \param TypeInfo Information about the corresponding C type.
16088///
16089/// \param isConstantEvaluated whether the evalaution should be performed in
16090/// constant context.
16091///
16092/// \returns true if the corresponding C type was found.
16093static bool GetMatchingCType(
16094 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16095 const ASTContext &Ctx,
16096 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16097 *MagicValues,
16098 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16099 bool isConstantEvaluated) {
16100 FoundWrongKind = false;
16101
16102 // Variable declaration that has type_tag_for_datatype attribute.
16103 const ValueDecl *VD = nullptr;
16104
16105 uint64_t MagicValue;
16106
16107 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16108 return false;
16109
16110 if (VD) {
16111 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16112 if (I->getArgumentKind() != ArgumentKind) {
16113 FoundWrongKind = true;
16114 return false;
16115 }
16116 TypeInfo.Type = I->getMatchingCType();
16117 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16118 TypeInfo.MustBeNull = I->getMustBeNull();
16119 return true;
16120 }
16121 return false;
16122 }
16123
16124 if (!MagicValues)
16125 return false;
16126
16127 llvm::DenseMap<Sema::TypeTagMagicValue,
16128 Sema::TypeTagData>::const_iterator I =
16129 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16130 if (I == MagicValues->end())
16131 return false;
16132
16133 TypeInfo = I->second;
16134 return true;
16135}
16136
16137void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16138 uint64_t MagicValue, QualType Type,
16139 bool LayoutCompatible,
16140 bool MustBeNull) {
16141 if (!TypeTagForDatatypeMagicValues)
16142 TypeTagForDatatypeMagicValues.reset(
16143 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16144
16145 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16146 (*TypeTagForDatatypeMagicValues)[Magic] =
16147 TypeTagData(Type, LayoutCompatible, MustBeNull);
16148}
16149
16150static bool IsSameCharType(QualType T1, QualType T2) {
16151 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16152 if (!BT1)
16153 return false;
16154
16155 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16156 if (!BT2)
16157 return false;
16158
16159 BuiltinType::Kind T1Kind = BT1->getKind();
16160 BuiltinType::Kind T2Kind = BT2->getKind();
16161
16162 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16163 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16164 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16165 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16166}
16167
16168void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16169 const ArrayRef<const Expr *> ExprArgs,
16170 SourceLocation CallSiteLoc) {
16171 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16172 bool IsPointerAttr = Attr->getIsPointer();
16173
16174 // Retrieve the argument representing the 'type_tag'.
16175 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16176 if (TypeTagIdxAST >= ExprArgs.size()) {
16177 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16178 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16179 return;
16180 }
16181 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16182 bool FoundWrongKind;
16183 TypeTagData TypeInfo;
16184 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16185 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16186 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16187 if (FoundWrongKind)
16188 Diag(Loc: TypeTagExpr->getExprLoc(),
16189 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16190 << TypeTagExpr->getSourceRange();
16191 return;
16192 }
16193
16194 // Retrieve the argument representing the 'arg_idx'.
16195 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16196 if (ArgumentIdxAST >= ExprArgs.size()) {
16197 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16198 << 1 << Attr->getArgumentIdx().getSourceIndex();
16199 return;
16200 }
16201 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16202 if (IsPointerAttr) {
16203 // Skip implicit cast of pointer to `void *' (as a function argument).
16204 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16205 if (ICE->getType()->isVoidPointerType() &&
16206 ICE->getCastKind() == CK_BitCast)
16207 ArgumentExpr = ICE->getSubExpr();
16208 }
16209 QualType ArgumentType = ArgumentExpr->getType();
16210
16211 // Passing a `void*' pointer shouldn't trigger a warning.
16212 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16213 return;
16214
16215 if (TypeInfo.MustBeNull) {
16216 // Type tag with matching void type requires a null pointer.
16217 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16218 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16219 Diag(Loc: ArgumentExpr->getExprLoc(),
16220 DiagID: diag::warn_type_safety_null_pointer_required)
16221 << ArgumentKind->getName()
16222 << ArgumentExpr->getSourceRange()
16223 << TypeTagExpr->getSourceRange();
16224 }
16225 return;
16226 }
16227
16228 QualType RequiredType = TypeInfo.Type;
16229 if (IsPointerAttr)
16230 RequiredType = Context.getPointerType(T: RequiredType);
16231
16232 bool mismatch = false;
16233 if (!TypeInfo.LayoutCompatible) {
16234 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16235
16236 // C++11 [basic.fundamental] p1:
16237 // Plain char, signed char, and unsigned char are three distinct types.
16238 //
16239 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16240 // char' depending on the current char signedness mode.
16241 if (mismatch)
16242 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16243 T2: RequiredType->getPointeeType())) ||
16244 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16245 mismatch = false;
16246 } else
16247 if (IsPointerAttr)
16248 mismatch = !isLayoutCompatible(C: Context,
16249 T1: ArgumentType->getPointeeType(),
16250 T2: RequiredType->getPointeeType());
16251 else
16252 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16253
16254 if (mismatch)
16255 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16256 << ArgumentType << ArgumentKind
16257 << TypeInfo.LayoutCompatible << RequiredType
16258 << ArgumentExpr->getSourceRange()
16259 << TypeTagExpr->getSourceRange();
16260}
16261
16262void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16263 CharUnits Alignment) {
16264 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16265 Args&: Alignment);
16266}
16267
16268void Sema::DiagnoseMisalignedMembers() {
16269 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16270 const NamedDecl *ND = m.RD;
16271 if (ND->getName().empty()) {
16272 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16273 ND = TD;
16274 }
16275 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16276 << m.MD << ND << m.E->getSourceRange();
16277 }
16278 currentEvaluationContext().MisalignedMembers.clear();
16279}
16280
16281void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16282 E = E->IgnoreParens();
16283 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16284 return;
16285 if (isa<UnaryOperator>(Val: E) &&
16286 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16287 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16288 if (isa<MemberExpr>(Val: Op)) {
16289 auto &MisalignedMembersForExpr =
16290 currentEvaluationContext().MisalignedMembers;
16291 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16292 if (MA != MisalignedMembersForExpr.end() &&
16293 (T->isDependentType() || T->isIntegerType() ||
16294 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16295 Context.getTypeAlignInChars(
16296 T: T->getPointeeType()) <= MA->Alignment))))
16297 MisalignedMembersForExpr.erase(CI: MA);
16298 }
16299 }
16300}
16301
16302void Sema::RefersToMemberWithReducedAlignment(
16303 Expr *E,
16304 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16305 Action) {
16306 const auto *ME = dyn_cast<MemberExpr>(Val: E);
16307 if (!ME)
16308 return;
16309
16310 // No need to check expressions with an __unaligned-qualified type.
16311 if (E->getType().getQualifiers().hasUnaligned())
16312 return;
16313
16314 // For a chain of MemberExpr like "a.b.c.d" this list
16315 // will keep FieldDecl's like [d, c, b].
16316 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16317 const MemberExpr *TopME = nullptr;
16318 bool AnyIsPacked = false;
16319 do {
16320 QualType BaseType = ME->getBase()->getType();
16321 if (BaseType->isDependentType())
16322 return;
16323 if (ME->isArrow())
16324 BaseType = BaseType->getPointeeType();
16325 auto *RD = BaseType->castAsRecordDecl();
16326 if (RD->isInvalidDecl())
16327 return;
16328
16329 ValueDecl *MD = ME->getMemberDecl();
16330 auto *FD = dyn_cast<FieldDecl>(Val: MD);
16331 // We do not care about non-data members.
16332 if (!FD || FD->isInvalidDecl())
16333 return;
16334
16335 AnyIsPacked =
16336 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16337 ReverseMemberChain.push_back(Elt: FD);
16338
16339 TopME = ME;
16340 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
16341 } while (ME);
16342 assert(TopME && "We did not compute a topmost MemberExpr!");
16343
16344 // Not the scope of this diagnostic.
16345 if (!AnyIsPacked)
16346 return;
16347
16348 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16349 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
16350 // TODO: The innermost base of the member expression may be too complicated.
16351 // For now, just disregard these cases. This is left for future
16352 // improvement.
16353 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
16354 return;
16355
16356 // Alignment expected by the whole expression.
16357 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
16358
16359 // No need to do anything else with this case.
16360 if (ExpectedAlignment.isOne())
16361 return;
16362
16363 // Synthesize offset of the whole access.
16364 CharUnits Offset;
16365 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
16366 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
16367
16368 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16369 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16370 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
16371
16372 // The base expression of the innermost MemberExpr may give
16373 // stronger guarantees than the class containing the member.
16374 if (DRE && !TopME->isArrow()) {
16375 const ValueDecl *VD = DRE->getDecl();
16376 if (!VD->getType()->isReferenceType())
16377 CompleteObjectAlignment =
16378 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
16379 }
16380
16381 // Check if the synthesized offset fulfills the alignment.
16382 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
16383 // It may fulfill the offset it but the effective alignment may still be
16384 // lower than the expected expression alignment.
16385 CompleteObjectAlignment < ExpectedAlignment) {
16386 // If this happens, we want to determine a sensible culprit of this.
16387 // Intuitively, watching the chain of member expressions from right to
16388 // left, we start with the required alignment (as required by the field
16389 // type) but some packed attribute in that chain has reduced the alignment.
16390 // It may happen that another packed structure increases it again. But if
16391 // we are here such increase has not been enough. So pointing the first
16392 // FieldDecl that either is packed or else its RecordDecl is,
16393 // seems reasonable.
16394 FieldDecl *FD = nullptr;
16395 CharUnits Alignment;
16396 for (FieldDecl *FDI : ReverseMemberChain) {
16397 if (FDI->hasAttr<PackedAttr>() ||
16398 FDI->getParent()->hasAttr<PackedAttr>()) {
16399 FD = FDI;
16400 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
16401 b: Context.getTypeAlignInChars(
16402 T: Context.getCanonicalTagType(TD: FD->getParent())));
16403 break;
16404 }
16405 }
16406 assert(FD && "We did not find a packed FieldDecl!");
16407 Action(E, FD->getParent(), FD, Alignment);
16408 }
16409}
16410
16411void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16412 using namespace std::placeholders;
16413
16414 RefersToMemberWithReducedAlignment(
16415 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
16416 args: _2, args: _3, args: _4));
16417}
16418
16419bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
16420 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16421 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16422 return true;
16423
16424 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
16425 if (A.isInvalid())
16426 return true;
16427
16428 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16429 QualType TyA = A.get()->getType();
16430
16431 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
16432 ArgTyRestr, ArgOrdinal: 1))
16433 return true;
16434
16435 TheCall->setType(TyA);
16436 return false;
16437}
16438
16439bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16440 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16441 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16442 TheCall->setType(*Res);
16443 return false;
16444 }
16445 return true;
16446}
16447
16448bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
16449 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16450 if (!Res)
16451 return true;
16452
16453 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16454 TheCall->setType(VecTy0->getElementType());
16455 else
16456 TheCall->setType(*Res);
16457
16458 return false;
16459}
16460
16461static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
16462 SourceLocation Loc) {
16463 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
16464 R = RHS->getEnumCoercedType(Ctx: S.Context);
16465 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16466 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
16467 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
16468 << LHS->getSourceRange() << RHS->getSourceRange()
16469 << /*Arithmetic Between*/ 0 << L << R;
16470 }
16471 return false;
16472}
16473
16474/// Check if all arguments have the same type. If the types don't match, emit an
16475/// error message and return true. Otherwise return false.
16476///
16477/// For scalars we directly compare their unqualified types. But even if we
16478/// compare unqualified vector types, a difference in qualifiers in the element
16479/// types can make the vector types be considered not equal. For example,
16480/// vector of 4 'const float' values vs vector of 4 'float' values.
16481/// So we compare unqualified types of their elements and number of elements.
16482static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
16483 ArrayRef<Expr *> Args) {
16484 assert(!Args.empty() && "Should have at least one argument.");
16485
16486 Expr *Arg0 = Args.front();
16487 QualType Ty0 = Arg0->getType();
16488
16489 auto EmitError = [&](Expr *ArgI) {
16490 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
16491 DiagID: diag::err_typecheck_call_different_arg_types)
16492 << Arg0->getType() << ArgI->getType();
16493 };
16494
16495 // Compare scalar types.
16496 if (!Ty0->isVectorType()) {
16497 for (Expr *ArgI : Args.drop_front())
16498 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
16499 EmitError(ArgI);
16500 return true;
16501 }
16502
16503 return false;
16504 }
16505
16506 // Compare vector types.
16507 const auto *Vec0 = Ty0->castAs<VectorType>();
16508 for (Expr *ArgI : Args.drop_front()) {
16509 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16510 if (!VecI ||
16511 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
16512 T2: VecI->getElementType()) ||
16513 Vec0->getNumElements() != VecI->getNumElements()) {
16514 EmitError(ArgI);
16515 return true;
16516 }
16517 }
16518
16519 return false;
16520}
16521
16522std::optional<QualType>
16523Sema::BuiltinVectorMath(CallExpr *TheCall,
16524 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16525 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
16526 return std::nullopt;
16527
16528 if (checkBuiltinVectorMathMixedEnums(
16529 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
16530 return std::nullopt;
16531
16532 Expr *Args[2];
16533 for (int I = 0; I < 2; ++I) {
16534 ExprResult Converted =
16535 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16536 if (Converted.isInvalid())
16537 return std::nullopt;
16538 Args[I] = Converted.get();
16539 }
16540
16541 SourceLocation LocA = Args[0]->getBeginLoc();
16542 QualType TyA = Args[0]->getType();
16543
16544 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
16545 return std::nullopt;
16546
16547 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16548 return std::nullopt;
16549
16550 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
16551 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
16552 return TyA;
16553}
16554
16555bool Sema::BuiltinElementwiseTernaryMath(
16556 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16557 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
16558 return true;
16559
16560 SourceLocation Loc = TheCall->getExprLoc();
16561 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
16562 RHS: TheCall->getArg(Arg: 1), Loc) ||
16563 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
16564 RHS: TheCall->getArg(Arg: 2), Loc))
16565 return true;
16566
16567 Expr *Args[3];
16568 for (int I = 0; I < 3; ++I) {
16569 ExprResult Converted =
16570 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16571 if (Converted.isInvalid())
16572 return true;
16573 Args[I] = Converted.get();
16574 }
16575
16576 int ArgOrdinal = 1;
16577 for (Expr *Arg : Args) {
16578 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
16579 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
16580 return true;
16581 }
16582
16583 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16584 return true;
16585
16586 for (int I = 0; I < 3; ++I)
16587 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
16588
16589 TheCall->setType(Args[0]->getType());
16590 return false;
16591}
16592
16593bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16594 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16595 return true;
16596
16597 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
16598 if (A.isInvalid())
16599 return true;
16600
16601 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16602 return false;
16603}
16604
16605bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16606 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16607 return true;
16608
16609 ExprResult Arg = TheCall->getArg(Arg: 0);
16610 QualType TyArg = Arg.get()->getType();
16611
16612 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16613 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
16614 DiagID: diag::err_builtin_invalid_arg_type)
16615 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16616
16617 TheCall->setType(TyArg);
16618 return false;
16619}
16620
16621ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16622 ExprResult CallResult) {
16623 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16624 return ExprError();
16625
16626 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
16627 if (MatrixArg.isInvalid())
16628 return MatrixArg;
16629 Expr *Matrix = MatrixArg.get();
16630
16631 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16632 if (!MType) {
16633 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16634 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16635 << Matrix->getType();
16636 return ExprError();
16637 }
16638
16639 // Create returned matrix type by swapping rows and columns of the argument
16640 // matrix type.
16641 QualType ResultType = Context.getConstantMatrixType(
16642 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
16643
16644 // Change the return type to the type of the returned matrix.
16645 TheCall->setType(ResultType);
16646
16647 // Update call argument to use the possibly converted matrix argument.
16648 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
16649 return CallResult;
16650}
16651
16652// Get and verify the matrix dimensions.
16653static std::optional<unsigned>
16654getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16655 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
16656 if (!Value) {
16657 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
16658 << Name;
16659 return {};
16660 }
16661 uint64_t Dim = Value->getZExtValue();
16662 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16663 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
16664 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16665 return {};
16666 }
16667 return Dim;
16668}
16669
16670ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16671 ExprResult CallResult) {
16672 if (!getLangOpts().MatrixTypes) {
16673 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16674 return ExprError();
16675 }
16676
16677 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16678 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
16679 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
16680 << /*column*/ 1 << /*load*/ 0;
16681 return ExprError();
16682 }
16683
16684 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
16685 return ExprError();
16686
16687 unsigned PtrArgIdx = 0;
16688 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
16689 Expr *RowsExpr = TheCall->getArg(Arg: 1);
16690 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
16691 Expr *StrideExpr = TheCall->getArg(Arg: 3);
16692
16693 bool ArgError = false;
16694
16695 // Check pointer argument.
16696 {
16697 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
16698 if (PtrConv.isInvalid())
16699 return PtrConv;
16700 PtrExpr = PtrConv.get();
16701 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
16702 if (PtrExpr->isTypeDependent()) {
16703 TheCall->setType(Context.DependentTy);
16704 return TheCall;
16705 }
16706 }
16707
16708 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16709 QualType ElementTy;
16710 if (!PtrTy) {
16711 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16712 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16713 << PtrExpr->getType();
16714 ArgError = true;
16715 } else {
16716 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16717
16718 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
16719 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16720 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16721 << /* no fp */ 0 << PtrExpr->getType();
16722 ArgError = true;
16723 }
16724 }
16725
16726 // Apply default Lvalue conversions and convert the expression to size_t.
16727 auto ApplyArgumentConversions = [this](Expr *E) {
16728 ExprResult Conv = DefaultLvalueConversion(E);
16729 if (Conv.isInvalid())
16730 return Conv;
16731
16732 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
16733 };
16734
16735 // Apply conversion to row and column expressions.
16736 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16737 if (!RowsConv.isInvalid()) {
16738 RowsExpr = RowsConv.get();
16739 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
16740 } else
16741 RowsExpr = nullptr;
16742
16743 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16744 if (!ColumnsConv.isInvalid()) {
16745 ColumnsExpr = ColumnsConv.get();
16746 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
16747 } else
16748 ColumnsExpr = nullptr;
16749
16750 // If any part of the result matrix type is still pending, just use
16751 // Context.DependentTy, until all parts are resolved.
16752 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16753 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16754 TheCall->setType(Context.DependentTy);
16755 return CallResult;
16756 }
16757
16758 // Check row and column dimensions.
16759 std::optional<unsigned> MaybeRows;
16760 if (RowsExpr)
16761 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
16762
16763 std::optional<unsigned> MaybeColumns;
16764 if (ColumnsExpr)
16765 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
16766
16767 // Check stride argument.
16768 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16769 if (StrideConv.isInvalid())
16770 return ExprError();
16771 StrideExpr = StrideConv.get();
16772 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
16773
16774 if (MaybeRows) {
16775 if (std::optional<llvm::APSInt> Value =
16776 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
16777 uint64_t Stride = Value->getZExtValue();
16778 if (Stride < *MaybeRows) {
16779 Diag(Loc: StrideExpr->getBeginLoc(),
16780 DiagID: diag::err_builtin_matrix_stride_too_small);
16781 ArgError = true;
16782 }
16783 }
16784 }
16785
16786 if (ArgError || !MaybeRows || !MaybeColumns)
16787 return ExprError();
16788
16789 TheCall->setType(
16790 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
16791 return CallResult;
16792}
16793
16794ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16795 ExprResult CallResult) {
16796 if (!getLangOpts().MatrixTypes) {
16797 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16798 return ExprError();
16799 }
16800
16801 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16802 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
16803 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
16804 << /*column*/ 1 << /*store*/ 1;
16805 return ExprError();
16806 }
16807
16808 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
16809 return ExprError();
16810
16811 unsigned PtrArgIdx = 1;
16812 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
16813 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
16814 Expr *StrideExpr = TheCall->getArg(Arg: 2);
16815
16816 bool ArgError = false;
16817
16818 {
16819 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
16820 if (MatrixConv.isInvalid())
16821 return MatrixConv;
16822 MatrixExpr = MatrixConv.get();
16823 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
16824 }
16825 if (MatrixExpr->isTypeDependent()) {
16826 TheCall->setType(Context.DependentTy);
16827 return TheCall;
16828 }
16829
16830 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16831 if (!MatrixTy) {
16832 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16833 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16834 ArgError = true;
16835 }
16836
16837 {
16838 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
16839 if (PtrConv.isInvalid())
16840 return PtrConv;
16841 PtrExpr = PtrConv.get();
16842 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
16843 if (PtrExpr->isTypeDependent()) {
16844 TheCall->setType(Context.DependentTy);
16845 return TheCall;
16846 }
16847 }
16848
16849 // Check pointer argument.
16850 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16851 if (!PtrTy) {
16852 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16853 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16854 << PtrExpr->getType();
16855 ArgError = true;
16856 } else {
16857 QualType ElementTy = PtrTy->getPointeeType();
16858 if (ElementTy.isConstQualified()) {
16859 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
16860 ArgError = true;
16861 }
16862 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16863 if (MatrixTy &&
16864 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
16865 Diag(Loc: PtrExpr->getBeginLoc(),
16866 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
16867 << ElementTy << MatrixTy->getElementType();
16868 ArgError = true;
16869 }
16870 }
16871
16872 // Apply default Lvalue conversions and convert the stride expression to
16873 // size_t.
16874 {
16875 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
16876 if (StrideConv.isInvalid())
16877 return StrideConv;
16878
16879 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
16880 if (StrideConv.isInvalid())
16881 return StrideConv;
16882 StrideExpr = StrideConv.get();
16883 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
16884 }
16885
16886 // Check stride argument.
16887 if (MatrixTy) {
16888 if (std::optional<llvm::APSInt> Value =
16889 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
16890 uint64_t Stride = Value->getZExtValue();
16891 if (Stride < MatrixTy->getNumRows()) {
16892 Diag(Loc: StrideExpr->getBeginLoc(),
16893 DiagID: diag::err_builtin_matrix_stride_too_small);
16894 ArgError = true;
16895 }
16896 }
16897 }
16898
16899 if (ArgError)
16900 return ExprError();
16901
16902 return CallResult;
16903}
16904
16905void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
16906 const NamedDecl *Callee) {
16907 // This warning does not make sense in code that has no runtime behavior.
16908 if (isUnevaluatedContext())
16909 return;
16910
16911 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16912
16913 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16914 return;
16915
16916 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16917 // all TCBs the callee is a part of.
16918 llvm::StringSet<> CalleeTCBs;
16919 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16920 CalleeTCBs.insert(key: A->getTCBName());
16921 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16922 CalleeTCBs.insert(key: A->getTCBName());
16923
16924 // Go through the TCBs the caller is a part of and emit warnings if Caller
16925 // is in a TCB that the Callee is not.
16926 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16927 StringRef CallerTCB = A->getTCBName();
16928 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
16929 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
16930 << Callee << CallerTCB;
16931 }
16932 }
16933}
16934