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.AnonymousTagNameStyle =
497 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::Plain);
498 }
499
500 Expr *makeOpaqueValueExpr(Expr *Inner) {
501 auto *OVE = new (S.Context)
502 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
503 Inner->getObjectKind(), Inner);
504 Actions.push_back(Elt: OVE);
505 return OVE;
506 }
507
508 Expr *getStringLiteral(llvm::StringRef Str) {
509 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
510 // Wrap the literal in parentheses to attach a source location.
511 return new (S.Context) ParenExpr(Loc, Loc, Lit);
512 }
513
514 bool callPrintFunction(llvm::StringRef Format,
515 llvm::ArrayRef<Expr *> Exprs = {}) {
516 SmallVector<Expr *, 8> Args;
517 assert(TheCall->getNumArgs() >= 2);
518 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
519 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
520 Args.push_back(Elt: getStringLiteral(Str: Format));
521 llvm::append_range(C&: Args, R&: Exprs);
522
523 // Register a note to explain why we're performing the call.
524 Sema::CodeSynthesisContext Ctx;
525 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
526 Ctx.PointOfInstantiation = Loc;
527 Ctx.CallArgs = Args.data();
528 Ctx.NumCallArgs = Args.size();
529 S.pushCodeSynthesisContext(Ctx);
530
531 ExprResult RealCall =
532 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
533 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
534
535 S.popCodeSynthesisContext();
536 if (!RealCall.isInvalid())
537 Actions.push_back(Elt: RealCall.get());
538 // Bail out if we've hit any errors, even if we managed to build the
539 // call. We don't want to produce more than one error.
540 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
541 }
542
543 Expr *getIndentString(unsigned Depth) {
544 if (!Depth)
545 return nullptr;
546
547 llvm::SmallString<32> Indent;
548 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
549 return getStringLiteral(Str: Indent);
550 }
551
552 Expr *getTypeString(QualType T) {
553 return getStringLiteral(Str: T.getAsString(Policy));
554 }
555
556 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
557 llvm::raw_svector_ostream OS(Str);
558
559 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
560 // than trying to print a single character.
561 if (auto *BT = T->getAs<BuiltinType>()) {
562 switch (BT->getKind()) {
563 case BuiltinType::Bool:
564 OS << "%d";
565 return true;
566 case BuiltinType::Char_U:
567 case BuiltinType::UChar:
568 OS << "%hhu";
569 return true;
570 case BuiltinType::Char_S:
571 case BuiltinType::SChar:
572 OS << "%hhd";
573 return true;
574 default:
575 break;
576 }
577 }
578
579 analyze_printf::PrintfSpecifier Specifier;
580 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
581 // We were able to guess how to format this.
582 if (Specifier.getConversionSpecifier().getKind() ==
583 analyze_printf::PrintfConversionSpecifier::sArg) {
584 // Wrap double-quotes around a '%s' specifier and limit its maximum
585 // length. Ideally we'd also somehow escape special characters in the
586 // contents but printf doesn't support that.
587 // FIXME: '%s' formatting is not safe in general.
588 OS << '"';
589 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
590 Specifier.toString(os&: OS);
591 OS << '"';
592 // FIXME: It would be nice to include a '...' if the string doesn't fit
593 // in the length limit.
594 } else {
595 Specifier.toString(os&: OS);
596 }
597 return true;
598 }
599
600 if (T->isPointerType()) {
601 // Format all pointers with '%p'.
602 OS << "%p";
603 return true;
604 }
605
606 return false;
607 }
608
609 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
610 Expr *IndentLit = getIndentString(Depth);
611 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
612 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
613 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
614 return true;
615
616 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
617 }
618
619 // Dump a record value. E should be a pointer or lvalue referring to an RD.
620 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
621 unsigned Depth) {
622 // FIXME: Decide what to do if RD is a union. At least we should probably
623 // turn off printing `const char*` members with `%s`, because that is very
624 // likely to crash if that's not the active member. Whatever we decide, we
625 // should document it.
626
627 // Build an OpaqueValueExpr so we can refer to E more than once without
628 // triggering re-evaluation.
629 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
630 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
631
632 if (callPrintFunction(Format: " {\n"))
633 return true;
634
635 // Dump each base class, regardless of whether they're aggregates.
636 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
637 for (const auto &Base : CXXRD->bases()) {
638 QualType BaseType =
639 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
640 : S.Context.getLValueReferenceType(T: Base.getType());
641 ExprResult BasePtr = S.BuildCStyleCastExpr(
642 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
643 Op: RecordArg);
644 if (BasePtr.isInvalid() ||
645 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
646 Depth: Depth + 1))
647 return true;
648 }
649 }
650
651 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
652
653 // Dump each field.
654 for (auto *D : RD->decls()) {
655 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
656 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
657 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
658 continue;
659
660 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
661 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
662 getTypeString(T: FD->getType()),
663 getStringLiteral(Str: FD->getName())};
664
665 if (FD->isBitField()) {
666 Format += ": %zu ";
667 QualType SizeT = S.Context.getSizeType();
668 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
669 FD->getBitWidthValue());
670 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
671 }
672
673 Format += "=";
674
675 ExprResult Field =
676 IFD ? S.BuildAnonymousStructUnionMemberReference(
677 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
678 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
679 : S.BuildFieldReferenceExpr(
680 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
681 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
682 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
683 if (Field.isInvalid())
684 return true;
685
686 auto *InnerRD = FD->getType()->getAsRecordDecl();
687 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
688 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
689 // Recursively print the values of members of aggregate record type.
690 if (callPrintFunction(Format, Exprs: Args) ||
691 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
692 return true;
693 } else {
694 Format += " ";
695 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
696 // We know how to print this field.
697 Args.push_back(Elt: Field.get());
698 } else {
699 // We don't know how to print this field. Print out its address
700 // with a format specifier that a smart tool will be able to
701 // recognize and treat specially.
702 Format += "*%p";
703 ExprResult FieldAddr =
704 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
705 if (FieldAddr.isInvalid())
706 return true;
707 Args.push_back(Elt: FieldAddr.get());
708 }
709 Format += "\n";
710 if (callPrintFunction(Format, Exprs: Args))
711 return true;
712 }
713 }
714
715 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
716 : callPrintFunction(Format: "}\n");
717 }
718
719 Expr *buildWrapper() {
720 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
721 resultIndex: PseudoObjectExpr::NoResult);
722 TheCall->setType(Wrapper->getType());
723 TheCall->setValueKind(Wrapper->getValueKind());
724 return Wrapper;
725 }
726};
727} // namespace
728
729static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
730 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
731 return ExprError();
732
733 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
734 if (PtrArgResult.isInvalid())
735 return ExprError();
736 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
737
738 // First argument should be a pointer to a struct.
739 QualType PtrArgType = PtrArgResult.get()->getType();
740 if (!PtrArgType->isPointerType() ||
741 !PtrArgType->getPointeeType()->isRecordType()) {
742 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
743 DiagID: diag::err_expected_struct_pointer_argument)
744 << 1 << TheCall->getDirectCallee() << PtrArgType;
745 return ExprError();
746 }
747 QualType Pointee = PtrArgType->getPointeeType();
748 const RecordDecl *RD = Pointee->getAsRecordDecl();
749 // Try to instantiate the class template as appropriate; otherwise, access to
750 // its data() may lead to a crash.
751 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
752 DiagID: diag::err_incomplete_type))
753 return ExprError();
754 // Second argument is a callable, but we can't fully validate it until we try
755 // calling it.
756 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
757 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
758 !FnArgType->isBlockPointerType() &&
759 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
760 auto *BT = FnArgType->getAs<BuiltinType>();
761 switch (BT ? BT->getKind() : BuiltinType::Void) {
762 case BuiltinType::Dependent:
763 case BuiltinType::Overload:
764 case BuiltinType::BoundMember:
765 case BuiltinType::PseudoObject:
766 case BuiltinType::UnknownAny:
767 case BuiltinType::BuiltinFn:
768 // This might be a callable.
769 break;
770
771 default:
772 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
773 DiagID: diag::err_expected_callable_argument)
774 << 2 << TheCall->getDirectCallee() << FnArgType;
775 return ExprError();
776 }
777 }
778
779 BuiltinDumpStructGenerator Generator(S, TheCall);
780
781 // Wrap parentheses around the given pointer. This is not necessary for
782 // correct code generation, but it means that when we pretty-print the call
783 // arguments in our diagnostics we will produce '(&s)->n' instead of the
784 // incorrect '&s->n'.
785 Expr *PtrArg = PtrArgResult.get();
786 PtrArg = new (S.Context)
787 ParenExpr(PtrArg->getBeginLoc(),
788 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
789 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
790 return ExprError();
791
792 return Generator.buildWrapper();
793}
794
795static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
796 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
797 return true;
798
799 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
800 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
801 Expr *Call = BuiltinCall->getArg(Arg: 0);
802 Expr *Chain = BuiltinCall->getArg(Arg: 1);
803
804 if (Call->getStmtClass() != Stmt::CallExprClass) {
805 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
806 << Call->getSourceRange();
807 return true;
808 }
809
810 auto CE = cast<CallExpr>(Val: Call);
811 if (CE->getCallee()->getType()->isBlockPointerType()) {
812 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
813 << Call->getSourceRange();
814 return true;
815 }
816
817 const Decl *TargetDecl = CE->getCalleeDecl();
818 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
819 if (FD->getBuiltinID()) {
820 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
826 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
832 if (ChainResult.isInvalid())
833 return true;
834 if (!ChainResult.get()->getType()->isPointerType()) {
835 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
836 << Chain->getSourceRange();
837 return true;
838 }
839
840 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
841 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
842 QualType BuiltinTy = S.Context.getFunctionType(
843 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
844 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
845
846 Builtin =
847 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
848
849 BuiltinCall->setType(CE->getType());
850 BuiltinCall->setValueKind(CE->getValueKind());
851 BuiltinCall->setObjectKind(CE->getObjectKind());
852 BuiltinCall->setCallee(Builtin);
853 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
854
855 return false;
856}
857
858namespace {
859
860class ScanfDiagnosticFormatHandler
861 : public analyze_format_string::FormatStringHandler {
862 // Accepts the argument index (relative to the first destination index) of the
863 // argument whose size we want.
864 using ComputeSizeFunction =
865 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
866
867 // Accepts the argument index (relative to the first destination index), the
868 // destination size, and the source size).
869 using DiagnoseFunction =
870 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
871
872 ComputeSizeFunction ComputeSizeArgument;
873 DiagnoseFunction Diagnose;
874
875public:
876 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
877 DiagnoseFunction Diagnose)
878 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
879
880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
881 const char *StartSpecifier,
882 unsigned specifierLen) override {
883 if (!FS.consumesDataArgument())
884 return true;
885
886 unsigned NulByte = 0;
887 switch ((FS.getConversionSpecifier().getKind())) {
888 default:
889 return true;
890 case analyze_format_string::ConversionSpecifier::sArg:
891 case analyze_format_string::ConversionSpecifier::ScanListArg:
892 NulByte = 1;
893 break;
894 case analyze_format_string::ConversionSpecifier::cArg:
895 break;
896 }
897
898 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
899 if (FW.getHowSpecified() !=
900 analyze_format_string::OptionalAmount::HowSpecified::Constant)
901 return true;
902
903 unsigned SourceSize = FW.getConstantAmount() + NulByte;
904
905 std::optional<llvm::APSInt> DestSizeAPS =
906 ComputeSizeArgument(FS.getArgIndex());
907 if (!DestSizeAPS)
908 return true;
909
910 unsigned DestSize = DestSizeAPS->getZExtValue();
911
912 if (DestSize < SourceSize)
913 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
914
915 return true;
916 }
917};
918
919class EstimateSizeFormatHandler
920 : public analyze_format_string::FormatStringHandler {
921 size_t Size;
922 /// Whether the format string contains Linux kernel's format specifier
923 /// extension.
924 bool IsKernelCompatible = true;
925
926public:
927 EstimateSizeFormatHandler(StringRef Format)
928 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
929 1 /* null byte always written by sprintf */) {}
930
931 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
932 const char *, unsigned SpecifierLen,
933 const TargetInfo &) override {
934
935 const size_t FieldWidth = computeFieldWidth(FS);
936 const size_t Precision = computePrecision(FS);
937
938 // The actual format.
939 switch (FS.getConversionSpecifier().getKind()) {
940 // Just a char.
941 case analyze_format_string::ConversionSpecifier::cArg:
942 case analyze_format_string::ConversionSpecifier::CArg:
943 Size += std::max(a: FieldWidth, b: (size_t)1);
944 break;
945 // Just an integer.
946 case analyze_format_string::ConversionSpecifier::dArg:
947 case analyze_format_string::ConversionSpecifier::DArg:
948 case analyze_format_string::ConversionSpecifier::iArg:
949 case analyze_format_string::ConversionSpecifier::oArg:
950 case analyze_format_string::ConversionSpecifier::OArg:
951 case analyze_format_string::ConversionSpecifier::uArg:
952 case analyze_format_string::ConversionSpecifier::UArg:
953 case analyze_format_string::ConversionSpecifier::xArg:
954 case analyze_format_string::ConversionSpecifier::XArg:
955 Size += std::max(a: FieldWidth, b: Precision);
956 break;
957
958 // %g style conversion switches between %f or %e style dynamically.
959 // %g removes trailing zeros, and does not print decimal point if there are
960 // no digits that follow it. Thus %g can print a single digit.
961 // FIXME: If it is alternative form:
962 // For g and G conversions, trailing zeros are not removed from the result.
963 case analyze_format_string::ConversionSpecifier::gArg:
964 case analyze_format_string::ConversionSpecifier::GArg:
965 Size += 1;
966 break;
967
968 // Floating point number in the form '[+]ddd.ddd'.
969 case analyze_format_string::ConversionSpecifier::fArg:
970 case analyze_format_string::ConversionSpecifier::FArg:
971 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
972 (Precision ? 1 + Precision
973 : 0) /* period + decimal */);
974 break;
975
976 // Floating point number in the form '[-]d.ddde[+-]dd'.
977 case analyze_format_string::ConversionSpecifier::eArg:
978 case analyze_format_string::ConversionSpecifier::EArg:
979 Size +=
980 std::max(a: FieldWidth,
981 b: 1 /* integer part */ +
982 (Precision ? 1 + Precision : 0) /* period + decimal */ +
983 1 /* e or E letter */ + 2 /* exponent */);
984 break;
985
986 // Floating point number in the form '[-]0xh.hhhhp±dd'.
987 case analyze_format_string::ConversionSpecifier::aArg:
988 case analyze_format_string::ConversionSpecifier::AArg:
989 Size +=
990 std::max(a: FieldWidth,
991 b: 2 /* 0x */ + 1 /* integer part */ +
992 (Precision ? 1 + Precision : 0) /* period + decimal */ +
993 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
994 break;
995
996 // Just a string.
997 case analyze_format_string::ConversionSpecifier::sArg:
998 case analyze_format_string::ConversionSpecifier::SArg:
999 Size += FieldWidth;
1000 break;
1001
1002 // Just a pointer in the form '0xddd'.
1003 case analyze_format_string::ConversionSpecifier::pArg:
1004 // Linux kernel has its own extesion for `%p` specifier.
1005 // Kernel Document:
1006 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1007 IsKernelCompatible = false;
1008 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1009 break;
1010
1011 // A plain percent.
1012 case analyze_format_string::ConversionSpecifier::PercentArg:
1013 Size += 1;
1014 break;
1015
1016 default:
1017 break;
1018 }
1019
1020 // If field width is specified, the sign/space is already accounted for
1021 // within the field width, so no additional size is needed.
1022 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1023 Size += 1;
1024
1025 if (FS.hasAlternativeForm()) {
1026 switch (FS.getConversionSpecifier().getKind()) {
1027 // For o conversion, it increases the precision, if and only if necessary,
1028 // to force the first digit of the result to be a zero
1029 // (if the value and precision are both 0, a single 0 is printed)
1030 case analyze_format_string::ConversionSpecifier::oArg:
1031 // For b conversion, a nonzero result has 0b prefixed to it.
1032 case analyze_format_string::ConversionSpecifier::bArg:
1033 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1034 // it.
1035 case analyze_format_string::ConversionSpecifier::xArg:
1036 case analyze_format_string::ConversionSpecifier::XArg:
1037 // Note: even when the prefix is added, if
1038 // (prefix_width <= FieldWidth - formatted_length) holds,
1039 // the prefix does not increase the format
1040 // size. e.g.(("%#3x", 0xf) is "0xf")
1041
1042 // If the result is zero, o, b, x, X adds nothing.
1043 break;
1044 // For a, A, e, E, f, F, g, and G conversions,
1045 // the result of converting a floating-point number always contains a
1046 // decimal-point
1047 case analyze_format_string::ConversionSpecifier::aArg:
1048 case analyze_format_string::ConversionSpecifier::AArg:
1049 case analyze_format_string::ConversionSpecifier::eArg:
1050 case analyze_format_string::ConversionSpecifier::EArg:
1051 case analyze_format_string::ConversionSpecifier::fArg:
1052 case analyze_format_string::ConversionSpecifier::FArg:
1053 case analyze_format_string::ConversionSpecifier::gArg:
1054 case analyze_format_string::ConversionSpecifier::GArg:
1055 Size += (Precision ? 0 : 1);
1056 break;
1057 // For other conversions, the behavior is undefined.
1058 default:
1059 break;
1060 }
1061 }
1062 assert(SpecifierLen <= Size && "no underflow");
1063 Size -= SpecifierLen;
1064 return true;
1065 }
1066
1067 size_t getSizeLowerBound() const { return Size; }
1068 bool isKernelCompatible() const { return IsKernelCompatible; }
1069
1070private:
1071 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1072 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1073 size_t FieldWidth = 0;
1074 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1075 FieldWidth = FW.getConstantAmount();
1076 return FieldWidth;
1077 }
1078
1079 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1080 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1081 size_t Precision = 0;
1082
1083 // See man 3 printf for default precision value based on the specifier.
1084 switch (FW.getHowSpecified()) {
1085 case analyze_format_string::OptionalAmount::NotSpecified:
1086 switch (FS.getConversionSpecifier().getKind()) {
1087 default:
1088 break;
1089 case analyze_format_string::ConversionSpecifier::dArg: // %d
1090 case analyze_format_string::ConversionSpecifier::DArg: // %D
1091 case analyze_format_string::ConversionSpecifier::iArg: // %i
1092 Precision = 1;
1093 break;
1094 case analyze_format_string::ConversionSpecifier::oArg: // %d
1095 case analyze_format_string::ConversionSpecifier::OArg: // %D
1096 case analyze_format_string::ConversionSpecifier::uArg: // %d
1097 case analyze_format_string::ConversionSpecifier::UArg: // %D
1098 case analyze_format_string::ConversionSpecifier::xArg: // %d
1099 case analyze_format_string::ConversionSpecifier::XArg: // %D
1100 Precision = 1;
1101 break;
1102 case analyze_format_string::ConversionSpecifier::fArg: // %f
1103 case analyze_format_string::ConversionSpecifier::FArg: // %F
1104 case analyze_format_string::ConversionSpecifier::eArg: // %e
1105 case analyze_format_string::ConversionSpecifier::EArg: // %E
1106 case analyze_format_string::ConversionSpecifier::gArg: // %g
1107 case analyze_format_string::ConversionSpecifier::GArg: // %G
1108 Precision = 6;
1109 break;
1110 case analyze_format_string::ConversionSpecifier::pArg: // %d
1111 Precision = 1;
1112 break;
1113 }
1114 break;
1115 case analyze_format_string::OptionalAmount::Constant:
1116 Precision = FW.getConstantAmount();
1117 break;
1118 default:
1119 break;
1120 }
1121 return Precision;
1122 }
1123};
1124
1125} // namespace
1126
1127static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1128 StringRef &FormatStrRef, size_t &StrLen,
1129 ASTContext &Context) {
1130 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1131 Format && (Format->isOrdinary() || Format->isUTF8())) {
1132 FormatStrRef = Format->getString();
1133 const ConstantArrayType *T =
1134 Context.getAsConstantArrayType(T: Format->getType());
1135 assert(T && "String literal not of constant array type!");
1136 size_t TypeSize = T->getZExtSize();
1137 // In case there's a null byte somewhere.
1138 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1139 return true;
1140 }
1141 return false;
1142}
1143
1144void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1145 CallExpr *TheCall) {
1146 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1147 isConstantEvaluatedContext())
1148 return;
1149
1150 bool UseDABAttr = false;
1151 const FunctionDecl *UseDecl = FD;
1152
1153 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1154 if (DABAttr) {
1155 UseDecl = DABAttr->getFunction();
1156 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1157 UseDABAttr = true;
1158 }
1159
1160 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1161
1162 if (!BuiltinID)
1163 return;
1164
1165 const TargetInfo &TI = getASTContext().getTargetInfo();
1166 unsigned SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1167
1168 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1169 // If we refer to a diagnose_as_builtin attribute, we need to change the
1170 // argument index to refer to the arguments of the called function. Unless
1171 // the index is out of bounds, which presumably means it's a variadic
1172 // function.
1173 if (!UseDABAttr)
1174 return Index;
1175 unsigned DABIndices = DABAttr->argIndices_size();
1176 unsigned NewIndex = Index < DABIndices
1177 ? DABAttr->argIndices_begin()[Index]
1178 : Index - DABIndices + FD->getNumParams();
1179 if (NewIndex >= TheCall->getNumArgs())
1180 return std::nullopt;
1181 return NewIndex;
1182 };
1183
1184 auto ComputeExplicitObjectSizeArgument =
1185 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1186 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1187 if (!IndexOptional)
1188 return std::nullopt;
1189 unsigned NewIndex = *IndexOptional;
1190 Expr::EvalResult Result;
1191 Expr *SizeArg = TheCall->getArg(Arg: NewIndex);
1192 if (!SizeArg->EvaluateAsInt(Result, Ctx: getASTContext()))
1193 return std::nullopt;
1194 llvm::APSInt Integer = Result.Val.getInt();
1195 Integer.setIsUnsigned(true);
1196 return Integer;
1197 };
1198
1199 auto ComputeSizeArgument =
1200 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1201 // If the parameter has a pass_object_size attribute, then we should use its
1202 // (potentially) more strict checking mode. Otherwise, conservatively assume
1203 // type 0.
1204 int BOSType = 0;
1205 // This check can fail for variadic functions.
1206 if (Index < FD->getNumParams()) {
1207 if (const auto *POS =
1208 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1209 BOSType = POS->getType();
1210 }
1211
1212 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1213 if (!IndexOptional)
1214 return std::nullopt;
1215 unsigned NewIndex = *IndexOptional;
1216
1217 if (NewIndex >= TheCall->getNumArgs())
1218 return std::nullopt;
1219
1220 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1221 if (std::optional<uint64_t> ObjSize =
1222 ObjArg->tryEvaluateObjectSize(Ctx: getASTContext(), Type: BOSType)) {
1223 // Get the object size in the target's size_t width.
1224 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1225 }
1226 return std::nullopt;
1227 };
1228
1229 auto ComputeStrLenArgument =
1230 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1231 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1232 if (!IndexOptional)
1233 return std::nullopt;
1234 unsigned NewIndex = *IndexOptional;
1235
1236 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1237
1238 if (std::optional<uint64_t> Result =
1239 ObjArg->tryEvaluateStrLen(Ctx: getASTContext())) {
1240 // Add 1 for null byte.
1241 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1242 }
1243 return std::nullopt;
1244 };
1245
1246 std::optional<llvm::APSInt> SourceSize;
1247 std::optional<llvm::APSInt> DestinationSize;
1248 unsigned DiagID = 0;
1249 bool IsChkVariant = false;
1250
1251 auto GetFunctionName = [&]() {
1252 std::string FunctionNameStr =
1253 getASTContext().BuiltinInfo.getName(ID: BuiltinID);
1254 llvm::StringRef FunctionName = FunctionNameStr;
1255 // Skim off the details of whichever builtin was called to produce a better
1256 // diagnostic, as it's unlikely that the user wrote the __builtin
1257 // explicitly.
1258 if (IsChkVariant) {
1259 FunctionName = FunctionName.drop_front(N: std::strlen(s: "__builtin___"));
1260 FunctionName = FunctionName.drop_back(N: std::strlen(s: "_chk"));
1261 } else {
1262 FunctionName.consume_front(Prefix: "__builtin_");
1263 }
1264 return FunctionName.str();
1265 };
1266
1267 switch (BuiltinID) {
1268 default:
1269 return;
1270 case Builtin::BI__builtin_strcat:
1271 case Builtin::BIstrcat:
1272 case Builtin::BI__builtin_stpcpy:
1273 case Builtin::BIstpcpy:
1274 case Builtin::BI__builtin_strcpy:
1275 case Builtin::BIstrcpy: {
1276 DiagID = diag::warn_fortify_strlen_overflow;
1277 SourceSize = ComputeStrLenArgument(1);
1278 DestinationSize = ComputeSizeArgument(0);
1279 break;
1280 }
1281
1282 case Builtin::BI__builtin___strcat_chk:
1283 case Builtin::BI__builtin___stpcpy_chk:
1284 case Builtin::BI__builtin___strcpy_chk: {
1285 DiagID = diag::warn_fortify_strlen_overflow;
1286 SourceSize = ComputeStrLenArgument(1);
1287 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1288 IsChkVariant = true;
1289 break;
1290 }
1291
1292 case Builtin::BIscanf:
1293 case Builtin::BIfscanf:
1294 case Builtin::BIsscanf: {
1295 unsigned FormatIndex = 1;
1296 unsigned DataIndex = 2;
1297 if (BuiltinID == Builtin::BIscanf) {
1298 FormatIndex = 0;
1299 DataIndex = 1;
1300 }
1301
1302 const auto *FormatExpr =
1303 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1304
1305 StringRef FormatStrRef;
1306 size_t StrLen;
1307 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1308 return;
1309
1310 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1311 unsigned SourceSize) {
1312 DiagID = diag::warn_fortify_scanf_overflow;
1313 unsigned Index = ArgIndex + DataIndex;
1314 std::string FunctionName = GetFunctionName();
1315 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1316 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1317 << DestSize << SourceSize);
1318 };
1319
1320 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1321 return ComputeSizeArgument(Index + DataIndex);
1322 };
1323 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1324 const char *FormatBytes = FormatStrRef.data();
1325 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1326 end: FormatBytes + StrLen, LO: getLangOpts(),
1327 Target: Context.getTargetInfo());
1328
1329 // Unlike the other cases, in this one we have already issued the diagnostic
1330 // here, so no need to continue (because unlike the other cases, here the
1331 // diagnostic refers to the argument number).
1332 return;
1333 }
1334
1335 case Builtin::BIsprintf:
1336 case Builtin::BI__builtin___sprintf_chk: {
1337 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1338 auto *FormatExpr = TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1339
1340 StringRef FormatStrRef;
1341 size_t StrLen;
1342 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1343 EstimateSizeFormatHandler H(FormatStrRef);
1344 const char *FormatBytes = FormatStrRef.data();
1345 if (!analyze_format_string::ParsePrintfString(
1346 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1347 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1348 DiagID = H.isKernelCompatible()
1349 ? diag::warn_format_overflow
1350 : diag::warn_format_overflow_non_kprintf;
1351 SourceSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1352 .extOrTrunc(width: SizeTypeWidth);
1353 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1354 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1355 IsChkVariant = true;
1356 } else {
1357 DestinationSize = ComputeSizeArgument(0);
1358 }
1359 break;
1360 }
1361 }
1362 return;
1363 }
1364 case Builtin::BI__builtin___memcpy_chk:
1365 case Builtin::BI__builtin___memmove_chk:
1366 case Builtin::BI__builtin___memset_chk:
1367 case Builtin::BI__builtin___strlcat_chk:
1368 case Builtin::BI__builtin___strlcpy_chk:
1369 case Builtin::BI__builtin___strncat_chk:
1370 case Builtin::BI__builtin___strncpy_chk:
1371 case Builtin::BI__builtin___stpncpy_chk:
1372 case Builtin::BI__builtin___memccpy_chk:
1373 case Builtin::BI__builtin___mempcpy_chk: {
1374 DiagID = diag::warn_builtin_chk_overflow;
1375 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1376 DestinationSize =
1377 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1378 IsChkVariant = true;
1379 break;
1380 }
1381
1382 case Builtin::BI__builtin___snprintf_chk:
1383 case Builtin::BI__builtin___vsnprintf_chk: {
1384 DiagID = diag::warn_builtin_chk_overflow;
1385 SourceSize = ComputeExplicitObjectSizeArgument(1);
1386 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1387 IsChkVariant = true;
1388 break;
1389 }
1390
1391 case Builtin::BIstrncat:
1392 case Builtin::BI__builtin_strncat:
1393 case Builtin::BIstrncpy:
1394 case Builtin::BI__builtin_strncpy:
1395 case Builtin::BIstpncpy:
1396 case Builtin::BI__builtin_stpncpy: {
1397 // Whether these functions overflow depends on the runtime strlen of the
1398 // string, not just the buffer size, so emitting the "always overflow"
1399 // diagnostic isn't quite right. We should still diagnose passing a buffer
1400 // size larger than the destination buffer though; this is a runtime abort
1401 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1402 DiagID = diag::warn_fortify_source_size_mismatch;
1403 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1404 DestinationSize = ComputeSizeArgument(0);
1405 break;
1406 }
1407
1408 case Builtin::BImemcpy:
1409 case Builtin::BI__builtin_memcpy:
1410 case Builtin::BImemmove:
1411 case Builtin::BI__builtin_memmove:
1412 case Builtin::BImemset:
1413 case Builtin::BI__builtin_memset:
1414 case Builtin::BImempcpy:
1415 case Builtin::BI__builtin_mempcpy: {
1416 DiagID = diag::warn_fortify_source_overflow;
1417 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1418 DestinationSize = ComputeSizeArgument(0);
1419 break;
1420 }
1421 case Builtin::BIsnprintf:
1422 case Builtin::BI__builtin_snprintf:
1423 case Builtin::BIvsnprintf:
1424 case Builtin::BI__builtin_vsnprintf: {
1425 DiagID = diag::warn_fortify_source_size_mismatch;
1426 SourceSize = ComputeExplicitObjectSizeArgument(1);
1427 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1428 StringRef FormatStrRef;
1429 size_t StrLen;
1430 if (SourceSize &&
1431 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1432 EstimateSizeFormatHandler H(FormatStrRef);
1433 const char *FormatBytes = FormatStrRef.data();
1434 if (!analyze_format_string::ParsePrintfString(
1435 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1436 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1437 llvm::APSInt FormatSize =
1438 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1439 .extOrTrunc(width: SizeTypeWidth);
1440 if (FormatSize > *SourceSize && *SourceSize != 0) {
1441 unsigned TruncationDiagID =
1442 H.isKernelCompatible() ? diag::warn_format_truncation
1443 : diag::warn_format_truncation_non_kprintf;
1444 SmallString<16> SpecifiedSizeStr;
1445 SmallString<16> FormatSizeStr;
1446 SourceSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1447 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1448 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1449 PD: PDiag(DiagID: TruncationDiagID)
1450 << GetFunctionName() << SpecifiedSizeStr
1451 << FormatSizeStr);
1452 }
1453 }
1454 }
1455 DestinationSize = ComputeSizeArgument(0);
1456 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1457 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1458 IdentifierInfo *FnInfo = FD->getIdentifier();
1459 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1460 }
1461 }
1462
1463 if (!SourceSize || !DestinationSize ||
1464 llvm::APSInt::compareValues(I1: *SourceSize, I2: *DestinationSize) <= 0)
1465 return;
1466
1467 std::string FunctionName = GetFunctionName();
1468
1469 SmallString<16> DestinationStr;
1470 SmallString<16> SourceStr;
1471 DestinationSize->toString(Str&: DestinationStr, /*Radix=*/10);
1472 SourceSize->toString(Str&: SourceStr, /*Radix=*/10);
1473 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1474 PD: PDiag(DiagID)
1475 << FunctionName << DestinationStr << SourceStr);
1476}
1477
1478static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1479 Scope::ScopeFlags NeededScopeFlags,
1480 unsigned DiagID) {
1481 // Scopes aren't available during instantiation. Fortunately, builtin
1482 // functions cannot be template args so they cannot be formed through template
1483 // instantiation. Therefore checking once during the parse is sufficient.
1484 if (SemaRef.inTemplateInstantiation())
1485 return false;
1486
1487 Scope *S = SemaRef.getCurScope();
1488 while (S && !S->isSEHExceptScope())
1489 S = S->getParent();
1490 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1491 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1492 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1493 << DRE->getDecl()->getIdentifier();
1494 return true;
1495 }
1496
1497 return false;
1498}
1499
1500// In OpenCL, __builtin_alloca_* should return a pointer to address space
1501// that corresponds to the stack address space i.e private address space.
1502static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1503 QualType RT = TheCall->getType();
1504 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1505 "__builtin_alloca has invalid address space");
1506
1507 RT = RT->getPointeeType();
1508 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1509 TheCall->setType(S.Context.getPointerType(T: RT));
1510}
1511
1512static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1513 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1514 return true;
1515
1516 for (Expr *Arg : TheCall->arguments()) {
1517 // If argument is dependent on a template parameter, we can't resolve now.
1518 if (Arg->isTypeDependent() || Arg->isValueDependent())
1519 continue;
1520 // Reject void types.
1521 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1522 if (ArgTy->isVoidType())
1523 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1524 }
1525
1526 TheCall->setType(S.Context.getSizeType());
1527 return false;
1528}
1529
1530namespace {
1531enum PointerAuthOpKind {
1532 PAO_Strip,
1533 PAO_Sign,
1534 PAO_Auth,
1535 PAO_SignGeneric,
1536 PAO_Discriminator,
1537 PAO_BlendPointer,
1538 PAO_BlendInteger
1539};
1540}
1541
1542bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1543 if (getLangOpts().PointerAuthIntrinsics)
1544 return false;
1545
1546 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1547 return true;
1548}
1549
1550static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1551 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1552}
1553
1554static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1555 // Convert it to type 'int'.
1556 if (convertArgumentToType(S, Value&: Arg, Ty: S.Context.IntTy))
1557 return true;
1558
1559 // Value-dependent expressions are okay; wait for template instantiation.
1560 if (Arg->isValueDependent())
1561 return false;
1562
1563 unsigned KeyValue;
1564 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1565}
1566
1567bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1568 // Attempt to constant-evaluate the expression.
1569 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1570 if (!KeyValue) {
1571 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1572 << 0 << Arg->getSourceRange();
1573 return true;
1574 }
1575
1576 // Ask the target to validate the key parameter.
1577 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1578 llvm::SmallString<32> Value;
1579 {
1580 llvm::raw_svector_ostream Str(Value);
1581 Str << *KeyValue;
1582 }
1583
1584 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1585 << Value << Arg->getSourceRange();
1586 return true;
1587 }
1588
1589 Result = KeyValue->getZExtValue();
1590 return false;
1591}
1592
1593bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1594 PointerAuthDiscArgKind Kind,
1595 unsigned &IntVal) {
1596 if (!Arg) {
1597 IntVal = 0;
1598 return true;
1599 }
1600
1601 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1602 if (!Result) {
1603 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1604 return false;
1605 }
1606
1607 unsigned Max;
1608 bool IsAddrDiscArg = false;
1609
1610 switch (Kind) {
1611 case PointerAuthDiscArgKind::Addr:
1612 Max = 1;
1613 IsAddrDiscArg = true;
1614 break;
1615 case PointerAuthDiscArgKind::Extra:
1616 Max = PointerAuthQualifier::MaxDiscriminator;
1617 break;
1618 };
1619
1620 if (*Result < 0 || *Result > Max) {
1621 if (IsAddrDiscArg)
1622 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1623 << Result->getExtValue();
1624 else
1625 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1626 << Result->getExtValue() << Max;
1627
1628 return false;
1629 };
1630
1631 IntVal = Result->getZExtValue();
1632 return true;
1633}
1634
1635static std::pair<const ValueDecl *, CharUnits>
1636findConstantBaseAndOffset(Sema &S, Expr *E) {
1637 // Must evaluate as a pointer.
1638 Expr::EvalResult Result;
1639 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1640 return {nullptr, CharUnits()};
1641
1642 const auto *BaseDecl =
1643 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1644 if (!BaseDecl)
1645 return {nullptr, CharUnits()};
1646
1647 return {BaseDecl, Result.Val.getLValueOffset()};
1648}
1649
1650static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1651 bool RequireConstant = false) {
1652 if (Arg->hasPlaceholderType()) {
1653 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1654 if (R.isInvalid())
1655 return true;
1656 Arg = R.get();
1657 }
1658
1659 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1660 return OpKind != PAO_BlendInteger;
1661 };
1662 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1663 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1664 OpKind == PAO_SignGeneric;
1665 };
1666
1667 // Require the value to have the right range of type.
1668 QualType ExpectedTy;
1669 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1670 ExpectedTy = Arg->getType().getUnqualifiedType();
1671 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1672 ExpectedTy = S.Context.VoidPtrTy;
1673 } else if (AllowsInteger(OpKind) &&
1674 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1675 ExpectedTy = S.Context.getUIntPtrType();
1676
1677 } else {
1678 // Diagnose the failures.
1679 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1680 << unsigned(OpKind == PAO_Discriminator ? 1
1681 : OpKind == PAO_BlendPointer ? 2
1682 : OpKind == PAO_BlendInteger ? 3
1683 : 0)
1684 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1685 << Arg->getType() << Arg->getSourceRange();
1686 return true;
1687 }
1688
1689 // Convert to that type. This should just be an lvalue-to-rvalue
1690 // conversion.
1691 if (convertArgumentToType(S, Value&: Arg, Ty: ExpectedTy))
1692 return true;
1693
1694 if (!RequireConstant) {
1695 // Warn about null pointers for non-generic sign and auth operations.
1696 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1697 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1698 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1699 ? diag::warn_ptrauth_sign_null_pointer
1700 : diag::warn_ptrauth_auth_null_pointer)
1701 << Arg->getSourceRange();
1702 }
1703
1704 return false;
1705 }
1706
1707 // Perform special checking on the arguments to ptrauth_sign_constant.
1708
1709 // The main argument.
1710 if (OpKind == PAO_Sign) {
1711 // Require the value we're signing to have a special form.
1712 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1713 bool Invalid;
1714
1715 // Must be rooted in a declaration reference.
1716 if (!BaseDecl)
1717 Invalid = true;
1718
1719 // If it's a function declaration, we can't have an offset.
1720 else if (isa<FunctionDecl>(Val: BaseDecl))
1721 Invalid = !Offset.isZero();
1722
1723 // Otherwise we're fine.
1724 else
1725 Invalid = false;
1726
1727 if (Invalid)
1728 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1729 return Invalid;
1730 }
1731
1732 // The discriminator argument.
1733 assert(OpKind == PAO_Discriminator);
1734
1735 // Must be a pointer or integer or blend thereof.
1736 Expr *Pointer = nullptr;
1737 Expr *Integer = nullptr;
1738 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1739 if (Call->getBuiltinCallee() ==
1740 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1741 Pointer = Call->getArg(Arg: 0);
1742 Integer = Call->getArg(Arg: 1);
1743 }
1744 }
1745 if (!Pointer && !Integer) {
1746 if (Arg->getType()->isPointerType())
1747 Pointer = Arg;
1748 else
1749 Integer = Arg;
1750 }
1751
1752 // Check the pointer.
1753 bool Invalid = false;
1754 if (Pointer) {
1755 assert(Pointer->getType()->isPointerType());
1756
1757 // TODO: if we're initializing a global, check that the address is
1758 // somehow related to what we're initializing. This probably will
1759 // never really be feasible and we'll have to catch it at link-time.
1760 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1761 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
1762 Invalid = true;
1763 }
1764
1765 // Check the integer.
1766 if (Integer) {
1767 assert(Integer->getType()->isIntegerType());
1768 if (!Integer->isEvaluatable(Ctx: S.Context))
1769 Invalid = true;
1770 }
1771
1772 if (Invalid)
1773 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
1774 return Invalid;
1775}
1776
1777static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
1778 if (S.checkArgCount(Call, DesiredArgCount: 2))
1779 return ExprError();
1780 if (checkPointerAuthEnabled(S, E: Call))
1781 return ExprError();
1782 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
1783 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
1784 return ExprError();
1785
1786 Call->setType(Call->getArgs()[0]->getType());
1787 return Call;
1788}
1789
1790static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
1791 if (S.checkArgCount(Call, DesiredArgCount: 2))
1792 return ExprError();
1793 if (checkPointerAuthEnabled(S, E: Call))
1794 return ExprError();
1795 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
1796 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
1797 return ExprError();
1798
1799 Call->setType(S.Context.getUIntPtrType());
1800 return Call;
1801}
1802
1803static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
1804 if (S.checkArgCount(Call, DesiredArgCount: 2))
1805 return ExprError();
1806 if (checkPointerAuthEnabled(S, E: Call))
1807 return ExprError();
1808 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
1809 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
1810 return ExprError();
1811
1812 Call->setType(S.Context.getUIntPtrType());
1813 return Call;
1814}
1815
1816static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
1817 PointerAuthOpKind OpKind,
1818 bool RequireConstant) {
1819 if (S.checkArgCount(Call, DesiredArgCount: 3))
1820 return ExprError();
1821 if (checkPointerAuthEnabled(S, E: Call))
1822 return ExprError();
1823 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
1824 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1825 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
1826 RequireConstant))
1827 return ExprError();
1828
1829 Call->setType(Call->getArgs()[0]->getType());
1830 return Call;
1831}
1832
1833static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
1834 if (S.checkArgCount(Call, DesiredArgCount: 5))
1835 return ExprError();
1836 if (checkPointerAuthEnabled(S, E: Call))
1837 return ExprError();
1838 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1839 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1840 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1841 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1842 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
1843 return ExprError();
1844
1845 Call->setType(Call->getArgs()[0]->getType());
1846 return Call;
1847}
1848
1849static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
1850 if (S.checkArgCount(Call, DesiredArgCount: 6))
1851 return ExprError();
1852 if (checkPointerAuthEnabled(S, E: Call))
1853 return ExprError();
1854 const Expr *AddendExpr = Call->getArg(Arg: 5);
1855 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
1856 if (!AddendIsConstInt) {
1857 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
1858 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
1859 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
1860 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
1861 << FDecl->getDeclName() << Arg->getSourceRange();
1862 }
1863 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1864 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1865 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1866 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1867 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
1868 !AddendIsConstInt)
1869 return ExprError();
1870
1871 Call->setType(Call->getArgs()[0]->getType());
1872 return Call;
1873}
1874
1875static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
1876 if (checkPointerAuthEnabled(S, E: Call))
1877 return ExprError();
1878
1879 // We've already performed normal call type-checking.
1880 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
1881
1882 // Operand must be an ordinary or UTF-8 string literal.
1883 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
1884 if (!Literal || Literal->getCharByteWidth() != 1) {
1885 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
1886 << (Literal ? 1 : 0) << Arg->getSourceRange();
1887 return ExprError();
1888 }
1889
1890 return Call;
1891}
1892
1893static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
1894 if (S.checkArgCount(Call, DesiredArgCount: 1))
1895 return ExprError();
1896 Expr *FirstArg = Call->getArg(Arg: 0);
1897 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
1898 if (FirstValue.isInvalid())
1899 return ExprError();
1900 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
1901 QualType FirstArgType = FirstArg->getType();
1902 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1903 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
1904
1905 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1906 if (!FirstArgRecord) {
1907 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
1908 << /*isPolymorphic=*/0 << FirstArgType;
1909 return ExprError();
1910 }
1911 if (S.RequireCompleteType(
1912 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
1913 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
1914 return ExprError();
1915 }
1916
1917 if (!FirstArgRecord->isPolymorphic()) {
1918 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
1919 << /*isPolymorphic=*/1 << FirstArgRecord;
1920 return ExprError();
1921 }
1922 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
1923 Call->setType(ReturnType);
1924 return Call;
1925}
1926
1927static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
1928 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
1929 return ExprError();
1930
1931 // Compute __builtin_launder's parameter type from the argument.
1932 // The parameter type is:
1933 // * The type of the argument if it's not an array or function type,
1934 // Otherwise,
1935 // * The decayed argument type.
1936 QualType ParamTy = [&]() {
1937 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
1938 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1939 return S.Context.getPointerType(T: Ty->getElementType());
1940 if (ArgTy->isFunctionType()) {
1941 return S.Context.getPointerType(T: ArgTy);
1942 }
1943 return ArgTy;
1944 }();
1945
1946 TheCall->setType(ParamTy);
1947
1948 auto DiagSelect = [&]() -> std::optional<unsigned> {
1949 if (!ParamTy->isPointerType())
1950 return 0;
1951 if (ParamTy->isFunctionPointerType())
1952 return 1;
1953 if (ParamTy->isVoidPointerType())
1954 return 2;
1955 return std::optional<unsigned>{};
1956 }();
1957 if (DiagSelect) {
1958 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
1959 << *DiagSelect << TheCall->getSourceRange();
1960 return ExprError();
1961 }
1962
1963 // We either have an incomplete class type, or we have a class template
1964 // whose instantiation has not been forced. Example:
1965 //
1966 // template <class T> struct Foo { T value; };
1967 // Foo<int> *p = nullptr;
1968 // auto *d = __builtin_launder(p);
1969 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
1970 DiagID: diag::err_incomplete_type))
1971 return ExprError();
1972
1973 assert(ParamTy->getPointeeType()->isObjectType() &&
1974 "Unhandled non-object pointer case");
1975
1976 InitializedEntity Entity =
1977 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
1978 ExprResult Arg =
1979 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
1980 if (Arg.isInvalid())
1981 return ExprError();
1982 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
1983
1984 return TheCall;
1985}
1986
1987static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
1988 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
1989 return ExprError();
1990
1991 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
1992 if (Arg.isInvalid())
1993 return ExprError();
1994 QualType ParamTy = Arg.get()->getType();
1995 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
1996 TheCall->setType(S.Context.BoolTy);
1997
1998 // Only accept pointers to objects as arguments, which should have object
1999 // pointer or void pointer types.
2000 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2001 // LWG4138: Function pointer types not allowed
2002 if (PT->getPointeeType()->isFunctionType()) {
2003 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2004 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2005 << 1;
2006 return ExprError();
2007 }
2008 // Disallow VLAs too since those shouldn't be able to
2009 // be a template parameter for `std::is_within_lifetime`
2010 if (PT->getPointeeType()->isVariableArrayType()) {
2011 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2012 << 1 << "__builtin_is_within_lifetime";
2013 return ExprError();
2014 }
2015 } else {
2016 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2017 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2018 << 0;
2019 return ExprError();
2020 }
2021 return TheCall;
2022}
2023
2024static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2025 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2026 return ExprError();
2027
2028 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2029 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2030 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2031 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2032 << /*a pointer*/ 0;
2033 return ExprError();
2034 }
2035
2036 QualType T = Dest->getPointeeType();
2037 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2038 DiagID: diag::err_incomplete_type))
2039 return ExprError();
2040
2041 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2042 T->isIncompleteArrayType()) {
2043 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2044 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2045 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2046 return ExprError();
2047 }
2048
2049 TheCall->setType(Dest);
2050
2051 QualType Src = TheCall->getArg(Arg: 1)->getType();
2052 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2053 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2054 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2055 << /*the same*/ 3;
2056 return ExprError();
2057 }
2058
2059 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2060 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2061 if (Size.isInvalid())
2062 return ExprError();
2063
2064 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2065 if (Size.isInvalid())
2066 return ExprError();
2067 SizeExpr = Size.get();
2068 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2069
2070 return TheCall;
2071}
2072
2073// Emit an error and return true if the current object format type is in the
2074// list of unsupported types.
2075static bool CheckBuiltinTargetNotInUnsupported(
2076 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2077 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2078 llvm::Triple::ObjectFormatType CurObjFormat =
2079 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2080 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2081 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2082 << TheCall->getSourceRange();
2083 return true;
2084 }
2085 return false;
2086}
2087
2088// Emit an error and return true if the current architecture is not in the list
2089// of supported architectures.
2090static bool
2091CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2092 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2093 llvm::Triple::ArchType CurArch =
2094 S.getASTContext().getTargetInfo().getTriple().getArch();
2095 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2096 return false;
2097 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2098 << TheCall->getSourceRange();
2099 return true;
2100}
2101
2102static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2103 SourceLocation CallSiteLoc);
2104
2105bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2106 CallExpr *TheCall) {
2107 switch (TI.getTriple().getArch()) {
2108 default:
2109 // Some builtins don't require additional checking, so just consider these
2110 // acceptable.
2111 return false;
2112 case llvm::Triple::arm:
2113 case llvm::Triple::armeb:
2114 case llvm::Triple::thumb:
2115 case llvm::Triple::thumbeb:
2116 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2117 case llvm::Triple::aarch64:
2118 case llvm::Triple::aarch64_32:
2119 case llvm::Triple::aarch64_be:
2120 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2121 case llvm::Triple::bpfeb:
2122 case llvm::Triple::bpfel:
2123 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2124 case llvm::Triple::dxil:
2125 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2126 case llvm::Triple::hexagon:
2127 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2128 case llvm::Triple::mips:
2129 case llvm::Triple::mipsel:
2130 case llvm::Triple::mips64:
2131 case llvm::Triple::mips64el:
2132 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2133 case llvm::Triple::spirv:
2134 case llvm::Triple::spirv32:
2135 case llvm::Triple::spirv64:
2136 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2137 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2138 return false;
2139 case llvm::Triple::systemz:
2140 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2141 case llvm::Triple::x86:
2142 case llvm::Triple::x86_64:
2143 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2144 case llvm::Triple::ppc:
2145 case llvm::Triple::ppcle:
2146 case llvm::Triple::ppc64:
2147 case llvm::Triple::ppc64le:
2148 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2149 case llvm::Triple::amdgcn:
2150 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2151 case llvm::Triple::riscv32:
2152 case llvm::Triple::riscv64:
2153 case llvm::Triple::riscv32be:
2154 case llvm::Triple::riscv64be:
2155 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2156 case llvm::Triple::loongarch32:
2157 case llvm::Triple::loongarch64:
2158 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2159 TheCall);
2160 case llvm::Triple::wasm32:
2161 case llvm::Triple::wasm64:
2162 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2163 case llvm::Triple::nvptx:
2164 case llvm::Triple::nvptx64:
2165 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2166 }
2167}
2168
2169static bool isValidMathElementType(QualType T) {
2170 return T->isDependentType() ||
2171 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2172}
2173
2174// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2175// not a valid type, emit an error message and return true. Otherwise return
2176// false.
2177static bool
2178checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2179 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2180 int ArgOrdinal) {
2181 clang::QualType EltTy =
2182 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2183 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2184 : ArgTy;
2185
2186 switch (ArgTyRestr) {
2187 case Sema::EltwiseBuiltinArgTyRestriction::None:
2188 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(T: ArgTy)) {
2189 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2190 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2191 << ArgTy;
2192 }
2193 break;
2194 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2195 if (!EltTy->isRealFloatingType()) {
2196 // FIXME: make diagnostic's wording correct for matrices
2197 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2198 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2199 << /* floating-point */ 1 << ArgTy;
2200 }
2201 break;
2202 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2203 if (!EltTy->isIntegerType()) {
2204 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2205 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2206 << /* no fp */ 0 << ArgTy;
2207 }
2208 break;
2209 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2210 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2211 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2212 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2213 << /* or fp */ 1 << ArgTy;
2214 }
2215 break;
2216 }
2217
2218 return false;
2219}
2220
2221/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2222/// This checks that the target supports the builtin and that the string
2223/// argument is constant and valid.
2224static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2225 const TargetInfo *AuxTI, unsigned BuiltinID) {
2226 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2227 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2228 "Expecting __builtin_cpu_...");
2229
2230 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2231 const TargetInfo *TheTI = &TI;
2232 auto SupportsBI = [=](const TargetInfo *TInfo) {
2233 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2234 (!IsCPUSupports && TInfo->supportsCpuIs()));
2235 };
2236 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2237 TheTI = AuxTI;
2238
2239 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2240 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2241 return S.Diag(Loc: TheCall->getBeginLoc(),
2242 DiagID: TI.getTriple().isOSAIX()
2243 ? diag::err_builtin_aix_os_unsupported
2244 : diag::err_builtin_target_unsupported)
2245 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2246
2247 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2248 // Check if the argument is a string literal.
2249 if (!isa<StringLiteral>(Val: Arg))
2250 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2251 << Arg->getSourceRange();
2252
2253 // Check the contents of the string.
2254 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2255 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2256 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2257 << Arg->getSourceRange();
2258 return false;
2259 }
2260 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2261 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2262 << Arg->getSourceRange();
2263 return false;
2264}
2265
2266/// Checks that __builtin_bswapg was called with a single argument, which is an
2267/// unsigned integer, and overrides the return value type to the integer type.
2268static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2269 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2270 return true;
2271 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2272 if (ArgRes.isInvalid())
2273 return true;
2274
2275 Expr *Arg = ArgRes.get();
2276 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2277 if (Arg->isTypeDependent())
2278 return false;
2279
2280 QualType ArgTy = Arg->getType();
2281
2282 if (!ArgTy->isIntegerType()) {
2283 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2284 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2285 << ArgTy;
2286 return true;
2287 }
2288 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2289 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2290 BT->getNumBits() != 1) {
2291 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2292 << ArgTy << BT->getNumBits();
2293 return true;
2294 }
2295 }
2296 TheCall->setType(ArgTy);
2297 return false;
2298}
2299
2300/// Checks that __builtin_bitreverseg was called with a single argument, which
2301/// is an integer
2302static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2303 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2304 return true;
2305 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2306 if (ArgRes.isInvalid())
2307 return true;
2308
2309 Expr *Arg = ArgRes.get();
2310 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2311 if (Arg->isTypeDependent())
2312 return false;
2313
2314 QualType ArgTy = Arg->getType();
2315
2316 if (!ArgTy->isIntegerType()) {
2317 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2318 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2319 << ArgTy;
2320 return true;
2321 }
2322 TheCall->setType(ArgTy);
2323 return false;
2324}
2325
2326/// Checks that __builtin_popcountg was called with a single argument, which is
2327/// an unsigned integer.
2328static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2329 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2330 return true;
2331
2332 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2333 if (ArgRes.isInvalid())
2334 return true;
2335
2336 Expr *Arg = ArgRes.get();
2337 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2338
2339 QualType ArgTy = Arg->getType();
2340
2341 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2342 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2343 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2344 << ArgTy;
2345 return true;
2346 }
2347 return false;
2348}
2349
2350/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2351/// an unsigned integer, and an optional second argument, which is promoted to
2352/// an 'int'.
2353static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2354 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2355 return true;
2356
2357 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2358 if (Arg0Res.isInvalid())
2359 return true;
2360
2361 Expr *Arg0 = Arg0Res.get();
2362 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2363
2364 QualType Arg0Ty = Arg0->getType();
2365
2366 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2367 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2368 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2369 << Arg0Ty;
2370 return true;
2371 }
2372
2373 if (TheCall->getNumArgs() > 1) {
2374 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2375 if (Arg1Res.isInvalid())
2376 return true;
2377
2378 Expr *Arg1 = Arg1Res.get();
2379 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2380
2381 QualType Arg1Ty = Arg1->getType();
2382
2383 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2384 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2385 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2386 return true;
2387 }
2388 }
2389
2390 return false;
2391}
2392
2393class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2394 unsigned ArgIndex;
2395 bool OnlyUnsigned;
2396
2397 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2398 QualType T) {
2399 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2400 << ArgIndex << /*scalar*/ 1
2401 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2402 << /*no fp*/ 0 << T;
2403 }
2404
2405public:
2406 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2407 : ContextualImplicitConverter(/*Suppress=*/false,
2408 /*SuppressConversion=*/true),
2409 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2410
2411 bool match(QualType T) override {
2412 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2413 }
2414
2415 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2416 QualType T) override {
2417 return emitError(S, Loc, T);
2418 }
2419
2420 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2421 QualType T) override {
2422 return emitError(S, Loc, T);
2423 }
2424
2425 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2426 QualType T,
2427 QualType ConvTy) override {
2428 return emitError(S, Loc, T);
2429 }
2430
2431 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2432 QualType ConvTy) override {
2433 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2434 }
2435
2436 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2437 QualType T) override {
2438 return emitError(S, Loc, T);
2439 }
2440
2441 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2442 QualType ConvTy) override {
2443 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2444 }
2445
2446 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2447 QualType T,
2448 QualType ConvTy) override {
2449 llvm_unreachable("conversion functions are permitted");
2450 }
2451};
2452
2453/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2454/// arguments, that the first argument is an unsigned integer type, and that
2455/// the second argument is an integer type.
2456static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2457 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2458 return true;
2459
2460 // First argument (value to rotate) must be unsigned integer type.
2461 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2462 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2463 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2464 if (Arg0Res.isInvalid())
2465 return true;
2466
2467 Expr *Arg0 = Arg0Res.get();
2468 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2469
2470 QualType Arg0Ty = Arg0->getType();
2471 if (!Arg0Ty->isUnsignedIntegerType())
2472 return true;
2473
2474 // Second argument (rotation count) must be integer type.
2475 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2476 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2477 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2478 if (Arg1Res.isInvalid())
2479 return true;
2480
2481 Expr *Arg1 = Arg1Res.get();
2482 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2483
2484 QualType Arg1Ty = Arg1->getType();
2485 if (!Arg1Ty->isIntegerType())
2486 return true;
2487
2488 TheCall->setType(Arg0Ty);
2489 return false;
2490}
2491
2492static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2493 unsigned Pos, bool AllowConst,
2494 bool AllowAS) {
2495 QualType MaskTy = MaskArg->getType();
2496 if (!MaskTy->isExtVectorBoolType())
2497 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2498 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2499 << MaskTy;
2500
2501 QualType PtrTy = PtrArg->getType();
2502 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2503 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2504 << Pos << "scalar pointer";
2505
2506 QualType PointeeTy = PtrTy->getPointeeType();
2507 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2508 (!AllowConst && PointeeTy.isConstQualified()) ||
2509 (!AllowAS && PointeeTy.hasAddressSpace())) {
2510 QualType Target =
2511 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2512 return S.Diag(Loc: PtrArg->getExprLoc(),
2513 DiagID: diag::err_typecheck_convert_incompatible)
2514 << PtrTy << Target << /*different qualifiers=*/5
2515 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2516 << PtrTy << Target;
2517 }
2518 return false;
2519}
2520
2521static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2522 bool TypeDependent = false;
2523 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2524 ExprResult Converted =
2525 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2526 if (Converted.isInvalid())
2527 return true;
2528 TheCall->setArg(Arg, ArgExpr: Converted.get());
2529 TypeDependent |= Converted.get()->isTypeDependent();
2530 }
2531
2532 if (TypeDependent)
2533 TheCall->setType(S.Context.DependentTy);
2534 return false;
2535}
2536
2537static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2538 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2539 return ExprError();
2540
2541 if (ConvertMaskedBuiltinArgs(S, TheCall))
2542 return ExprError();
2543
2544 Expr *MaskArg = TheCall->getArg(Arg: 0);
2545 Expr *PtrArg = TheCall->getArg(Arg: 1);
2546 if (TheCall->isTypeDependent())
2547 return TheCall;
2548
2549 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2550 AllowAS: TheCall->getBuiltinCallee() ==
2551 Builtin::BI__builtin_masked_load))
2552 return ExprError();
2553
2554 QualType MaskTy = MaskArg->getType();
2555 QualType PtrTy = PtrArg->getType();
2556 QualType PointeeTy = PtrTy->getPointeeType();
2557 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2558
2559 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2560 NumElts: MaskVecTy->getNumElements());
2561 if (TheCall->getNumArgs() == 3) {
2562 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2563 QualType PassThruTy = PassThruArg->getType();
2564 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2565 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2566 << /* third argument */ 3 << RetTy;
2567 }
2568
2569 TheCall->setType(RetTy);
2570 return TheCall;
2571}
2572
2573static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2574 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2575 return ExprError();
2576
2577 if (ConvertMaskedBuiltinArgs(S, TheCall))
2578 return ExprError();
2579
2580 Expr *MaskArg = TheCall->getArg(Arg: 0);
2581 Expr *ValArg = TheCall->getArg(Arg: 1);
2582 Expr *PtrArg = TheCall->getArg(Arg: 2);
2583 if (TheCall->isTypeDependent())
2584 return TheCall;
2585
2586 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2587 AllowAS: TheCall->getBuiltinCallee() ==
2588 Builtin::BI__builtin_masked_store))
2589 return ExprError();
2590
2591 QualType MaskTy = MaskArg->getType();
2592 QualType PtrTy = PtrArg->getType();
2593 QualType ValTy = ValArg->getType();
2594 if (!ValTy->isVectorType())
2595 return ExprError(
2596 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2597 << 2 << "vector");
2598
2599 QualType PointeeTy = PtrTy->getPointeeType();
2600 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2601 QualType MemoryTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2602 NumElts: MaskVecTy->getNumElements());
2603 if (!S.Context.hasSameType(T1: ValTy.getUnqualifiedType(),
2604 T2: MemoryTy.getUnqualifiedType()))
2605 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2606 DiagID: diag::err_vec_builtin_incompatible_vector)
2607 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2608 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2609 TheCall->getArg(Arg: 1)->getEndLoc()));
2610
2611 TheCall->setType(S.Context.VoidTy);
2612 return TheCall;
2613}
2614
2615static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2616 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2617 return ExprError();
2618
2619 if (ConvertMaskedBuiltinArgs(S, TheCall))
2620 return ExprError();
2621
2622 Expr *MaskArg = TheCall->getArg(Arg: 0);
2623 Expr *IdxArg = TheCall->getArg(Arg: 1);
2624 Expr *PtrArg = TheCall->getArg(Arg: 2);
2625 if (TheCall->isTypeDependent())
2626 return TheCall;
2627
2628 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2629 /*AllowAS=*/true))
2630 return ExprError();
2631
2632 QualType IdxTy = IdxArg->getType();
2633 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2634 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2635 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2636 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2637 << IdxTy;
2638
2639 QualType MaskTy = MaskArg->getType();
2640 QualType PtrTy = PtrArg->getType();
2641 QualType PointeeTy = PtrTy->getPointeeType();
2642 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2643 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2644 return ExprError(
2645 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2646 << S.getASTContext().BuiltinInfo.getQuotedName(
2647 ID: TheCall->getBuiltinCallee())
2648 << MaskTy << IdxTy);
2649
2650 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2651 NumElts: MaskVecTy->getNumElements());
2652 if (TheCall->getNumArgs() == 4) {
2653 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2654 QualType PassThruTy = PassThruArg->getType();
2655 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2656 return S.Diag(Loc: PassThruArg->getExprLoc(),
2657 DiagID: diag::err_vec_masked_load_store_ptr)
2658 << /* fourth argument */ 4 << RetTy;
2659 }
2660
2661 TheCall->setType(RetTy);
2662 return TheCall;
2663}
2664
2665static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2666 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2667 return ExprError();
2668
2669 if (ConvertMaskedBuiltinArgs(S, TheCall))
2670 return ExprError();
2671
2672 Expr *MaskArg = TheCall->getArg(Arg: 0);
2673 Expr *IdxArg = TheCall->getArg(Arg: 1);
2674 Expr *ValArg = TheCall->getArg(Arg: 2);
2675 Expr *PtrArg = TheCall->getArg(Arg: 3);
2676 if (TheCall->isTypeDependent())
2677 return TheCall;
2678
2679 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2680 /*AllowAS=*/true))
2681 return ExprError();
2682
2683 QualType IdxTy = IdxArg->getType();
2684 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2685 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2686 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2687 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2688 << IdxTy;
2689
2690 QualType ValTy = ValArg->getType();
2691 QualType MaskTy = MaskArg->getType();
2692 QualType PtrTy = PtrArg->getType();
2693 QualType PointeeTy = PtrTy->getPointeeType();
2694
2695 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2696 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2697 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2698 return ExprError(
2699 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2700 << S.getASTContext().BuiltinInfo.getQuotedName(
2701 ID: TheCall->getBuiltinCallee())
2702 << MaskTy << IdxTy);
2703 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2704 return ExprError(
2705 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2706 << S.getASTContext().BuiltinInfo.getQuotedName(
2707 ID: TheCall->getBuiltinCallee())
2708 << MaskTy << ValTy);
2709
2710 QualType ArgTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2711 NumElts: MaskVecTy->getNumElements());
2712 if (!S.Context.hasSameType(T1: ValTy.getUnqualifiedType(), T2: ArgTy))
2713 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2714 DiagID: diag::err_vec_builtin_incompatible_vector)
2715 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2716 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2717 TheCall->getArg(Arg: 1)->getEndLoc()));
2718
2719 TheCall->setType(S.Context.VoidTy);
2720 return TheCall;
2721}
2722
2723static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
2724 SourceLocation Loc = TheCall->getBeginLoc();
2725 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2726 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2727
2728 if (Args.size() == 0) {
2729 S.Diag(Loc: TheCall->getBeginLoc(),
2730 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2731 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2732 << /*is_non_object=*/0 << TheCall->getSourceRange();
2733 return ExprError();
2734 }
2735
2736 QualType FuncT = Args[0]->getType();
2737
2738 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2739 if (Args.size() < 2) {
2740 S.Diag(Loc: TheCall->getBeginLoc(),
2741 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2742 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2743 << /*is_non_object=*/0 << TheCall->getSourceRange();
2744 return ExprError();
2745 }
2746
2747 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2748 QualType ObjectT = Args[1]->getType();
2749
2750 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2751 return ExprError();
2752
2753 ExprResult ObjectArg = [&]() -> ExprResult {
2754 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2755 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2756 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2757 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2758 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2759 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2760 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
2761 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
2762 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
2763 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
2764 return Args[1];
2765 }
2766
2767 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2768 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2769 // reference_wrapper;
2770 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2771 if (RD->isInStdNamespace() &&
2772 RD->getDeclName().getAsString() == "reference_wrapper") {
2773 CXXScopeSpec SS;
2774 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
2775 UnqualifiedId GetID;
2776 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
2777
2778 ExprResult MemExpr = S.ActOnMemberAccessExpr(
2779 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
2780 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
2781
2782 if (MemExpr.isInvalid())
2783 return ExprError();
2784
2785 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
2786 }
2787 }
2788
2789 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2790 // class T and t1 does not satisfy the previous two items;
2791
2792 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
2793 }();
2794
2795 if (ObjectArg.isInvalid())
2796 return ExprError();
2797
2798 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
2799 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
2800 if (BinOp.isInvalid())
2801 return ExprError();
2802
2803 if (MPT->isMemberDataPointer())
2804 return BinOp;
2805
2806 auto *MemCall = new (S.Context)
2807 ParenExpr(SourceLocation(), SourceLocation(), BinOp.get());
2808
2809 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
2810 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
2811 }
2812 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
2813 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
2814}
2815
2816// Performs a similar job to Sema::UsualUnaryConversions, but without any
2817// implicit promotion of integral/enumeration types.
2818static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
2819 // First, convert to an r-value.
2820 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
2821 if (Res.isInvalid())
2822 return ExprError();
2823
2824 // Promote floating-point types.
2825 return S.UsualUnaryFPConversions(E: Res.get());
2826}
2827
2828static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
2829 if (const auto *TyA = VecTy->getAs<VectorType>())
2830 return TyA->getElementType();
2831 if (VecTy->isSizelessVectorType())
2832 return VecTy->getSizelessVectorEltType(Ctx: Context);
2833 return QualType();
2834}
2835
2836ExprResult
2837Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2838 CallExpr *TheCall) {
2839 ExprResult TheCallResult(TheCall);
2840
2841 // Find out if any arguments are required to be integer constant expressions.
2842 unsigned ICEArguments = 0;
2843 ASTContext::GetBuiltinTypeError Error;
2844 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
2845 if (Error != ASTContext::GE_None)
2846 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2847
2848 // If any arguments are required to be ICE's, check and diagnose.
2849 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2850 // Skip arguments not required to be ICE's.
2851 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2852
2853 llvm::APSInt Result;
2854 // If we don't have enough arguments, continue so we can issue better
2855 // diagnostic in checkArgCount(...)
2856 if (ArgNo < TheCall->getNumArgs() &&
2857 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
2858 return true;
2859 ICEArguments &= ~(1 << ArgNo);
2860 }
2861
2862 FPOptions FPO;
2863 switch (BuiltinID) {
2864 case Builtin::BI__builtin_cpu_supports:
2865 case Builtin::BI__builtin_cpu_is:
2866 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
2867 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
2868 return ExprError();
2869 break;
2870 case Builtin::BI__builtin_cpu_init:
2871 if (!Context.getTargetInfo().supportsCpuInit()) {
2872 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2873 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2874 return ExprError();
2875 }
2876 break;
2877 case Builtin::BI__builtin___CFStringMakeConstantString:
2878 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2879 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2880 if (CheckBuiltinTargetNotInUnsupported(
2881 S&: *this, BuiltinID, TheCall,
2882 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2883 return ExprError();
2884 assert(TheCall->getNumArgs() == 1 &&
2885 "Wrong # arguments to builtin CFStringMakeConstantString");
2886 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
2887 return ExprError();
2888 break;
2889 case Builtin::BI__builtin_ms_va_start:
2890 case Builtin::BI__builtin_stdarg_start:
2891 case Builtin::BI__builtin_va_start:
2892 case Builtin::BI__builtin_c23_va_start:
2893 if (BuiltinVAStart(BuiltinID, TheCall))
2894 return ExprError();
2895 break;
2896 case Builtin::BI__va_start: {
2897 switch (Context.getTargetInfo().getTriple().getArch()) {
2898 case llvm::Triple::aarch64:
2899 case llvm::Triple::arm:
2900 case llvm::Triple::thumb:
2901 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
2902 return ExprError();
2903 break;
2904 default:
2905 if (BuiltinVAStart(BuiltinID, TheCall))
2906 return ExprError();
2907 break;
2908 }
2909 break;
2910 }
2911
2912 // The acquire, release, and no fence variants are ARM and AArch64 only.
2913 case Builtin::BI_interlockedbittestandset_acq:
2914 case Builtin::BI_interlockedbittestandset_rel:
2915 case Builtin::BI_interlockedbittestandset_nf:
2916 case Builtin::BI_interlockedbittestandreset_acq:
2917 case Builtin::BI_interlockedbittestandreset_rel:
2918 case Builtin::BI_interlockedbittestandreset_nf:
2919 if (CheckBuiltinTargetInSupported(
2920 S&: *this, TheCall,
2921 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2922 return ExprError();
2923 break;
2924
2925 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2926 case Builtin::BI_bittest64:
2927 case Builtin::BI_bittestandcomplement64:
2928 case Builtin::BI_bittestandreset64:
2929 case Builtin::BI_bittestandset64:
2930 case Builtin::BI_interlockedbittestandreset64:
2931 case Builtin::BI_interlockedbittestandset64:
2932 if (CheckBuiltinTargetInSupported(
2933 S&: *this, TheCall,
2934 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2935 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2936 return ExprError();
2937 break;
2938
2939 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2940 case Builtin::BI_interlockedbittestandreset64_acq:
2941 case Builtin::BI_interlockedbittestandreset64_rel:
2942 case Builtin::BI_interlockedbittestandreset64_nf:
2943 case Builtin::BI_interlockedbittestandset64_acq:
2944 case Builtin::BI_interlockedbittestandset64_rel:
2945 case Builtin::BI_interlockedbittestandset64_nf:
2946 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
2947 return ExprError();
2948 break;
2949
2950 case Builtin::BI__builtin_set_flt_rounds:
2951 if (CheckBuiltinTargetInSupported(
2952 S&: *this, TheCall,
2953 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2954 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2955 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2956 llvm::Triple::ppc64le}))
2957 return ExprError();
2958 break;
2959
2960 case Builtin::BI__builtin_isgreater:
2961 case Builtin::BI__builtin_isgreaterequal:
2962 case Builtin::BI__builtin_isless:
2963 case Builtin::BI__builtin_islessequal:
2964 case Builtin::BI__builtin_islessgreater:
2965 case Builtin::BI__builtin_isunordered:
2966 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2967 return ExprError();
2968 break;
2969 case Builtin::BI__builtin_fpclassify:
2970 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
2971 return ExprError();
2972 break;
2973 case Builtin::BI__builtin_isfpclass:
2974 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
2975 return ExprError();
2976 break;
2977 case Builtin::BI__builtin_isfinite:
2978 case Builtin::BI__builtin_isinf:
2979 case Builtin::BI__builtin_isinf_sign:
2980 case Builtin::BI__builtin_isnan:
2981 case Builtin::BI__builtin_issignaling:
2982 case Builtin::BI__builtin_isnormal:
2983 case Builtin::BI__builtin_issubnormal:
2984 case Builtin::BI__builtin_iszero:
2985 case Builtin::BI__builtin_signbit:
2986 case Builtin::BI__builtin_signbitf:
2987 case Builtin::BI__builtin_signbitl:
2988 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
2989 return ExprError();
2990 break;
2991 case Builtin::BI__builtin_shufflevector:
2992 return BuiltinShuffleVector(TheCall);
2993 // TheCall will be freed by the smart pointer here, but that's fine, since
2994 // BuiltinShuffleVector guts it, but then doesn't release it.
2995 case Builtin::BI__builtin_masked_load:
2996 case Builtin::BI__builtin_masked_expand_load:
2997 return BuiltinMaskedLoad(S&: *this, TheCall);
2998 case Builtin::BI__builtin_masked_store:
2999 case Builtin::BI__builtin_masked_compress_store:
3000 return BuiltinMaskedStore(S&: *this, TheCall);
3001 case Builtin::BI__builtin_masked_gather:
3002 return BuiltinMaskedGather(S&: *this, TheCall);
3003 case Builtin::BI__builtin_masked_scatter:
3004 return BuiltinMaskedScatter(S&: *this, TheCall);
3005 case Builtin::BI__builtin_invoke:
3006 return BuiltinInvoke(S&: *this, TheCall);
3007 case Builtin::BI__builtin_prefetch:
3008 if (BuiltinPrefetch(TheCall))
3009 return ExprError();
3010 break;
3011 case Builtin::BI__builtin_alloca_with_align:
3012 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3013 if (BuiltinAllocaWithAlign(TheCall))
3014 return ExprError();
3015 [[fallthrough]];
3016 case Builtin::BI__builtin_alloca:
3017 case Builtin::BI__builtin_alloca_uninitialized:
3018 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3019 << TheCall->getDirectCallee();
3020 if (getLangOpts().OpenCL) {
3021 builtinAllocaAddrSpace(S&: *this, TheCall);
3022 }
3023 break;
3024 case Builtin::BI__builtin_infer_alloc_token:
3025 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3026 return ExprError();
3027 break;
3028 case Builtin::BI__arithmetic_fence:
3029 if (BuiltinArithmeticFence(TheCall))
3030 return ExprError();
3031 break;
3032 case Builtin::BI__assume:
3033 case Builtin::BI__builtin_assume:
3034 if (BuiltinAssume(TheCall))
3035 return ExprError();
3036 break;
3037 case Builtin::BI__builtin_assume_aligned:
3038 if (BuiltinAssumeAligned(TheCall))
3039 return ExprError();
3040 break;
3041 case Builtin::BI__builtin_dynamic_object_size:
3042 case Builtin::BI__builtin_object_size:
3043 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3044 return ExprError();
3045 break;
3046 case Builtin::BI__builtin_longjmp:
3047 if (BuiltinLongjmp(TheCall))
3048 return ExprError();
3049 break;
3050 case Builtin::BI__builtin_setjmp:
3051 if (BuiltinSetjmp(TheCall))
3052 return ExprError();
3053 break;
3054 case Builtin::BI__builtin_complex:
3055 if (BuiltinComplex(TheCall))
3056 return ExprError();
3057 break;
3058 case Builtin::BI__builtin_classify_type:
3059 case Builtin::BI__builtin_constant_p: {
3060 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3061 return true;
3062 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3063 if (Arg.isInvalid()) return true;
3064 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3065 TheCall->setType(Context.IntTy);
3066 break;
3067 }
3068 case Builtin::BI__builtin_launder:
3069 return BuiltinLaunder(S&: *this, TheCall);
3070 case Builtin::BI__builtin_is_within_lifetime:
3071 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3072 case Builtin::BI__builtin_trivially_relocate:
3073 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3074
3075 case Builtin::BI__sync_fetch_and_add:
3076 case Builtin::BI__sync_fetch_and_add_1:
3077 case Builtin::BI__sync_fetch_and_add_2:
3078 case Builtin::BI__sync_fetch_and_add_4:
3079 case Builtin::BI__sync_fetch_and_add_8:
3080 case Builtin::BI__sync_fetch_and_add_16:
3081 case Builtin::BI__sync_fetch_and_sub:
3082 case Builtin::BI__sync_fetch_and_sub_1:
3083 case Builtin::BI__sync_fetch_and_sub_2:
3084 case Builtin::BI__sync_fetch_and_sub_4:
3085 case Builtin::BI__sync_fetch_and_sub_8:
3086 case Builtin::BI__sync_fetch_and_sub_16:
3087 case Builtin::BI__sync_fetch_and_or:
3088 case Builtin::BI__sync_fetch_and_or_1:
3089 case Builtin::BI__sync_fetch_and_or_2:
3090 case Builtin::BI__sync_fetch_and_or_4:
3091 case Builtin::BI__sync_fetch_and_or_8:
3092 case Builtin::BI__sync_fetch_and_or_16:
3093 case Builtin::BI__sync_fetch_and_and:
3094 case Builtin::BI__sync_fetch_and_and_1:
3095 case Builtin::BI__sync_fetch_and_and_2:
3096 case Builtin::BI__sync_fetch_and_and_4:
3097 case Builtin::BI__sync_fetch_and_and_8:
3098 case Builtin::BI__sync_fetch_and_and_16:
3099 case Builtin::BI__sync_fetch_and_xor:
3100 case Builtin::BI__sync_fetch_and_xor_1:
3101 case Builtin::BI__sync_fetch_and_xor_2:
3102 case Builtin::BI__sync_fetch_and_xor_4:
3103 case Builtin::BI__sync_fetch_and_xor_8:
3104 case Builtin::BI__sync_fetch_and_xor_16:
3105 case Builtin::BI__sync_fetch_and_nand:
3106 case Builtin::BI__sync_fetch_and_nand_1:
3107 case Builtin::BI__sync_fetch_and_nand_2:
3108 case Builtin::BI__sync_fetch_and_nand_4:
3109 case Builtin::BI__sync_fetch_and_nand_8:
3110 case Builtin::BI__sync_fetch_and_nand_16:
3111 case Builtin::BI__sync_add_and_fetch:
3112 case Builtin::BI__sync_add_and_fetch_1:
3113 case Builtin::BI__sync_add_and_fetch_2:
3114 case Builtin::BI__sync_add_and_fetch_4:
3115 case Builtin::BI__sync_add_and_fetch_8:
3116 case Builtin::BI__sync_add_and_fetch_16:
3117 case Builtin::BI__sync_sub_and_fetch:
3118 case Builtin::BI__sync_sub_and_fetch_1:
3119 case Builtin::BI__sync_sub_and_fetch_2:
3120 case Builtin::BI__sync_sub_and_fetch_4:
3121 case Builtin::BI__sync_sub_and_fetch_8:
3122 case Builtin::BI__sync_sub_and_fetch_16:
3123 case Builtin::BI__sync_and_and_fetch:
3124 case Builtin::BI__sync_and_and_fetch_1:
3125 case Builtin::BI__sync_and_and_fetch_2:
3126 case Builtin::BI__sync_and_and_fetch_4:
3127 case Builtin::BI__sync_and_and_fetch_8:
3128 case Builtin::BI__sync_and_and_fetch_16:
3129 case Builtin::BI__sync_or_and_fetch:
3130 case Builtin::BI__sync_or_and_fetch_1:
3131 case Builtin::BI__sync_or_and_fetch_2:
3132 case Builtin::BI__sync_or_and_fetch_4:
3133 case Builtin::BI__sync_or_and_fetch_8:
3134 case Builtin::BI__sync_or_and_fetch_16:
3135 case Builtin::BI__sync_xor_and_fetch:
3136 case Builtin::BI__sync_xor_and_fetch_1:
3137 case Builtin::BI__sync_xor_and_fetch_2:
3138 case Builtin::BI__sync_xor_and_fetch_4:
3139 case Builtin::BI__sync_xor_and_fetch_8:
3140 case Builtin::BI__sync_xor_and_fetch_16:
3141 case Builtin::BI__sync_nand_and_fetch:
3142 case Builtin::BI__sync_nand_and_fetch_1:
3143 case Builtin::BI__sync_nand_and_fetch_2:
3144 case Builtin::BI__sync_nand_and_fetch_4:
3145 case Builtin::BI__sync_nand_and_fetch_8:
3146 case Builtin::BI__sync_nand_and_fetch_16:
3147 case Builtin::BI__sync_val_compare_and_swap:
3148 case Builtin::BI__sync_val_compare_and_swap_1:
3149 case Builtin::BI__sync_val_compare_and_swap_2:
3150 case Builtin::BI__sync_val_compare_and_swap_4:
3151 case Builtin::BI__sync_val_compare_and_swap_8:
3152 case Builtin::BI__sync_val_compare_and_swap_16:
3153 case Builtin::BI__sync_bool_compare_and_swap:
3154 case Builtin::BI__sync_bool_compare_and_swap_1:
3155 case Builtin::BI__sync_bool_compare_and_swap_2:
3156 case Builtin::BI__sync_bool_compare_and_swap_4:
3157 case Builtin::BI__sync_bool_compare_and_swap_8:
3158 case Builtin::BI__sync_bool_compare_and_swap_16:
3159 case Builtin::BI__sync_lock_test_and_set:
3160 case Builtin::BI__sync_lock_test_and_set_1:
3161 case Builtin::BI__sync_lock_test_and_set_2:
3162 case Builtin::BI__sync_lock_test_and_set_4:
3163 case Builtin::BI__sync_lock_test_and_set_8:
3164 case Builtin::BI__sync_lock_test_and_set_16:
3165 case Builtin::BI__sync_lock_release:
3166 case Builtin::BI__sync_lock_release_1:
3167 case Builtin::BI__sync_lock_release_2:
3168 case Builtin::BI__sync_lock_release_4:
3169 case Builtin::BI__sync_lock_release_8:
3170 case Builtin::BI__sync_lock_release_16:
3171 case Builtin::BI__sync_swap:
3172 case Builtin::BI__sync_swap_1:
3173 case Builtin::BI__sync_swap_2:
3174 case Builtin::BI__sync_swap_4:
3175 case Builtin::BI__sync_swap_8:
3176 case Builtin::BI__sync_swap_16:
3177 return BuiltinAtomicOverloaded(TheCallResult);
3178 case Builtin::BI__sync_synchronize:
3179 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3180 << TheCall->getCallee()->getSourceRange();
3181 break;
3182 case Builtin::BI__builtin_nontemporal_load:
3183 case Builtin::BI__builtin_nontemporal_store:
3184 return BuiltinNontemporalOverloaded(TheCallResult);
3185 case Builtin::BI__builtin_memcpy_inline: {
3186 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3187 // We warn about copying to or from `nullptr` pointers when `size` is
3188 // greater than 0. When `size` is value dependent we cannot evaluate its
3189 // value so we bail out.
3190 if (SizeOp->isValueDependent())
3191 break;
3192 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3193 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3194 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3195 }
3196 break;
3197 }
3198 case Builtin::BI__builtin_memset_inline: {
3199 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3200 // We warn about filling to `nullptr` pointers when `size` is greater than
3201 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3202 // out.
3203 if (SizeOp->isValueDependent())
3204 break;
3205 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3206 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3207 break;
3208 }
3209#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3210 case Builtin::BI##ID: \
3211 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3212#include "clang/Basic/Builtins.inc"
3213 case Builtin::BI__annotation:
3214 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3215 return ExprError();
3216 break;
3217 case Builtin::BI__builtin_annotation:
3218 if (BuiltinAnnotation(S&: *this, TheCall))
3219 return ExprError();
3220 break;
3221 case Builtin::BI__builtin_addressof:
3222 if (BuiltinAddressof(S&: *this, TheCall))
3223 return ExprError();
3224 break;
3225 case Builtin::BI__builtin_function_start:
3226 if (BuiltinFunctionStart(S&: *this, TheCall))
3227 return ExprError();
3228 break;
3229 case Builtin::BI__builtin_is_aligned:
3230 case Builtin::BI__builtin_align_up:
3231 case Builtin::BI__builtin_align_down:
3232 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3233 return ExprError();
3234 break;
3235 case Builtin::BI__builtin_add_overflow:
3236 case Builtin::BI__builtin_sub_overflow:
3237 case Builtin::BI__builtin_mul_overflow:
3238 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3239 return ExprError();
3240 break;
3241 case Builtin::BI__builtin_operator_new:
3242 case Builtin::BI__builtin_operator_delete: {
3243 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3244 ExprResult Res =
3245 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3246 return Res;
3247 }
3248 case Builtin::BI__builtin_dump_struct:
3249 return BuiltinDumpStruct(S&: *this, TheCall);
3250 case Builtin::BI__builtin_expect_with_probability: {
3251 // We first want to ensure we are called with 3 arguments
3252 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3253 return ExprError();
3254 // then check probability is constant float in range [0.0, 1.0]
3255 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3256 SmallVector<PartialDiagnosticAt, 8> Notes;
3257 Expr::EvalResult Eval;
3258 Eval.Diag = &Notes;
3259 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3260 !Eval.Val.isFloat()) {
3261 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3262 << ProbArg->getSourceRange();
3263 for (const PartialDiagnosticAt &PDiag : Notes)
3264 Diag(Loc: PDiag.first, PD: PDiag.second);
3265 return ExprError();
3266 }
3267 llvm::APFloat Probability = Eval.Val.getFloat();
3268 bool LoseInfo = false;
3269 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3270 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3271 if (!(Probability >= llvm::APFloat(0.0) &&
3272 Probability <= llvm::APFloat(1.0))) {
3273 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3274 << ProbArg->getSourceRange();
3275 return ExprError();
3276 }
3277 break;
3278 }
3279 case Builtin::BI__builtin_preserve_access_index:
3280 if (BuiltinPreserveAI(S&: *this, TheCall))
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_call_with_static_chain:
3284 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3285 return ExprError();
3286 break;
3287 case Builtin::BI__exception_code:
3288 case Builtin::BI_exception_code:
3289 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3290 DiagID: diag::err_seh___except_block))
3291 return ExprError();
3292 break;
3293 case Builtin::BI__exception_info:
3294 case Builtin::BI_exception_info:
3295 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3296 DiagID: diag::err_seh___except_filter))
3297 return ExprError();
3298 break;
3299 case Builtin::BI__GetExceptionInfo:
3300 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3301 return ExprError();
3302
3303 if (CheckCXXThrowOperand(
3304 ThrowLoc: TheCall->getBeginLoc(),
3305 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3306 E: TheCall))
3307 return ExprError();
3308
3309 TheCall->setType(Context.VoidPtrTy);
3310 break;
3311 case Builtin::BIaddressof:
3312 case Builtin::BI__addressof:
3313 case Builtin::BIforward:
3314 case Builtin::BIforward_like:
3315 case Builtin::BImove:
3316 case Builtin::BImove_if_noexcept:
3317 case Builtin::BIas_const: {
3318 // These are all expected to be of the form
3319 // T &/&&/* f(U &/&&)
3320 // where T and U only differ in qualification.
3321 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3322 return ExprError();
3323 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3324 QualType Result = FDecl->getReturnType();
3325 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3326 BuiltinID == Builtin::BI__addressof;
3327 if (!(Param->isReferenceType() &&
3328 (ReturnsPointer ? Result->isAnyPointerType()
3329 : Result->isReferenceType()) &&
3330 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3331 T2: Result->getPointeeType()))) {
3332 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3333 << FDecl;
3334 return ExprError();
3335 }
3336 break;
3337 }
3338 case Builtin::BI__builtin_ptrauth_strip:
3339 return PointerAuthStrip(S&: *this, Call: TheCall);
3340 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3341 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3342 case Builtin::BI__builtin_ptrauth_sign_constant:
3343 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3344 /*RequireConstant=*/true);
3345 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3346 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3347 /*RequireConstant=*/false);
3348 case Builtin::BI__builtin_ptrauth_auth:
3349 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3350 /*RequireConstant=*/false);
3351 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3352 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3353 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3354 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3355 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3356 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3357 case Builtin::BI__builtin_ptrauth_string_discriminator:
3358 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3359
3360 case Builtin::BI__builtin_get_vtable_pointer:
3361 return GetVTablePointer(S&: *this, Call: TheCall);
3362
3363 // OpenCL v2.0, s6.13.16 - Pipe functions
3364 case Builtin::BIread_pipe:
3365 case Builtin::BIwrite_pipe:
3366 // Since those two functions are declared with var args, we need a semantic
3367 // check for the argument.
3368 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BIreserve_read_pipe:
3372 case Builtin::BIreserve_write_pipe:
3373 case Builtin::BIwork_group_reserve_read_pipe:
3374 case Builtin::BIwork_group_reserve_write_pipe:
3375 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3376 return ExprError();
3377 break;
3378 case Builtin::BIsub_group_reserve_read_pipe:
3379 case Builtin::BIsub_group_reserve_write_pipe:
3380 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3381 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3382 return ExprError();
3383 break;
3384 case Builtin::BIcommit_read_pipe:
3385 case Builtin::BIcommit_write_pipe:
3386 case Builtin::BIwork_group_commit_read_pipe:
3387 case Builtin::BIwork_group_commit_write_pipe:
3388 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3389 return ExprError();
3390 break;
3391 case Builtin::BIsub_group_commit_read_pipe:
3392 case Builtin::BIsub_group_commit_write_pipe:
3393 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3394 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3395 return ExprError();
3396 break;
3397 case Builtin::BIget_pipe_num_packets:
3398 case Builtin::BIget_pipe_max_packets:
3399 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3400 return ExprError();
3401 break;
3402 case Builtin::BIto_global:
3403 case Builtin::BIto_local:
3404 case Builtin::BIto_private:
3405 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3406 return ExprError();
3407 break;
3408 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3409 case Builtin::BIenqueue_kernel:
3410 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3411 return ExprError();
3412 break;
3413 case Builtin::BIget_kernel_work_group_size:
3414 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3415 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3416 return ExprError();
3417 break;
3418 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3419 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3420 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3421 return ExprError();
3422 break;
3423 case Builtin::BI__builtin_os_log_format:
3424 Cleanup.setExprNeedsCleanups(true);
3425 [[fallthrough]];
3426 case Builtin::BI__builtin_os_log_format_buffer_size:
3427 if (BuiltinOSLogFormat(TheCall))
3428 return ExprError();
3429 break;
3430 case Builtin::BI__builtin_frame_address:
3431 case Builtin::BI__builtin_return_address: {
3432 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3433 return ExprError();
3434
3435 // -Wframe-address warning if non-zero passed to builtin
3436 // return/frame address.
3437 Expr::EvalResult Result;
3438 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3439 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3440 Result.Val.getInt() != 0)
3441 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3442 << ((BuiltinID == Builtin::BI__builtin_return_address)
3443 ? "__builtin_return_address"
3444 : "__builtin_frame_address")
3445 << TheCall->getSourceRange();
3446 break;
3447 }
3448
3449 case Builtin::BI__builtin_nondeterministic_value: {
3450 if (BuiltinNonDeterministicValue(TheCall))
3451 return ExprError();
3452 break;
3453 }
3454
3455 // __builtin_elementwise_abs restricts the element type to signed integers or
3456 // floating point types only.
3457 case Builtin::BI__builtin_elementwise_abs:
3458 if (PrepareBuiltinElementwiseMathOneArgCall(
3459 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3460 return ExprError();
3461 break;
3462
3463 // These builtins restrict the element type to floating point
3464 // types only.
3465 case Builtin::BI__builtin_elementwise_acos:
3466 case Builtin::BI__builtin_elementwise_asin:
3467 case Builtin::BI__builtin_elementwise_atan:
3468 case Builtin::BI__builtin_elementwise_ceil:
3469 case Builtin::BI__builtin_elementwise_cos:
3470 case Builtin::BI__builtin_elementwise_cosh:
3471 case Builtin::BI__builtin_elementwise_exp:
3472 case Builtin::BI__builtin_elementwise_exp2:
3473 case Builtin::BI__builtin_elementwise_exp10:
3474 case Builtin::BI__builtin_elementwise_floor:
3475 case Builtin::BI__builtin_elementwise_log:
3476 case Builtin::BI__builtin_elementwise_log2:
3477 case Builtin::BI__builtin_elementwise_log10:
3478 case Builtin::BI__builtin_elementwise_roundeven:
3479 case Builtin::BI__builtin_elementwise_round:
3480 case Builtin::BI__builtin_elementwise_rint:
3481 case Builtin::BI__builtin_elementwise_nearbyint:
3482 case Builtin::BI__builtin_elementwise_sin:
3483 case Builtin::BI__builtin_elementwise_sinh:
3484 case Builtin::BI__builtin_elementwise_sqrt:
3485 case Builtin::BI__builtin_elementwise_tan:
3486 case Builtin::BI__builtin_elementwise_tanh:
3487 case Builtin::BI__builtin_elementwise_trunc:
3488 case Builtin::BI__builtin_elementwise_canonicalize:
3489 if (PrepareBuiltinElementwiseMathOneArgCall(
3490 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3491 return ExprError();
3492 break;
3493 case Builtin::BI__builtin_elementwise_fma:
3494 if (BuiltinElementwiseTernaryMath(TheCall))
3495 return ExprError();
3496 break;
3497
3498 case Builtin::BI__builtin_elementwise_ldexp: {
3499 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3500 return ExprError();
3501
3502 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3503 if (A.isInvalid())
3504 return ExprError();
3505 QualType TyA = A.get()->getType();
3506 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3507 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3508 return ExprError();
3509
3510 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3511 if (Exp.isInvalid())
3512 return ExprError();
3513 QualType TyExp = Exp.get()->getType();
3514 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3515 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3516 ArgOrdinal: 2))
3517 return ExprError();
3518
3519 // Check the two arguments are either scalars or vectors of equal length.
3520 const auto *Vec0 = TyA->getAs<VectorType>();
3521 const auto *Vec1 = TyExp->getAs<VectorType>();
3522 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3523 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3524 if (Arg0Length != Arg1Length) {
3525 Diag(Loc: Exp.get()->getBeginLoc(),
3526 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3527 << TyA << TyExp << A.get()->getSourceRange()
3528 << Exp.get()->getSourceRange();
3529 return ExprError();
3530 }
3531
3532 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3533 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3534 TheCall->setType(TyA);
3535 break;
3536 }
3537
3538 // These builtins restrict the element type to floating point
3539 // types only, and take in two arguments.
3540 case Builtin::BI__builtin_elementwise_minnum:
3541 case Builtin::BI__builtin_elementwise_maxnum:
3542 case Builtin::BI__builtin_elementwise_minimum:
3543 case Builtin::BI__builtin_elementwise_maximum:
3544 case Builtin::BI__builtin_elementwise_minimumnum:
3545 case Builtin::BI__builtin_elementwise_maximumnum:
3546 case Builtin::BI__builtin_elementwise_atan2:
3547 case Builtin::BI__builtin_elementwise_fmod:
3548 case Builtin::BI__builtin_elementwise_pow:
3549 if (BuiltinElementwiseMath(TheCall,
3550 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3551 return ExprError();
3552 break;
3553 // These builtins restrict the element type to integer
3554 // types only.
3555 case Builtin::BI__builtin_elementwise_add_sat:
3556 case Builtin::BI__builtin_elementwise_sub_sat:
3557 if (BuiltinElementwiseMath(TheCall,
3558 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3559 return ExprError();
3560 break;
3561 case Builtin::BI__builtin_elementwise_fshl:
3562 case Builtin::BI__builtin_elementwise_fshr:
3563 if (BuiltinElementwiseTernaryMath(
3564 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3565 return ExprError();
3566 break;
3567 case Builtin::BI__builtin_elementwise_min:
3568 case Builtin::BI__builtin_elementwise_max: {
3569 if (BuiltinElementwiseMath(TheCall))
3570 return ExprError();
3571 Expr *Arg0 = TheCall->getArg(Arg: 0);
3572 Expr *Arg1 = TheCall->getArg(Arg: 1);
3573 QualType Ty0 = Arg0->getType();
3574 QualType Ty1 = Arg1->getType();
3575 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3576 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3577 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3578 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3579 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3580 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
3581 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
3582 break;
3583 }
3584 case Builtin::BI__builtin_elementwise_popcount:
3585 case Builtin::BI__builtin_elementwise_bitreverse:
3586 if (PrepareBuiltinElementwiseMathOneArgCall(
3587 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3588 return ExprError();
3589 break;
3590 case Builtin::BI__builtin_elementwise_copysign: {
3591 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3592 return ExprError();
3593
3594 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3595 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3596 if (Magnitude.isInvalid() || Sign.isInvalid())
3597 return ExprError();
3598
3599 QualType MagnitudeTy = Magnitude.get()->getType();
3600 QualType SignTy = Sign.get()->getType();
3601 if (checkMathBuiltinElementType(
3602 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3603 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3604 checkMathBuiltinElementType(
3605 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3606 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3607 return ExprError();
3608 }
3609
3610 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3611 return Diag(Loc: Sign.get()->getBeginLoc(),
3612 DiagID: diag::err_typecheck_call_different_arg_types)
3613 << MagnitudeTy << SignTy;
3614 }
3615
3616 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3617 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3618 TheCall->setType(Magnitude.get()->getType());
3619 break;
3620 }
3621 case Builtin::BI__builtin_elementwise_clzg:
3622 case Builtin::BI__builtin_elementwise_ctzg:
3623 // These builtins can be unary or binary. Note for empty calls we call the
3624 // unary checker in order to not emit an error that says the function
3625 // expects 2 arguments, which would be misleading.
3626 if (TheCall->getNumArgs() <= 1) {
3627 if (PrepareBuiltinElementwiseMathOneArgCall(
3628 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3629 return ExprError();
3630 } else if (BuiltinElementwiseMath(
3631 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3632 return ExprError();
3633 break;
3634 case Builtin::BI__builtin_reduce_max:
3635 case Builtin::BI__builtin_reduce_min: {
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()) {
3649 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3650 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3651 << Arg->getType();
3652 return ExprError();
3653 }
3654
3655 TheCall->setType(ElTy);
3656 break;
3657 }
3658 case Builtin::BI__builtin_reduce_maximum:
3659 case Builtin::BI__builtin_reduce_minimum: {
3660 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3661 return ExprError();
3662
3663 const Expr *Arg = TheCall->getArg(Arg: 0);
3664 const auto *TyA = Arg->getType()->getAs<VectorType>();
3665
3666 QualType ElTy;
3667 if (TyA)
3668 ElTy = TyA->getElementType();
3669 else if (Arg->getType()->isSizelessVectorType())
3670 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3671
3672 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3673 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3674 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3675 << Arg->getType();
3676 return ExprError();
3677 }
3678
3679 TheCall->setType(ElTy);
3680 break;
3681 }
3682
3683 // These builtins support vectors of integers only.
3684 // TODO: ADD/MUL should support floating-point types.
3685 case Builtin::BI__builtin_reduce_add:
3686 case Builtin::BI__builtin_reduce_mul:
3687 case Builtin::BI__builtin_reduce_xor:
3688 case Builtin::BI__builtin_reduce_or:
3689 case Builtin::BI__builtin_reduce_and: {
3690 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3691 return ExprError();
3692
3693 const Expr *Arg = TheCall->getArg(Arg: 0);
3694
3695 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
3696 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3697 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3698 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3699 << Arg->getType();
3700 return ExprError();
3701 }
3702
3703 TheCall->setType(ElTy);
3704 break;
3705 }
3706
3707 case Builtin::BI__builtin_reduce_assoc_fadd:
3708 case Builtin::BI__builtin_reduce_in_order_fadd: {
3709 // For in-order reductions require the user to specify the start value.
3710 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3711 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
3712 return ExprError();
3713
3714 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3715 if (Vec.isInvalid())
3716 return ExprError();
3717
3718 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
3719
3720 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
3721 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3722 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3723 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3724 << Vec.get()->getType();
3725 return ExprError();
3726 }
3727
3728 if (TheCall->getNumArgs() == 2) {
3729 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3730 if (StartValue.isInvalid())
3731 return ExprError();
3732
3733 if (!StartValue.get()->getType()->isRealFloatingType()) {
3734 Diag(Loc: StartValue.get()->getBeginLoc(),
3735 DiagID: diag::err_builtin_invalid_arg_type)
3736 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3737 << StartValue.get()->getType();
3738 return ExprError();
3739 }
3740 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
3741 }
3742
3743 TheCall->setType(ElTy);
3744 break;
3745 }
3746
3747 case Builtin::BI__builtin_matrix_transpose:
3748 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
3749
3750 case Builtin::BI__builtin_matrix_column_major_load:
3751 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
3752
3753 case Builtin::BI__builtin_matrix_column_major_store:
3754 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
3755
3756 case Builtin::BI__builtin_verbose_trap:
3757 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
3758 return ExprError();
3759 break;
3760
3761 case Builtin::BI__builtin_get_device_side_mangled_name: {
3762 auto Check = [](CallExpr *TheCall) {
3763 if (TheCall->getNumArgs() != 1)
3764 return false;
3765 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
3766 if (!DRE)
3767 return false;
3768 auto *D = DRE->getDecl();
3769 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
3770 return false;
3771 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3772 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3773 };
3774 if (!Check(TheCall)) {
3775 Diag(Loc: TheCall->getBeginLoc(),
3776 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
3777 return ExprError();
3778 }
3779 break;
3780 }
3781 case Builtin::BI__builtin_bswapg:
3782 if (BuiltinBswapg(S&: *this, TheCall))
3783 return ExprError();
3784 break;
3785 case Builtin::BI__builtin_bitreverseg:
3786 if (BuiltinBitreverseg(S&: *this, TheCall))
3787 return ExprError();
3788 break;
3789 case Builtin::BI__builtin_popcountg:
3790 if (BuiltinPopcountg(S&: *this, TheCall))
3791 return ExprError();
3792 break;
3793 case Builtin::BI__builtin_clzg:
3794 case Builtin::BI__builtin_ctzg:
3795 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
3796 return ExprError();
3797 break;
3798
3799 case Builtin::BI__builtin_stdc_rotate_left:
3800 case Builtin::BI__builtin_stdc_rotate_right:
3801 if (BuiltinRotateGeneric(S&: *this, TheCall))
3802 return ExprError();
3803 break;
3804
3805 case Builtin::BI__builtin_allow_runtime_check: {
3806 Expr *Arg = TheCall->getArg(Arg: 0);
3807 // Check if the argument is a string literal.
3808 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
3809 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3810 << Arg->getSourceRange();
3811 return ExprError();
3812 }
3813 break;
3814 }
3815
3816 case Builtin::BI__builtin_allow_sanitize_check: {
3817 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3818 return ExprError();
3819
3820 Expr *Arg = TheCall->getArg(Arg: 0);
3821 // Check if the argument is a string literal.
3822 const StringLiteral *SanitizerName =
3823 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
3824 if (!SanitizerName) {
3825 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3826 << Arg->getSourceRange();
3827 return ExprError();
3828 }
3829 // Validate the sanitizer name.
3830 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3831 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
3832 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3833 Value: true)
3834 .Default(Value: false)) {
3835 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
3836 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3837 << Arg->getSourceRange();
3838 return ExprError();
3839 }
3840 break;
3841 }
3842 case Builtin::BI__builtin_counted_by_ref:
3843 if (BuiltinCountedByRef(TheCall))
3844 return ExprError();
3845 break;
3846 }
3847
3848 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3849 return ExprError();
3850
3851 // Since the target specific builtins for each arch overlap, only check those
3852 // of the arch we are compiling for.
3853 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
3854 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
3855 assert(Context.getAuxTargetInfo() &&
3856 "Aux Target Builtin, but not an aux target?");
3857
3858 if (CheckTSBuiltinFunctionCall(
3859 TI: *Context.getAuxTargetInfo(),
3860 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
3861 return ExprError();
3862 } else {
3863 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
3864 TheCall))
3865 return ExprError();
3866 }
3867 }
3868
3869 return TheCallResult;
3870}
3871
3872bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3873 llvm::APSInt Result;
3874 // We can't check the value of a dependent argument.
3875 Expr *Arg = TheCall->getArg(Arg: ArgNum);
3876 if (Arg->isTypeDependent() || Arg->isValueDependent())
3877 return false;
3878
3879 // Check constant-ness first.
3880 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3881 return true;
3882
3883 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3884 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3885 return false;
3886
3887 return Diag(Loc: TheCall->getBeginLoc(),
3888 DiagID: diag::err_argument_not_contiguous_bit_field)
3889 << ArgNum << Arg->getSourceRange();
3890}
3891
3892bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3893 unsigned FirstArg, FormatStringInfo *FSI) {
3894 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3895 bool IsVariadic = false;
3896 if (const FunctionType *FnTy = D->getFunctionType())
3897 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
3898 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
3899 IsVariadic = BD->isVariadic();
3900 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
3901 IsVariadic = OMD->isVariadic();
3902
3903 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3904 IsVariadic, FSI);
3905}
3906
3907bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3908 bool HasImplicitThisParam, bool IsVariadic,
3909 FormatStringInfo *FSI) {
3910 if (FirstArg == 0)
3911 FSI->ArgPassingKind = FAPK_VAList;
3912 else if (IsVariadic)
3913 FSI->ArgPassingKind = FAPK_Variadic;
3914 else
3915 FSI->ArgPassingKind = FAPK_Fixed;
3916 FSI->FormatIdx = FormatIdx - 1;
3917 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3918
3919 // The way the format attribute works in GCC, the implicit this argument
3920 // of member functions is counted. However, it doesn't appear in our own
3921 // lists, so decrement format_idx in that case.
3922 if (HasImplicitThisParam) {
3923 if(FSI->FormatIdx == 0)
3924 return false;
3925 --FSI->FormatIdx;
3926 if (FSI->FirstDataArg != 0)
3927 --FSI->FirstDataArg;
3928 }
3929 return true;
3930}
3931
3932/// Checks if a the given expression evaluates to null.
3933///
3934/// Returns true if the value evaluates to null.
3935static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3936 // Treat (smart) pointers constructed from nullptr as null, whether we can
3937 // const-evaluate them or not.
3938 // This must happen first: the smart pointer expr might have _Nonnull type!
3939 if (isa<CXXNullPtrLiteralExpr>(
3940 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
3941 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
3942 return true;
3943
3944 // If the expression has non-null type, it doesn't evaluate to null.
3945 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3946 if (*nullability == NullabilityKind::NonNull)
3947 return false;
3948 }
3949
3950 // As a special case, transparent unions initialized with zero are
3951 // considered null for the purposes of the nonnull attribute.
3952 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3953 UT &&
3954 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3955 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
3956 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
3957 Expr = ILE->getInit(Init: 0);
3958 }
3959
3960 bool Result;
3961 return (!Expr->isValueDependent() &&
3962 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
3963 !Result);
3964}
3965
3966static void CheckNonNullArgument(Sema &S,
3967 const Expr *ArgExpr,
3968 SourceLocation CallSiteLoc) {
3969 if (CheckNonNullExpr(S, Expr: ArgExpr))
3970 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
3971 PD: S.PDiag(DiagID: diag::warn_null_arg)
3972 << ArgExpr->getSourceRange());
3973}
3974
3975/// Determine whether the given type has a non-null nullability annotation.
3976static bool isNonNullType(QualType type) {
3977 if (auto nullability = type->getNullability())
3978 return *nullability == NullabilityKind::NonNull;
3979
3980 return false;
3981}
3982
3983static void CheckNonNullArguments(Sema &S,
3984 const NamedDecl *FDecl,
3985 const FunctionProtoType *Proto,
3986 ArrayRef<const Expr *> Args,
3987 SourceLocation CallSiteLoc) {
3988 assert((FDecl || Proto) && "Need a function declaration or prototype");
3989
3990 // Already checked by constant evaluator.
3991 if (S.isConstantEvaluatedContext())
3992 return;
3993 // Check the attributes attached to the method/function itself.
3994 llvm::SmallBitVector NonNullArgs;
3995 if (FDecl) {
3996 // Handle the nonnull attribute on the function/method declaration itself.
3997 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3998 if (!NonNull->args_size()) {
3999 // Easy case: all pointer arguments are nonnull.
4000 for (const auto *Arg : Args)
4001 if (S.isValidPointerAttrType(T: Arg->getType()))
4002 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4003 return;
4004 }
4005
4006 for (const ParamIdx &Idx : NonNull->args()) {
4007 unsigned IdxAST = Idx.getASTIndex();
4008 if (IdxAST >= Args.size())
4009 continue;
4010 if (NonNullArgs.empty())
4011 NonNullArgs.resize(N: Args.size());
4012 NonNullArgs.set(IdxAST);
4013 }
4014 }
4015 }
4016
4017 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4018 // Handle the nonnull attribute on the parameters of the
4019 // function/method.
4020 ArrayRef<ParmVarDecl*> parms;
4021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4022 parms = FD->parameters();
4023 else
4024 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4025
4026 unsigned ParamIndex = 0;
4027 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4028 I != E; ++I, ++ParamIndex) {
4029 const ParmVarDecl *PVD = *I;
4030 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4031 if (NonNullArgs.empty())
4032 NonNullArgs.resize(N: Args.size());
4033
4034 NonNullArgs.set(ParamIndex);
4035 }
4036 }
4037 } else {
4038 // If we have a non-function, non-method declaration but no
4039 // function prototype, try to dig out the function prototype.
4040 if (!Proto) {
4041 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4042 QualType type = VD->getType().getNonReferenceType();
4043 if (auto pointerType = type->getAs<PointerType>())
4044 type = pointerType->getPointeeType();
4045 else if (auto blockType = type->getAs<BlockPointerType>())
4046 type = blockType->getPointeeType();
4047 // FIXME: data member pointers?
4048
4049 // Dig out the function prototype, if there is one.
4050 Proto = type->getAs<FunctionProtoType>();
4051 }
4052 }
4053
4054 // Fill in non-null argument information from the nullability
4055 // information on the parameter types (if we have them).
4056 if (Proto) {
4057 unsigned Index = 0;
4058 for (auto paramType : Proto->getParamTypes()) {
4059 if (isNonNullType(type: paramType)) {
4060 if (NonNullArgs.empty())
4061 NonNullArgs.resize(N: Args.size());
4062
4063 NonNullArgs.set(Index);
4064 }
4065
4066 ++Index;
4067 }
4068 }
4069 }
4070
4071 // Check for non-null arguments.
4072 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4073 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4074 if (NonNullArgs[ArgIndex])
4075 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4076 }
4077}
4078
4079void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4080 StringRef ParamName, QualType ArgTy,
4081 QualType ParamTy) {
4082
4083 // If a function accepts a pointer or reference type
4084 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4085 return;
4086
4087 // If the parameter is a pointer type, get the pointee type for the
4088 // argument too. If the parameter is a reference type, don't try to get
4089 // the pointee type for the argument.
4090 if (ParamTy->isPointerType())
4091 ArgTy = ArgTy->getPointeeType();
4092
4093 // Remove reference or pointer
4094 ParamTy = ParamTy->getPointeeType();
4095
4096 // Find expected alignment, and the actual alignment of the passed object.
4097 // getTypeAlignInChars requires complete types
4098 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4099 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4100 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4101 return;
4102
4103 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4104 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4105
4106 // If the argument is less aligned than the parameter, there is a
4107 // potential alignment issue.
4108 if (ArgAlign < ParamAlign)
4109 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4110 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4111 << ParamName << (FDecl != nullptr) << FDecl;
4112}
4113
4114void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4115 const Expr *ThisArg,
4116 ArrayRef<const Expr *> Args) {
4117 if (!FD || Args.empty())
4118 return;
4119 auto GetArgAt = [&](int Idx) -> const Expr * {
4120 if (Idx == LifetimeCaptureByAttr::Global ||
4121 Idx == LifetimeCaptureByAttr::Unknown)
4122 return nullptr;
4123 if (IsMemberFunction && Idx == 0)
4124 return ThisArg;
4125 return Args[Idx - IsMemberFunction];
4126 };
4127 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4128 unsigned ArgIdx) {
4129 if (!Attr)
4130 return;
4131
4132 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4133 for (int CapturingParamIdx : Attr->params()) {
4134 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4135 // initialization codepath.
4136 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4137 isa<CXXConstructorDecl>(Val: FD))
4138 continue;
4139 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4140 CapturingEntity CE{.Entity: Capturing};
4141 // Ensure that 'Captured' outlives the 'Capturing' entity.
4142 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4143 }
4144 };
4145 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4146 HandleCaptureByAttr(FD->getParamDecl(i: I)->getAttr<LifetimeCaptureByAttr>(),
4147 I + IsMemberFunction);
4148 // Check when the implicit object param is captured.
4149 if (IsMemberFunction) {
4150 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4151 if (!TSI)
4152 return;
4153 AttributedTypeLoc ATL;
4154 for (TypeLoc TL = TSI->getTypeLoc();
4155 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4156 TL = ATL.getModifiedLoc())
4157 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4158 }
4159}
4160
4161void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4162 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4163 bool IsMemberFunction, SourceLocation Loc,
4164 SourceRange Range, VariadicCallType CallType) {
4165 // FIXME: We should check as much as we can in the template definition.
4166 if (CurContext->isDependentContext())
4167 return;
4168
4169 // Printf and scanf checking.
4170 llvm::SmallBitVector CheckedVarArgs;
4171 if (FDecl) {
4172 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4173 // Only create vector if there are format attributes.
4174 CheckedVarArgs.resize(N: Args.size());
4175 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4176 CheckedVarArgs);
4177 }
4178
4179 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4180 CheckedVarArgs.resize(N: Args.size());
4181 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4182 CheckedVarArgs);
4183 }
4184 }
4185
4186 // Refuse POD arguments that weren't caught by the format string
4187 // checks above.
4188 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4189 if (CallType != VariadicCallType::DoesNotApply &&
4190 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4191 unsigned NumParams = Proto ? Proto->getNumParams()
4192 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4193 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4194 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4195 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4196 : 0;
4197
4198 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4199 // Args[ArgIdx] can be null in malformed code.
4200 if (const Expr *Arg = Args[ArgIdx]) {
4201 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4202 checkVariadicArgument(E: Arg, CT: CallType);
4203 }
4204 }
4205 }
4206 if (FD)
4207 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4208 if (FDecl || Proto) {
4209 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4210
4211 // Type safety checking.
4212 if (FDecl) {
4213 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4214 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4215 }
4216 }
4217
4218 // Check that passed arguments match the alignment of original arguments.
4219 // Try to get the missing prototype from the declaration.
4220 if (!Proto && FDecl) {
4221 const auto *FT = FDecl->getFunctionType();
4222 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4223 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4224 }
4225 if (Proto) {
4226 // For variadic functions, we may have more args than parameters.
4227 // For some K&R functions, we may have less args than parameters.
4228 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4229 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4230 bool IsScalableArg = false;
4231 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4232 // Args[ArgIdx] can be null in malformed code.
4233 if (const Expr *Arg = Args[ArgIdx]) {
4234 if (Arg->containsErrors())
4235 continue;
4236
4237 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4238 FDecl->hasLinkage() &&
4239 FDecl->getFormalLinkage() != Linkage::Internal &&
4240 CallType == VariadicCallType::DoesNotApply)
4241 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4242
4243 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4244 if (ParamTy->isSizelessVectorType())
4245 IsScalableArg = true;
4246 QualType ArgTy = Arg->getType();
4247 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4248 ArgTy, ParamTy);
4249 }
4250 }
4251
4252 // If the callee has an AArch64 SME attribute to indicate that it is an
4253 // __arm_streaming function, then the caller requires SME to be available.
4254 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4255 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4256 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4257 llvm::StringMap<bool> CallerFeatureMap;
4258 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4259 if (!CallerFeatureMap.contains(Key: "sme"))
4260 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4261 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4262 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4263 }
4264 }
4265
4266 // If the call requires a streaming-mode change and has scalable vector
4267 // arguments or return values, then warn the user that the streaming and
4268 // non-streaming vector lengths may be different.
4269 // When both streaming and non-streaming vector lengths are defined and
4270 // mismatched, produce an error.
4271 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4272 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4273 (IsScalableArg || IsScalableRet)) {
4274 bool IsCalleeStreaming =
4275 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4276 bool IsCalleeStreamingCompatible =
4277 ExtInfo.AArch64SMEAttributes &
4278 FunctionType::SME_PStateSMCompatibleMask;
4279 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4280 if (!IsCalleeStreamingCompatible &&
4281 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4282 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4283 const LangOptions &LO = getLangOpts();
4284 unsigned VL = LO.VScaleMin * 128;
4285 unsigned SVL = LO.VScaleStreamingMin * 128;
4286 bool IsVLMismatch = VL && SVL && VL != SVL;
4287
4288 auto EmitDiag = [&](bool IsArg) {
4289 if (IsVLMismatch) {
4290 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4291 // Emit warning for streaming-compatible callers
4292 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4293 << IsArg << IsCalleeStreaming << SVL << VL;
4294 else
4295 // Emit error otherwise
4296 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4297 << IsArg << SVL << VL;
4298 } else
4299 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4300 << IsArg;
4301 };
4302
4303 if (IsScalableArg)
4304 EmitDiag(true);
4305 if (IsScalableRet)
4306 EmitDiag(false);
4307 }
4308 }
4309
4310 FunctionType::ArmStateValue CalleeArmZAState =
4311 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4312 FunctionType::ArmStateValue CalleeArmZT0State =
4313 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4314 if (CalleeArmZAState != FunctionType::ARM_None ||
4315 CalleeArmZT0State != FunctionType::ARM_None) {
4316 bool CallerHasZAState = false;
4317 bool CallerHasZT0State = false;
4318 if (CallerFD) {
4319 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4320 if (Attr && Attr->isNewZA())
4321 CallerHasZAState = true;
4322 if (Attr && Attr->isNewZT0())
4323 CallerHasZT0State = true;
4324 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4325 CallerHasZAState |=
4326 FunctionType::getArmZAState(
4327 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4328 FunctionType::ARM_None;
4329 CallerHasZT0State |=
4330 FunctionType::getArmZT0State(
4331 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4332 FunctionType::ARM_None;
4333 }
4334 }
4335
4336 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4337 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4338
4339 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4340 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4341
4342 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4343 CalleeArmZT0State != FunctionType::ARM_None) {
4344 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4345 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4346 }
4347 }
4348 }
4349
4350 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4351 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4352 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4353 if (!Arg->isValueDependent()) {
4354 Expr::EvalResult Align;
4355 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4356 const llvm::APSInt &I = Align.Val.getInt();
4357 if (!I.isPowerOf2())
4358 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4359 << Arg->getSourceRange();
4360
4361 if (I > Sema::MaximumAlignment)
4362 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4363 << Arg->getSourceRange() << Sema::MaximumAlignment;
4364 }
4365 }
4366 }
4367
4368 if (FD)
4369 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4370}
4371
4372void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4373 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4374 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4375 }
4376}
4377
4378void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4379 ArrayRef<const Expr *> Args,
4380 const FunctionProtoType *Proto,
4381 SourceLocation Loc) {
4382 VariadicCallType CallType = Proto->isVariadic()
4383 ? VariadicCallType::Constructor
4384 : VariadicCallType::DoesNotApply;
4385
4386 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4387 CheckArgAlignment(
4388 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4389 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4390
4391 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4392 Loc, Range: SourceRange(), CallType);
4393}
4394
4395bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4396 const FunctionProtoType *Proto) {
4397 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4398 isa<CXXMethodDecl>(Val: FDecl);
4399 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4400 IsMemberOperatorCall;
4401 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4402 Fn: TheCall->getCallee());
4403 Expr** Args = TheCall->getArgs();
4404 unsigned NumArgs = TheCall->getNumArgs();
4405
4406 Expr *ImplicitThis = nullptr;
4407 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4408 // If this is a call to a member operator, hide the first
4409 // argument from checkCall.
4410 // FIXME: Our choice of AST representation here is less than ideal.
4411 ImplicitThis = Args[0];
4412 ++Args;
4413 --NumArgs;
4414 } else if (IsMemberFunction && !FDecl->isStatic() &&
4415 !FDecl->hasCXXExplicitFunctionObjectParameter())
4416 ImplicitThis =
4417 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4418
4419 if (ImplicitThis) {
4420 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4421 // used.
4422 QualType ThisType = ImplicitThis->getType();
4423 if (!ThisType->isPointerType()) {
4424 assert(!ThisType->isReferenceType());
4425 ThisType = Context.getPointerType(T: ThisType);
4426 }
4427
4428 QualType ThisTypeFromDecl = Context.getPointerType(
4429 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4430
4431 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4432 ParamTy: ThisTypeFromDecl);
4433 }
4434
4435 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4436 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4437 Range: TheCall->getCallee()->getSourceRange(), CallType);
4438
4439 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4440 // None of the checks below are needed for functions that don't have
4441 // simple names (e.g., C++ conversion functions).
4442 if (!FnInfo)
4443 return false;
4444
4445 // Enforce TCB except for builtin calls, which are always allowed.
4446 if (FDecl->getBuiltinID() == 0)
4447 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4448
4449 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4450 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4451 CheckInfNaNFunction(Call: TheCall, FDecl);
4452
4453 if (getLangOpts().ObjC)
4454 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4455
4456 unsigned CMId = FDecl->getMemoryFunctionKind();
4457
4458 // Handle memory setting and copying functions.
4459 switch (CMId) {
4460 case 0:
4461 return false;
4462 case Builtin::BIstrlcpy: // fallthrough
4463 case Builtin::BIstrlcat:
4464 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4465 break;
4466 case Builtin::BIstrncat:
4467 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4468 break;
4469 case Builtin::BIfree:
4470 CheckFreeArguments(E: TheCall);
4471 break;
4472 default:
4473 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4474 }
4475
4476 return false;
4477}
4478
4479bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4480 const FunctionProtoType *Proto) {
4481 QualType Ty;
4482 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4483 Ty = V->getType().getNonReferenceType();
4484 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4485 Ty = F->getType().getNonReferenceType();
4486 else
4487 return false;
4488
4489 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4490 !Ty->isFunctionProtoType())
4491 return false;
4492
4493 VariadicCallType CallType;
4494 if (!Proto || !Proto->isVariadic()) {
4495 CallType = VariadicCallType::DoesNotApply;
4496 } else if (Ty->isBlockPointerType()) {
4497 CallType = VariadicCallType::Block;
4498 } else { // Ty->isFunctionPointerType()
4499 CallType = VariadicCallType::Function;
4500 }
4501
4502 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4503 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4504 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4505 Range: TheCall->getCallee()->getSourceRange(), CallType);
4506
4507 return false;
4508}
4509
4510bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4511 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4512 Fn: TheCall->getCallee());
4513 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4514 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4515 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4516 Range: TheCall->getCallee()->getSourceRange(), CallType);
4517
4518 return false;
4519}
4520
4521static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4522 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4523 return false;
4524
4525 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4526 switch (Op) {
4527 case AtomicExpr::AO__c11_atomic_init:
4528 case AtomicExpr::AO__opencl_atomic_init:
4529 llvm_unreachable("There is no ordering argument for an init");
4530
4531 case AtomicExpr::AO__c11_atomic_load:
4532 case AtomicExpr::AO__opencl_atomic_load:
4533 case AtomicExpr::AO__hip_atomic_load:
4534 case AtomicExpr::AO__atomic_load_n:
4535 case AtomicExpr::AO__atomic_load:
4536 case AtomicExpr::AO__scoped_atomic_load_n:
4537 case AtomicExpr::AO__scoped_atomic_load:
4538 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4539 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4540
4541 case AtomicExpr::AO__c11_atomic_store:
4542 case AtomicExpr::AO__opencl_atomic_store:
4543 case AtomicExpr::AO__hip_atomic_store:
4544 case AtomicExpr::AO__atomic_store:
4545 case AtomicExpr::AO__atomic_store_n:
4546 case AtomicExpr::AO__scoped_atomic_store:
4547 case AtomicExpr::AO__scoped_atomic_store_n:
4548 case AtomicExpr::AO__atomic_clear:
4549 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4550 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4551 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4552
4553 default:
4554 return true;
4555 }
4556}
4557
4558ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4559 AtomicExpr::AtomicOp Op) {
4560 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4561 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4562 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4563 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4564 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4565 Op);
4566}
4567
4568ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4569 SourceLocation RParenLoc, MultiExprArg Args,
4570 AtomicExpr::AtomicOp Op,
4571 AtomicArgumentOrder ArgOrder) {
4572 // All the non-OpenCL operations take one of the following forms.
4573 // The OpenCL operations take the __c11 forms with one extra argument for
4574 // synchronization scope.
4575 enum {
4576 // C __c11_atomic_init(A *, C)
4577 Init,
4578
4579 // C __c11_atomic_load(A *, int)
4580 Load,
4581
4582 // void __atomic_load(A *, CP, int)
4583 LoadCopy,
4584
4585 // void __atomic_store(A *, CP, int)
4586 Copy,
4587
4588 // C __c11_atomic_add(A *, M, int)
4589 Arithmetic,
4590
4591 // C __atomic_exchange_n(A *, CP, int)
4592 Xchg,
4593
4594 // void __atomic_exchange(A *, C *, CP, int)
4595 GNUXchg,
4596
4597 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4598 C11CmpXchg,
4599
4600 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4601 GNUCmpXchg,
4602
4603 // bool __atomic_test_and_set(A *, int)
4604 TestAndSetByte,
4605
4606 // void __atomic_clear(A *, int)
4607 ClearByte,
4608 } Form = Init;
4609
4610 const unsigned NumForm = ClearByte + 1;
4611 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4612 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4613 // where:
4614 // C is an appropriate type,
4615 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4616 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4617 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4618 // the int parameters are for orderings.
4619
4620 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4621 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4622 "need to update code for modified forms");
4623 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4624 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4625 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4626 "need to update code for modified C11 atomics");
4627 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4628 Op <= AtomicExpr::AO__opencl_atomic_store;
4629 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4630 Op <= AtomicExpr::AO__hip_atomic_store;
4631 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4632 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4633 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4634 Op <= AtomicExpr::AO__c11_atomic_store) ||
4635 IsOpenCL;
4636 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4637 Op == AtomicExpr::AO__atomic_store_n ||
4638 Op == AtomicExpr::AO__atomic_exchange_n ||
4639 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4640 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4641 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4642 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4643 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4644 // Bit mask for extra allowed value types other than integers for atomic
4645 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4646 // allow floating point.
4647 enum ArithOpExtraValueType {
4648 AOEVT_None = 0,
4649 AOEVT_Pointer = 1,
4650 AOEVT_FP = 2,
4651 };
4652 unsigned ArithAllows = AOEVT_None;
4653
4654 switch (Op) {
4655 case AtomicExpr::AO__c11_atomic_init:
4656 case AtomicExpr::AO__opencl_atomic_init:
4657 Form = Init;
4658 break;
4659
4660 case AtomicExpr::AO__c11_atomic_load:
4661 case AtomicExpr::AO__opencl_atomic_load:
4662 case AtomicExpr::AO__hip_atomic_load:
4663 case AtomicExpr::AO__atomic_load_n:
4664 case AtomicExpr::AO__scoped_atomic_load_n:
4665 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4666 Form = Load;
4667 break;
4668
4669 case AtomicExpr::AO__atomic_load:
4670 case AtomicExpr::AO__scoped_atomic_load:
4671 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4672 Form = LoadCopy;
4673 break;
4674
4675 case AtomicExpr::AO__c11_atomic_store:
4676 case AtomicExpr::AO__opencl_atomic_store:
4677 case AtomicExpr::AO__hip_atomic_store:
4678 case AtomicExpr::AO__atomic_store:
4679 case AtomicExpr::AO__atomic_store_n:
4680 case AtomicExpr::AO__scoped_atomic_store:
4681 case AtomicExpr::AO__scoped_atomic_store_n:
4682 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4683 Form = Copy;
4684 break;
4685 case AtomicExpr::AO__atomic_fetch_add:
4686 case AtomicExpr::AO__atomic_fetch_sub:
4687 case AtomicExpr::AO__atomic_add_fetch:
4688 case AtomicExpr::AO__atomic_sub_fetch:
4689 case AtomicExpr::AO__scoped_atomic_fetch_add:
4690 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4691 case AtomicExpr::AO__scoped_atomic_add_fetch:
4692 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4693 case AtomicExpr::AO__c11_atomic_fetch_add:
4694 case AtomicExpr::AO__c11_atomic_fetch_sub:
4695 case AtomicExpr::AO__opencl_atomic_fetch_add:
4696 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4697 case AtomicExpr::AO__hip_atomic_fetch_add:
4698 case AtomicExpr::AO__hip_atomic_fetch_sub:
4699 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4700 Form = Arithmetic;
4701 break;
4702 case AtomicExpr::AO__atomic_fetch_max:
4703 case AtomicExpr::AO__atomic_fetch_min:
4704 case AtomicExpr::AO__atomic_max_fetch:
4705 case AtomicExpr::AO__atomic_min_fetch:
4706 case AtomicExpr::AO__scoped_atomic_fetch_max:
4707 case AtomicExpr::AO__scoped_atomic_fetch_min:
4708 case AtomicExpr::AO__scoped_atomic_max_fetch:
4709 case AtomicExpr::AO__scoped_atomic_min_fetch:
4710 case AtomicExpr::AO__c11_atomic_fetch_max:
4711 case AtomicExpr::AO__c11_atomic_fetch_min:
4712 case AtomicExpr::AO__opencl_atomic_fetch_max:
4713 case AtomicExpr::AO__opencl_atomic_fetch_min:
4714 case AtomicExpr::AO__hip_atomic_fetch_max:
4715 case AtomicExpr::AO__hip_atomic_fetch_min:
4716 ArithAllows = AOEVT_FP;
4717 Form = Arithmetic;
4718 break;
4719 case AtomicExpr::AO__c11_atomic_fetch_and:
4720 case AtomicExpr::AO__c11_atomic_fetch_or:
4721 case AtomicExpr::AO__c11_atomic_fetch_xor:
4722 case AtomicExpr::AO__hip_atomic_fetch_and:
4723 case AtomicExpr::AO__hip_atomic_fetch_or:
4724 case AtomicExpr::AO__hip_atomic_fetch_xor:
4725 case AtomicExpr::AO__c11_atomic_fetch_nand:
4726 case AtomicExpr::AO__opencl_atomic_fetch_and:
4727 case AtomicExpr::AO__opencl_atomic_fetch_or:
4728 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4729 case AtomicExpr::AO__atomic_fetch_and:
4730 case AtomicExpr::AO__atomic_fetch_or:
4731 case AtomicExpr::AO__atomic_fetch_xor:
4732 case AtomicExpr::AO__atomic_fetch_nand:
4733 case AtomicExpr::AO__atomic_and_fetch:
4734 case AtomicExpr::AO__atomic_or_fetch:
4735 case AtomicExpr::AO__atomic_xor_fetch:
4736 case AtomicExpr::AO__atomic_nand_fetch:
4737 case AtomicExpr::AO__atomic_fetch_uinc:
4738 case AtomicExpr::AO__atomic_fetch_udec:
4739 case AtomicExpr::AO__scoped_atomic_fetch_and:
4740 case AtomicExpr::AO__scoped_atomic_fetch_or:
4741 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4742 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4743 case AtomicExpr::AO__scoped_atomic_and_fetch:
4744 case AtomicExpr::AO__scoped_atomic_or_fetch:
4745 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4746 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4747 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4748 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4749 Form = Arithmetic;
4750 break;
4751
4752 case AtomicExpr::AO__c11_atomic_exchange:
4753 case AtomicExpr::AO__hip_atomic_exchange:
4754 case AtomicExpr::AO__opencl_atomic_exchange:
4755 case AtomicExpr::AO__atomic_exchange_n:
4756 case AtomicExpr::AO__scoped_atomic_exchange_n:
4757 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4758 Form = Xchg;
4759 break;
4760
4761 case AtomicExpr::AO__atomic_exchange:
4762 case AtomicExpr::AO__scoped_atomic_exchange:
4763 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4764 Form = GNUXchg;
4765 break;
4766
4767 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4768 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4769 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4770 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4771 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4772 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4773 Form = C11CmpXchg;
4774 break;
4775
4776 case AtomicExpr::AO__atomic_compare_exchange:
4777 case AtomicExpr::AO__atomic_compare_exchange_n:
4778 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4779 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4780 ArithAllows = AOEVT_Pointer;
4781 Form = GNUCmpXchg;
4782 break;
4783
4784 case AtomicExpr::AO__atomic_test_and_set:
4785 Form = TestAndSetByte;
4786 break;
4787
4788 case AtomicExpr::AO__atomic_clear:
4789 Form = ClearByte;
4790 break;
4791 }
4792
4793 unsigned AdjustedNumArgs = NumArgs[Form];
4794 if ((IsOpenCL || IsHIP || IsScoped) &&
4795 Op != AtomicExpr::AO__opencl_atomic_init)
4796 ++AdjustedNumArgs;
4797 // Check we have the right number of arguments.
4798 if (Args.size() < AdjustedNumArgs) {
4799 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
4800 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4801 << /*is non object*/ 0 << ExprRange;
4802 return ExprError();
4803 } else if (Args.size() > AdjustedNumArgs) {
4804 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
4805 DiagID: diag::err_typecheck_call_too_many_args)
4806 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4807 << /*is non object*/ 0 << ExprRange;
4808 return ExprError();
4809 }
4810
4811 // Inspect the first argument of the atomic operation.
4812 Expr *Ptr = Args[0];
4813 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
4814 if (ConvertedPtr.isInvalid())
4815 return ExprError();
4816
4817 Ptr = ConvertedPtr.get();
4818 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4819 if (!pointerType) {
4820 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4821 << Ptr->getType() << 0 << Ptr->getSourceRange();
4822 return ExprError();
4823 }
4824
4825 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4826 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4827 QualType ValType = AtomTy; // 'C'
4828 if (IsC11) {
4829 if (!AtomTy->isAtomicType()) {
4830 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
4831 << Ptr->getType() << Ptr->getSourceRange();
4832 return ExprError();
4833 }
4834 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4835 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4836 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
4837 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4838 << Ptr->getSourceRange();
4839 return ExprError();
4840 }
4841 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4842 } else if (Form != Load && Form != LoadCopy) {
4843 if (ValType.isConstQualified()) {
4844 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
4845 << Ptr->getType() << Ptr->getSourceRange();
4846 return ExprError();
4847 }
4848 }
4849
4850 if (Form != TestAndSetByte && Form != ClearByte) {
4851 // Pointer to object of size zero is not allowed.
4852 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
4853 DiagID: diag::err_incomplete_type))
4854 return ExprError();
4855
4856 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
4857 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4858 << Ptr->getType() << 1 << Ptr->getSourceRange();
4859 return ExprError();
4860 }
4861 } else {
4862 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4863 // non-const pointer type, including void* and pointers to incomplete
4864 // structs, but only access the first byte.
4865 AtomTy = Context.CharTy;
4866 AtomTy = AtomTy.withCVRQualifiers(
4867 CVR: pointerType->getPointeeType().getCVRQualifiers());
4868 QualType PointerQT = Context.getPointerType(T: AtomTy);
4869 pointerType = PointerQT->getAs<PointerType>();
4870 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
4871 ValType = AtomTy;
4872 }
4873
4874 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4875 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4876 Diag(Loc: ExprRange.getBegin(),
4877 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
4878 << 0 << Ptr->getType() << Ptr->getSourceRange();
4879 return ExprError();
4880 }
4881
4882 // For an arithmetic operation, the implied arithmetic must be well-formed.
4883 // For _n operations, the value type must also be a valid atomic type.
4884 if (Form == Arithmetic || IsN) {
4885 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4886 // trivial type errors.
4887 auto IsAllowedValueType = [&](QualType ValType,
4888 unsigned AllowedType) -> bool {
4889 bool IsX87LongDouble =
4890 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
4891 &Context.getTargetInfo().getLongDoubleFormat() ==
4892 &llvm::APFloat::x87DoubleExtended();
4893 if (ValType->isIntegerType())
4894 return true;
4895 if (ValType->isPointerType())
4896 return AllowedType & AOEVT_Pointer;
4897 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4898 return false;
4899 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4900 if (IsX87LongDouble)
4901 return false;
4902 return true;
4903 };
4904 if (!IsAllowedValueType(ValType, ArithAllows)) {
4905 auto DID = ArithAllows & AOEVT_FP
4906 ? (ArithAllows & AOEVT_Pointer
4907 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4908 : diag::err_atomic_op_needs_atomic_int_or_fp)
4909 : (ArithAllows & AOEVT_Pointer
4910 ? diag::err_atomic_op_needs_atomic_int_or_ptr
4911 : diag::err_atomic_op_needs_atomic_int);
4912 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
4913 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4914 return ExprError();
4915 }
4916 if (IsC11 && ValType->isPointerType() &&
4917 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
4918 DiagID: diag::err_incomplete_type)) {
4919 return ExprError();
4920 }
4921 }
4922
4923 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4924 !AtomTy->isScalarType()) {
4925 // For GNU atomics, require a trivially-copyable type. This is not part of
4926 // the GNU atomics specification but we enforce it for consistency with
4927 // other atomics which generally all require a trivially-copyable type. This
4928 // is because atomics just copy bits.
4929 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
4930 << Ptr->getType() << Ptr->getSourceRange();
4931 return ExprError();
4932 }
4933
4934 switch (ValType.getObjCLifetime()) {
4935 case Qualifiers::OCL_None:
4936 case Qualifiers::OCL_ExplicitNone:
4937 // okay
4938 break;
4939
4940 case Qualifiers::OCL_Weak:
4941 case Qualifiers::OCL_Strong:
4942 case Qualifiers::OCL_Autoreleasing:
4943 // FIXME: Can this happen? By this point, ValType should be known
4944 // to be trivially copyable.
4945 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
4946 << ValType << Ptr->getSourceRange();
4947 return ExprError();
4948 }
4949
4950 // All atomic operations have an overload which takes a pointer to a volatile
4951 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4952 // into the result or the other operands. Similarly atomic_load takes a
4953 // pointer to a const 'A'.
4954 ValType.removeLocalVolatile();
4955 ValType.removeLocalConst();
4956 QualType ResultType = ValType;
4957 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4958 Form == ClearByte)
4959 ResultType = Context.VoidTy;
4960 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4961 ResultType = Context.BoolTy;
4962
4963 // The type of a parameter passed 'by value'. In the GNU atomics, such
4964 // arguments are actually passed as pointers.
4965 QualType ByValType = ValType; // 'CP'
4966 bool IsPassedByAddress = false;
4967 if (!IsC11 && !IsHIP && !IsN) {
4968 ByValType = Ptr->getType();
4969 IsPassedByAddress = true;
4970 }
4971
4972 SmallVector<Expr *, 5> APIOrderedArgs;
4973 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4974 APIOrderedArgs.push_back(Elt: Args[0]);
4975 switch (Form) {
4976 case Init:
4977 case Load:
4978 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
4979 break;
4980 case LoadCopy:
4981 case Copy:
4982 case Arithmetic:
4983 case Xchg:
4984 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4985 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4986 break;
4987 case GNUXchg:
4988 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4989 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
4990 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4991 break;
4992 case C11CmpXchg:
4993 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4994 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
4995 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4996 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
4997 break;
4998 case GNUCmpXchg:
4999 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5000 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5001 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5002 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5003 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5004 break;
5005 case TestAndSetByte:
5006 case ClearByte:
5007 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5008 break;
5009 }
5010 } else
5011 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5012
5013 // The first argument's non-CV pointer type is used to deduce the type of
5014 // subsequent arguments, except for:
5015 // - weak flag (always converted to bool)
5016 // - memory order (always converted to int)
5017 // - scope (always converted to int)
5018 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5019 QualType Ty;
5020 if (i < NumVals[Form] + 1) {
5021 switch (i) {
5022 case 0:
5023 // The first argument is always a pointer. It has a fixed type.
5024 // It is always dereferenced, a nullptr is undefined.
5025 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5026 // Nothing else to do: we already know all we want about this pointer.
5027 continue;
5028 case 1:
5029 // The second argument is the non-atomic operand. For arithmetic, this
5030 // is always passed by value, and for a compare_exchange it is always
5031 // passed by address. For the rest, GNU uses by-address and C11 uses
5032 // by-value.
5033 assert(Form != Load);
5034 if (Form == Arithmetic && ValType->isPointerType())
5035 Ty = Context.getPointerDiffType();
5036 else if (Form == Init || Form == Arithmetic)
5037 Ty = ValType;
5038 else if (Form == Copy || Form == Xchg) {
5039 if (IsPassedByAddress) {
5040 // The value pointer is always dereferenced, a nullptr is undefined.
5041 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5042 CallSiteLoc: ExprRange.getBegin());
5043 }
5044 Ty = ByValType;
5045 } else {
5046 Expr *ValArg = APIOrderedArgs[i];
5047 // The value pointer is always dereferenced, a nullptr is undefined.
5048 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5049 LangAS AS = LangAS::Default;
5050 // Keep address space of non-atomic pointer type.
5051 if (const PointerType *PtrTy =
5052 ValArg->getType()->getAs<PointerType>()) {
5053 AS = PtrTy->getPointeeType().getAddressSpace();
5054 }
5055 Ty = Context.getPointerType(
5056 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5057 }
5058 break;
5059 case 2:
5060 // The third argument to compare_exchange / GNU exchange is the desired
5061 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5062 if (IsPassedByAddress)
5063 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5064 Ty = ByValType;
5065 break;
5066 case 3:
5067 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5068 Ty = Context.BoolTy;
5069 break;
5070 }
5071 } else {
5072 // The order(s) and scope are always converted to int.
5073 Ty = Context.IntTy;
5074 }
5075
5076 InitializedEntity Entity =
5077 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5078 ExprResult Arg = APIOrderedArgs[i];
5079 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5080 if (Arg.isInvalid())
5081 return true;
5082 APIOrderedArgs[i] = Arg.get();
5083 }
5084
5085 // Permute the arguments into a 'consistent' order.
5086 SmallVector<Expr*, 5> SubExprs;
5087 SubExprs.push_back(Elt: Ptr);
5088 switch (Form) {
5089 case Init:
5090 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5091 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5092 break;
5093 case Load:
5094 case TestAndSetByte:
5095 case ClearByte:
5096 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5097 break;
5098 case LoadCopy:
5099 case Copy:
5100 case Arithmetic:
5101 case Xchg:
5102 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5103 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5104 break;
5105 case GNUXchg:
5106 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5107 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5108 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5109 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5110 break;
5111 case C11CmpXchg:
5112 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5113 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5114 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5115 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5116 break;
5117 case GNUCmpXchg:
5118 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5119 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5120 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5121 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5122 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5123 break;
5124 }
5125
5126 // If the memory orders are constants, check they are valid.
5127 if (SubExprs.size() >= 2 && Form != Init) {
5128 std::optional<llvm::APSInt> Success =
5129 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5130 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5131 Diag(Loc: SubExprs[1]->getBeginLoc(),
5132 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5133 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5134 << SubExprs[1]->getSourceRange();
5135 }
5136 if (SubExprs.size() >= 5) {
5137 if (std::optional<llvm::APSInt> Failure =
5138 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5139 if (!llvm::is_contained(
5140 Set: {llvm::AtomicOrderingCABI::relaxed,
5141 llvm::AtomicOrderingCABI::consume,
5142 llvm::AtomicOrderingCABI::acquire,
5143 llvm::AtomicOrderingCABI::seq_cst},
5144 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5145 Diag(Loc: SubExprs[3]->getBeginLoc(),
5146 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5147 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5148 }
5149 }
5150 }
5151 }
5152
5153 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5154 auto *Scope = Args[Args.size() - 1];
5155 if (std::optional<llvm::APSInt> Result =
5156 Scope->getIntegerConstantExpr(Ctx: Context)) {
5157 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5158 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5159 << Scope->getSourceRange();
5160 }
5161 SubExprs.push_back(Elt: Scope);
5162 }
5163
5164 AtomicExpr *AE = new (Context)
5165 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5166
5167 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5168 Op == AtomicExpr::AO__c11_atomic_store ||
5169 Op == AtomicExpr::AO__opencl_atomic_load ||
5170 Op == AtomicExpr::AO__hip_atomic_load ||
5171 Op == AtomicExpr::AO__opencl_atomic_store ||
5172 Op == AtomicExpr::AO__hip_atomic_store) &&
5173 Context.AtomicUsesUnsupportedLibcall(E: AE))
5174 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5175 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5176 Op == AtomicExpr::AO__opencl_atomic_load ||
5177 Op == AtomicExpr::AO__hip_atomic_load)
5178 ? 0
5179 : 1);
5180
5181 if (ValType->isBitIntType()) {
5182 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5183 return ExprError();
5184 }
5185
5186 return AE;
5187}
5188
5189/// checkBuiltinArgument - Given a call to a builtin function, perform
5190/// normal type-checking on the given argument, updating the call in
5191/// place. This is useful when a builtin function requires custom
5192/// type-checking for some of its arguments but not necessarily all of
5193/// them.
5194///
5195/// Returns true on error.
5196static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5197 FunctionDecl *Fn = E->getDirectCallee();
5198 assert(Fn && "builtin call without direct callee!");
5199
5200 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5201 InitializedEntity Entity =
5202 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5203
5204 ExprResult Arg = E->getArg(Arg: ArgIndex);
5205 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5206 if (Arg.isInvalid())
5207 return true;
5208
5209 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5210 return false;
5211}
5212
5213ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5214 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5215 Expr *Callee = TheCall->getCallee();
5216 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5217 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5218
5219 // Ensure that we have at least one argument to do type inference from.
5220 if (TheCall->getNumArgs() < 1) {
5221 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5222 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5223 << Callee->getSourceRange();
5224 return ExprError();
5225 }
5226
5227 // Inspect the first argument of the atomic builtin. This should always be
5228 // a pointer type, whose element is an integral scalar or pointer type.
5229 // Because it is a pointer type, we don't have to worry about any implicit
5230 // casts here.
5231 // FIXME: We don't allow floating point scalars as input.
5232 Expr *FirstArg = TheCall->getArg(Arg: 0);
5233 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5234 if (FirstArgResult.isInvalid())
5235 return ExprError();
5236 FirstArg = FirstArgResult.get();
5237 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5238
5239 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5240 if (!pointerType) {
5241 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5242 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5243 return ExprError();
5244 }
5245
5246 QualType ValType = pointerType->getPointeeType();
5247 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5248 !ValType->isBlockPointerType()) {
5249 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5250 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5251 return ExprError();
5252 }
5253 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5254 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5255 Diag(Loc: FirstArg->getBeginLoc(),
5256 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5257 << 1 << ValType << FirstArg->getSourceRange();
5258 return ExprError();
5259 }
5260
5261 if (ValType.isConstQualified()) {
5262 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5263 << FirstArg->getType() << FirstArg->getSourceRange();
5264 return ExprError();
5265 }
5266
5267 switch (ValType.getObjCLifetime()) {
5268 case Qualifiers::OCL_None:
5269 case Qualifiers::OCL_ExplicitNone:
5270 // okay
5271 break;
5272
5273 case Qualifiers::OCL_Weak:
5274 case Qualifiers::OCL_Strong:
5275 case Qualifiers::OCL_Autoreleasing:
5276 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5277 << ValType << FirstArg->getSourceRange();
5278 return ExprError();
5279 }
5280
5281 // Strip any qualifiers off ValType.
5282 ValType = ValType.getUnqualifiedType();
5283
5284 // The majority of builtins return a value, but a few have special return
5285 // types, so allow them to override appropriately below.
5286 QualType ResultType = ValType;
5287
5288 // We need to figure out which concrete builtin this maps onto. For example,
5289 // __sync_fetch_and_add with a 2 byte object turns into
5290 // __sync_fetch_and_add_2.
5291#define BUILTIN_ROW(x) \
5292 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5293 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5294
5295 static const unsigned BuiltinIndices[][5] = {
5296 BUILTIN_ROW(__sync_fetch_and_add),
5297 BUILTIN_ROW(__sync_fetch_and_sub),
5298 BUILTIN_ROW(__sync_fetch_and_or),
5299 BUILTIN_ROW(__sync_fetch_and_and),
5300 BUILTIN_ROW(__sync_fetch_and_xor),
5301 BUILTIN_ROW(__sync_fetch_and_nand),
5302
5303 BUILTIN_ROW(__sync_add_and_fetch),
5304 BUILTIN_ROW(__sync_sub_and_fetch),
5305 BUILTIN_ROW(__sync_and_and_fetch),
5306 BUILTIN_ROW(__sync_or_and_fetch),
5307 BUILTIN_ROW(__sync_xor_and_fetch),
5308 BUILTIN_ROW(__sync_nand_and_fetch),
5309
5310 BUILTIN_ROW(__sync_val_compare_and_swap),
5311 BUILTIN_ROW(__sync_bool_compare_and_swap),
5312 BUILTIN_ROW(__sync_lock_test_and_set),
5313 BUILTIN_ROW(__sync_lock_release),
5314 BUILTIN_ROW(__sync_swap)
5315 };
5316#undef BUILTIN_ROW
5317
5318 // Determine the index of the size.
5319 unsigned SizeIndex;
5320 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5321 case 1: SizeIndex = 0; break;
5322 case 2: SizeIndex = 1; break;
5323 case 4: SizeIndex = 2; break;
5324 case 8: SizeIndex = 3; break;
5325 case 16: SizeIndex = 4; break;
5326 default:
5327 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5328 << FirstArg->getType() << FirstArg->getSourceRange();
5329 return ExprError();
5330 }
5331
5332 // Each of these builtins has one pointer argument, followed by some number of
5333 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5334 // that we ignore. Find out which row of BuiltinIndices to read from as well
5335 // as the number of fixed args.
5336 unsigned BuiltinID = FDecl->getBuiltinID();
5337 unsigned BuiltinIndex, NumFixed = 1;
5338 bool WarnAboutSemanticsChange = false;
5339 switch (BuiltinID) {
5340 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5341 case Builtin::BI__sync_fetch_and_add:
5342 case Builtin::BI__sync_fetch_and_add_1:
5343 case Builtin::BI__sync_fetch_and_add_2:
5344 case Builtin::BI__sync_fetch_and_add_4:
5345 case Builtin::BI__sync_fetch_and_add_8:
5346 case Builtin::BI__sync_fetch_and_add_16:
5347 BuiltinIndex = 0;
5348 break;
5349
5350 case Builtin::BI__sync_fetch_and_sub:
5351 case Builtin::BI__sync_fetch_and_sub_1:
5352 case Builtin::BI__sync_fetch_and_sub_2:
5353 case Builtin::BI__sync_fetch_and_sub_4:
5354 case Builtin::BI__sync_fetch_and_sub_8:
5355 case Builtin::BI__sync_fetch_and_sub_16:
5356 BuiltinIndex = 1;
5357 break;
5358
5359 case Builtin::BI__sync_fetch_and_or:
5360 case Builtin::BI__sync_fetch_and_or_1:
5361 case Builtin::BI__sync_fetch_and_or_2:
5362 case Builtin::BI__sync_fetch_and_or_4:
5363 case Builtin::BI__sync_fetch_and_or_8:
5364 case Builtin::BI__sync_fetch_and_or_16:
5365 BuiltinIndex = 2;
5366 break;
5367
5368 case Builtin::BI__sync_fetch_and_and:
5369 case Builtin::BI__sync_fetch_and_and_1:
5370 case Builtin::BI__sync_fetch_and_and_2:
5371 case Builtin::BI__sync_fetch_and_and_4:
5372 case Builtin::BI__sync_fetch_and_and_8:
5373 case Builtin::BI__sync_fetch_and_and_16:
5374 BuiltinIndex = 3;
5375 break;
5376
5377 case Builtin::BI__sync_fetch_and_xor:
5378 case Builtin::BI__sync_fetch_and_xor_1:
5379 case Builtin::BI__sync_fetch_and_xor_2:
5380 case Builtin::BI__sync_fetch_and_xor_4:
5381 case Builtin::BI__sync_fetch_and_xor_8:
5382 case Builtin::BI__sync_fetch_and_xor_16:
5383 BuiltinIndex = 4;
5384 break;
5385
5386 case Builtin::BI__sync_fetch_and_nand:
5387 case Builtin::BI__sync_fetch_and_nand_1:
5388 case Builtin::BI__sync_fetch_and_nand_2:
5389 case Builtin::BI__sync_fetch_and_nand_4:
5390 case Builtin::BI__sync_fetch_and_nand_8:
5391 case Builtin::BI__sync_fetch_and_nand_16:
5392 BuiltinIndex = 5;
5393 WarnAboutSemanticsChange = true;
5394 break;
5395
5396 case Builtin::BI__sync_add_and_fetch:
5397 case Builtin::BI__sync_add_and_fetch_1:
5398 case Builtin::BI__sync_add_and_fetch_2:
5399 case Builtin::BI__sync_add_and_fetch_4:
5400 case Builtin::BI__sync_add_and_fetch_8:
5401 case Builtin::BI__sync_add_and_fetch_16:
5402 BuiltinIndex = 6;
5403 break;
5404
5405 case Builtin::BI__sync_sub_and_fetch:
5406 case Builtin::BI__sync_sub_and_fetch_1:
5407 case Builtin::BI__sync_sub_and_fetch_2:
5408 case Builtin::BI__sync_sub_and_fetch_4:
5409 case Builtin::BI__sync_sub_and_fetch_8:
5410 case Builtin::BI__sync_sub_and_fetch_16:
5411 BuiltinIndex = 7;
5412 break;
5413
5414 case Builtin::BI__sync_and_and_fetch:
5415 case Builtin::BI__sync_and_and_fetch_1:
5416 case Builtin::BI__sync_and_and_fetch_2:
5417 case Builtin::BI__sync_and_and_fetch_4:
5418 case Builtin::BI__sync_and_and_fetch_8:
5419 case Builtin::BI__sync_and_and_fetch_16:
5420 BuiltinIndex = 8;
5421 break;
5422
5423 case Builtin::BI__sync_or_and_fetch:
5424 case Builtin::BI__sync_or_and_fetch_1:
5425 case Builtin::BI__sync_or_and_fetch_2:
5426 case Builtin::BI__sync_or_and_fetch_4:
5427 case Builtin::BI__sync_or_and_fetch_8:
5428 case Builtin::BI__sync_or_and_fetch_16:
5429 BuiltinIndex = 9;
5430 break;
5431
5432 case Builtin::BI__sync_xor_and_fetch:
5433 case Builtin::BI__sync_xor_and_fetch_1:
5434 case Builtin::BI__sync_xor_and_fetch_2:
5435 case Builtin::BI__sync_xor_and_fetch_4:
5436 case Builtin::BI__sync_xor_and_fetch_8:
5437 case Builtin::BI__sync_xor_and_fetch_16:
5438 BuiltinIndex = 10;
5439 break;
5440
5441 case Builtin::BI__sync_nand_and_fetch:
5442 case Builtin::BI__sync_nand_and_fetch_1:
5443 case Builtin::BI__sync_nand_and_fetch_2:
5444 case Builtin::BI__sync_nand_and_fetch_4:
5445 case Builtin::BI__sync_nand_and_fetch_8:
5446 case Builtin::BI__sync_nand_and_fetch_16:
5447 BuiltinIndex = 11;
5448 WarnAboutSemanticsChange = true;
5449 break;
5450
5451 case Builtin::BI__sync_val_compare_and_swap:
5452 case Builtin::BI__sync_val_compare_and_swap_1:
5453 case Builtin::BI__sync_val_compare_and_swap_2:
5454 case Builtin::BI__sync_val_compare_and_swap_4:
5455 case Builtin::BI__sync_val_compare_and_swap_8:
5456 case Builtin::BI__sync_val_compare_and_swap_16:
5457 BuiltinIndex = 12;
5458 NumFixed = 2;
5459 break;
5460
5461 case Builtin::BI__sync_bool_compare_and_swap:
5462 case Builtin::BI__sync_bool_compare_and_swap_1:
5463 case Builtin::BI__sync_bool_compare_and_swap_2:
5464 case Builtin::BI__sync_bool_compare_and_swap_4:
5465 case Builtin::BI__sync_bool_compare_and_swap_8:
5466 case Builtin::BI__sync_bool_compare_and_swap_16:
5467 BuiltinIndex = 13;
5468 NumFixed = 2;
5469 ResultType = Context.BoolTy;
5470 break;
5471
5472 case Builtin::BI__sync_lock_test_and_set:
5473 case Builtin::BI__sync_lock_test_and_set_1:
5474 case Builtin::BI__sync_lock_test_and_set_2:
5475 case Builtin::BI__sync_lock_test_and_set_4:
5476 case Builtin::BI__sync_lock_test_and_set_8:
5477 case Builtin::BI__sync_lock_test_and_set_16:
5478 BuiltinIndex = 14;
5479 break;
5480
5481 case Builtin::BI__sync_lock_release:
5482 case Builtin::BI__sync_lock_release_1:
5483 case Builtin::BI__sync_lock_release_2:
5484 case Builtin::BI__sync_lock_release_4:
5485 case Builtin::BI__sync_lock_release_8:
5486 case Builtin::BI__sync_lock_release_16:
5487 BuiltinIndex = 15;
5488 NumFixed = 0;
5489 ResultType = Context.VoidTy;
5490 break;
5491
5492 case Builtin::BI__sync_swap:
5493 case Builtin::BI__sync_swap_1:
5494 case Builtin::BI__sync_swap_2:
5495 case Builtin::BI__sync_swap_4:
5496 case Builtin::BI__sync_swap_8:
5497 case Builtin::BI__sync_swap_16:
5498 BuiltinIndex = 16;
5499 break;
5500 }
5501
5502 // Now that we know how many fixed arguments we expect, first check that we
5503 // have at least that many.
5504 if (TheCall->getNumArgs() < 1+NumFixed) {
5505 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5506 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5507 << Callee->getSourceRange();
5508 return ExprError();
5509 }
5510
5511 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5512 << Callee->getSourceRange();
5513
5514 if (WarnAboutSemanticsChange) {
5515 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5516 << Callee->getSourceRange();
5517 }
5518
5519 // Get the decl for the concrete builtin from this, we can tell what the
5520 // concrete integer type we should convert to is.
5521 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5522 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5523 FunctionDecl *NewBuiltinDecl;
5524 if (NewBuiltinID == BuiltinID)
5525 NewBuiltinDecl = FDecl;
5526 else {
5527 // Perform builtin lookup to avoid redeclaring it.
5528 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5529 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5530 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5531 assert(Res.getFoundDecl());
5532 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5533 if (!NewBuiltinDecl)
5534 return ExprError();
5535 }
5536
5537 // The first argument --- the pointer --- has a fixed type; we
5538 // deduce the types of the rest of the arguments accordingly. Walk
5539 // the remaining arguments, converting them to the deduced value type.
5540 for (unsigned i = 0; i != NumFixed; ++i) {
5541 ExprResult Arg = TheCall->getArg(Arg: i+1);
5542
5543 // GCC does an implicit conversion to the pointer or integer ValType. This
5544 // can fail in some cases (1i -> int**), check for this error case now.
5545 // Initialize the argument.
5546 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5547 Type: ValType, /*consume*/ Consumed: false);
5548 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5549 if (Arg.isInvalid())
5550 return ExprError();
5551
5552 // Okay, we have something that *can* be converted to the right type. Check
5553 // to see if there is a potentially weird extension going on here. This can
5554 // happen when you do an atomic operation on something like an char* and
5555 // pass in 42. The 42 gets converted to char. This is even more strange
5556 // for things like 45.123 -> char, etc.
5557 // FIXME: Do this check.
5558 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
5559 }
5560
5561 // Create a new DeclRefExpr to refer to the new decl.
5562 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5563 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
5564 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
5565 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
5566
5567 // Set the callee in the CallExpr.
5568 // FIXME: This loses syntactic information.
5569 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
5570 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
5571 CK: CK_BuiltinFnToFnPtr);
5572 TheCall->setCallee(PromotedCall.get());
5573
5574 // Change the result type of the call to match the original value type. This
5575 // is arbitrary, but the codegen for these builtins ins design to handle it
5576 // gracefully.
5577 TheCall->setType(ResultType);
5578
5579 // Prohibit problematic uses of bit-precise integer types with atomic
5580 // builtins. The arguments would have already been converted to the first
5581 // argument's type, so only need to check the first argument.
5582 const auto *BitIntValType = ValType->getAs<BitIntType>();
5583 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
5584 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
5585 return ExprError();
5586 }
5587
5588 return TheCallResult;
5589}
5590
5591ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5592 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5593 DeclRefExpr *DRE =
5594 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5595 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5596 unsigned BuiltinID = FDecl->getBuiltinID();
5597 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5598 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5599 "Unexpected nontemporal load/store builtin!");
5600 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5601 unsigned numArgs = isStore ? 2 : 1;
5602
5603 // Ensure that we have the proper number of arguments.
5604 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
5605 return ExprError();
5606
5607 // Inspect the last argument of the nontemporal builtin. This should always
5608 // be a pointer type, from which we imply the type of the memory access.
5609 // Because it is a pointer type, we don't have to worry about any implicit
5610 // casts here.
5611 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
5612 ExprResult PointerArgResult =
5613 DefaultFunctionArrayLvalueConversion(E: PointerArg);
5614
5615 if (PointerArgResult.isInvalid())
5616 return ExprError();
5617 PointerArg = PointerArgResult.get();
5618 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
5619
5620 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5621 if (!pointerType) {
5622 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
5623 << PointerArg->getType() << PointerArg->getSourceRange();
5624 return ExprError();
5625 }
5626
5627 QualType ValType = pointerType->getPointeeType();
5628
5629 // Strip any qualifiers off ValType.
5630 ValType = ValType.getUnqualifiedType();
5631 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5632 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5633 !ValType->isVectorType()) {
5634 Diag(Loc: DRE->getBeginLoc(),
5635 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5636 << PointerArg->getType() << PointerArg->getSourceRange();
5637 return ExprError();
5638 }
5639
5640 if (!isStore) {
5641 TheCall->setType(ValType);
5642 return TheCallResult;
5643 }
5644
5645 ExprResult ValArg = TheCall->getArg(Arg: 0);
5646 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5647 Context, Type: ValType, /*consume*/ Consumed: false);
5648 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
5649 if (ValArg.isInvalid())
5650 return ExprError();
5651
5652 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
5653 TheCall->setType(Context.VoidTy);
5654 return TheCallResult;
5655}
5656
5657/// CheckObjCString - Checks that the format string argument to the os_log()
5658/// and os_trace() functions is correct, and converts it to const char *.
5659ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5660 Arg = Arg->IgnoreParenCasts();
5661 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
5662 if (!Literal) {
5663 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
5664 Literal = ObjcLiteral->getString();
5665 }
5666 }
5667
5668 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5669 return ExprError(
5670 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
5671 << Arg->getSourceRange());
5672 }
5673
5674 ExprResult Result(Literal);
5675 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
5676 InitializedEntity Entity =
5677 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
5678 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
5679 return Result;
5680}
5681
5682/// Check that the user is calling the appropriate va_start builtin for the
5683/// target and calling convention.
5684static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5685 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5686 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5687 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5688 TT.getArch() == llvm::Triple::aarch64_32);
5689 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5690 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5691 if (IsX64 || IsAArch64) {
5692 CallingConv CC = CC_C;
5693 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5694 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5695 if (IsMSVAStart) {
5696 // Don't allow this in System V ABI functions.
5697 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5698 return S.Diag(Loc: Fn->getBeginLoc(),
5699 DiagID: diag::err_ms_va_start_used_in_sysv_function);
5700 } else {
5701 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5702 // On x64 Windows, don't allow this in System V ABI functions.
5703 // (Yes, that means there's no corresponding way to support variadic
5704 // System V ABI functions on Windows.)
5705 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5706 (!IsWindowsOrUEFI && CC == CC_Win64))
5707 return S.Diag(Loc: Fn->getBeginLoc(),
5708 DiagID: diag::err_va_start_used_in_wrong_abi_function)
5709 << !IsWindowsOrUEFI;
5710 }
5711 return false;
5712 }
5713
5714 if (IsMSVAStart)
5715 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
5716 return false;
5717}
5718
5719static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5720 ParmVarDecl **LastParam = nullptr) {
5721 // Determine whether the current function, block, or obj-c method is variadic
5722 // and get its parameter list.
5723 bool IsVariadic = false;
5724 ArrayRef<ParmVarDecl *> Params;
5725 DeclContext *Caller = S.CurContext;
5726 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
5727 IsVariadic = Block->isVariadic();
5728 Params = Block->parameters();
5729 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
5730 IsVariadic = FD->isVariadic();
5731 Params = FD->parameters();
5732 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
5733 IsVariadic = MD->isVariadic();
5734 // FIXME: This isn't correct for methods (results in bogus warning).
5735 Params = MD->parameters();
5736 } else if (isa<CapturedDecl>(Val: Caller)) {
5737 // We don't support va_start in a CapturedDecl.
5738 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
5739 return true;
5740 } else {
5741 // This must be some other declcontext that parses exprs.
5742 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
5743 return true;
5744 }
5745
5746 if (!IsVariadic) {
5747 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
5748 return true;
5749 }
5750
5751 if (LastParam)
5752 *LastParam = Params.empty() ? nullptr : Params.back();
5753
5754 return false;
5755}
5756
5757bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5758 Expr *Fn = TheCall->getCallee();
5759 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
5760 return true;
5761
5762 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5763 // This builtin requires one argument (the va_list), allows two arguments,
5764 // but diagnoses more than two arguments. e.g.,
5765 // __builtin_c23_va_start(); // error
5766 // __builtin_c23_va_start(list); // ok
5767 // __builtin_c23_va_start(list, param); // ok
5768 // __builtin_c23_va_start(list, anything, anything); // error
5769 // This differs from the GCC behavior in that they accept the last case
5770 // with a warning, but it doesn't seem like a useful behavior to allow.
5771 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
5772 return true;
5773 } else {
5774 // In C23 mode, va_start only needs one argument. However, the builtin still
5775 // requires two arguments (which matches the behavior of the GCC builtin),
5776 // <stdarg.h> passes `0` as the second argument in C23 mode.
5777 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5778 return true;
5779 }
5780
5781 // Type-check the first argument normally.
5782 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
5783 return true;
5784
5785 // Check that the current function is variadic, and get its last parameter.
5786 ParmVarDecl *LastParam;
5787 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
5788 return true;
5789
5790 // Verify that the second argument to the builtin is the last non-variadic
5791 // argument of the current function or method. In C23 mode, if the call is
5792 // not to __builtin_c23_va_start, and the second argument is an integer
5793 // constant expression with value 0, then we don't bother with this check.
5794 // For __builtin_c23_va_start, we only perform the check for the second
5795 // argument being the last argument to the current function if there is a
5796 // second argument present.
5797 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5798 TheCall->getNumArgs() < 2) {
5799 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5800 return false;
5801 }
5802
5803 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
5804 if (std::optional<llvm::APSInt> Val =
5805 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
5806 Val && LangOpts.C23 && *Val == 0 &&
5807 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5808 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5809 return false;
5810 }
5811
5812 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5813 // next block.
5814 QualType Type;
5815 SourceLocation ParamLoc;
5816 bool IsCRegister = false;
5817 bool SecondArgIsLastNonVariadicArgument = false;
5818 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
5819 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
5820 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5821
5822 Type = PV->getType();
5823 ParamLoc = PV->getLocation();
5824 IsCRegister =
5825 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5826 }
5827 }
5828
5829 if (!SecondArgIsLastNonVariadicArgument)
5830 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
5831 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5832 else if (IsCRegister || Type->isReferenceType() ||
5833 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
5834 // Promotable integers are UB, but enumerations need a bit of
5835 // extra checking to see what their promotable type actually is.
5836 if (!Context.isPromotableIntegerType(T: Type))
5837 return false;
5838 const auto *ED = Type->getAsEnumDecl();
5839 if (!ED)
5840 return true;
5841 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
5842 }()) {
5843 unsigned Reason = 0;
5844 if (Type->isReferenceType()) Reason = 1;
5845 else if (IsCRegister) Reason = 2;
5846 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
5847 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
5848 }
5849
5850 return false;
5851}
5852
5853bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5854 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5855 const LangOptions &LO = getLangOpts();
5856
5857 if (LO.CPlusPlus)
5858 return Arg->getType()
5859 .getCanonicalType()
5860 .getTypePtr()
5861 ->getPointeeType()
5862 .withoutLocalFastQualifiers() == Context.CharTy;
5863
5864 // In C, allow aliasing through `char *`, this is required for AArch64 at
5865 // least.
5866 return true;
5867 };
5868
5869 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5870 // const char *named_addr);
5871
5872 Expr *Func = Call->getCallee();
5873
5874 if (Call->getNumArgs() < 3)
5875 return Diag(Loc: Call->getEndLoc(),
5876 DiagID: diag::err_typecheck_call_too_few_args_at_least)
5877 << 0 /*function call*/ << 3 << Call->getNumArgs()
5878 << /*is non object*/ 0;
5879
5880 // Type-check the first argument normally.
5881 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
5882 return true;
5883
5884 // Check that the current function is variadic.
5885 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
5886 return true;
5887
5888 // __va_start on Windows does not validate the parameter qualifiers
5889
5890 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
5891 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5892
5893 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
5894 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5895
5896 const QualType &ConstCharPtrTy =
5897 Context.getPointerType(T: Context.CharTy.withConst());
5898 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5899 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5900 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5901 << 0 /* qualifier difference */
5902 << 3 /* parameter mismatch */
5903 << 2 << Arg1->getType() << ConstCharPtrTy;
5904
5905 const QualType SizeTy = Context.getSizeType();
5906 if (!Context.hasSameType(
5907 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
5908 T2: SizeTy))
5909 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5910 << Arg2->getType() << SizeTy << 1 /* different class */
5911 << 0 /* qualifier difference */
5912 << 3 /* parameter mismatch */
5913 << 3 << Arg2->getType() << SizeTy;
5914
5915 return false;
5916}
5917
5918bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5919 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5920 return true;
5921
5922 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5923 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
5924 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5925 << 1 << 0 << TheCall->getSourceRange();
5926
5927 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
5928 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
5929
5930 // Do standard promotions between the two arguments, returning their common
5931 // type.
5932 QualType Res = UsualArithmeticConversions(
5933 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
5934 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5935 return true;
5936
5937 // Make sure any conversions are pushed back into the call; this is
5938 // type safe since unordered compare builtins are declared as "_Bool
5939 // foo(...)".
5940 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
5941 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
5942
5943 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5944 return false;
5945
5946 // If the common type isn't a real floating type, then the arguments were
5947 // invalid for this operation.
5948 if (Res.isNull() || !Res->isRealFloatingType())
5949 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
5950 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
5951 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5952 << SourceRange(OrigArg0.get()->getBeginLoc(),
5953 OrigArg1.get()->getEndLoc());
5954
5955 return false;
5956}
5957
5958bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5959 unsigned BuiltinID) {
5960 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
5961 return true;
5962
5963 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
5964 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5965 BuiltinID == Builtin::BI__builtin_isinf ||
5966 BuiltinID == Builtin::BI__builtin_isinf_sign))
5967 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5968 << 0 << 0 << TheCall->getSourceRange();
5969
5970 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5971 BuiltinID == Builtin::BI__builtin_isunordered))
5972 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5973 << 1 << 0 << TheCall->getSourceRange();
5974
5975 bool IsFPClass = NumArgs == 2;
5976
5977 // Find out position of floating-point argument.
5978 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5979
5980 // We can count on all parameters preceding the floating-point just being int.
5981 // Try all of those.
5982 for (unsigned i = 0; i < FPArgNo; ++i) {
5983 Expr *Arg = TheCall->getArg(Arg: i);
5984
5985 if (Arg->isTypeDependent())
5986 return false;
5987
5988 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
5989 Action: AssignmentAction::Passing);
5990
5991 if (Res.isInvalid())
5992 return true;
5993 TheCall->setArg(Arg: i, ArgExpr: Res.get());
5994 }
5995
5996 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
5997
5998 if (OrigArg->isTypeDependent())
5999 return false;
6000
6001 // Usual Unary Conversions will convert half to float, which we want for
6002 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6003 // type how it is, but do normal L->Rvalue conversions.
6004 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6005 ExprResult Res = UsualUnaryConversions(E: OrigArg);
6006
6007 if (!Res.isUsable())
6008 return true;
6009 OrigArg = Res.get();
6010 } else {
6011 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6012
6013 if (!Res.isUsable())
6014 return true;
6015 OrigArg = Res.get();
6016 }
6017 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6018
6019 QualType VectorResultTy;
6020 QualType ElementTy = OrigArg->getType();
6021 // TODO: When all classification function are implemented with is_fpclass,
6022 // vector argument can be supported in all of them.
6023 if (ElementTy->isVectorType() && IsFPClass) {
6024 VectorResultTy = GetSignedVectorType(V: ElementTy);
6025 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6026 }
6027
6028 // This operation requires a non-_Complex floating-point number.
6029 if (!ElementTy->isRealFloatingType())
6030 return Diag(Loc: OrigArg->getBeginLoc(),
6031 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6032 << OrigArg->getType() << OrigArg->getSourceRange();
6033
6034 // __builtin_isfpclass has integer parameter that specify test mask. It is
6035 // passed in (...), so it should be analyzed completely here.
6036 if (IsFPClass)
6037 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6038 return true;
6039
6040 // TODO: enable this code to all classification functions.
6041 if (IsFPClass) {
6042 QualType ResultTy;
6043 if (!VectorResultTy.isNull())
6044 ResultTy = VectorResultTy;
6045 else
6046 ResultTy = Context.IntTy;
6047 TheCall->setType(ResultTy);
6048 }
6049
6050 return false;
6051}
6052
6053bool Sema::BuiltinComplex(CallExpr *TheCall) {
6054 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6055 return true;
6056
6057 bool Dependent = false;
6058 for (unsigned I = 0; I != 2; ++I) {
6059 Expr *Arg = TheCall->getArg(Arg: I);
6060 QualType T = Arg->getType();
6061 if (T->isDependentType()) {
6062 Dependent = true;
6063 continue;
6064 }
6065
6066 // Despite supporting _Complex int, GCC requires a real floating point type
6067 // for the operands of __builtin_complex.
6068 if (!T->isRealFloatingType()) {
6069 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6070 << Arg->getType() << Arg->getSourceRange();
6071 }
6072
6073 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6074 if (Converted.isInvalid())
6075 return true;
6076 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6077 }
6078
6079 if (Dependent) {
6080 TheCall->setType(Context.DependentTy);
6081 return false;
6082 }
6083
6084 Expr *Real = TheCall->getArg(Arg: 0);
6085 Expr *Imag = TheCall->getArg(Arg: 1);
6086 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6087 return Diag(Loc: Real->getBeginLoc(),
6088 DiagID: diag::err_typecheck_call_different_arg_types)
6089 << Real->getType() << Imag->getType()
6090 << Real->getSourceRange() << Imag->getSourceRange();
6091 }
6092
6093 TheCall->setType(Context.getComplexType(T: Real->getType()));
6094 return false;
6095}
6096
6097/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6098// This is declared to take (...), so we have to check everything.
6099ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6100 unsigned NumArgs = TheCall->getNumArgs();
6101 if (NumArgs < 2)
6102 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6103 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6104 << 0 /*function call*/ << 2 << NumArgs
6105 << /*is non object*/ 0 << TheCall->getSourceRange());
6106
6107 // Determine which of the following types of shufflevector we're checking:
6108 // 1) unary, vector mask: (lhs, mask)
6109 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6110 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6111 unsigned NumElements = 0;
6112
6113 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6114 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6115 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6116 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6117
6118 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6119 return ExprError(
6120 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6121 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6122 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6123 TheCall->getArg(Arg: 1)->getEndLoc()));
6124
6125 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6126 unsigned NumResElements = NumArgs - 2;
6127
6128 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6129 // with mask. If so, verify that RHS is an integer vector type with the
6130 // same number of elts as lhs.
6131 if (NumArgs == 2) {
6132 if (!RHSType->hasIntegerRepresentation() ||
6133 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6134 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6135 DiagID: diag::err_vec_builtin_incompatible_vector)
6136 << TheCall->getDirectCallee()
6137 << /*isMoreThanTwoArgs*/ false
6138 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6139 TheCall->getArg(Arg: 1)->getEndLoc()));
6140 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6141 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6142 DiagID: diag::err_vec_builtin_incompatible_vector)
6143 << TheCall->getDirectCallee()
6144 << /*isMoreThanTwoArgs*/ false
6145 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6146 TheCall->getArg(Arg: 1)->getEndLoc()));
6147 } else if (NumElements != NumResElements) {
6148 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6149 ResType = ResType->isExtVectorType()
6150 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6151 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6152 VecKind: VectorKind::Generic);
6153 }
6154 }
6155
6156 for (unsigned I = 2; I != NumArgs; ++I) {
6157 Expr *Arg = TheCall->getArg(Arg: I);
6158 if (Arg->isTypeDependent() || Arg->isValueDependent())
6159 continue;
6160
6161 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6162 if (!Result)
6163 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6164 DiagID: diag::err_shufflevector_nonconstant_argument)
6165 << Arg->getSourceRange());
6166
6167 // Allow -1 which will be translated to undef in the IR.
6168 if (Result->isSigned() && Result->isAllOnes())
6169 ;
6170 else if (Result->getActiveBits() > 64 ||
6171 Result->getZExtValue() >= NumElements * 2)
6172 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6173 DiagID: diag::err_shufflevector_argument_too_large)
6174 << Arg->getSourceRange());
6175
6176 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6177 }
6178
6179 auto *Result = new (Context) ShuffleVectorExpr(
6180 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6181 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6182
6183 // All moved to Result.
6184 TheCall->shrinkNumArgs(NewNumArgs: 0);
6185 return Result;
6186}
6187
6188ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6189 SourceLocation BuiltinLoc,
6190 SourceLocation RParenLoc) {
6191 ExprValueKind VK = VK_PRValue;
6192 ExprObjectKind OK = OK_Ordinary;
6193 QualType DstTy = TInfo->getType();
6194 QualType SrcTy = E->getType();
6195
6196 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6197 return ExprError(Diag(Loc: BuiltinLoc,
6198 DiagID: diag::err_convertvector_non_vector)
6199 << E->getSourceRange());
6200 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6201 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6202 << "second"
6203 << "__builtin_convertvector");
6204
6205 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6206 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6207 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6208 if (SrcElts != DstElts)
6209 return ExprError(Diag(Loc: BuiltinLoc,
6210 DiagID: diag::err_convertvector_incompatible_vector)
6211 << E->getSourceRange());
6212 }
6213
6214 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6215 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6216}
6217
6218bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6219 unsigned NumArgs = TheCall->getNumArgs();
6220
6221 if (NumArgs > 3)
6222 return Diag(Loc: TheCall->getEndLoc(),
6223 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6224 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6225 << TheCall->getSourceRange();
6226
6227 // Argument 0 is checked for us and the remaining arguments must be
6228 // constant integers.
6229 for (unsigned i = 1; i != NumArgs; ++i)
6230 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6231 return true;
6232
6233 return false;
6234}
6235
6236bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6237 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6238 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6239 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6240 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6241 return true;
6242 Expr *Arg = TheCall->getArg(Arg: 0);
6243 if (Arg->isInstantiationDependent())
6244 return false;
6245
6246 QualType ArgTy = Arg->getType();
6247 if (!ArgTy->hasFloatingRepresentation())
6248 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6249 << ArgTy;
6250 if (Arg->isLValue()) {
6251 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6252 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6253 }
6254 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6255 return false;
6256}
6257
6258bool Sema::BuiltinAssume(CallExpr *TheCall) {
6259 Expr *Arg = TheCall->getArg(Arg: 0);
6260 if (Arg->isInstantiationDependent()) return false;
6261
6262 if (Arg->HasSideEffects(Ctx: Context))
6263 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6264 << Arg->getSourceRange()
6265 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6266
6267 return false;
6268}
6269
6270bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6271 // The alignment must be a constant integer.
6272 Expr *Arg = TheCall->getArg(Arg: 1);
6273
6274 // We can't check the value of a dependent argument.
6275 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6276 if (const auto *UE =
6277 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6278 if (UE->getKind() == UETT_AlignOf ||
6279 UE->getKind() == UETT_PreferredAlignOf)
6280 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6281 << Arg->getSourceRange();
6282
6283 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6284
6285 if (!Result.isPowerOf2())
6286 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6287 << Arg->getSourceRange();
6288
6289 if (Result < Context.getCharWidth())
6290 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6291 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6292
6293 if (Result > std::numeric_limits<int32_t>::max())
6294 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6295 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6296 }
6297
6298 return false;
6299}
6300
6301bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6302 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6303 return true;
6304
6305 unsigned NumArgs = TheCall->getNumArgs();
6306 Expr *FirstArg = TheCall->getArg(Arg: 0);
6307
6308 {
6309 ExprResult FirstArgResult =
6310 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6311 if (!FirstArgResult.get()->getType()->isPointerType()) {
6312 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6313 << TheCall->getSourceRange();
6314 return true;
6315 }
6316 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6317 }
6318
6319 // The alignment must be a constant integer.
6320 Expr *SecondArg = TheCall->getArg(Arg: 1);
6321
6322 // We can't check the value of a dependent argument.
6323 if (!SecondArg->isValueDependent()) {
6324 llvm::APSInt Result;
6325 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6326 return true;
6327
6328 if (!Result.isPowerOf2())
6329 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6330 << SecondArg->getSourceRange();
6331
6332 if (Result > Sema::MaximumAlignment)
6333 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6334 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6335
6336 TheCall->setArg(Arg: 1,
6337 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6338 }
6339
6340 if (NumArgs > 2) {
6341 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6342 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6343 return true;
6344 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6345 }
6346
6347 return false;
6348}
6349
6350bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6351 unsigned BuiltinID =
6352 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6353 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6354
6355 unsigned NumArgs = TheCall->getNumArgs();
6356 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6357 if (NumArgs < NumRequiredArgs) {
6358 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6359 << 0 /* function call */ << NumRequiredArgs << NumArgs
6360 << /*is non object*/ 0 << TheCall->getSourceRange();
6361 }
6362 if (NumArgs >= NumRequiredArgs + 0x100) {
6363 return Diag(Loc: TheCall->getEndLoc(),
6364 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6365 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6366 << /*is non object*/ 0 << TheCall->getSourceRange();
6367 }
6368 unsigned i = 0;
6369
6370 // For formatting call, check buffer arg.
6371 if (!IsSizeCall) {
6372 ExprResult Arg(TheCall->getArg(Arg: i));
6373 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6374 Context, Type: Context.VoidPtrTy, Consumed: false);
6375 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6376 if (Arg.isInvalid())
6377 return true;
6378 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6379 i++;
6380 }
6381
6382 // Check string literal arg.
6383 unsigned FormatIdx = i;
6384 {
6385 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6386 if (Arg.isInvalid())
6387 return true;
6388 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6389 i++;
6390 }
6391
6392 // Make sure variadic args are scalar.
6393 unsigned FirstDataArg = i;
6394 while (i < NumArgs) {
6395 ExprResult Arg = DefaultVariadicArgumentPromotion(
6396 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6397 if (Arg.isInvalid())
6398 return true;
6399 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6400 if (ArgSize.getQuantity() >= 0x100) {
6401 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6402 << i << (int)ArgSize.getQuantity() << 0xff
6403 << TheCall->getSourceRange();
6404 }
6405 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6406 i++;
6407 }
6408
6409 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6410 // call to avoid duplicate diagnostics.
6411 if (!IsSizeCall) {
6412 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6413 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6414 bool Success = CheckFormatArguments(
6415 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6416 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6417 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6418 if (!Success)
6419 return true;
6420 }
6421
6422 if (IsSizeCall) {
6423 TheCall->setType(Context.getSizeType());
6424 } else {
6425 TheCall->setType(Context.VoidPtrTy);
6426 }
6427 return false;
6428}
6429
6430bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6431 llvm::APSInt &Result) {
6432 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6433
6434 if (Arg->isTypeDependent() || Arg->isValueDependent())
6435 return false;
6436
6437 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6438 if (!R) {
6439 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6440 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6441 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6442 << FDecl->getDeclName() << Arg->getSourceRange();
6443 }
6444 Result = *R;
6445
6446 return false;
6447}
6448
6449bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6450 int High, bool RangeIsError) {
6451 if (isConstantEvaluatedContext())
6452 return false;
6453 llvm::APSInt Result;
6454
6455 // We can't check the value of a dependent argument.
6456 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6457 if (Arg->isTypeDependent() || Arg->isValueDependent())
6458 return false;
6459
6460 // Check constant-ness first.
6461 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6462 return true;
6463
6464 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6465 if (RangeIsError)
6466 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6467 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6468 else
6469 // Defer the warning until we know if the code will be emitted so that
6470 // dead code can ignore this.
6471 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6472 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6473 << toString(I: Result, Radix: 10) << Low << High
6474 << Arg->getSourceRange());
6475 }
6476
6477 return false;
6478}
6479
6480bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6481 unsigned Num) {
6482 llvm::APSInt Result;
6483
6484 // We can't check the value of a dependent argument.
6485 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6486 if (Arg->isTypeDependent() || Arg->isValueDependent())
6487 return false;
6488
6489 // Check constant-ness first.
6490 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6491 return true;
6492
6493 if (Result.getSExtValue() % Num != 0)
6494 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6495 << Num << Arg->getSourceRange();
6496
6497 return false;
6498}
6499
6500bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6501 llvm::APSInt Result;
6502
6503 // We can't check the value of a dependent argument.
6504 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6505 if (Arg->isTypeDependent() || Arg->isValueDependent())
6506 return false;
6507
6508 // Check constant-ness first.
6509 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6510 return true;
6511
6512 if (Result.isPowerOf2())
6513 return false;
6514
6515 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6516 << Arg->getSourceRange();
6517}
6518
6519static bool IsShiftedByte(llvm::APSInt Value) {
6520 if (Value.isNegative())
6521 return false;
6522
6523 // Check if it's a shifted byte, by shifting it down
6524 while (true) {
6525 // If the value fits in the bottom byte, the check passes.
6526 if (Value < 0x100)
6527 return true;
6528
6529 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6530 // fails.
6531 if ((Value & 0xFF) != 0)
6532 return false;
6533
6534 // If the bottom 8 bits are all 0, but something above that is nonzero,
6535 // then shifting the value right by 8 bits won't affect whether it's a
6536 // shifted byte or not. So do that, and go round again.
6537 Value >>= 8;
6538 }
6539}
6540
6541bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6542 unsigned ArgBits) {
6543 llvm::APSInt Result;
6544
6545 // We can't check the value of a dependent argument.
6546 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6547 if (Arg->isTypeDependent() || Arg->isValueDependent())
6548 return false;
6549
6550 // Check constant-ness first.
6551 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6552 return true;
6553
6554 // Truncate to the given size.
6555 Result = Result.getLoBits(numBits: ArgBits);
6556 Result.setIsUnsigned(true);
6557
6558 if (IsShiftedByte(Value: Result))
6559 return false;
6560
6561 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
6562 << Arg->getSourceRange();
6563}
6564
6565bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6566 unsigned ArgNum,
6567 unsigned ArgBits) {
6568 llvm::APSInt Result;
6569
6570 // We can't check the value of a dependent argument.
6571 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6572 if (Arg->isTypeDependent() || Arg->isValueDependent())
6573 return false;
6574
6575 // Check constant-ness first.
6576 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6577 return true;
6578
6579 // Truncate to the given size.
6580 Result = Result.getLoBits(numBits: ArgBits);
6581 Result.setIsUnsigned(true);
6582
6583 // Check to see if it's in either of the required forms.
6584 if (IsShiftedByte(Value: Result) ||
6585 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6586 return false;
6587
6588 return Diag(Loc: TheCall->getBeginLoc(),
6589 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
6590 << Arg->getSourceRange();
6591}
6592
6593bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6594 if (!Context.getTargetInfo().hasSjLjLowering())
6595 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
6596 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6597
6598 Expr *Arg = TheCall->getArg(Arg: 1);
6599 llvm::APSInt Result;
6600
6601 // TODO: This is less than ideal. Overload this to take a value.
6602 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6603 return true;
6604
6605 if (Result != 1)
6606 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
6607 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6608
6609 return false;
6610}
6611
6612bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6613 if (!Context.getTargetInfo().hasSjLjLowering())
6614 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
6615 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6616 return false;
6617}
6618
6619bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6620 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6621 return true;
6622
6623 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
6624 if (ArgRes.isInvalid())
6625 return true;
6626
6627 // For simplicity, we support only limited expressions for the argument.
6628 // Specifically a flexible array member or a pointer with counted_by:
6629 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6630 // complex casting, which really shouldn't be a huge problem.
6631 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6632 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6633 return Diag(Loc: Arg->getBeginLoc(),
6634 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6635 << Arg->getSourceRange();
6636
6637 if (Arg->HasSideEffects(Ctx: Context))
6638 return Diag(Loc: Arg->getBeginLoc(),
6639 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
6640 << Arg->getSourceRange();
6641
6642 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
6643 const auto *CATy =
6644 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6645
6646 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6647 // Member has counted_by attribute - return pointer to count field
6648 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
6649 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6650 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
6651 return false;
6652 }
6653 }
6654
6655 // FAMs and pointers without counted_by return void*
6656 QualType MemberTy = ME->getMemberDecl()->getType();
6657 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6658 return Diag(Loc: Arg->getBeginLoc(),
6659 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6660 << Arg->getSourceRange();
6661 } else {
6662 return Diag(Loc: Arg->getBeginLoc(),
6663 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6664 << Arg->getSourceRange();
6665 }
6666
6667 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
6668 return false;
6669}
6670
6671/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6672/// It allows leaking and modification of bounds safety information.
6673bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6674 BuiltinCountedByRefKind K) {
6675 const CallExpr *CE =
6676 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
6677 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6678 return false;
6679
6680 switch (K) {
6681 case BuiltinCountedByRefKind::Assignment:
6682 case BuiltinCountedByRefKind::Initializer:
6683 Diag(Loc: E->getExprLoc(),
6684 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6685 << 0 << E->getSourceRange();
6686 break;
6687 case BuiltinCountedByRefKind::FunctionArg:
6688 Diag(Loc: E->getExprLoc(),
6689 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6690 << 1 << E->getSourceRange();
6691 break;
6692 case BuiltinCountedByRefKind::ReturnArg:
6693 Diag(Loc: E->getExprLoc(),
6694 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6695 << 2 << E->getSourceRange();
6696 break;
6697 case BuiltinCountedByRefKind::ArraySubscript:
6698 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6699 << 0 << E->getSourceRange();
6700 break;
6701 case BuiltinCountedByRefKind::BinaryExpr:
6702 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6703 << 1 << E->getSourceRange();
6704 break;
6705 }
6706
6707 return true;
6708}
6709
6710namespace {
6711
6712class UncoveredArgHandler {
6713 enum { Unknown = -1, AllCovered = -2 };
6714
6715 signed FirstUncoveredArg = Unknown;
6716 SmallVector<const Expr *, 4> DiagnosticExprs;
6717
6718public:
6719 UncoveredArgHandler() = default;
6720
6721 bool hasUncoveredArg() const {
6722 return (FirstUncoveredArg >= 0);
6723 }
6724
6725 unsigned getUncoveredArg() const {
6726 assert(hasUncoveredArg() && "no uncovered argument");
6727 return FirstUncoveredArg;
6728 }
6729
6730 void setAllCovered() {
6731 // A string has been found with all arguments covered, so clear out
6732 // the diagnostics.
6733 DiagnosticExprs.clear();
6734 FirstUncoveredArg = AllCovered;
6735 }
6736
6737 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6738 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6739
6740 // Don't update if a previous string covers all arguments.
6741 if (FirstUncoveredArg == AllCovered)
6742 return;
6743
6744 // UncoveredArgHandler tracks the highest uncovered argument index
6745 // and with it all the strings that match this index.
6746 if (NewFirstUncoveredArg == FirstUncoveredArg)
6747 DiagnosticExprs.push_back(Elt: StrExpr);
6748 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6749 DiagnosticExprs.clear();
6750 DiagnosticExprs.push_back(Elt: StrExpr);
6751 FirstUncoveredArg = NewFirstUncoveredArg;
6752 }
6753 }
6754
6755 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6756};
6757
6758enum StringLiteralCheckType {
6759 SLCT_NotALiteral,
6760 SLCT_UncheckedLiteral,
6761 SLCT_CheckedLiteral
6762};
6763
6764} // namespace
6765
6766static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6767 BinaryOperatorKind BinOpKind,
6768 bool AddendIsRight) {
6769 unsigned BitWidth = Offset.getBitWidth();
6770 unsigned AddendBitWidth = Addend.getBitWidth();
6771 // There might be negative interim results.
6772 if (Addend.isUnsigned()) {
6773 Addend = Addend.zext(width: ++AddendBitWidth);
6774 Addend.setIsSigned(true);
6775 }
6776 // Adjust the bit width of the APSInts.
6777 if (AddendBitWidth > BitWidth) {
6778 Offset = Offset.sext(width: AddendBitWidth);
6779 BitWidth = AddendBitWidth;
6780 } else if (BitWidth > AddendBitWidth) {
6781 Addend = Addend.sext(width: BitWidth);
6782 }
6783
6784 bool Ov = false;
6785 llvm::APSInt ResOffset = Offset;
6786 if (BinOpKind == BO_Add)
6787 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
6788 else {
6789 assert(AddendIsRight && BinOpKind == BO_Sub &&
6790 "operator must be add or sub with addend on the right");
6791 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
6792 }
6793
6794 // We add an offset to a pointer here so we should support an offset as big as
6795 // possible.
6796 if (Ov) {
6797 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6798 "index (intermediate) result too big");
6799 Offset = Offset.sext(width: 2 * BitWidth);
6800 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6801 return;
6802 }
6803
6804 Offset = std::move(ResOffset);
6805}
6806
6807namespace {
6808
6809// This is a wrapper class around StringLiteral to support offsetted string
6810// literals as format strings. It takes the offset into account when returning
6811// the string and its length or the source locations to display notes correctly.
6812class FormatStringLiteral {
6813 const StringLiteral *FExpr;
6814 int64_t Offset;
6815
6816public:
6817 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6818 : FExpr(fexpr), Offset(Offset) {}
6819
6820 const StringLiteral *getFormatString() const { return FExpr; }
6821
6822 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
6823
6824 unsigned getByteLength() const {
6825 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6826 }
6827
6828 unsigned getLength() const { return FExpr->getLength() - Offset; }
6829 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6830
6831 StringLiteralKind getKind() const { return FExpr->getKind(); }
6832
6833 QualType getType() const { return FExpr->getType(); }
6834
6835 bool isAscii() const { return FExpr->isOrdinary(); }
6836 bool isWide() const { return FExpr->isWide(); }
6837 bool isUTF8() const { return FExpr->isUTF8(); }
6838 bool isUTF16() const { return FExpr->isUTF16(); }
6839 bool isUTF32() const { return FExpr->isUTF32(); }
6840 bool isPascal() const { return FExpr->isPascal(); }
6841
6842 SourceLocation getLocationOfByte(
6843 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6844 const TargetInfo &Target, unsigned *StartToken = nullptr,
6845 unsigned *StartTokenByteOffset = nullptr) const {
6846 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
6847 StartToken, StartTokenByteOffset);
6848 }
6849
6850 SourceLocation getBeginLoc() const LLVM_READONLY {
6851 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6852 }
6853
6854 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6855};
6856
6857} // namespace
6858
6859static void CheckFormatString(
6860 Sema &S, const FormatStringLiteral *FExpr,
6861 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6862 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
6863 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6864 bool inFunctionCall, VariadicCallType CallType,
6865 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6866 bool IgnoreStringsWithoutSpecifiers);
6867
6868static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6869 const Expr *E);
6870
6871// Determine if an expression is a string literal or constant string.
6872// If this function returns false on the arguments to a function expecting a
6873// format string, we will usually need to emit a warning.
6874// True string literals are then checked by CheckFormatString.
6875static StringLiteralCheckType
6876checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6877 const Expr *E, ArrayRef<const Expr *> Args,
6878 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6879 unsigned firstDataArg, FormatStringType Type,
6880 VariadicCallType CallType, bool InFunctionCall,
6881 llvm::SmallBitVector &CheckedVarArgs,
6882 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6883 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6884 bool IgnoreStringsWithoutSpecifiers = false) {
6885 if (S.isConstantEvaluatedContext())
6886 return SLCT_NotALiteral;
6887tryAgain:
6888 assert(Offset.isSigned() && "invalid offset");
6889
6890 if (E->isTypeDependent() || E->isValueDependent())
6891 return SLCT_NotALiteral;
6892
6893 E = E->IgnoreParenCasts();
6894
6895 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
6896 // Technically -Wformat-nonliteral does not warn about this case.
6897 // The behavior of printf and friends in this case is implementation
6898 // dependent. Ideally if the format string cannot be null then
6899 // it should have a 'nonnull' attribute in the function prototype.
6900 return SLCT_UncheckedLiteral;
6901
6902 switch (E->getStmtClass()) {
6903 case Stmt::InitListExprClass:
6904 // Handle expressions like {"foobar"}.
6905 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
6906 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
6907 format_idx, firstDataArg, Type, CallType,
6908 /*InFunctionCall*/ false, CheckedVarArgs,
6909 UncoveredArg, Offset, CallerFormatParamIdx,
6910 IgnoreStringsWithoutSpecifiers);
6911 }
6912 return SLCT_NotALiteral;
6913 case Stmt::BinaryConditionalOperatorClass:
6914 case Stmt::ConditionalOperatorClass: {
6915 // The expression is a literal if both sub-expressions were, and it was
6916 // completely checked only if both sub-expressions were checked.
6917 const AbstractConditionalOperator *C =
6918 cast<AbstractConditionalOperator>(Val: E);
6919
6920 // Determine whether it is necessary to check both sub-expressions, for
6921 // example, because the condition expression is a constant that can be
6922 // evaluated at compile time.
6923 bool CheckLeft = true, CheckRight = true;
6924
6925 bool Cond;
6926 if (C->getCond()->EvaluateAsBooleanCondition(
6927 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
6928 if (Cond)
6929 CheckRight = false;
6930 else
6931 CheckLeft = false;
6932 }
6933
6934 // We need to maintain the offsets for the right and the left hand side
6935 // separately to check if every possible indexed expression is a valid
6936 // string literal. They might have different offsets for different string
6937 // literals in the end.
6938 StringLiteralCheckType Left;
6939 if (!CheckLeft)
6940 Left = SLCT_UncheckedLiteral;
6941 else {
6942 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
6943 Args, APK, format_idx, firstDataArg, Type,
6944 CallType, InFunctionCall, CheckedVarArgs,
6945 UncoveredArg, Offset, CallerFormatParamIdx,
6946 IgnoreStringsWithoutSpecifiers);
6947 if (Left == SLCT_NotALiteral || !CheckRight) {
6948 return Left;
6949 }
6950 }
6951
6952 StringLiteralCheckType Right = checkFormatStringExpr(
6953 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
6954 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6955 UncoveredArg, Offset, CallerFormatParamIdx,
6956 IgnoreStringsWithoutSpecifiers);
6957
6958 return (CheckLeft && Left < Right) ? Left : Right;
6959 }
6960
6961 case Stmt::ImplicitCastExprClass:
6962 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
6963 goto tryAgain;
6964
6965 case Stmt::OpaqueValueExprClass:
6966 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
6967 E = src;
6968 goto tryAgain;
6969 }
6970 return SLCT_NotALiteral;
6971
6972 case Stmt::PredefinedExprClass:
6973 // While __func__, etc., are technically not string literals, they
6974 // cannot contain format specifiers and thus are not a security
6975 // liability.
6976 return SLCT_UncheckedLiteral;
6977
6978 case Stmt::DeclRefExprClass: {
6979 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
6980
6981 // As an exception, do not flag errors for variables binding to
6982 // const string literals.
6983 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
6984 bool isConstant = false;
6985 QualType T = DR->getType();
6986
6987 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6988 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
6989 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6990 isConstant = T.isConstant(Ctx: S.Context) &&
6991 PT->getPointeeType().isConstant(Ctx: S.Context);
6992 } else if (T->isObjCObjectPointerType()) {
6993 // In ObjC, there is usually no "const ObjectPointer" type,
6994 // so don't check if the pointee type is constant.
6995 isConstant = T.isConstant(Ctx: S.Context);
6996 }
6997
6998 if (isConstant) {
6999 if (const Expr *Init = VD->getAnyInitializer()) {
7000 // Look through initializers like const char c[] = { "foo" }
7001 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7002 if (InitList->isStringLiteralInit())
7003 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7004 }
7005 return checkFormatStringExpr(
7006 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7007 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7008 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7009 }
7010 }
7011
7012 // When the format argument is an argument of this function, and this
7013 // function also has the format attribute, there are several interactions
7014 // for which there shouldn't be a warning. For instance, when calling
7015 // v*printf from a function that has the printf format attribute, we
7016 // should not emit a warning about using `fmt`, even though it's not
7017 // constant, because the arguments have already been checked for the
7018 // caller of `logmessage`:
7019 //
7020 // __attribute__((format(printf, 1, 2)))
7021 // void logmessage(char const *fmt, ...) {
7022 // va_list ap;
7023 // va_start(ap, fmt);
7024 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7025 // ...
7026 // }
7027 //
7028 // Another interaction that we need to support is using a format string
7029 // specified by the format_matches attribute:
7030 //
7031 // __attribute__((format_matches(printf, 1, "%s %d")))
7032 // void logmessage(char const *fmt, const char *a, int b) {
7033 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7034 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7035 // ...
7036 // }
7037 //
7038 // Yet another interaction that we need to support is calling a variadic
7039 // format function from a format function that has fixed arguments. For
7040 // instance:
7041 //
7042 // __attribute__((format(printf, 1, 2)))
7043 // void logstring(char const *fmt, char const *str) {
7044 // printf(fmt, str); /* do not emit a warning about "fmt" */
7045 // }
7046 //
7047 // Same (and perhaps more relatably) for the variadic template case:
7048 //
7049 // template<typename... Args>
7050 // __attribute__((format(printf, 1, 2)))
7051 // void log(const char *fmt, Args&&... args) {
7052 // printf(fmt, forward<Args>(args)...);
7053 // /* do not emit a warning about "fmt" */
7054 // }
7055 //
7056 // Due to implementation difficulty, we only check the format, not the
7057 // format arguments, in all cases.
7058 //
7059 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7060 if (CallerFormatParamIdx)
7061 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7062 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7063 for (const auto *PVFormatMatches :
7064 D->specific_attrs<FormatMatchesAttr>()) {
7065 Sema::FormatStringInfo CalleeFSI;
7066 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7067 FirstArg: 0, FSI: &CalleeFSI))
7068 continue;
7069 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7070 // If using the wrong type of format string, emit a diagnostic
7071 // here and stop checking to avoid irrelevant diagnostics.
7072 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7073 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7074 DiagID: diag::warn_format_string_type_incompatible)
7075 << PVFormatMatches->getType()->getName()
7076 << S.GetFormatStringTypeName(FST: Type);
7077 if (!InFunctionCall) {
7078 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7079 DiagID: diag::note_format_string_defined);
7080 }
7081 return SLCT_UncheckedLiteral;
7082 }
7083 return checkFormatStringExpr(
7084 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7085 Args, APK, format_idx, firstDataArg, Type, CallType,
7086 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7087 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7088 }
7089 }
7090
7091 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7092 Sema::FormatStringInfo CallerFSI;
7093 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7094 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7095 continue;
7096 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7097 // We also check if the formats are compatible.
7098 // We can't pass a 'scanf' string to a 'printf' function.
7099 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7100 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7101 DiagID: diag::warn_format_string_type_incompatible)
7102 << PVFormat->getType()->getName()
7103 << S.GetFormatStringTypeName(FST: Type);
7104 if (!InFunctionCall) {
7105 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7106 }
7107 return SLCT_UncheckedLiteral;
7108 }
7109 // Lastly, check that argument passing kinds transition in a
7110 // way that makes sense:
7111 // from a caller with FAPK_VAList, allow FAPK_VAList
7112 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7113 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7114 // from a caller with FAPK_Variadic, allow FAPK_VAList
7115 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7116 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7117 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7118 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7119 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7120 return SLCT_UncheckedLiteral;
7121 }
7122 }
7123 }
7124 }
7125 }
7126 }
7127
7128 return SLCT_NotALiteral;
7129 }
7130
7131 case Stmt::CallExprClass:
7132 case Stmt::CXXMemberCallExprClass: {
7133 const CallExpr *CE = cast<CallExpr>(Val: E);
7134 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7135 bool IsFirst = true;
7136 StringLiteralCheckType CommonResult;
7137 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7138 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7139 StringLiteralCheckType Result = checkFormatStringExpr(
7140 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7141 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7142 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7143 if (IsFirst) {
7144 CommonResult = Result;
7145 IsFirst = false;
7146 }
7147 }
7148 if (!IsFirst)
7149 return CommonResult;
7150
7151 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7152 unsigned BuiltinID = FD->getBuiltinID();
7153 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7154 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7155 const Expr *Arg = CE->getArg(Arg: 0);
7156 return checkFormatStringExpr(
7157 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7158 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7159 UncoveredArg, Offset, CallerFormatParamIdx,
7160 IgnoreStringsWithoutSpecifiers);
7161 }
7162 }
7163 }
7164 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7165 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7166 format_idx, firstDataArg, Type, CallType,
7167 /*InFunctionCall*/ false, CheckedVarArgs,
7168 UncoveredArg, Offset, CallerFormatParamIdx,
7169 IgnoreStringsWithoutSpecifiers);
7170 return SLCT_NotALiteral;
7171 }
7172 case Stmt::ObjCMessageExprClass: {
7173 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7174 if (const auto *MD = ME->getMethodDecl()) {
7175 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7176 // As a special case heuristic, if we're using the method -[NSBundle
7177 // localizedStringForKey:value:table:], ignore any key strings that lack
7178 // format specifiers. The idea is that if the key doesn't have any
7179 // format specifiers then its probably just a key to map to the
7180 // localized strings. If it does have format specifiers though, then its
7181 // likely that the text of the key is the format string in the
7182 // programmer's language, and should be checked.
7183 const ObjCInterfaceDecl *IFace;
7184 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7185 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7186 MD->getSelector().isKeywordSelector(
7187 Names: {"localizedStringForKey", "value", "table"})) {
7188 IgnoreStringsWithoutSpecifiers = true;
7189 }
7190
7191 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7192 return checkFormatStringExpr(
7193 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7194 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7195 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7196 }
7197 }
7198
7199 return SLCT_NotALiteral;
7200 }
7201 case Stmt::ObjCStringLiteralClass:
7202 case Stmt::StringLiteralClass: {
7203 const StringLiteral *StrE = nullptr;
7204
7205 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7206 StrE = ObjCFExpr->getString();
7207 else
7208 StrE = cast<StringLiteral>(Val: E);
7209
7210 if (StrE) {
7211 if (Offset.isNegative() || Offset > StrE->getLength()) {
7212 // TODO: It would be better to have an explicit warning for out of
7213 // bounds literals.
7214 return SLCT_NotALiteral;
7215 }
7216 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7217 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7218 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7219 CallType, CheckedVarArgs, UncoveredArg,
7220 IgnoreStringsWithoutSpecifiers);
7221 return SLCT_CheckedLiteral;
7222 }
7223
7224 return SLCT_NotALiteral;
7225 }
7226 case Stmt::BinaryOperatorClass: {
7227 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7228
7229 // A string literal + an int offset is still a string literal.
7230 if (BinOp->isAdditiveOp()) {
7231 Expr::EvalResult LResult, RResult;
7232
7233 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7234 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7235 InConstantContext: S.isConstantEvaluatedContext());
7236 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7237 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7238 InConstantContext: S.isConstantEvaluatedContext());
7239
7240 if (LIsInt != RIsInt) {
7241 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7242
7243 if (LIsInt) {
7244 if (BinOpKind == BO_Add) {
7245 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7246 E = BinOp->getRHS();
7247 goto tryAgain;
7248 }
7249 } else {
7250 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7251 E = BinOp->getLHS();
7252 goto tryAgain;
7253 }
7254 }
7255 }
7256
7257 return SLCT_NotALiteral;
7258 }
7259 case Stmt::UnaryOperatorClass: {
7260 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7261 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7262 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7263 Expr::EvalResult IndexResult;
7264 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7265 AllowSideEffects: Expr::SE_NoSideEffects,
7266 InConstantContext: S.isConstantEvaluatedContext())) {
7267 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7268 /*RHS is int*/ AddendIsRight: true);
7269 E = ASE->getBase();
7270 goto tryAgain;
7271 }
7272 }
7273
7274 return SLCT_NotALiteral;
7275 }
7276
7277 default:
7278 return SLCT_NotALiteral;
7279 }
7280}
7281
7282// If this expression can be evaluated at compile-time,
7283// check if the result is a StringLiteral and return it
7284// otherwise return nullptr
7285static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7286 const Expr *E) {
7287 Expr::EvalResult Result;
7288 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7289 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7290 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7291 return LVE;
7292 }
7293 return nullptr;
7294}
7295
7296StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7297 switch (FST) {
7298 case FormatStringType::Scanf:
7299 return "scanf";
7300 case FormatStringType::Printf:
7301 return "printf";
7302 case FormatStringType::NSString:
7303 return "NSString";
7304 case FormatStringType::Strftime:
7305 return "strftime";
7306 case FormatStringType::Strfmon:
7307 return "strfmon";
7308 case FormatStringType::Kprintf:
7309 return "kprintf";
7310 case FormatStringType::FreeBSDKPrintf:
7311 return "freebsd_kprintf";
7312 case FormatStringType::OSLog:
7313 return "os_log";
7314 default:
7315 return "<unknown>";
7316 }
7317}
7318
7319FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7320 return llvm::StringSwitch<FormatStringType>(Flavor)
7321 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7322 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7323 Value: FormatStringType::Printf)
7324 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7325 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7326 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7327 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7328 Value: FormatStringType::Kprintf)
7329 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7330 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7331 .Case(S: "os_log", Value: FormatStringType::OSLog)
7332 .Default(Value: FormatStringType::Unknown);
7333}
7334
7335FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7336 return GetFormatStringType(Flavor: Format->getType()->getName());
7337}
7338
7339FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7340 return GetFormatStringType(Flavor: Format->getType()->getName());
7341}
7342
7343bool Sema::CheckFormatArguments(const FormatAttr *Format,
7344 ArrayRef<const Expr *> Args, bool IsCXXMember,
7345 VariadicCallType CallType, SourceLocation Loc,
7346 SourceRange Range,
7347 llvm::SmallBitVector &CheckedVarArgs) {
7348 FormatStringInfo FSI;
7349 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7350 HasImplicitThisParam: IsCXXMember,
7351 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7352 return CheckFormatArguments(
7353 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7354 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7355 return false;
7356}
7357
7358bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7359 ArrayRef<const Expr *> Args, bool IsCXXMember,
7360 VariadicCallType CallType, SourceLocation Loc,
7361 SourceRange Range,
7362 llvm::SmallBitVector &CheckedVarArgs) {
7363 FormatStringInfo FSI;
7364 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7365 FSI: &FSI)) {
7366 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7367 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7368 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7369 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7370 CallType, Loc, range: Range, CheckedVarArgs);
7371 }
7372 return false;
7373}
7374
7375static bool CheckMissingFormatAttribute(
7376 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7377 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7378 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7379 SourceLocation Loc) {
7380 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7381 return false;
7382
7383 DeclContext *DC = S->CurContext;
7384 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7385 return false;
7386 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7387
7388 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7389
7390 // Find the offset to convert between attribute and parameter indexes.
7391 unsigned CallerArgumentIndexOffset =
7392 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7393
7394 unsigned FirstArgumentIndex = -1;
7395 switch (APK) {
7396 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7397 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7398 // As an extension, clang allows the format attribute on non-variadic
7399 // functions.
7400 // Caller must have fixed arguments to pass them to a fixed or variadic
7401 // function. Try to match caller and callee arguments. If successful, then
7402 // emit a diag with the caller idx, otherwise we can't determine the callee
7403 // arguments.
7404 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7405 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7406 // There aren't enough arguments in the caller to pass to callee.
7407 return false;
7408 }
7409 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7410 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7411 const auto *Arg =
7412 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7413 if (!Arg)
7414 return false;
7415 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7416 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7417 return false;
7418 }
7419 FirstArgumentIndex =
7420 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7421 break;
7422 }
7423 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7424 // Caller arguments are either variadic or a va_list.
7425 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7426 ? (NumCallerParams + CallerArgumentIndexOffset)
7427 : 0;
7428 break;
7429 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7430 // The callee has a format_matches attribute. We will emit that instead.
7431 if (!ReferenceFormatString)
7432 return false;
7433 break;
7434 }
7435
7436 // Emit the diagnostic and fixit.
7437 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7438 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7439 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7440 do {
7441 std::string Attr, Fixit;
7442 llvm::raw_string_ostream AttrOS(Attr);
7443 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7444 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7445 << FirstArgumentIndex << ")";
7446 } else {
7447 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7448 << ", \"";
7449 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7450 AttrOS << "\")";
7451 }
7452 AttrOS.flush();
7453 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7454 if (ND)
7455 DB << ND;
7456 else
7457 DB << "block";
7458
7459 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7460 if (isa<BlockDecl>(Val: Caller))
7461 break;
7462
7463 SourceLocation SL;
7464 llvm::raw_string_ostream IS(Fixit);
7465 // The attribute goes at the start of the declaration in C/C++ functions
7466 // and methods, but after the declaration for Objective-C methods.
7467 if (isa<ObjCMethodDecl>(Val: Caller)) {
7468 IS << ' ';
7469 SL = Caller->getEndLoc();
7470 }
7471 const LangOptions &LO = S->getLangOpts();
7472 if (LO.C23 || LO.CPlusPlus11)
7473 IS << "[[gnu::" << Attr << "]]";
7474 else if (LO.ObjC || LO.GNUMode)
7475 IS << "__attribute__((" << Attr << "))";
7476 else
7477 break;
7478 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7479 IS << ' ';
7480 SL = Caller->getBeginLoc();
7481 }
7482 IS.flush();
7483
7484 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7485 } while (false);
7486
7487 // Add implicit format or format_matches attribute.
7488 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7489 Caller->addAttr(A: FormatAttr::CreateImplicit(
7490 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7491 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7492 } else {
7493 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7494 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7495 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7496 }
7497
7498 {
7499 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7500 if (ND)
7501 DB << ND;
7502 else
7503 DB << "block";
7504 }
7505 return true;
7506}
7507
7508bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7509 Sema::FormatArgumentPassingKind APK,
7510 StringLiteral *ReferenceFormatString,
7511 unsigned format_idx, unsigned firstDataArg,
7512 FormatStringType Type,
7513 VariadicCallType CallType, SourceLocation Loc,
7514 SourceRange Range,
7515 llvm::SmallBitVector &CheckedVarArgs) {
7516 // CHECK: printf/scanf-like function is called with no format string.
7517 if (format_idx >= Args.size()) {
7518 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7519 return false;
7520 }
7521
7522 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7523
7524 // CHECK: format string is not a string literal.
7525 //
7526 // Dynamically generated format strings are difficult to
7527 // automatically vet at compile time. Requiring that format strings
7528 // are string literals: (1) permits the checking of format strings by
7529 // the compiler and thereby (2) can practically remove the source of
7530 // many format string exploits.
7531
7532 // Format string can be either ObjC string (e.g. @"%d") or
7533 // C string (e.g. "%d")
7534 // ObjC string uses the same format specifiers as C string, so we can use
7535 // the same format string checking logic for both ObjC and C strings.
7536 UncoveredArgHandler UncoveredArg;
7537 std::optional<unsigned> CallerParamIdx;
7538 StringLiteralCheckType CT = checkFormatStringExpr(
7539 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
7540 firstDataArg, Type, CallType,
7541 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
7542 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
7543
7544 // Generate a diagnostic where an uncovered argument is detected.
7545 if (UncoveredArg.hasUncoveredArg()) {
7546 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7547 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7548 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
7549 }
7550
7551 if (CT != SLCT_NotALiteral)
7552 // Literal format string found, check done!
7553 return CT == SLCT_CheckedLiteral;
7554
7555 // Do not emit diag when the string param is a macro expansion and the
7556 // format is either NSString or CFString. This is a hack to prevent
7557 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7558 // which are usually used in place of NS and CF string literals.
7559 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7560 if (Type == FormatStringType::NSString &&
7561 SourceMgr.isInSystemMacro(loc: FormatLoc))
7562 return false;
7563
7564 if (CallerParamIdx && CheckMissingFormatAttribute(
7565 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
7566 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
7567 return false;
7568
7569 // Strftime is particular as it always uses a single 'time' argument,
7570 // so it is safe to pass a non-literal string.
7571 if (Type == FormatStringType::Strftime)
7572 return false;
7573
7574 // If there are no arguments specified, warn with -Wformat-security, otherwise
7575 // warn only with -Wformat-nonliteral.
7576 if (Args.size() == firstDataArg) {
7577 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
7578 << OrigFormatExpr->getSourceRange();
7579 switch (Type) {
7580 default:
7581 break;
7582 case FormatStringType::Kprintf:
7583 case FormatStringType::FreeBSDKPrintf:
7584 case FormatStringType::Printf:
7585 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7586 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
7587 break;
7588 case FormatStringType::NSString:
7589 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7590 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
7591 break;
7592 }
7593 } else {
7594 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
7595 << OrigFormatExpr->getSourceRange();
7596 }
7597 return false;
7598}
7599
7600namespace {
7601
7602class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7603protected:
7604 Sema &S;
7605 const FormatStringLiteral *FExpr;
7606 const Expr *OrigFormatExpr;
7607 const FormatStringType FSType;
7608 const unsigned FirstDataArg;
7609 const unsigned NumDataArgs;
7610 const char *Beg; // Start of format string.
7611 const Sema::FormatArgumentPassingKind ArgPassingKind;
7612 ArrayRef<const Expr *> Args;
7613 unsigned FormatIdx;
7614 llvm::SmallBitVector CoveredArgs;
7615 bool usesPositionalArgs = false;
7616 bool atFirstArg = true;
7617 bool inFunctionCall;
7618 VariadicCallType CallType;
7619 llvm::SmallBitVector &CheckedVarArgs;
7620 UncoveredArgHandler &UncoveredArg;
7621
7622public:
7623 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7624 const Expr *origFormatExpr, const FormatStringType type,
7625 unsigned firstDataArg, unsigned numDataArgs,
7626 const char *beg, Sema::FormatArgumentPassingKind APK,
7627 ArrayRef<const Expr *> Args, unsigned formatIdx,
7628 bool inFunctionCall, VariadicCallType callType,
7629 llvm::SmallBitVector &CheckedVarArgs,
7630 UncoveredArgHandler &UncoveredArg)
7631 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7632 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7633 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7634 inFunctionCall(inFunctionCall), CallType(callType),
7635 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7636 CoveredArgs.resize(N: numDataArgs);
7637 CoveredArgs.reset();
7638 }
7639
7640 bool HasFormatArguments() const {
7641 return ArgPassingKind == Sema::FAPK_Fixed ||
7642 ArgPassingKind == Sema::FAPK_Variadic;
7643 }
7644
7645 void DoneProcessing();
7646
7647 void HandleIncompleteSpecifier(const char *startSpecifier,
7648 unsigned specifierLen) override;
7649
7650 void HandleInvalidLengthModifier(
7651 const analyze_format_string::FormatSpecifier &FS,
7652 const analyze_format_string::ConversionSpecifier &CS,
7653 const char *startSpecifier, unsigned specifierLen,
7654 unsigned DiagID);
7655
7656 void HandleNonStandardLengthModifier(
7657 const analyze_format_string::FormatSpecifier &FS,
7658 const char *startSpecifier, unsigned specifierLen);
7659
7660 void HandleNonStandardConversionSpecifier(
7661 const analyze_format_string::ConversionSpecifier &CS,
7662 const char *startSpecifier, unsigned specifierLen);
7663
7664 void HandlePosition(const char *startPos, unsigned posLen) override;
7665
7666 void HandleInvalidPosition(const char *startSpecifier,
7667 unsigned specifierLen,
7668 analyze_format_string::PositionContext p) override;
7669
7670 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7671
7672 void HandleNullChar(const char *nullCharacter) override;
7673
7674 template <typename Range>
7675 static void
7676 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7677 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7678 bool IsStringLocation, Range StringRange,
7679 ArrayRef<FixItHint> Fixit = {});
7680
7681protected:
7682 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7683 const char *startSpec,
7684 unsigned specifierLen,
7685 const char *csStart, unsigned csLen);
7686
7687 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7688 const char *startSpec,
7689 unsigned specifierLen);
7690
7691 SourceRange getFormatStringRange();
7692 CharSourceRange getSpecifierRange(const char *startSpecifier,
7693 unsigned specifierLen);
7694 SourceLocation getLocationOfByte(const char *x);
7695
7696 const Expr *getDataArg(unsigned i) const;
7697
7698 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7699 const analyze_format_string::ConversionSpecifier &CS,
7700 const char *startSpecifier, unsigned specifierLen,
7701 unsigned argIndex);
7702
7703 template <typename Range>
7704 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7705 bool IsStringLocation, Range StringRange,
7706 ArrayRef<FixItHint> Fixit = {});
7707};
7708
7709} // namespace
7710
7711SourceRange CheckFormatHandler::getFormatStringRange() {
7712 return OrigFormatExpr->getSourceRange();
7713}
7714
7715CharSourceRange CheckFormatHandler::
7716getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7717 SourceLocation Start = getLocationOfByte(x: startSpecifier);
7718 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
7719
7720 // Advance the end SourceLocation by one due to half-open ranges.
7721 End = End.getLocWithOffset(Offset: 1);
7722
7723 return CharSourceRange::getCharRange(B: Start, E: End);
7724}
7725
7726SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7727 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
7728 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
7729}
7730
7731void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7732 unsigned specifierLen){
7733 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
7734 Loc: getLocationOfByte(x: startSpecifier),
7735 /*IsStringLocation*/true,
7736 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7737}
7738
7739void CheckFormatHandler::HandleInvalidLengthModifier(
7740 const analyze_format_string::FormatSpecifier &FS,
7741 const analyze_format_string::ConversionSpecifier &CS,
7742 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7743 using namespace analyze_format_string;
7744
7745 const LengthModifier &LM = FS.getLengthModifier();
7746 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7747
7748 // See if we know how to fix this length modifier.
7749 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7750 if (FixedLM) {
7751 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7752 Loc: getLocationOfByte(x: LM.getStart()),
7753 /*IsStringLocation*/true,
7754 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7755
7756 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7757 << FixedLM->toString()
7758 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7759
7760 } else {
7761 FixItHint Hint;
7762 if (DiagID == diag::warn_format_nonsensical_length)
7763 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
7764
7765 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7766 Loc: getLocationOfByte(x: LM.getStart()),
7767 /*IsStringLocation*/true,
7768 StringRange: getSpecifierRange(startSpecifier, specifierLen),
7769 FixIt: Hint);
7770 }
7771}
7772
7773void CheckFormatHandler::HandleNonStandardLengthModifier(
7774 const analyze_format_string::FormatSpecifier &FS,
7775 const char *startSpecifier, unsigned specifierLen) {
7776 using namespace analyze_format_string;
7777
7778 const LengthModifier &LM = FS.getLengthModifier();
7779 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7780
7781 // See if we know how to fix this length modifier.
7782 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7783 if (FixedLM) {
7784 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7785 << LM.toString() << 0,
7786 Loc: getLocationOfByte(x: LM.getStart()),
7787 /*IsStringLocation*/true,
7788 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7789
7790 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7791 << FixedLM->toString()
7792 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7793
7794 } else {
7795 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7796 << LM.toString() << 0,
7797 Loc: getLocationOfByte(x: LM.getStart()),
7798 /*IsStringLocation*/true,
7799 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7800 }
7801}
7802
7803void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7804 const analyze_format_string::ConversionSpecifier &CS,
7805 const char *startSpecifier, unsigned specifierLen) {
7806 using namespace analyze_format_string;
7807
7808 // See if we know how to fix this conversion specifier.
7809 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7810 if (FixedCS) {
7811 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7812 << CS.toString() << /*conversion specifier*/1,
7813 Loc: getLocationOfByte(x: CS.getStart()),
7814 /*IsStringLocation*/true,
7815 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7816
7817 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
7818 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
7819 << FixedCS->toString()
7820 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
7821 } else {
7822 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7823 << CS.toString() << /*conversion specifier*/1,
7824 Loc: getLocationOfByte(x: CS.getStart()),
7825 /*IsStringLocation*/true,
7826 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7827 }
7828}
7829
7830void CheckFormatHandler::HandlePosition(const char *startPos,
7831 unsigned posLen) {
7832 if (!S.getDiagnostics().isIgnored(
7833 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
7834 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
7835 Loc: getLocationOfByte(x: startPos),
7836 /*IsStringLocation*/ true,
7837 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7838}
7839
7840void CheckFormatHandler::HandleInvalidPosition(
7841 const char *startSpecifier, unsigned specifierLen,
7842 analyze_format_string::PositionContext p) {
7843 if (!S.getDiagnostics().isIgnored(
7844 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
7845 EmitFormatDiagnostic(
7846 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7847 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
7848 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7849}
7850
7851void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7852 unsigned posLen) {
7853 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
7854 Loc: SourceLocation()))
7855 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
7856 Loc: getLocationOfByte(x: startPos),
7857 /*IsStringLocation*/ true,
7858 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7859}
7860
7861void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7862 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
7863 // The presence of a null character is likely an error.
7864 EmitFormatDiagnostic(
7865 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
7866 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/true,
7867 StringRange: getFormatStringRange());
7868 }
7869}
7870
7871// Note that this may return NULL if there was an error parsing or building
7872// one of the argument expressions.
7873const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7874 return Args[FirstDataArg + i];
7875}
7876
7877void CheckFormatHandler::DoneProcessing() {
7878 // Does the number of data arguments exceed the number of
7879 // format conversions in the format string?
7880 if (HasFormatArguments()) {
7881 // Find any arguments that weren't covered.
7882 CoveredArgs.flip();
7883 signed notCoveredArg = CoveredArgs.find_first();
7884 if (notCoveredArg >= 0) {
7885 assert((unsigned)notCoveredArg < NumDataArgs);
7886 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
7887 } else {
7888 UncoveredArg.setAllCovered();
7889 }
7890 }
7891}
7892
7893void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7894 const Expr *ArgExpr) {
7895 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7896 "Invalid state");
7897
7898 if (!ArgExpr)
7899 return;
7900
7901 SourceLocation Loc = ArgExpr->getBeginLoc();
7902
7903 if (S.getSourceManager().isInSystemMacro(loc: Loc))
7904 return;
7905
7906 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
7907 for (auto E : DiagnosticExprs)
7908 PDiag << E->getSourceRange();
7909
7910 CheckFormatHandler::EmitFormatDiagnostic(
7911 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0],
7912 PDiag, Loc, /*IsStringLocation*/false,
7913 StringRange: DiagnosticExprs[0]->getSourceRange());
7914}
7915
7916bool
7917CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7918 SourceLocation Loc,
7919 const char *startSpec,
7920 unsigned specifierLen,
7921 const char *csStart,
7922 unsigned csLen) {
7923 bool keepGoing = true;
7924 if (argIndex < NumDataArgs) {
7925 // Consider the argument coverered, even though the specifier doesn't
7926 // make sense.
7927 CoveredArgs.set(argIndex);
7928 }
7929 else {
7930 // If argIndex exceeds the number of data arguments we
7931 // don't issue a warning because that is just a cascade of warnings (and
7932 // they may have intended '%%' anyway). We don't want to continue processing
7933 // the format string after this point, however, as we will like just get
7934 // gibberish when trying to match arguments.
7935 keepGoing = false;
7936 }
7937
7938 StringRef Specifier(csStart, csLen);
7939
7940 // If the specifier in non-printable, it could be the first byte of a UTF-8
7941 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7942 // hex value.
7943 std::string CodePointStr;
7944 if (!llvm::sys::locale::isPrint(c: *csStart)) {
7945 llvm::UTF32 CodePoint;
7946 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7947 const llvm::UTF8 *E =
7948 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7949 llvm::ConversionResult Result =
7950 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
7951
7952 if (Result != llvm::conversionOK) {
7953 unsigned char FirstChar = *csStart;
7954 CodePoint = (llvm::UTF32)FirstChar;
7955 }
7956
7957 llvm::raw_string_ostream OS(CodePointStr);
7958 if (CodePoint < 256)
7959 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
7960 else if (CodePoint <= 0xFFFF)
7961 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
7962 else
7963 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
7964 Specifier = CodePointStr;
7965 }
7966
7967 EmitFormatDiagnostic(
7968 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
7969 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7970
7971 return keepGoing;
7972}
7973
7974void
7975CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7976 const char *startSpec,
7977 unsigned specifierLen) {
7978 EmitFormatDiagnostic(
7979 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args),
7980 Loc, /*isStringLoc*/IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7981}
7982
7983bool
7984CheckFormatHandler::CheckNumArgs(
7985 const analyze_format_string::FormatSpecifier &FS,
7986 const analyze_format_string::ConversionSpecifier &CS,
7987 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7988
7989 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7990 PartialDiagnostic PDiag = FS.usesPositionalArg()
7991 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
7992 << (argIndex+1) << NumDataArgs)
7993 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
7994 EmitFormatDiagnostic(
7995 PDiag, Loc: getLocationOfByte(x: CS.getStart()), /*IsStringLocation*/true,
7996 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7997
7998 // Since more arguments than conversion tokens are given, by extension
7999 // all arguments are covered, so mark this as so.
8000 UncoveredArg.setAllCovered();
8001 return false;
8002 }
8003 return true;
8004}
8005
8006template<typename Range>
8007void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8008 SourceLocation Loc,
8009 bool IsStringLocation,
8010 Range StringRange,
8011 ArrayRef<FixItHint> FixIt) {
8012 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8013 Loc, IsStringLocation, StringRange, FixIt);
8014}
8015
8016/// If the format string is not within the function call, emit a note
8017/// so that the function call and string are in diagnostic messages.
8018///
8019/// \param InFunctionCall if true, the format string is within the function
8020/// call and only one diagnostic message will be produced. Otherwise, an
8021/// extra note will be emitted pointing to location of the format string.
8022///
8023/// \param ArgumentExpr the expression that is passed as the format string
8024/// argument in the function call. Used for getting locations when two
8025/// diagnostics are emitted.
8026///
8027/// \param PDiag the callee should already have provided any strings for the
8028/// diagnostic message. This function only adds locations and fixits
8029/// to diagnostics.
8030///
8031/// \param Loc primary location for diagnostic. If two diagnostics are
8032/// required, one will be at Loc and a new SourceLocation will be created for
8033/// the other one.
8034///
8035/// \param IsStringLocation if true, Loc points to the format string should be
8036/// used for the note. Otherwise, Loc points to the argument list and will
8037/// be used with PDiag.
8038///
8039/// \param StringRange some or all of the string to highlight. This is
8040/// templated so it can accept either a CharSourceRange or a SourceRange.
8041///
8042/// \param FixIt optional fix it hint for the format string.
8043template <typename Range>
8044void CheckFormatHandler::EmitFormatDiagnostic(
8045 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8046 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8047 Range StringRange, ArrayRef<FixItHint> FixIt) {
8048 if (InFunctionCall) {
8049 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8050 D << StringRange;
8051 D << FixIt;
8052 } else {
8053 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8054 << ArgumentExpr->getSourceRange();
8055
8056 const Sema::SemaDiagnosticBuilder &Note =
8057 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8058 diag::note_format_string_defined);
8059
8060 Note << StringRange;
8061 Note << FixIt;
8062 }
8063}
8064
8065//===--- CHECK: Printf format string checking -----------------------------===//
8066
8067namespace {
8068
8069class CheckPrintfHandler : public CheckFormatHandler {
8070public:
8071 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8072 const Expr *origFormatExpr, const FormatStringType type,
8073 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8074 const char *beg, Sema::FormatArgumentPassingKind APK,
8075 ArrayRef<const Expr *> Args, unsigned formatIdx,
8076 bool inFunctionCall, VariadicCallType CallType,
8077 llvm::SmallBitVector &CheckedVarArgs,
8078 UncoveredArgHandler &UncoveredArg)
8079 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8080 numDataArgs, beg, APK, Args, formatIdx,
8081 inFunctionCall, CallType, CheckedVarArgs,
8082 UncoveredArg) {}
8083
8084 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8085
8086 /// Returns true if '%@' specifiers are allowed in the format string.
8087 bool allowsObjCArg() const {
8088 return FSType == FormatStringType::NSString ||
8089 FSType == FormatStringType::OSLog ||
8090 FSType == FormatStringType::OSTrace;
8091 }
8092
8093 bool HandleInvalidPrintfConversionSpecifier(
8094 const analyze_printf::PrintfSpecifier &FS,
8095 const char *startSpecifier,
8096 unsigned specifierLen) override;
8097
8098 void handleInvalidMaskType(StringRef MaskType) override;
8099
8100 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8101 const char *startSpecifier, unsigned specifierLen,
8102 const TargetInfo &Target) override;
8103 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8104 const char *StartSpecifier,
8105 unsigned SpecifierLen,
8106 const Expr *E);
8107
8108 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8109 const char *startSpecifier, unsigned specifierLen);
8110 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8111 const analyze_printf::OptionalAmount &Amt,
8112 unsigned type,
8113 const char *startSpecifier, unsigned specifierLen);
8114 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8115 const analyze_printf::OptionalFlag &flag,
8116 const char *startSpecifier, unsigned specifierLen);
8117 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8118 const analyze_printf::OptionalFlag &ignoredFlag,
8119 const analyze_printf::OptionalFlag &flag,
8120 const char *startSpecifier, unsigned specifierLen);
8121 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8122 const Expr *E);
8123
8124 void HandleEmptyObjCModifierFlag(const char *startFlag,
8125 unsigned flagLen) override;
8126
8127 void HandleInvalidObjCModifierFlag(const char *startFlag,
8128 unsigned flagLen) override;
8129
8130 void
8131 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8132 const char *flagsEnd,
8133 const char *conversionPosition) override;
8134};
8135
8136/// Keeps around the information needed to verify that two specifiers are
8137/// compatible.
8138class EquatableFormatArgument {
8139public:
8140 enum SpecifierSensitivity : unsigned {
8141 SS_None,
8142 SS_Private,
8143 SS_Public,
8144 SS_Sensitive
8145 };
8146
8147 enum FormatArgumentRole : unsigned {
8148 FAR_Data,
8149 FAR_FieldWidth,
8150 FAR_Precision,
8151 FAR_Auxiliary, // FreeBSD kernel %b and %D
8152 };
8153
8154private:
8155 analyze_format_string::ArgType ArgType;
8156 analyze_format_string::LengthModifier::Kind LengthMod;
8157 StringRef SpecifierLetter;
8158 CharSourceRange Range;
8159 SourceLocation ElementLoc;
8160 FormatArgumentRole Role : 2;
8161 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8162 unsigned Position : 14;
8163 unsigned ModifierFor : 14; // not set for FAR_Data
8164
8165 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8166 bool InFunctionCall) const;
8167
8168public:
8169 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8170 analyze_format_string::LengthModifier::Kind LengthMod,
8171 StringRef SpecifierLetter,
8172 analyze_format_string::ArgType ArgType,
8173 FormatArgumentRole Role,
8174 SpecifierSensitivity Sensitivity, unsigned Position,
8175 unsigned ModifierFor)
8176 : ArgType(ArgType), LengthMod(LengthMod),
8177 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8178 Role(Role), Sensitivity(Sensitivity), Position(Position),
8179 ModifierFor(ModifierFor) {}
8180
8181 unsigned getPosition() const { return Position; }
8182 SourceLocation getSourceLocation() const { return ElementLoc; }
8183 CharSourceRange getSourceRange() const { return Range; }
8184 analyze_format_string::LengthModifier getLengthModifier() const {
8185 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8186 }
8187 void setModifierFor(unsigned V) { ModifierFor = V; }
8188
8189 std::string buildFormatSpecifier() const {
8190 std::string result;
8191 llvm::raw_string_ostream(result)
8192 << getLengthModifier().toString() << SpecifierLetter;
8193 return result;
8194 }
8195
8196 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8197 const Expr *FmtExpr, bool InFunctionCall) const;
8198};
8199
8200/// Turns format strings into lists of EquatableSpecifier objects.
8201class DecomposePrintfHandler : public CheckPrintfHandler {
8202 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8203 bool HadError;
8204
8205 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8206 const Expr *origFormatExpr,
8207 const FormatStringType type, unsigned firstDataArg,
8208 unsigned numDataArgs, bool isObjC, const char *beg,
8209 Sema::FormatArgumentPassingKind APK,
8210 ArrayRef<const Expr *> Args, unsigned formatIdx,
8211 bool inFunctionCall, VariadicCallType CallType,
8212 llvm::SmallBitVector &CheckedVarArgs,
8213 UncoveredArgHandler &UncoveredArg,
8214 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8215 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8216 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8217 inFunctionCall, CallType, CheckedVarArgs,
8218 UncoveredArg),
8219 Specs(Specs), HadError(false) {}
8220
8221public:
8222 static bool
8223 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8224 FormatStringType type, bool IsObjC, bool InFunctionCall,
8225 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8226
8227 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8228 const char *startSpecifier,
8229 unsigned specifierLen,
8230 const TargetInfo &Target) override;
8231};
8232
8233} // namespace
8234
8235bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8236 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8237 unsigned specifierLen) {
8238 const analyze_printf::PrintfConversionSpecifier &CS =
8239 FS.getConversionSpecifier();
8240
8241 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
8242 Loc: getLocationOfByte(x: CS.getStart()),
8243 startSpec: startSpecifier, specifierLen,
8244 csStart: CS.getStart(), csLen: CS.getLength());
8245}
8246
8247void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8248 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8249}
8250
8251// Error out if struct or complex type argments are passed to os_log.
8252static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8253 QualType T) {
8254 if (FSType != FormatStringType::OSLog)
8255 return false;
8256 return T->isRecordType() || T->isComplexType();
8257}
8258
8259bool CheckPrintfHandler::HandleAmount(
8260 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8261 const char *startSpecifier, unsigned specifierLen) {
8262 if (Amt.hasDataArgument()) {
8263 if (HasFormatArguments()) {
8264 unsigned argIndex = Amt.getArgIndex();
8265 if (argIndex >= NumDataArgs) {
8266 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8267 << k,
8268 Loc: getLocationOfByte(x: Amt.getStart()),
8269 /*IsStringLocation*/ true,
8270 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8271 // Don't do any more checking. We will just emit
8272 // spurious errors.
8273 return false;
8274 }
8275
8276 // Type check the data argument. It should be an 'int'.
8277 // Although not in conformance with C99, we also allow the argument to be
8278 // an 'unsigned int' as that is a reasonably safe case. GCC also
8279 // doesn't emit a warning for that case.
8280 CoveredArgs.set(argIndex);
8281 const Expr *Arg = getDataArg(i: argIndex);
8282 if (!Arg)
8283 return false;
8284
8285 QualType T = Arg->getType();
8286
8287 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8288 assert(AT.isValid());
8289
8290 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8291 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8292 ? diag::err_printf_asterisk_wrong_type
8293 : diag::warn_printf_asterisk_wrong_type;
8294 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8295 << k << AT.getRepresentativeTypeName(C&: S.Context)
8296 << T << Arg->getSourceRange(),
8297 Loc: getLocationOfByte(x: Amt.getStart()),
8298 /*IsStringLocation*/ true,
8299 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8300 // Don't do any more checking. We will just emit
8301 // spurious errors.
8302 return false;
8303 }
8304 }
8305 }
8306 return true;
8307}
8308
8309void CheckPrintfHandler::HandleInvalidAmount(
8310 const analyze_printf::PrintfSpecifier &FS,
8311 const analyze_printf::OptionalAmount &Amt,
8312 unsigned type,
8313 const char *startSpecifier,
8314 unsigned specifierLen) {
8315 const analyze_printf::PrintfConversionSpecifier &CS =
8316 FS.getConversionSpecifier();
8317
8318 FixItHint fixit =
8319 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8320 ? FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(),
8321 specifierLen: Amt.getConstantLength()))
8322 : FixItHint();
8323
8324 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8325 << type << CS.toString(),
8326 Loc: getLocationOfByte(x: Amt.getStart()),
8327 /*IsStringLocation*/true,
8328 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8329 FixIt: fixit);
8330}
8331
8332void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8333 const analyze_printf::OptionalFlag &flag,
8334 const char *startSpecifier,
8335 unsigned specifierLen) {
8336 // Warn about pointless flag with a fixit removal.
8337 const analyze_printf::PrintfConversionSpecifier &CS =
8338 FS.getConversionSpecifier();
8339 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8340 << flag.toString() << CS.toString(),
8341 Loc: getLocationOfByte(x: flag.getPosition()),
8342 /*IsStringLocation*/true,
8343 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8344 FixIt: FixItHint::CreateRemoval(
8345 RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8346}
8347
8348void CheckPrintfHandler::HandleIgnoredFlag(
8349 const analyze_printf::PrintfSpecifier &FS,
8350 const analyze_printf::OptionalFlag &ignoredFlag,
8351 const analyze_printf::OptionalFlag &flag,
8352 const char *startSpecifier,
8353 unsigned specifierLen) {
8354 // Warn about ignored flag with a fixit removal.
8355 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8356 << ignoredFlag.toString() << flag.toString(),
8357 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8358 /*IsStringLocation*/true,
8359 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8360 FixIt: FixItHint::CreateRemoval(
8361 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8362}
8363
8364void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8365 unsigned flagLen) {
8366 // Warn about an empty flag.
8367 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag),
8368 Loc: getLocationOfByte(x: startFlag),
8369 /*IsStringLocation*/true,
8370 StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8371}
8372
8373void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8374 unsigned flagLen) {
8375 // Warn about an invalid flag.
8376 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8377 StringRef flag(startFlag, flagLen);
8378 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8379 Loc: getLocationOfByte(x: startFlag),
8380 /*IsStringLocation*/true,
8381 StringRange: Range, FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8382}
8383
8384void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8385 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8386 // Warn about using '[...]' without a '@' conversion.
8387 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8388 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8389 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8390 Loc: getLocationOfByte(x: conversionPosition),
8391 /*IsStringLocation*/ true, StringRange: Range,
8392 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8393}
8394
8395void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8396 const Expr *FmtExpr,
8397 bool InFunctionCall) const {
8398 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8399 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8400}
8401
8402bool EquatableFormatArgument::VerifyCompatible(
8403 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8404 bool InFunctionCall) const {
8405 using MK = analyze_format_string::ArgType::MatchKind;
8406 if (Role != Other.Role) {
8407 // diagnose and stop
8408 EmitDiagnostic(
8409 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8410 FmtExpr, InFunctionCall);
8411 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8412 return false;
8413 }
8414
8415 if (Role != FAR_Data) {
8416 if (ModifierFor != Other.ModifierFor) {
8417 // diagnose and stop
8418 EmitDiagnostic(S,
8419 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8420 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8421 FmtExpr, InFunctionCall);
8422 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8423 return false;
8424 }
8425 return true;
8426 }
8427
8428 bool HadError = false;
8429 if (Sensitivity != Other.Sensitivity) {
8430 // diagnose and continue
8431 EmitDiagnostic(S,
8432 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8433 << Sensitivity << Other.Sensitivity,
8434 FmtExpr, InFunctionCall);
8435 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8436 << 0 << Other.Range;
8437 }
8438
8439 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8440 case MK::Match:
8441 break;
8442
8443 case MK::MatchPromotion:
8444 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8445 // MatchPromotion is treated as a failure by format_matches.
8446 case MK::NoMatch:
8447 case MK::NoMatchTypeConfusion:
8448 case MK::NoMatchPromotionTypeConfusion:
8449 EmitDiagnostic(S,
8450 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8451 << buildFormatSpecifier()
8452 << Other.buildFormatSpecifier(),
8453 FmtExpr, InFunctionCall);
8454 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8455 << 0 << Other.Range;
8456 break;
8457
8458 case MK::NoMatchPedantic:
8459 EmitDiagnostic(S,
8460 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8461 << buildFormatSpecifier()
8462 << Other.buildFormatSpecifier(),
8463 FmtExpr, InFunctionCall);
8464 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8465 << 0 << Other.Range;
8466 break;
8467
8468 case MK::NoMatchSignedness:
8469 EmitDiagnostic(S,
8470 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8471 << buildFormatSpecifier()
8472 << Other.buildFormatSpecifier(),
8473 FmtExpr, InFunctionCall);
8474 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8475 << 0 << Other.Range;
8476 break;
8477 }
8478 return !HadError;
8479}
8480
8481bool DecomposePrintfHandler::GetSpecifiers(
8482 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8483 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8484 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8485 StringRef Data = FSL->getString();
8486 const char *Str = Data.data();
8487 llvm::SmallBitVector BV;
8488 UncoveredArgHandler UA;
8489 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8490 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8491 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8492 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8493 UA, Args);
8494
8495 if (!analyze_format_string::ParsePrintfString(
8496 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8497 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8498 H.DoneProcessing();
8499 if (H.HadError)
8500 return false;
8501
8502 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8503 const EquatableFormatArgument &B) {
8504 return A.getPosition() < B.getPosition();
8505 });
8506 return true;
8507}
8508
8509bool DecomposePrintfHandler::HandlePrintfSpecifier(
8510 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8511 unsigned specifierLen, const TargetInfo &Target) {
8512 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8513 specifierLen, Target)) {
8514 HadError = true;
8515 return false;
8516 }
8517
8518 // Do not add any specifiers to the list for %%. This is possibly incorrect
8519 // if using a precision/width with a data argument, but that combination is
8520 // meaningless and we wouldn't know which format to attach the
8521 // precision/width to.
8522 const auto &CS = FS.getConversionSpecifier();
8523 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8524 return true;
8525
8526 // have to patch these to have the right ModifierFor if they are used
8527 const unsigned Unset = ~0;
8528 unsigned FieldWidthIndex = Unset;
8529 unsigned PrecisionIndex = Unset;
8530
8531 // field width?
8532 const auto &FieldWidth = FS.getFieldWidth();
8533 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8534 FieldWidthIndex = Specs.size();
8535 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8536 Args: getLocationOfByte(x: FieldWidth.getStart()),
8537 Args: analyze_format_string::LengthModifier::None, Args: "*",
8538 Args: FieldWidth.getArgType(Ctx&: S.Context),
8539 Args: EquatableFormatArgument::FAR_FieldWidth,
8540 Args: EquatableFormatArgument::SS_None,
8541 Args: FieldWidth.usesPositionalArg()
8542 ? FieldWidth.getPositionalArgIndex() - 1
8543 : FieldWidthIndex,
8544 Args: 0);
8545 }
8546 // precision?
8547 const auto &Precision = FS.getPrecision();
8548 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8549 PrecisionIndex = Specs.size();
8550 Specs.emplace_back(
8551 Args: getSpecifierRange(startSpecifier, specifierLen),
8552 Args: getLocationOfByte(x: Precision.getStart()),
8553 Args: analyze_format_string::LengthModifier::None, Args: ".*",
8554 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
8555 Args: EquatableFormatArgument::SS_None,
8556 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8557 : PrecisionIndex,
8558 Args: 0);
8559 }
8560
8561 // this specifier
8562 unsigned SpecIndex =
8563 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8564 if (FieldWidthIndex != Unset)
8565 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8566 if (PrecisionIndex != Unset)
8567 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8568
8569 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8570 if (FS.isPrivate())
8571 Sensitivity = EquatableFormatArgument::SS_Private;
8572 else if (FS.isPublic())
8573 Sensitivity = EquatableFormatArgument::SS_Public;
8574 else if (FS.isSensitive())
8575 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8576 else
8577 Sensitivity = EquatableFormatArgument::SS_None;
8578
8579 Specs.emplace_back(
8580 Args: getSpecifierRange(startSpecifier, specifierLen),
8581 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier().getKind(),
8582 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
8583 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
8584
8585 // auxiliary argument?
8586 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
8587 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
8588 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8589 Args: getLocationOfByte(x: CS.getStart()),
8590 Args: analyze_format_string::LengthModifier::None,
8591 Args: CS.getCharacters(),
8592 Args: analyze_format_string::ArgType::CStrTy,
8593 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
8594 Args: SpecIndex + 1, Args&: SpecIndex);
8595 }
8596 return true;
8597}
8598
8599// Determines if the specified is a C++ class or struct containing
8600// a member with the specified name and kind (e.g. a CXXMethodDecl named
8601// "c_str()").
8602template<typename MemberKind>
8603static llvm::SmallPtrSet<MemberKind*, 1>
8604CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8605 auto *RD = Ty->getAsCXXRecordDecl();
8606 llvm::SmallPtrSet<MemberKind*, 1> Results;
8607
8608 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8609 return Results;
8610
8611 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8612 Sema::LookupMemberName);
8613 R.suppressDiagnostics();
8614
8615 // We just need to include all members of the right kind turned up by the
8616 // filter, at this point.
8617 if (S.LookupQualifiedName(R, LookupCtx: RD))
8618 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8619 NamedDecl *decl = (*I)->getUnderlyingDecl();
8620 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8621 Results.insert(FK);
8622 }
8623 return Results;
8624}
8625
8626/// Check if we could call '.c_str()' on an object.
8627///
8628/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8629/// allow the call, or if it would be ambiguous).
8630bool Sema::hasCStrMethod(const Expr *E) {
8631 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8632
8633 MethodSet Results =
8634 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
8635 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8636 MI != ME; ++MI)
8637 if ((*MI)->getMinRequiredArguments() == 0)
8638 return true;
8639 return false;
8640}
8641
8642// Check if a (w)string was passed when a (w)char* was needed, and offer a
8643// better diagnostic if so. AT is assumed to be valid.
8644// Returns true when a c_str() conversion method is found.
8645bool CheckPrintfHandler::checkForCStrMembers(
8646 const analyze_printf::ArgType &AT, const Expr *E) {
8647 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8648
8649 MethodSet Results =
8650 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
8651
8652 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8653 MI != ME; ++MI) {
8654 const CXXMethodDecl *Method = *MI;
8655 if (Method->getMinRequiredArguments() == 0 &&
8656 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
8657 // FIXME: Suggest parens if the expression needs them.
8658 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
8659 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
8660 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
8661 return true;
8662 }
8663 }
8664
8665 return false;
8666}
8667
8668bool CheckPrintfHandler::HandlePrintfSpecifier(
8669 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8670 unsigned specifierLen, const TargetInfo &Target) {
8671 using namespace analyze_format_string;
8672 using namespace analyze_printf;
8673
8674 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8675
8676 if (FS.consumesDataArgument()) {
8677 if (atFirstArg) {
8678 atFirstArg = false;
8679 usesPositionalArgs = FS.usesPositionalArg();
8680 }
8681 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8682 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
8683 startSpec: startSpecifier, specifierLen);
8684 return false;
8685 }
8686 }
8687
8688 // First check if the field width, precision, and conversion specifier
8689 // have matching data arguments.
8690 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0,
8691 startSpecifier, specifierLen)) {
8692 return false;
8693 }
8694
8695 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1,
8696 startSpecifier, specifierLen)) {
8697 return false;
8698 }
8699
8700 if (!CS.consumesDataArgument()) {
8701 // FIXME: Technically specifying a precision or field width here
8702 // makes no sense. Worth issuing a warning at some point.
8703 return true;
8704 }
8705
8706 // Consume the argument.
8707 unsigned argIndex = FS.getArgIndex();
8708 if (argIndex < NumDataArgs) {
8709 // The check to see if the argIndex is valid will come later.
8710 // We set the bit here because we may exit early from this
8711 // function if we encounter some other error.
8712 CoveredArgs.set(argIndex);
8713 }
8714
8715 // FreeBSD kernel extensions.
8716 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8717 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8718 // We need at least two arguments.
8719 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
8720 return false;
8721
8722 if (HasFormatArguments()) {
8723 // Claim the second argument.
8724 CoveredArgs.set(argIndex + 1);
8725
8726 // Type check the first argument (int for %b, pointer for %D)
8727 const Expr *Ex = getDataArg(i: argIndex);
8728 const analyze_printf::ArgType &AT =
8729 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8730 ? ArgType(S.Context.IntTy)
8731 : ArgType::CPointerTy;
8732 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
8733 EmitFormatDiagnostic(
8734 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8735 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8736 << false << Ex->getSourceRange(),
8737 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8738 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8739
8740 // Type check the second argument (char * for both %b and %D)
8741 Ex = getDataArg(i: argIndex + 1);
8742 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8743 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
8744 EmitFormatDiagnostic(
8745 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8746 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8747 << false << Ex->getSourceRange(),
8748 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8749 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8750 }
8751 return true;
8752 }
8753
8754 // Check for using an Objective-C specific conversion specifier
8755 // in a non-ObjC literal.
8756 if (!allowsObjCArg() && CS.isObjCArg()) {
8757 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8758 specifierLen);
8759 }
8760
8761 // %P can only be used with os_log.
8762 if (FSType != FormatStringType::OSLog &&
8763 CS.getKind() == ConversionSpecifier::PArg) {
8764 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8765 specifierLen);
8766 }
8767
8768 // %n is not allowed with os_log.
8769 if (FSType == FormatStringType::OSLog &&
8770 CS.getKind() == ConversionSpecifier::nArg) {
8771 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
8772 Loc: getLocationOfByte(x: CS.getStart()),
8773 /*IsStringLocation*/ false,
8774 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8775
8776 return true;
8777 }
8778
8779 // Only scalars are allowed for os_trace.
8780 if (FSType == FormatStringType::OSTrace &&
8781 (CS.getKind() == ConversionSpecifier::PArg ||
8782 CS.getKind() == ConversionSpecifier::sArg ||
8783 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8784 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8785 specifierLen);
8786 }
8787
8788 // Check for use of public/private annotation outside of os_log().
8789 if (FSType != FormatStringType::OSLog) {
8790 if (FS.isPublic().isSet()) {
8791 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8792 << "public",
8793 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
8794 /*IsStringLocation*/ false,
8795 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8796 }
8797 if (FS.isPrivate().isSet()) {
8798 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8799 << "private",
8800 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
8801 /*IsStringLocation*/ false,
8802 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8803 }
8804 }
8805
8806 const llvm::Triple &Triple = Target.getTriple();
8807 if (CS.getKind() == ConversionSpecifier::nArg &&
8808 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8809 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
8810 Loc: getLocationOfByte(x: CS.getStart()),
8811 /*IsStringLocation*/ false,
8812 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8813 }
8814
8815 // Check for invalid use of field width
8816 if (!FS.hasValidFieldWidth()) {
8817 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
8818 startSpecifier, specifierLen);
8819 }
8820
8821 // Check for invalid use of precision
8822 if (!FS.hasValidPrecision()) {
8823 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
8824 startSpecifier, specifierLen);
8825 }
8826
8827 // Precision is mandatory for %P specifier.
8828 if (CS.getKind() == ConversionSpecifier::PArg &&
8829 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8830 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
8831 Loc: getLocationOfByte(x: startSpecifier),
8832 /*IsStringLocation*/ false,
8833 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8834 }
8835
8836 // Check each flag does not conflict with any other component.
8837 if (!FS.hasValidThousandsGroupingPrefix())
8838 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8839 if (!FS.hasValidLeadingZeros())
8840 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
8841 if (!FS.hasValidPlusPrefix())
8842 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
8843 if (!FS.hasValidSpacePrefix())
8844 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
8845 if (!FS.hasValidAlternativeForm())
8846 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
8847 if (!FS.hasValidLeftJustified())
8848 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
8849
8850 // Check that flags are not ignored by another flag
8851 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8852 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
8853 startSpecifier, specifierLen);
8854 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8855 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
8856 startSpecifier, specifierLen);
8857
8858 // Check the length modifier is valid with the given conversion specifier.
8859 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
8860 LO: S.getLangOpts()))
8861 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8862 DiagID: diag::warn_format_nonsensical_length);
8863 else if (!FS.hasStandardLengthModifier())
8864 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8865 else if (!FS.hasStandardLengthConversionCombination())
8866 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8867 DiagID: diag::warn_format_non_standard_conversion_spec);
8868
8869 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
8870 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8871
8872 // The remaining checks depend on the data arguments.
8873 if (!HasFormatArguments())
8874 return true;
8875
8876 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8877 return false;
8878
8879 const Expr *Arg = getDataArg(i: argIndex);
8880 if (!Arg)
8881 return true;
8882
8883 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
8884}
8885
8886static bool requiresParensToAddCast(const Expr *E) {
8887 // FIXME: We should have a general way to reason about operator
8888 // precedence and whether parens are actually needed here.
8889 // Take care of a few common cases where they aren't.
8890 const Expr *Inside = E->IgnoreImpCasts();
8891 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
8892 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8893
8894 switch (Inside->getStmtClass()) {
8895 case Stmt::ArraySubscriptExprClass:
8896 case Stmt::CallExprClass:
8897 case Stmt::CharacterLiteralClass:
8898 case Stmt::CXXBoolLiteralExprClass:
8899 case Stmt::DeclRefExprClass:
8900 case Stmt::FloatingLiteralClass:
8901 case Stmt::IntegerLiteralClass:
8902 case Stmt::MemberExprClass:
8903 case Stmt::ObjCArrayLiteralClass:
8904 case Stmt::ObjCBoolLiteralExprClass:
8905 case Stmt::ObjCBoxedExprClass:
8906 case Stmt::ObjCDictionaryLiteralClass:
8907 case Stmt::ObjCEncodeExprClass:
8908 case Stmt::ObjCIvarRefExprClass:
8909 case Stmt::ObjCMessageExprClass:
8910 case Stmt::ObjCPropertyRefExprClass:
8911 case Stmt::ObjCStringLiteralClass:
8912 case Stmt::ObjCSubscriptRefExprClass:
8913 case Stmt::ParenExprClass:
8914 case Stmt::StringLiteralClass:
8915 case Stmt::UnaryOperatorClass:
8916 return false;
8917 default:
8918 return true;
8919 }
8920}
8921
8922static std::pair<QualType, StringRef>
8923shouldNotPrintDirectly(const ASTContext &Context,
8924 QualType IntendedTy,
8925 const Expr *E) {
8926 // Use a 'while' to peel off layers of typedefs.
8927 QualType TyTy = IntendedTy;
8928 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8929 StringRef Name = UserTy->getDecl()->getName();
8930 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8931 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
8932 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
8933 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
8934 .Case(S: "SInt32", Value: Context.IntTy)
8935 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
8936 .Default(Value: QualType());
8937
8938 if (!CastTy.isNull())
8939 return std::make_pair(x&: CastTy, y&: Name);
8940
8941 TyTy = UserTy->desugar();
8942 }
8943
8944 // Strip parens if necessary.
8945 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
8946 return shouldNotPrintDirectly(Context,
8947 IntendedTy: PE->getSubExpr()->getType(),
8948 E: PE->getSubExpr());
8949
8950 // If this is a conditional expression, then its result type is constructed
8951 // via usual arithmetic conversions and thus there might be no necessary
8952 // typedef sugar there. Recurse to operands to check for NSInteger &
8953 // Co. usage condition.
8954 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
8955 QualType TrueTy, FalseTy;
8956 StringRef TrueName, FalseName;
8957
8958 std::tie(args&: TrueTy, args&: TrueName) =
8959 shouldNotPrintDirectly(Context,
8960 IntendedTy: CO->getTrueExpr()->getType(),
8961 E: CO->getTrueExpr());
8962 std::tie(args&: FalseTy, args&: FalseName) =
8963 shouldNotPrintDirectly(Context,
8964 IntendedTy: CO->getFalseExpr()->getType(),
8965 E: CO->getFalseExpr());
8966
8967 if (TrueTy == FalseTy)
8968 return std::make_pair(x&: TrueTy, y&: TrueName);
8969 else if (TrueTy.isNull())
8970 return std::make_pair(x&: FalseTy, y&: FalseName);
8971 else if (FalseTy.isNull())
8972 return std::make_pair(x&: TrueTy, y&: TrueName);
8973 }
8974
8975 return std::make_pair(x: QualType(), y: StringRef());
8976}
8977
8978/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8979/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8980/// type do not count.
8981static bool
8982isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8983 QualType From = ICE->getSubExpr()->getType();
8984 QualType To = ICE->getType();
8985 // It's an integer promotion if the destination type is the promoted
8986 // source type.
8987 if (ICE->getCastKind() == CK_IntegralCast &&
8988 S.Context.isPromotableIntegerType(T: From) &&
8989 S.Context.getPromotedIntegerType(PromotableType: From) == To)
8990 return true;
8991 // Look through vector types, since we do default argument promotion for
8992 // those in OpenCL.
8993 if (const auto *VecTy = From->getAs<ExtVectorType>())
8994 From = VecTy->getElementType();
8995 if (const auto *VecTy = To->getAs<ExtVectorType>())
8996 To = VecTy->getElementType();
8997 // It's a floating promotion if the source type is a lower rank.
8998 return ICE->getCastKind() == CK_FloatingCast &&
8999 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9000}
9001
9002static analyze_format_string::ArgType::MatchKind
9003handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9004 DiagnosticsEngine &Diags, SourceLocation Loc) {
9005 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9006 if (Diags.isIgnored(
9007 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9008 Loc) ||
9009 Diags.isIgnored(
9010 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9011 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9012 return analyze_format_string::ArgType::Match;
9013 }
9014 }
9015 return Match;
9016}
9017
9018bool
9019CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9020 const char *StartSpecifier,
9021 unsigned SpecifierLen,
9022 const Expr *E) {
9023 using namespace analyze_format_string;
9024 using namespace analyze_printf;
9025
9026 // Now type check the data expression that matches the
9027 // format specifier.
9028 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9029 if (!AT.isValid())
9030 return true;
9031
9032 QualType ExprTy = E->getType();
9033 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9034 ExprTy = TET->getUnderlyingExpr()->getType();
9035 }
9036
9037 if (const OverflowBehaviorType *OBT =
9038 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9039 ExprTy = OBT->getUnderlyingType();
9040
9041 // When using the format attribute in C++, you can receive a function or an
9042 // array that will necessarily decay to a pointer when passed to the final
9043 // format consumer. Apply decay before type comparison.
9044 if (ExprTy->canDecayToPointerType())
9045 ExprTy = S.Context.getDecayedType(T: ExprTy);
9046
9047 // Diagnose attempts to print a boolean value as a character. Unlike other
9048 // -Wformat diagnostics, this is fine from a type perspective, but it still
9049 // doesn't make sense.
9050 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9051 E->isKnownToHaveBooleanValue()) {
9052 const CharSourceRange &CSR =
9053 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9054 SmallString<4> FSString;
9055 llvm::raw_svector_ostream os(FSString);
9056 FS.toString(os);
9057 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9058 << FSString,
9059 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9060 return true;
9061 }
9062
9063 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9064 // dumping raw class data (like is-a pointer), not actual data.
9065 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9066 ExprTy->isObjCObjectPointerType()) {
9067 const CharSourceRange &CSR =
9068 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9069 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9070 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9071 return true;
9072 }
9073
9074 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9075 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9076 ArgType::MatchKind OrigMatch = Match;
9077
9078 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9079 if (Match == ArgType::Match)
9080 return true;
9081
9082 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9083 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9084
9085 // Look through argument promotions for our error message's reported type.
9086 // This includes the integral and floating promotions, but excludes array
9087 // and function pointer decay (seeing that an argument intended to be a
9088 // string has type 'char [6]' is probably more confusing than 'char *') and
9089 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9090 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9091 if (isArithmeticArgumentPromotion(S, ICE)) {
9092 E = ICE->getSubExpr();
9093 ExprTy = E->getType();
9094
9095 // Check if we didn't match because of an implicit cast from a 'char'
9096 // or 'short' to an 'int'. This is done because printf is a varargs
9097 // function.
9098 if (ICE->getType() == S.Context.IntTy ||
9099 ICE->getType() == S.Context.UnsignedIntTy) {
9100 // All further checking is done on the subexpression
9101 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9102 if (OrigMatch == ArgType::NoMatchSignedness &&
9103 ImplicitMatch != ArgType::NoMatchSignedness)
9104 // If the original match was a signedness match this match on the
9105 // implicit cast type also need to be signedness match otherwise we
9106 // might introduce new unexpected warnings from -Wformat-signedness.
9107 return true;
9108 ImplicitMatch = handleFormatSignedness(
9109 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9110 if (ImplicitMatch == ArgType::Match)
9111 return true;
9112 }
9113 }
9114 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9115 // Special case for 'a', which has type 'int' in C.
9116 // Note, however, that we do /not/ want to treat multibyte constants like
9117 // 'MooV' as characters! This form is deprecated but still exists. In
9118 // addition, don't treat expressions as of type 'char' if one byte length
9119 // modifier is provided.
9120 if (ExprTy == S.Context.IntTy &&
9121 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9122 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9123 ExprTy = S.Context.CharTy;
9124 // To improve check results, we consider a character literal in C
9125 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9126 // more likely a type confusion situation, so we will suggest to
9127 // use '%hhd' instead by discarding the MatchPromotion.
9128 if (Match == ArgType::MatchPromotion)
9129 Match = ArgType::NoMatch;
9130 }
9131 }
9132 if (Match == ArgType::MatchPromotion) {
9133 // WG14 N2562 only clarified promotions in *printf
9134 // For NSLog in ObjC, just preserve -Wformat behavior
9135 if (!S.getLangOpts().ObjC &&
9136 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9137 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9138 return true;
9139 Match = ArgType::NoMatch;
9140 }
9141 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9142 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9143 Match = ImplicitMatch;
9144 assert(Match != ArgType::MatchPromotion);
9145
9146 // Look through unscoped enums to their underlying type.
9147 bool IsEnum = false;
9148 bool IsScopedEnum = false;
9149 QualType IntendedTy = ExprTy;
9150 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9151 IntendedTy = ED->getIntegerType();
9152 if (!ED->isScoped()) {
9153 ExprTy = IntendedTy;
9154 // This controls whether we're talking about the underlying type or not,
9155 // which we only want to do when it's an unscoped enum.
9156 IsEnum = true;
9157 } else {
9158 IsScopedEnum = true;
9159 }
9160 }
9161
9162 // %C in an Objective-C context prints a unichar, not a wchar_t.
9163 // If the argument is an integer of some kind, believe the %C and suggest
9164 // a cast instead of changing the conversion specifier.
9165 if (isObjCContext() &&
9166 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9167 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9168 !ExprTy->isCharType()) {
9169 // 'unichar' is defined as a typedef of unsigned short, but we should
9170 // prefer using the typedef if it is visible.
9171 IntendedTy = S.Context.UnsignedShortTy;
9172
9173 // While we are here, check if the value is an IntegerLiteral that happens
9174 // to be within the valid range.
9175 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9176 const llvm::APInt &V = IL->getValue();
9177 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9178 return true;
9179 }
9180
9181 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9182 Sema::LookupOrdinaryName);
9183 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9184 NamedDecl *ND = Result.getFoundDecl();
9185 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9186 if (TD->getUnderlyingType() == IntendedTy)
9187 IntendedTy =
9188 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9189 /*Qualifier=*/std::nullopt, Decl: TD);
9190 }
9191 }
9192 }
9193
9194 // Special-case some of Darwin's platform-independence types by suggesting
9195 // casts to primitive types that are known to be large enough.
9196 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9197 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9198 QualType CastTy;
9199 std::tie(args&: CastTy, args&: CastTyName) = shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9200 if (!CastTy.isNull()) {
9201 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9202 // (long in ASTContext). Only complain to pedants or when they're the
9203 // underlying type of a scoped enum (which always needs a cast).
9204 if (!IsScopedEnum &&
9205 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9206 (AT.isSizeT() || AT.isPtrdiffT()) &&
9207 AT.matchesType(C&: S.Context, argTy: CastTy))
9208 Match = ArgType::NoMatchPedantic;
9209 IntendedTy = CastTy;
9210 ShouldNotPrintDirectly = true;
9211 }
9212 }
9213
9214 // We may be able to offer a FixItHint if it is a supported type.
9215 PrintfSpecifier fixedFS = FS;
9216 bool Success =
9217 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9218
9219 if (Success) {
9220 // Get the fix string from the fixed format specifier
9221 SmallString<16> buf;
9222 llvm::raw_svector_ostream os(buf);
9223 fixedFS.toString(os);
9224
9225 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9226
9227 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9228 unsigned Diag;
9229 switch (Match) {
9230 case ArgType::Match:
9231 case ArgType::MatchPromotion:
9232 case ArgType::NoMatchPromotionTypeConfusion:
9233 llvm_unreachable("expected non-matching");
9234 case ArgType::NoMatchSignedness:
9235 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9236 break;
9237 case ArgType::NoMatchPedantic:
9238 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9239 break;
9240 case ArgType::NoMatchTypeConfusion:
9241 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9242 break;
9243 case ArgType::NoMatch:
9244 Diag = diag::warn_format_conversion_argument_type_mismatch;
9245 break;
9246 }
9247
9248 // In this case, the specifier is wrong and should be changed to match
9249 // the argument.
9250 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9251 << AT.getRepresentativeTypeName(C&: S.Context)
9252 << IntendedTy << IsEnum << E->getSourceRange(),
9253 Loc: E->getBeginLoc(),
9254 /*IsStringLocation*/ false, StringRange: SpecRange,
9255 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9256 } else {
9257 // The canonical type for formatting this value is different from the
9258 // actual type of the expression. (This occurs, for example, with Darwin's
9259 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9260 // should be printed as 'long' for 64-bit compatibility.)
9261 // Rather than emitting a normal format/argument mismatch, we want to
9262 // add a cast to the recommended type (and correct the format string
9263 // if necessary). We should also do so for scoped enumerations.
9264 SmallString<16> CastBuf;
9265 llvm::raw_svector_ostream CastFix(CastBuf);
9266 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9267 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9268 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9269
9270 SmallVector<FixItHint,4> Hints;
9271 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9272 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9273 Loc: E->getExprLoc());
9274 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9275 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9276
9277 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9278 // If there's already a cast present, just replace it.
9279 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9280 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9281
9282 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9283 // If the expression has high enough precedence,
9284 // just write the C-style cast.
9285 Hints.push_back(
9286 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9287 } else {
9288 // Otherwise, add parens around the expression as well as the cast.
9289 CastFix << "(";
9290 Hints.push_back(
9291 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9292
9293 // We don't use getLocForEndOfToken because it returns invalid source
9294 // locations for macro expansions (by design).
9295 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9296 SourceLocation After = EndLoc.getLocWithOffset(
9297 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9298 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9299 }
9300
9301 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9302 // The expression has a type that should not be printed directly.
9303 // We extract the name from the typedef because we don't want to show
9304 // the underlying type in the diagnostic.
9305 StringRef Name;
9306 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9307 Name = TypedefTy->getDecl()->getName();
9308 else
9309 Name = CastTyName;
9310 unsigned Diag = Match == ArgType::NoMatchPedantic
9311 ? diag::warn_format_argument_needs_cast_pedantic
9312 : diag::warn_format_argument_needs_cast;
9313 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9314 << E->getSourceRange(),
9315 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9316 StringRange: SpecRange, FixIt: Hints);
9317 } else {
9318 // In this case, the expression could be printed using a different
9319 // specifier, but we've decided that the specifier is probably correct
9320 // and we should cast instead. Just use the normal warning message.
9321
9322 unsigned Diag =
9323 IsScopedEnum
9324 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9325 : diag::warn_format_conversion_argument_type_mismatch;
9326
9327 EmitFormatDiagnostic(
9328 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9329 << IsEnum << E->getSourceRange(),
9330 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9331 }
9332 }
9333 } else {
9334 const CharSourceRange &CSR = getSpecifierRange(startSpecifier: StartSpecifier,
9335 specifierLen: SpecifierLen);
9336 // Since the warning for passing non-POD types to variadic functions
9337 // was deferred until now, we emit a warning for non-POD
9338 // arguments here.
9339 bool EmitTypeMismatch = false;
9340 switch (S.isValidVarArgType(Ty: ExprTy)) {
9341 case VarArgKind::Valid:
9342 case VarArgKind::ValidInCXX11: {
9343 unsigned Diag;
9344 switch (Match) {
9345 case ArgType::Match:
9346 case ArgType::MatchPromotion:
9347 case ArgType::NoMatchPromotionTypeConfusion:
9348 llvm_unreachable("expected non-matching");
9349 case ArgType::NoMatchSignedness:
9350 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9351 break;
9352 case ArgType::NoMatchPedantic:
9353 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9354 break;
9355 case ArgType::NoMatchTypeConfusion:
9356 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9357 break;
9358 case ArgType::NoMatch:
9359 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)
9360 ? diag::err_format_conversion_argument_type_mismatch
9361 : diag::warn_format_conversion_argument_type_mismatch;
9362 break;
9363 }
9364
9365 EmitFormatDiagnostic(
9366 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9367 << IsEnum << CSR << E->getSourceRange(),
9368 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9369 break;
9370 }
9371 case VarArgKind::Undefined:
9372 case VarArgKind::MSVCUndefined:
9373 if (CallType == VariadicCallType::DoesNotApply) {
9374 EmitTypeMismatch = true;
9375 } else {
9376 EmitFormatDiagnostic(
9377 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9378 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9379 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9380 << E->getSourceRange(),
9381 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9382 checkForCStrMembers(AT, E);
9383 }
9384 break;
9385
9386 case VarArgKind::Invalid:
9387 if (CallType == VariadicCallType::DoesNotApply)
9388 EmitTypeMismatch = true;
9389 else if (ExprTy->isObjCObjectType())
9390 EmitFormatDiagnostic(
9391 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9392 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9393 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9394 << E->getSourceRange(),
9395 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9396 else
9397 // FIXME: If this is an initializer list, suggest removing the braces
9398 // or inserting a cast to the target type.
9399 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9400 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9401 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9402 break;
9403 }
9404
9405 if (EmitTypeMismatch) {
9406 // The function is not variadic, so we do not generate warnings about
9407 // being allowed to pass that object as a variadic argument. Instead,
9408 // since there are inherently no printf specifiers for types which cannot
9409 // be passed as variadic arguments, emit a plain old specifier mismatch
9410 // argument.
9411 EmitFormatDiagnostic(
9412 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9413 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9414 << E->getSourceRange(),
9415 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9416 }
9417
9418 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9419 "format string specifier index out of range");
9420 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9421 }
9422
9423 return true;
9424}
9425
9426//===--- CHECK: Scanf format string checking ------------------------------===//
9427
9428namespace {
9429
9430class CheckScanfHandler : public CheckFormatHandler {
9431public:
9432 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9433 const Expr *origFormatExpr, FormatStringType type,
9434 unsigned firstDataArg, unsigned numDataArgs,
9435 const char *beg, Sema::FormatArgumentPassingKind APK,
9436 ArrayRef<const Expr *> Args, unsigned formatIdx,
9437 bool inFunctionCall, VariadicCallType CallType,
9438 llvm::SmallBitVector &CheckedVarArgs,
9439 UncoveredArgHandler &UncoveredArg)
9440 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9441 numDataArgs, beg, APK, Args, formatIdx,
9442 inFunctionCall, CallType, CheckedVarArgs,
9443 UncoveredArg) {}
9444
9445 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9446 const char *startSpecifier,
9447 unsigned specifierLen) override;
9448
9449 bool HandleInvalidScanfConversionSpecifier(
9450 const analyze_scanf::ScanfSpecifier &FS,
9451 const char *startSpecifier,
9452 unsigned specifierLen) override;
9453
9454 void HandleIncompleteScanList(const char *start, const char *end) override;
9455};
9456
9457} // namespace
9458
9459void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9460 const char *end) {
9461 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9462 Loc: getLocationOfByte(x: end), /*IsStringLocation*/true,
9463 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9464}
9465
9466bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9467 const analyze_scanf::ScanfSpecifier &FS,
9468 const char *startSpecifier,
9469 unsigned specifierLen) {
9470 const analyze_scanf::ScanfConversionSpecifier &CS =
9471 FS.getConversionSpecifier();
9472
9473 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
9474 Loc: getLocationOfByte(x: CS.getStart()),
9475 startSpec: startSpecifier, specifierLen,
9476 csStart: CS.getStart(), csLen: CS.getLength());
9477}
9478
9479bool CheckScanfHandler::HandleScanfSpecifier(
9480 const analyze_scanf::ScanfSpecifier &FS,
9481 const char *startSpecifier,
9482 unsigned specifierLen) {
9483 using namespace analyze_scanf;
9484 using namespace analyze_format_string;
9485
9486 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9487
9488 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9489 // be used to decide if we are using positional arguments consistently.
9490 if (FS.consumesDataArgument()) {
9491 if (atFirstArg) {
9492 atFirstArg = false;
9493 usesPositionalArgs = FS.usesPositionalArg();
9494 }
9495 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9496 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9497 startSpec: startSpecifier, specifierLen);
9498 return false;
9499 }
9500 }
9501
9502 // Check if the field with is non-zero.
9503 const OptionalAmount &Amt = FS.getFieldWidth();
9504 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9505 if (Amt.getConstantAmount() == 0) {
9506 const CharSourceRange &R = getSpecifierRange(startSpecifier: Amt.getStart(),
9507 specifierLen: Amt.getConstantLength());
9508 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9509 Loc: getLocationOfByte(x: Amt.getStart()),
9510 /*IsStringLocation*/true, StringRange: R,
9511 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9512 }
9513 }
9514
9515 if (!FS.consumesDataArgument()) {
9516 // FIXME: Technically specifying a precision or field width here
9517 // makes no sense. Worth issuing a warning at some point.
9518 return true;
9519 }
9520
9521 // Consume the argument.
9522 unsigned argIndex = FS.getArgIndex();
9523 if (argIndex < NumDataArgs) {
9524 // The check to see if the argIndex is valid will come later.
9525 // We set the bit here because we may exit early from this
9526 // function if we encounter some other error.
9527 CoveredArgs.set(argIndex);
9528 }
9529
9530 // Check the length modifier is valid with the given conversion specifier.
9531 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9532 LO: S.getLangOpts()))
9533 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9534 DiagID: diag::warn_format_nonsensical_length);
9535 else if (!FS.hasStandardLengthModifier())
9536 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9537 else if (!FS.hasStandardLengthConversionCombination())
9538 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9539 DiagID: diag::warn_format_non_standard_conversion_spec);
9540
9541 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9542 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9543
9544 // The remaining checks depend on the data arguments.
9545 if (!HasFormatArguments())
9546 return true;
9547
9548 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9549 return false;
9550
9551 // Check that the argument type matches the format specifier.
9552 const Expr *Ex = getDataArg(i: argIndex);
9553 if (!Ex)
9554 return true;
9555
9556 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
9557
9558 if (!AT.isValid()) {
9559 return true;
9560 }
9561
9562 analyze_format_string::ArgType::MatchKind Match =
9563 AT.matchesType(C&: S.Context, argTy: Ex->getType());
9564 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
9565 if (Match == analyze_format_string::ArgType::Match)
9566 return true;
9567 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9568 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
9569
9570 ScanfSpecifier fixedFS = FS;
9571 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
9572 LangOpt: S.getLangOpts(), Ctx&: S.Context);
9573
9574 unsigned Diag =
9575 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9576 : Signedness
9577 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9578 : diag::warn_format_conversion_argument_type_mismatch;
9579
9580 if (Success) {
9581 // Get the fix string from the fixed format specifier.
9582 SmallString<128> buf;
9583 llvm::raw_svector_ostream os(buf);
9584 fixedFS.toString(os);
9585
9586 EmitFormatDiagnostic(
9587 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
9588 << Ex->getType() << false << Ex->getSourceRange(),
9589 Loc: Ex->getBeginLoc(),
9590 /*IsStringLocation*/ false,
9591 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9592 FixIt: FixItHint::CreateReplacement(
9593 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
9594 } else {
9595 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9596 << AT.getRepresentativeTypeName(C&: S.Context)
9597 << Ex->getType() << false << Ex->getSourceRange(),
9598 Loc: Ex->getBeginLoc(),
9599 /*IsStringLocation*/ false,
9600 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9601 }
9602
9603 return true;
9604}
9605
9606static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9607 ArrayRef<EquatableFormatArgument> RefArgs,
9608 const StringLiteral *Fmt,
9609 ArrayRef<EquatableFormatArgument> FmtArgs,
9610 const Expr *FmtExpr, bool InFunctionCall) {
9611 bool HadError = false;
9612 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9613 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9614 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9615 // In positional-style format strings, the same specifier can appear
9616 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9617 // are sorted by getPosition(), and we process each range of equal
9618 // getPosition() values as one group.
9619 // RefArgs are taken from a string literal that was given to
9620 // attribute(format_matches), and if we got this far, we have already
9621 // verified that if it has positional specifiers that appear in multiple
9622 // locations, then they are all mutually compatible. What's left for us to
9623 // do is verify that all specifiers with the same position in FmtArgs are
9624 // compatible with the RefArgs specifiers. We check each specifier from
9625 // FmtArgs against the first member of the RefArgs group.
9626 for (; FmtIter < FmtEnd; ++FmtIter) {
9627 // Clang does not diagnose missing format specifiers in positional-style
9628 // strings (TODO: which it probably should do, as it is UB to skip over a
9629 // format argument). Skip specifiers if needed.
9630 if (FmtIter->getPosition() < RefIter->getPosition())
9631 continue;
9632
9633 // Delimits a new getPosition() value.
9634 if (FmtIter->getPosition() > RefIter->getPosition())
9635 break;
9636
9637 HadError |=
9638 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
9639 }
9640
9641 // Jump RefIter to the start of the next group.
9642 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
9643 return Arg.getPosition() != RefIter->getPosition();
9644 });
9645 }
9646
9647 if (FmtIter < FmtEnd) {
9648 CheckFormatHandler::EmitFormatDiagnostic(
9649 S, InFunctionCall, ArgumentExpr: FmtExpr,
9650 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
9651 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
9652 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
9653 } else if (RefIter < RefEnd) {
9654 CheckFormatHandler::EmitFormatDiagnostic(
9655 S, InFunctionCall, ArgumentExpr: FmtExpr,
9656 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
9657 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
9658 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
9659 << 1 << RefIter->getSourceRange();
9660 }
9661 return !HadError;
9662}
9663
9664static void CheckFormatString(
9665 Sema &S, const FormatStringLiteral *FExpr,
9666 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9667 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
9668 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9669 bool inFunctionCall, VariadicCallType CallType,
9670 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9671 bool IgnoreStringsWithoutSpecifiers) {
9672 // CHECK: is the format string a wide literal?
9673 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9674 CheckFormatHandler::EmitFormatDiagnostic(
9675 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9676 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
9677 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9678 return;
9679 }
9680
9681 // Str - The format string. NOTE: this is NOT null-terminated!
9682 StringRef StrRef = FExpr->getString();
9683 const char *Str = StrRef.data();
9684 // Account for cases where the string literal is truncated in a declaration.
9685 const ConstantArrayType *T =
9686 S.Context.getAsConstantArrayType(T: FExpr->getType());
9687 assert(T && "String literal not of constant array type!");
9688 size_t TypeSize = T->getZExtSize();
9689 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9690 const unsigned numDataArgs = Args.size() - firstDataArg;
9691
9692 if (IgnoreStringsWithoutSpecifiers &&
9693 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9694 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9695 return;
9696
9697 // Emit a warning if the string literal is truncated and does not contain an
9698 // embedded null character.
9699 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
9700 CheckFormatHandler::EmitFormatDiagnostic(
9701 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9702 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
9703 Loc: FExpr->getBeginLoc(),
9704 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
9705 return;
9706 }
9707
9708 // CHECK: empty format string?
9709 if (StrLen == 0 && numDataArgs > 0) {
9710 CheckFormatHandler::EmitFormatDiagnostic(
9711 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9712 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
9713 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9714 return;
9715 }
9716
9717 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
9718 Type == FormatStringType::Kprintf ||
9719 Type == FormatStringType::FreeBSDKPrintf ||
9720 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
9721 bool IsObjC =
9722 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9723 if (ReferenceFormatString == nullptr) {
9724 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9725 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9726 inFunctionCall, CallType, CheckedVarArgs,
9727 UncoveredArg);
9728
9729 if (!analyze_format_string::ParsePrintfString(
9730 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9731 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
9732 Type == FormatStringType::FreeBSDKPrintf))
9733 H.DoneProcessing();
9734 } else {
9735 S.CheckFormatStringsCompatible(
9736 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
9737 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
9738 }
9739 } else if (Type == FormatStringType::Scanf) {
9740 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9741 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9742 CallType, CheckedVarArgs, UncoveredArg);
9743
9744 if (!analyze_format_string::ParseScanfString(
9745 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9746 H.DoneProcessing();
9747 } // TODO: handle other formats
9748}
9749
9750bool Sema::CheckFormatStringsCompatible(
9751 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9752 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9753 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9754 Type != FormatStringType::Kprintf &&
9755 Type != FormatStringType::FreeBSDKPrintf &&
9756 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9757 return true;
9758
9759 bool IsObjC =
9760 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9761 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
9762 FormatStringLiteral RefLit = AuthoritativeFormatString;
9763 FormatStringLiteral TestLit = TestedFormatString;
9764 const Expr *Arg;
9765 bool DiagAtStringLiteral;
9766 if (FunctionCallArg) {
9767 Arg = FunctionCallArg;
9768 DiagAtStringLiteral = false;
9769 } else {
9770 Arg = TestedFormatString;
9771 DiagAtStringLiteral = true;
9772 }
9773 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
9774 FmtExpr: AuthoritativeFormatString, Type,
9775 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
9776 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
9777 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
9778 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
9779 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
9780 InFunctionCall: DiagAtStringLiteral);
9781 }
9782 return false;
9783}
9784
9785bool Sema::ValidateFormatString(FormatStringType Type,
9786 const StringLiteral *Str) {
9787 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9788 Type != FormatStringType::Kprintf &&
9789 Type != FormatStringType::FreeBSDKPrintf &&
9790 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9791 return true;
9792
9793 FormatStringLiteral RefLit = Str;
9794 llvm::SmallVector<EquatableFormatArgument, 9> Args;
9795 bool IsObjC =
9796 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9797 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
9798 InFunctionCall: true, Args))
9799 return false;
9800
9801 // Group arguments by getPosition() value, and check that each member of the
9802 // group is compatible with the first member. This verifies that when
9803 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9804 // are mutually compatible. As an optimization, don't test the first member
9805 // against itself.
9806 bool HadError = false;
9807 auto Iter = Args.begin();
9808 auto End = Args.end();
9809 while (Iter != End) {
9810 const auto &FirstInGroup = *Iter;
9811 for (++Iter;
9812 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9813 ++Iter) {
9814 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
9815 }
9816 }
9817 return !HadError;
9818}
9819
9820bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9821 // Str - The format string. NOTE: this is NOT null-terminated!
9822 StringRef StrRef = FExpr->getString();
9823 const char *Str = StrRef.data();
9824 // Account for cases where the string literal is truncated in a declaration.
9825 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
9826 assert(T && "String literal not of constant array type!");
9827 size_t TypeSize = T->getZExtSize();
9828 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9829 return analyze_format_string::ParseFormatStringHasSArg(beg: Str, end: Str + StrLen,
9830 LO: getLangOpts(),
9831 Target: Context.getTargetInfo());
9832}
9833
9834//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9835
9836// Returns the related absolute value function that is larger, of 0 if one
9837// does not exist.
9838static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9839 switch (AbsFunction) {
9840 default:
9841 return 0;
9842
9843 case Builtin::BI__builtin_abs:
9844 return Builtin::BI__builtin_labs;
9845 case Builtin::BI__builtin_labs:
9846 return Builtin::BI__builtin_llabs;
9847 case Builtin::BI__builtin_llabs:
9848 return 0;
9849
9850 case Builtin::BI__builtin_fabsf:
9851 return Builtin::BI__builtin_fabs;
9852 case Builtin::BI__builtin_fabs:
9853 return Builtin::BI__builtin_fabsl;
9854 case Builtin::BI__builtin_fabsl:
9855 return 0;
9856
9857 case Builtin::BI__builtin_cabsf:
9858 return Builtin::BI__builtin_cabs;
9859 case Builtin::BI__builtin_cabs:
9860 return Builtin::BI__builtin_cabsl;
9861 case Builtin::BI__builtin_cabsl:
9862 return 0;
9863
9864 case Builtin::BIabs:
9865 return Builtin::BIlabs;
9866 case Builtin::BIlabs:
9867 return Builtin::BIllabs;
9868 case Builtin::BIllabs:
9869 return 0;
9870
9871 case Builtin::BIfabsf:
9872 return Builtin::BIfabs;
9873 case Builtin::BIfabs:
9874 return Builtin::BIfabsl;
9875 case Builtin::BIfabsl:
9876 return 0;
9877
9878 case Builtin::BIcabsf:
9879 return Builtin::BIcabs;
9880 case Builtin::BIcabs:
9881 return Builtin::BIcabsl;
9882 case Builtin::BIcabsl:
9883 return 0;
9884 }
9885}
9886
9887// Returns the argument type of the absolute value function.
9888static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9889 unsigned AbsType) {
9890 if (AbsType == 0)
9891 return QualType();
9892
9893 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9894 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
9895 if (Error != ASTContext::GE_None)
9896 return QualType();
9897
9898 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9899 if (!FT)
9900 return QualType();
9901
9902 if (FT->getNumParams() != 1)
9903 return QualType();
9904
9905 return FT->getParamType(i: 0);
9906}
9907
9908// Returns the best absolute value function, or zero, based on type and
9909// current absolute value function.
9910static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9911 unsigned AbsFunctionKind) {
9912 unsigned BestKind = 0;
9913 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
9914 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9915 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
9916 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
9917 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
9918 if (BestKind == 0)
9919 BestKind = Kind;
9920 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
9921 BestKind = Kind;
9922 break;
9923 }
9924 }
9925 }
9926 return BestKind;
9927}
9928
9929enum AbsoluteValueKind {
9930 AVK_Integer,
9931 AVK_Floating,
9932 AVK_Complex
9933};
9934
9935static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9936 if (T->isIntegralOrEnumerationType())
9937 return AVK_Integer;
9938 if (T->isRealFloatingType())
9939 return AVK_Floating;
9940 if (T->isAnyComplexType())
9941 return AVK_Complex;
9942
9943 llvm_unreachable("Type not integer, floating, or complex");
9944}
9945
9946// Changes the absolute value function to a different type. Preserves whether
9947// the function is a builtin.
9948static unsigned changeAbsFunction(unsigned AbsKind,
9949 AbsoluteValueKind ValueKind) {
9950 switch (ValueKind) {
9951 case AVK_Integer:
9952 switch (AbsKind) {
9953 default:
9954 return 0;
9955 case Builtin::BI__builtin_fabsf:
9956 case Builtin::BI__builtin_fabs:
9957 case Builtin::BI__builtin_fabsl:
9958 case Builtin::BI__builtin_cabsf:
9959 case Builtin::BI__builtin_cabs:
9960 case Builtin::BI__builtin_cabsl:
9961 return Builtin::BI__builtin_abs;
9962 case Builtin::BIfabsf:
9963 case Builtin::BIfabs:
9964 case Builtin::BIfabsl:
9965 case Builtin::BIcabsf:
9966 case Builtin::BIcabs:
9967 case Builtin::BIcabsl:
9968 return Builtin::BIabs;
9969 }
9970 case AVK_Floating:
9971 switch (AbsKind) {
9972 default:
9973 return 0;
9974 case Builtin::BI__builtin_abs:
9975 case Builtin::BI__builtin_labs:
9976 case Builtin::BI__builtin_llabs:
9977 case Builtin::BI__builtin_cabsf:
9978 case Builtin::BI__builtin_cabs:
9979 case Builtin::BI__builtin_cabsl:
9980 return Builtin::BI__builtin_fabsf;
9981 case Builtin::BIabs:
9982 case Builtin::BIlabs:
9983 case Builtin::BIllabs:
9984 case Builtin::BIcabsf:
9985 case Builtin::BIcabs:
9986 case Builtin::BIcabsl:
9987 return Builtin::BIfabsf;
9988 }
9989 case AVK_Complex:
9990 switch (AbsKind) {
9991 default:
9992 return 0;
9993 case Builtin::BI__builtin_abs:
9994 case Builtin::BI__builtin_labs:
9995 case Builtin::BI__builtin_llabs:
9996 case Builtin::BI__builtin_fabsf:
9997 case Builtin::BI__builtin_fabs:
9998 case Builtin::BI__builtin_fabsl:
9999 return Builtin::BI__builtin_cabsf;
10000 case Builtin::BIabs:
10001 case Builtin::BIlabs:
10002 case Builtin::BIllabs:
10003 case Builtin::BIfabsf:
10004 case Builtin::BIfabs:
10005 case Builtin::BIfabsl:
10006 return Builtin::BIcabsf;
10007 }
10008 }
10009 llvm_unreachable("Unable to convert function");
10010}
10011
10012static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10013 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10014 if (!FnInfo)
10015 return 0;
10016
10017 switch (FDecl->getBuiltinID()) {
10018 default:
10019 return 0;
10020 case Builtin::BI__builtin_abs:
10021 case Builtin::BI__builtin_fabs:
10022 case Builtin::BI__builtin_fabsf:
10023 case Builtin::BI__builtin_fabsl:
10024 case Builtin::BI__builtin_labs:
10025 case Builtin::BI__builtin_llabs:
10026 case Builtin::BI__builtin_cabs:
10027 case Builtin::BI__builtin_cabsf:
10028 case Builtin::BI__builtin_cabsl:
10029 case Builtin::BIabs:
10030 case Builtin::BIlabs:
10031 case Builtin::BIllabs:
10032 case Builtin::BIfabs:
10033 case Builtin::BIfabsf:
10034 case Builtin::BIfabsl:
10035 case Builtin::BIcabs:
10036 case Builtin::BIcabsf:
10037 case Builtin::BIcabsl:
10038 return FDecl->getBuiltinID();
10039 }
10040 llvm_unreachable("Unknown Builtin type");
10041}
10042
10043// If the replacement is valid, emit a note with replacement function.
10044// Additionally, suggest including the proper header if not already included.
10045static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10046 unsigned AbsKind, QualType ArgType) {
10047 bool EmitHeaderHint = true;
10048 const char *HeaderName = nullptr;
10049 std::string FunctionName;
10050 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10051 FunctionName = "std::abs";
10052 if (ArgType->isIntegralOrEnumerationType()) {
10053 HeaderName = "cstdlib";
10054 } else if (ArgType->isRealFloatingType()) {
10055 HeaderName = "cmath";
10056 } else {
10057 llvm_unreachable("Invalid Type");
10058 }
10059
10060 // Lookup all std::abs
10061 if (NamespaceDecl *Std = S.getStdNamespace()) {
10062 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10063 R.suppressDiagnostics();
10064 S.LookupQualifiedName(R, LookupCtx: Std);
10065
10066 for (const auto *I : R) {
10067 const FunctionDecl *FDecl = nullptr;
10068 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10069 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10070 } else {
10071 FDecl = dyn_cast<FunctionDecl>(Val: I);
10072 }
10073 if (!FDecl)
10074 continue;
10075
10076 // Found std::abs(), check that they are the right ones.
10077 if (FDecl->getNumParams() != 1)
10078 continue;
10079
10080 // Check that the parameter type can handle the argument.
10081 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10082 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10083 S.Context.getTypeSize(T: ArgType) <=
10084 S.Context.getTypeSize(T: ParamType)) {
10085 // Found a function, don't need the header hint.
10086 EmitHeaderHint = false;
10087 break;
10088 }
10089 }
10090 }
10091 } else {
10092 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10093 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10094
10095 if (HeaderName) {
10096 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10097 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10098 R.suppressDiagnostics();
10099 S.LookupName(R, S: S.getCurScope());
10100
10101 if (R.isSingleResult()) {
10102 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10103 if (FD && FD->getBuiltinID() == AbsKind) {
10104 EmitHeaderHint = false;
10105 } else {
10106 return;
10107 }
10108 } else if (!R.empty()) {
10109 return;
10110 }
10111 }
10112 }
10113
10114 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10115 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10116
10117 if (!HeaderName)
10118 return;
10119
10120 if (!EmitHeaderHint)
10121 return;
10122
10123 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10124 << FunctionName;
10125}
10126
10127template <std::size_t StrLen>
10128static bool IsStdFunction(const FunctionDecl *FDecl,
10129 const char (&Str)[StrLen]) {
10130 if (!FDecl)
10131 return false;
10132 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10133 return false;
10134 if (!FDecl->isInStdNamespace())
10135 return false;
10136
10137 return true;
10138}
10139
10140enum class MathCheck { NaN, Inf };
10141static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10142 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10143 return llvm::is_contained(Set: names, Element: calleeName);
10144 };
10145
10146 switch (Check) {
10147 case MathCheck::NaN:
10148 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10149 "__builtin_nanf16", "__builtin_nanf128"});
10150 case MathCheck::Inf:
10151 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10152 "__builtin_inff16", "__builtin_inff128"});
10153 }
10154 llvm_unreachable("unknown MathCheck");
10155}
10156
10157static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10158 if (FDecl->getName() != "infinity")
10159 return false;
10160
10161 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10162 const CXXRecordDecl *RDecl = MDecl->getParent();
10163 if (RDecl->getName() != "numeric_limits")
10164 return false;
10165
10166 if (const NamespaceDecl *NSDecl =
10167 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10168 return NSDecl->isStdNamespace();
10169 }
10170
10171 return false;
10172}
10173
10174void Sema::CheckInfNaNFunction(const CallExpr *Call,
10175 const FunctionDecl *FDecl) {
10176 if (!FDecl->getIdentifier())
10177 return;
10178
10179 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10180 if (FPO.getNoHonorNaNs() &&
10181 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10182 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10183 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10184 << 1 << 0 << Call->getSourceRange();
10185 return;
10186 }
10187
10188 if (FPO.getNoHonorInfs() &&
10189 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10190 IsInfinityFunction(FDecl) ||
10191 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10192 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10193 << 0 << 0 << Call->getSourceRange();
10194 }
10195}
10196
10197void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10198 const FunctionDecl *FDecl) {
10199 if (Call->getNumArgs() != 1)
10200 return;
10201
10202 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10203 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10204 if (AbsKind == 0 && !IsStdAbs)
10205 return;
10206
10207 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10208 QualType ParamType = Call->getArg(Arg: 0)->getType();
10209
10210 // Unsigned types cannot be negative. Suggest removing the absolute value
10211 // function call.
10212 if (ArgType->isUnsignedIntegerType()) {
10213 std::string FunctionName =
10214 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10215 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10216 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10217 << FunctionName
10218 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10219 return;
10220 }
10221
10222 // Taking the absolute value of a pointer is very suspicious, they probably
10223 // wanted to index into an array, dereference a pointer, call a function, etc.
10224 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10225 unsigned DiagType = 0;
10226 if (ArgType->isFunctionType())
10227 DiagType = 1;
10228 else if (ArgType->isArrayType())
10229 DiagType = 2;
10230
10231 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10232 return;
10233 }
10234
10235 // std::abs has overloads which prevent most of the absolute value problems
10236 // from occurring.
10237 if (IsStdAbs)
10238 return;
10239
10240 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10241 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10242
10243 // The argument and parameter are the same kind. Check if they are the right
10244 // size.
10245 if (ArgValueKind == ParamValueKind) {
10246 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10247 return;
10248
10249 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10250 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10251 << FDecl << ArgType << ParamType;
10252
10253 if (NewAbsKind == 0)
10254 return;
10255
10256 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10257 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10258 return;
10259 }
10260
10261 // ArgValueKind != ParamValueKind
10262 // The wrong type of absolute value function was used. Attempt to find the
10263 // proper one.
10264 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10265 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10266 if (NewAbsKind == 0)
10267 return;
10268
10269 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10270 << FDecl << ParamValueKind << ArgValueKind;
10271
10272 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10273 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10274}
10275
10276//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10277void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10278 const FunctionDecl *FDecl) {
10279 if (!Call || !FDecl) return;
10280
10281 // Ignore template specializations and macros.
10282 if (inTemplateInstantiation()) return;
10283 if (Call->getExprLoc().isMacroID()) return;
10284
10285 // Only care about the one template argument, two function parameter std::max
10286 if (Call->getNumArgs() != 2) return;
10287 if (!IsStdFunction(FDecl, Str: "max")) return;
10288 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10289 if (!ArgList) return;
10290 if (ArgList->size() != 1) return;
10291
10292 // Check that template type argument is unsigned integer.
10293 const auto& TA = ArgList->get(Idx: 0);
10294 if (TA.getKind() != TemplateArgument::Type) return;
10295 QualType ArgType = TA.getAsType();
10296 if (!ArgType->isUnsignedIntegerType()) return;
10297
10298 // See if either argument is a literal zero.
10299 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10300 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10301 if (!MTE) return false;
10302 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10303 if (!Num) return false;
10304 if (Num->getValue() != 0) return false;
10305 return true;
10306 };
10307
10308 const Expr *FirstArg = Call->getArg(Arg: 0);
10309 const Expr *SecondArg = Call->getArg(Arg: 1);
10310 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10311 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10312
10313 // Only warn when exactly one argument is zero.
10314 if (IsFirstArgZero == IsSecondArgZero) return;
10315
10316 SourceRange FirstRange = FirstArg->getSourceRange();
10317 SourceRange SecondRange = SecondArg->getSourceRange();
10318
10319 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10320
10321 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10322 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10323
10324 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10325 SourceRange RemovalRange;
10326 if (IsFirstArgZero) {
10327 RemovalRange = SourceRange(FirstRange.getBegin(),
10328 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10329 } else {
10330 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10331 SecondRange.getEnd());
10332 }
10333
10334 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10335 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10336 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10337}
10338
10339//===--- CHECK: Standard memory functions ---------------------------------===//
10340
10341/// Takes the expression passed to the size_t parameter of functions
10342/// such as memcmp, strncat, etc and warns if it's a comparison.
10343///
10344/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10345static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10346 const IdentifierInfo *FnName,
10347 SourceLocation FnLoc,
10348 SourceLocation RParenLoc) {
10349 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10350 if (!Size)
10351 return false;
10352
10353 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10354 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10355 return false;
10356
10357 SourceRange SizeRange = Size->getSourceRange();
10358 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10359 << SizeRange << FnName;
10360 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10361 << FnName
10362 << FixItHint::CreateInsertion(
10363 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10364 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10365 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10366 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10367 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10368 Code: ")");
10369
10370 return true;
10371}
10372
10373/// Determine whether the given type is or contains a dynamic class type
10374/// (e.g., whether it has a vtable).
10375static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10376 bool &IsContained) {
10377 // Look through array types while ignoring qualifiers.
10378 const Type *Ty = T->getBaseElementTypeUnsafe();
10379 IsContained = false;
10380
10381 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10382 RD = RD ? RD->getDefinition() : nullptr;
10383 if (!RD || RD->isInvalidDecl())
10384 return nullptr;
10385
10386 if (RD->isDynamicClass())
10387 return RD;
10388
10389 // Check all the fields. If any bases were dynamic, the class is dynamic.
10390 // It's impossible for a class to transitively contain itself by value, so
10391 // infinite recursion is impossible.
10392 for (auto *FD : RD->fields()) {
10393 bool SubContained;
10394 if (const CXXRecordDecl *ContainedRD =
10395 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10396 IsContained = true;
10397 return ContainedRD;
10398 }
10399 }
10400
10401 return nullptr;
10402}
10403
10404static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10405 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10406 if (Unary->getKind() == UETT_SizeOf)
10407 return Unary;
10408 return nullptr;
10409}
10410
10411/// If E is a sizeof expression, returns its argument expression,
10412/// otherwise returns NULL.
10413static const Expr *getSizeOfExprArg(const Expr *E) {
10414 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10415 if (!SizeOf->isArgumentType())
10416 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10417 return nullptr;
10418}
10419
10420/// If E is a sizeof expression, returns its argument type.
10421static QualType getSizeOfArgType(const Expr *E) {
10422 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10423 return SizeOf->getTypeOfArgument();
10424 return QualType();
10425}
10426
10427namespace {
10428
10429struct SearchNonTrivialToInitializeField
10430 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10431 using Super =
10432 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10433
10434 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10435
10436 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10437 SourceLocation SL) {
10438 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10439 asDerived().visitArray(PDIK, AT, SL);
10440 return;
10441 }
10442
10443 Super::visitWithKind(PDIK, FT, Args&: SL);
10444 }
10445
10446 void visitARCStrong(QualType FT, SourceLocation SL) {
10447 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10448 }
10449 void visitARCWeak(QualType FT, SourceLocation SL) {
10450 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10451 }
10452 void visitStruct(QualType FT, SourceLocation SL) {
10453 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10454 visit(FT: FD->getType(), Args: FD->getLocation());
10455 }
10456 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10457 const ArrayType *AT, SourceLocation SL) {
10458 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10459 }
10460 void visitTrivial(QualType FT, SourceLocation SL) {}
10461
10462 static void diag(QualType RT, const Expr *E, Sema &S) {
10463 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10464 }
10465
10466 ASTContext &getContext() { return S.getASTContext(); }
10467
10468 const Expr *E;
10469 Sema &S;
10470};
10471
10472struct SearchNonTrivialToCopyField
10473 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10474 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10475
10476 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10477
10478 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10479 SourceLocation SL) {
10480 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10481 asDerived().visitArray(PCK, AT, SL);
10482 return;
10483 }
10484
10485 Super::visitWithKind(PCK, FT, Args&: SL);
10486 }
10487
10488 void visitARCStrong(QualType FT, SourceLocation SL) {
10489 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10490 }
10491 void visitARCWeak(QualType FT, SourceLocation SL) {
10492 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10493 }
10494 void visitPtrAuth(QualType FT, SourceLocation SL) {
10495 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10496 }
10497 void visitStruct(QualType FT, SourceLocation SL) {
10498 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10499 visit(FT: FD->getType(), Args: FD->getLocation());
10500 }
10501 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10502 SourceLocation SL) {
10503 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10504 }
10505 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10506 SourceLocation SL) {}
10507 void visitTrivial(QualType FT, SourceLocation SL) {}
10508 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10509
10510 static void diag(QualType RT, const Expr *E, Sema &S) {
10511 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10512 }
10513
10514 ASTContext &getContext() { return S.getASTContext(); }
10515
10516 const Expr *E;
10517 Sema &S;
10518};
10519
10520}
10521
10522/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10523static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10524 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10525
10526 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
10527 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10528 return false;
10529
10530 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
10531 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
10532 }
10533
10534 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
10535}
10536
10537/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10538///
10539/// \code
10540/// #define MACRO 0
10541/// foo(MACRO);
10542/// foo(0);
10543/// \endcode
10544///
10545/// This should return true for the first call to foo, but not for the second
10546/// (regardless of whether foo is a macro or function).
10547static bool isArgumentExpandedFromMacro(SourceManager &SM,
10548 SourceLocation CallLoc,
10549 SourceLocation ArgLoc) {
10550 if (!CallLoc.isMacroID())
10551 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
10552
10553 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
10554 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
10555}
10556
10557/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10558/// last two arguments transposed.
10559static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10560 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10561 return;
10562
10563 const Expr *SizeArg =
10564 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10565
10566 auto isLiteralZero = [](const Expr *E) {
10567 return (isa<IntegerLiteral>(Val: E) &&
10568 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
10569 (isa<CharacterLiteral>(Val: E) &&
10570 cast<CharacterLiteral>(Val: E)->getValue() == 0);
10571 };
10572
10573 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10574 SourceLocation CallLoc = Call->getRParenLoc();
10575 SourceManager &SM = S.getSourceManager();
10576 if (isLiteralZero(SizeArg) &&
10577 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
10578
10579 SourceLocation DiagLoc = SizeArg->getExprLoc();
10580
10581 // Some platforms #define bzero to __builtin_memset. See if this is the
10582 // case, and if so, emit a better diagnostic.
10583 if (BId == Builtin::BIbzero ||
10584 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10585 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
10586 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
10587 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
10588 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
10589 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
10590 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
10591 }
10592 return;
10593 }
10594
10595 // If the second argument to a memset is a sizeof expression and the third
10596 // isn't, this is also likely an error. This should catch
10597 // 'memset(buf, sizeof(buf), 0xff)'.
10598 if (BId == Builtin::BImemset &&
10599 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
10600 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
10601 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
10602 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
10603 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
10604 return;
10605 }
10606}
10607
10608void Sema::CheckMemaccessArguments(const CallExpr *Call,
10609 unsigned BId,
10610 IdentifierInfo *FnName) {
10611 assert(BId != 0);
10612
10613 // It is possible to have a non-standard definition of memset. Validate
10614 // we have enough arguments, and if not, abort further checking.
10615 unsigned ExpectedNumArgs =
10616 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10617 if (Call->getNumArgs() < ExpectedNumArgs)
10618 return;
10619
10620 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10621 BId == Builtin::BIstrndup ? 1 : 2);
10622 unsigned LenArg =
10623 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10624 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
10625
10626 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
10627 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10628 return;
10629
10630 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10631 CheckMemaccessSize(S&: *this, BId, Call);
10632
10633 // We have special checking when the length is a sizeof expression.
10634 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
10635
10636 // Although widely used, 'bzero' is not a standard function. Be more strict
10637 // with the argument types before allowing diagnostics and only allow the
10638 // form bzero(ptr, sizeof(...)).
10639 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10640 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10641 return;
10642
10643 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10644 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
10645 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
10646
10647 QualType DestTy = Dest->getType();
10648 QualType PointeeTy;
10649 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10650 PointeeTy = DestPtrTy->getPointeeType();
10651
10652 // Never warn about void type pointers. This can be used to suppress
10653 // false positives.
10654 if (PointeeTy->isVoidType())
10655 continue;
10656
10657 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10658 // actually comparing the expressions for equality. Because computing the
10659 // expression IDs can be expensive, we only do this if the diagnostic is
10660 // enabled.
10661 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
10662 break;
10663
10664 // Also check for cases where the sizeof argument is the exact same
10665 // type as the memory argument, and where it points to a user-defined
10666 // record type.
10667 if (SizeOfArgTy != QualType()) {
10668 if (PointeeTy->isRecordType() &&
10669 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
10670 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
10671 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
10672 << FnName << SizeOfArgTy << ArgIdx
10673 << PointeeTy << Dest->getSourceRange()
10674 << LenExpr->getSourceRange());
10675 break;
10676 }
10677 }
10678 } else if (DestTy->isArrayType()) {
10679 PointeeTy = DestTy;
10680 }
10681
10682 if (PointeeTy == QualType())
10683 continue;
10684
10685 // Always complain about dynamic classes.
10686 bool IsContained;
10687 if (const CXXRecordDecl *ContainedRD =
10688 getContainedDynamicClass(T: PointeeTy, IsContained)) {
10689
10690 unsigned OperationType = 0;
10691 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10692 // "overwritten" if we're warning about the destination for any call
10693 // but memcmp; otherwise a verb appropriate to the call.
10694 if (ArgIdx != 0 || IsCmp) {
10695 if (BId == Builtin::BImemcpy)
10696 OperationType = 1;
10697 else if(BId == Builtin::BImemmove)
10698 OperationType = 2;
10699 else if (IsCmp)
10700 OperationType = 3;
10701 }
10702
10703 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10704 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
10705 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10706 << IsContained << ContainedRD << OperationType
10707 << Call->getCallee()->getSourceRange());
10708 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10709 BId != Builtin::BImemset)
10710 DiagRuntimeBehavior(
10711 Loc: Dest->getExprLoc(), Statement: Dest,
10712 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
10713 << ArgIdx << FnName << PointeeTy
10714 << Call->getCallee()->getSourceRange());
10715 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10716
10717 // FIXME: Do not consider incomplete types even though they may be
10718 // completed later. GCC does not diagnose such code, but we may want to
10719 // consider diagnosing it in the future, perhaps under a different, but
10720 // related, diagnostic group.
10721 bool NonTriviallyCopyableCXXRecord =
10722 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10723 !PointeeTy.isTriviallyCopyableType(Context);
10724
10725 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10726 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
10727 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10728 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10729 << ArgIdx << FnName << PointeeTy << 0);
10730 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
10731 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10732 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10733 // FIXME: Limiting this warning to dest argument until we decide
10734 // whether it's valid for source argument too.
10735 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10736 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10737 << FnName << PointeeTy);
10738 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10739 RD->isNonTrivialToPrimitiveCopy()) {
10740 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10741 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10742 << ArgIdx << FnName << PointeeTy << 1);
10743 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
10744 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10745 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10746 // FIXME: Limiting this warning to dest argument until we decide
10747 // whether it's valid for source argument too.
10748 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10749 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10750 << FnName << PointeeTy);
10751 } else {
10752 continue;
10753 }
10754 } else
10755 continue;
10756
10757 DiagRuntimeBehavior(
10758 Loc: Dest->getExprLoc(), Statement: Dest,
10759 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
10760 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
10761 break;
10762 }
10763}
10764
10765bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10766 IdentifierInfo *FnName) {
10767 llvm::FoldingSetNodeID SizeOfArgID;
10768 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
10769 if (!SizeOfArg)
10770 return false;
10771 // Computing this warning is expensive, so we only do so if the warning is
10772 // enabled.
10773 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
10774 Loc: SizeOfArg->getExprLoc()))
10775 return false;
10776 QualType DestTy = Dest->getType();
10777 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10778 if (!DestPtrTy)
10779 return false;
10780
10781 QualType PointeeTy = DestPtrTy->getPointeeType();
10782
10783 if (SizeOfArgID == llvm::FoldingSetNodeID())
10784 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
10785
10786 llvm::FoldingSetNodeID DestID;
10787 Dest->Profile(ID&: DestID, Context, Canonical: true);
10788 if (DestID == SizeOfArgID) {
10789 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10790 // over sizeof(src) as well.
10791 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10792 StringRef ReadableName = FnName->getName();
10793
10794 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
10795 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10796 ActionIdx = 1; // If its an address-of operator, just remove it.
10797 if (!PointeeTy->isIncompleteType() &&
10798 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
10799 ActionIdx = 2; // If the pointee's size is sizeof(char),
10800 // suggest an explicit length.
10801
10802 // If the function is defined as a builtin macro, do not show macro
10803 // expansion.
10804 SourceLocation SL = SizeOfArg->getExprLoc();
10805 SourceRange DSR = Dest->getSourceRange();
10806 SourceRange SSR = SizeOfArg->getSourceRange();
10807 SourceManager &SM = getSourceManager();
10808
10809 if (SM.isMacroArgExpansion(Loc: SL)) {
10810 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
10811 SL = SM.getSpellingLoc(Loc: SL);
10812 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
10813 SM.getSpellingLoc(Loc: DSR.getEnd()));
10814 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
10815 SM.getSpellingLoc(Loc: SSR.getEnd()));
10816 }
10817
10818 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10819 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
10820 << ReadableName << PointeeTy << DestTy << DSR
10821 << SSR);
10822 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10823 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
10824 << ActionIdx << SSR);
10825 return true;
10826 }
10827 return false;
10828}
10829
10830// A little helper routine: ignore addition and subtraction of integer literals.
10831// This intentionally does not ignore all integer constant expressions because
10832// we don't want to remove sizeof().
10833static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10834 Ex = Ex->IgnoreParenCasts();
10835
10836 while (true) {
10837 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
10838 if (!BO || !BO->isAdditiveOp())
10839 break;
10840
10841 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10842 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10843
10844 if (isa<IntegerLiteral>(Val: RHS))
10845 Ex = LHS;
10846 else if (isa<IntegerLiteral>(Val: LHS))
10847 Ex = RHS;
10848 else
10849 break;
10850 }
10851
10852 return Ex;
10853}
10854
10855static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10856 ASTContext &Context) {
10857 // Only handle constant-sized or VLAs, but not flexible members.
10858 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
10859 // Only issue the FIXIT for arrays of size > 1.
10860 if (CAT->getZExtSize() <= 1)
10861 return false;
10862 } else if (!Ty->isVariableArrayType()) {
10863 return false;
10864 }
10865 return true;
10866}
10867
10868void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10869 IdentifierInfo *FnName) {
10870
10871 // Don't crash if the user has the wrong number of arguments
10872 unsigned NumArgs = Call->getNumArgs();
10873 if ((NumArgs != 3) && (NumArgs != 4))
10874 return;
10875
10876 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
10877 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
10878 const Expr *CompareWithSrc = nullptr;
10879
10880 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
10881 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10882 return;
10883
10884 // Look for 'strlcpy(dst, x, sizeof(x))'
10885 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
10886 CompareWithSrc = Ex;
10887 else {
10888 // Look for 'strlcpy(dst, x, strlen(x))'
10889 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
10890 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10891 SizeCall->getNumArgs() == 1)
10892 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
10893 }
10894 }
10895
10896 if (!CompareWithSrc)
10897 return;
10898
10899 // Determine if the argument to sizeof/strlen is equal to the source
10900 // argument. In principle there's all kinds of things you could do
10901 // here, for instance creating an == expression and evaluating it with
10902 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10903 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
10904 if (!SrcArgDRE)
10905 return;
10906
10907 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
10908 if (!CompareWithSrcDRE ||
10909 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10910 return;
10911
10912 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
10913 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
10914 << OriginalSizeArg->getSourceRange() << FnName;
10915
10916 // Output a FIXIT hint if the destination is an array (rather than a
10917 // pointer to an array). This could be enhanced to handle some
10918 // pointers if we know the actual size, like if DstArg is 'array+2'
10919 // we could say 'sizeof(array)-2'.
10920 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
10921 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
10922 return;
10923
10924 SmallString<128> sizeString;
10925 llvm::raw_svector_ostream OS(sizeString);
10926 OS << "sizeof(";
10927 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10928 OS << ")";
10929
10930 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
10931 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
10932 Code: OS.str());
10933}
10934
10935/// Check if two expressions refer to the same declaration.
10936static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10937 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
10938 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
10939 return D1->getDecl() == D2->getDecl();
10940 return false;
10941}
10942
10943static const Expr *getStrlenExprArg(const Expr *E) {
10944 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
10945 const FunctionDecl *FD = CE->getDirectCallee();
10946 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10947 return nullptr;
10948 return CE->getArg(Arg: 0)->IgnoreParenCasts();
10949 }
10950 return nullptr;
10951}
10952
10953void Sema::CheckStrncatArguments(const CallExpr *CE,
10954 const IdentifierInfo *FnName) {
10955 // Don't crash if the user has the wrong number of arguments.
10956 if (CE->getNumArgs() < 3)
10957 return;
10958 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
10959 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
10960 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
10961
10962 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
10963 RParenLoc: CE->getRParenLoc()))
10964 return;
10965
10966 // Identify common expressions, which are wrongly used as the size argument
10967 // to strncat and may lead to buffer overflows.
10968 unsigned PatternType = 0;
10969 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
10970 // - sizeof(dst)
10971 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
10972 PatternType = 1;
10973 // - sizeof(src)
10974 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
10975 PatternType = 2;
10976 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
10977 if (BE->getOpcode() == BO_Sub) {
10978 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10979 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10980 // - sizeof(dst) - strlen(dst)
10981 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
10982 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
10983 PatternType = 1;
10984 // - sizeof(src) - (anything)
10985 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
10986 PatternType = 2;
10987 }
10988 }
10989
10990 if (PatternType == 0)
10991 return;
10992
10993 // Generate the diagnostic.
10994 SourceLocation SL = LenArg->getBeginLoc();
10995 SourceRange SR = LenArg->getSourceRange();
10996 SourceManager &SM = getSourceManager();
10997
10998 // If the function is defined as a builtin macro, do not show macro expansion.
10999 if (SM.isMacroArgExpansion(Loc: SL)) {
11000 SL = SM.getSpellingLoc(Loc: SL);
11001 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11002 SM.getSpellingLoc(Loc: SR.getEnd()));
11003 }
11004
11005 // Check if the destination is an array (rather than a pointer to an array).
11006 QualType DstTy = DstArg->getType();
11007 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11008 Context);
11009 if (!isKnownSizeArray) {
11010 if (PatternType == 1)
11011 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11012 else
11013 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11014 return;
11015 }
11016
11017 if (PatternType == 1)
11018 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11019 else
11020 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11021
11022 SmallString<128> sizeString;
11023 llvm::raw_svector_ostream OS(sizeString);
11024 OS << "sizeof(";
11025 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11026 OS << ") - ";
11027 OS << "strlen(";
11028 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11029 OS << ") - 1";
11030
11031 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11032 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11033}
11034
11035namespace {
11036void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11037 const UnaryOperator *UnaryExpr, const Decl *D) {
11038 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11039 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11040 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11041 return;
11042 }
11043}
11044
11045void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11046 const UnaryOperator *UnaryExpr) {
11047 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11048 const Decl *D = Lvalue->getDecl();
11049 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11050 if (!DD->getType()->isReferenceType())
11051 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11052 }
11053 }
11054
11055 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11056 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11057 D: Lvalue->getMemberDecl());
11058}
11059
11060void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11061 const UnaryOperator *UnaryExpr) {
11062 const auto *Lambda = dyn_cast<LambdaExpr>(
11063 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11064 if (!Lambda)
11065 return;
11066
11067 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11068 << CalleeName << 2 /*object: lambda expression*/;
11069}
11070
11071void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11072 const DeclRefExpr *Lvalue) {
11073 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11074 if (Var == nullptr)
11075 return;
11076
11077 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11078 << CalleeName << 0 /*object: */ << Var;
11079}
11080
11081void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11082 const CastExpr *Cast) {
11083 SmallString<128> SizeString;
11084 llvm::raw_svector_ostream OS(SizeString);
11085
11086 clang::CastKind Kind = Cast->getCastKind();
11087 if (Kind == clang::CK_BitCast &&
11088 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11089 return;
11090 if (Kind == clang::CK_IntegralToPointer &&
11091 !isa<IntegerLiteral>(
11092 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11093 return;
11094
11095 switch (Cast->getCastKind()) {
11096 case clang::CK_BitCast:
11097 case clang::CK_IntegralToPointer:
11098 case clang::CK_FunctionToPointerDecay:
11099 OS << '\'';
11100 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11101 OS << '\'';
11102 break;
11103 default:
11104 return;
11105 }
11106
11107 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11108 << CalleeName << 0 /*object: */ << OS.str();
11109}
11110} // namespace
11111
11112void Sema::CheckFreeArguments(const CallExpr *E) {
11113 const std::string CalleeName =
11114 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11115
11116 { // Prefer something that doesn't involve a cast to make things simpler.
11117 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11118 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11119 switch (UnaryExpr->getOpcode()) {
11120 case UnaryOperator::Opcode::UO_AddrOf:
11121 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11122 case UnaryOperator::Opcode::UO_Plus:
11123 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11124 default:
11125 break;
11126 }
11127
11128 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11129 if (Lvalue->getType()->isArrayType())
11130 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11131
11132 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11133 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11134 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11135 return;
11136 }
11137
11138 if (isa<BlockExpr>(Val: Arg)) {
11139 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11140 << CalleeName << 1 /*object: block*/;
11141 return;
11142 }
11143 }
11144 // Maybe the cast was important, check after the other cases.
11145 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11146 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11147}
11148
11149void
11150Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11151 SourceLocation ReturnLoc,
11152 bool isObjCMethod,
11153 const AttrVec *Attrs,
11154 const FunctionDecl *FD) {
11155 // Check if the return value is null but should not be.
11156 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11157 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11158 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11159 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11160 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11161
11162 // C++11 [basic.stc.dynamic.allocation]p4:
11163 // If an allocation function declared with a non-throwing
11164 // exception-specification fails to allocate storage, it shall return
11165 // a null pointer. Any other allocation function that fails to allocate
11166 // storage shall indicate failure only by throwing an exception [...]
11167 if (FD) {
11168 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11169 if (Op == OO_New || Op == OO_Array_New) {
11170 const FunctionProtoType *Proto
11171 = FD->getType()->castAs<FunctionProtoType>();
11172 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11173 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11174 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11175 << FD << getLangOpts().CPlusPlus11;
11176 }
11177 }
11178
11179 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11180 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11181 }
11182
11183 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11184 // here prevent the user from using a PPC MMA type as trailing return type.
11185 if (Context.getTargetInfo().getTriple().isPPC64())
11186 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11187}
11188
11189void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11190 const Expr *RHS, BinaryOperatorKind Opcode) {
11191 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11192 return;
11193
11194 // Match and capture subexpressions such as "(float) X == 0.1".
11195 const FloatingLiteral *FPLiteral;
11196 const CastExpr *FPCast;
11197 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11198 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11199 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11200 return FPLiteral && FPCast;
11201 };
11202
11203 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11204 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11205 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11206 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11207 TargetTy->isFloatingPoint()) {
11208 bool Lossy;
11209 llvm::APFloat TargetC = FPLiteral->getValue();
11210 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11211 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11212 if (Lossy) {
11213 // If the literal cannot be represented in the source type, then a
11214 // check for == is always false and check for != is always true.
11215 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11216 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11217 << LHS->getSourceRange() << RHS->getSourceRange();
11218 return;
11219 }
11220 }
11221 }
11222
11223 // Match a more general floating-point equality comparison (-Wfloat-equal).
11224 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11225 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11226
11227 // Special case: check for x == x (which is OK).
11228 // Do not emit warnings for such cases.
11229 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11230 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11231 if (DRL->getDecl() == DRR->getDecl())
11232 return;
11233
11234 // Special case: check for comparisons against literals that can be exactly
11235 // represented by APFloat. In such cases, do not emit a warning. This
11236 // is a heuristic: often comparison against such literals are used to
11237 // detect if a value in a variable has not changed. This clearly can
11238 // lead to false negatives.
11239 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11240 if (FLL->isExact())
11241 return;
11242 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11243 if (FLR->isExact())
11244 return;
11245
11246 // Check for comparisons with builtin types.
11247 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11248 CL && CL->getBuiltinCallee())
11249 return;
11250
11251 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11252 CR && CR->getBuiltinCallee())
11253 return;
11254
11255 // Emit the diagnostic.
11256 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11257 << LHS->getSourceRange() << RHS->getSourceRange();
11258}
11259
11260//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11261//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11262
11263namespace {
11264
11265/// Structure recording the 'active' range of an integer-valued
11266/// expression.
11267struct IntRange {
11268 /// The number of bits active in the int. Note that this includes exactly one
11269 /// sign bit if !NonNegative.
11270 unsigned Width;
11271
11272 /// True if the int is known not to have negative values. If so, all leading
11273 /// bits before Width are known zero, otherwise they are known to be the
11274 /// same as the MSB within Width.
11275 bool NonNegative;
11276
11277 IntRange(unsigned Width, bool NonNegative)
11278 : Width(Width), NonNegative(NonNegative) {}
11279
11280 /// Number of bits excluding the sign bit.
11281 unsigned valueBits() const {
11282 return NonNegative ? Width : Width - 1;
11283 }
11284
11285 /// Returns the range of the bool type.
11286 static IntRange forBoolType() {
11287 return IntRange(1, true);
11288 }
11289
11290 /// Returns the range of an opaque value of the given integral type.
11291 static IntRange forValueOfType(ASTContext &C, QualType T) {
11292 return forValueOfCanonicalType(C,
11293 T: T->getCanonicalTypeInternal().getTypePtr());
11294 }
11295
11296 /// Returns the range of an opaque value of a canonical integral type.
11297 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11298 assert(T->isCanonicalUnqualified());
11299
11300 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11301 T = VT->getElementType().getTypePtr();
11302 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11303 T = MT->getElementType().getTypePtr();
11304 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11305 T = CT->getElementType().getTypePtr();
11306 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11307 T = AT->getValueType().getTypePtr();
11308 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11309 T = OBT->getUnderlyingType().getTypePtr();
11310
11311 if (!C.getLangOpts().CPlusPlus) {
11312 // For enum types in C code, use the underlying datatype.
11313 if (const auto *ED = T->getAsEnumDecl())
11314 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11315 } else if (auto *Enum = T->getAsEnumDecl()) {
11316 // For enum types in C++, use the known bit width of the enumerators.
11317 // In C++11, enums can have a fixed underlying type. Use this type to
11318 // compute the range.
11319 if (Enum->isFixed()) {
11320 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11321 !Enum->getIntegerType()->isSignedIntegerType());
11322 }
11323
11324 unsigned NumPositive = Enum->getNumPositiveBits();
11325 unsigned NumNegative = Enum->getNumNegativeBits();
11326
11327 if (NumNegative == 0)
11328 return IntRange(NumPositive, true/*NonNegative*/);
11329 else
11330 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11331 false/*NonNegative*/);
11332 }
11333
11334 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11335 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11336
11337 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11338 assert(BT->isInteger());
11339
11340 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11341 }
11342
11343 /// Returns the "target" range of a canonical integral type, i.e.
11344 /// the range of values expressible in the type.
11345 ///
11346 /// This matches forValueOfCanonicalType except that enums have the
11347 /// full range of their type, not the range of their enumerators.
11348 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11349 assert(T->isCanonicalUnqualified());
11350
11351 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11352 T = VT->getElementType().getTypePtr();
11353 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11354 T = MT->getElementType().getTypePtr();
11355 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11356 T = CT->getElementType().getTypePtr();
11357 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11358 T = AT->getValueType().getTypePtr();
11359 if (const auto *ED = T->getAsEnumDecl())
11360 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11361 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11362 T = OBT->getUnderlyingType().getTypePtr();
11363
11364 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11365 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11366
11367 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11368 assert(BT->isInteger());
11369
11370 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11371 }
11372
11373 /// Returns the supremum of two ranges: i.e. their conservative merge.
11374 static IntRange join(IntRange L, IntRange R) {
11375 bool Unsigned = L.NonNegative && R.NonNegative;
11376 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11377 L.NonNegative && R.NonNegative);
11378 }
11379
11380 /// Return the range of a bitwise-AND of the two ranges.
11381 static IntRange bit_and(IntRange L, IntRange R) {
11382 unsigned Bits = std::max(a: L.Width, b: R.Width);
11383 bool NonNegative = false;
11384 if (L.NonNegative) {
11385 Bits = std::min(a: Bits, b: L.Width);
11386 NonNegative = true;
11387 }
11388 if (R.NonNegative) {
11389 Bits = std::min(a: Bits, b: R.Width);
11390 NonNegative = true;
11391 }
11392 return IntRange(Bits, NonNegative);
11393 }
11394
11395 /// Return the range of a sum of the two ranges.
11396 static IntRange sum(IntRange L, IntRange R) {
11397 bool Unsigned = L.NonNegative && R.NonNegative;
11398 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11399 Unsigned);
11400 }
11401
11402 /// Return the range of a difference of the two ranges.
11403 static IntRange difference(IntRange L, IntRange R) {
11404 // We need a 1-bit-wider range if:
11405 // 1) LHS can be negative: least value can be reduced.
11406 // 2) RHS can be negative: greatest value can be increased.
11407 bool CanWiden = !L.NonNegative || !R.NonNegative;
11408 bool Unsigned = L.NonNegative && R.Width == 0;
11409 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11410 !Unsigned,
11411 Unsigned);
11412 }
11413
11414 /// Return the range of a product of the two ranges.
11415 static IntRange product(IntRange L, IntRange R) {
11416 // If both LHS and RHS can be negative, we can form
11417 // -2^L * -2^R = 2^(L + R)
11418 // which requires L + R + 1 value bits to represent.
11419 bool CanWiden = !L.NonNegative && !R.NonNegative;
11420 bool Unsigned = L.NonNegative && R.NonNegative;
11421 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11422 Unsigned);
11423 }
11424
11425 /// Return the range of a remainder operation between the two ranges.
11426 static IntRange rem(IntRange L, IntRange R) {
11427 // The result of a remainder can't be larger than the result of
11428 // either side. The sign of the result is the sign of the LHS.
11429 bool Unsigned = L.NonNegative;
11430 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11431 Unsigned);
11432 }
11433};
11434
11435} // namespace
11436
11437static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11438 if (value.isSigned() && value.isNegative())
11439 return IntRange(value.getSignificantBits(), false);
11440
11441 if (value.getBitWidth() > MaxWidth)
11442 value = value.trunc(width: MaxWidth);
11443
11444 // isNonNegative() just checks the sign bit without considering
11445 // signedness.
11446 return IntRange(value.getActiveBits(), true);
11447}
11448
11449static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11450 if (result.isInt())
11451 return GetValueRange(value&: result.getInt(), MaxWidth);
11452
11453 if (result.isVector()) {
11454 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11455 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11456 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11457 R = IntRange::join(L: R, R: El);
11458 }
11459 return R;
11460 }
11461
11462 if (result.isComplexInt()) {
11463 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11464 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11465 return IntRange::join(L: R, R: I);
11466 }
11467
11468 // This can happen with lossless casts to intptr_t of "based" lvalues.
11469 // Assume it might use arbitrary bits.
11470 // FIXME: The only reason we need to pass the type in here is to get
11471 // the sign right on this one case. It would be nice if APValue
11472 // preserved this.
11473 assert(result.isLValue() || result.isAddrLabelDiff());
11474 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11475}
11476
11477static QualType GetExprType(const Expr *E) {
11478 QualType Ty = E->getType();
11479 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11480 Ty = AtomicRHS->getValueType();
11481 return Ty;
11482}
11483
11484/// Attempts to estimate an approximate range for the given integer expression.
11485/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11486/// reliable estimation cannot be determined.
11487///
11488/// \param MaxWidth The width to which the value will be truncated.
11489/// \param InConstantContext If \c true, interpret the expression within a
11490/// constant context.
11491/// \param Approximate If \c true, provide a likely range of values by assuming
11492/// that arithmetic on narrower types remains within those types.
11493/// If \c false, return a range that includes all possible values
11494/// resulting from the expression.
11495/// \returns A range of values that the expression might take, or
11496/// std::nullopt if a reliable estimation cannot be determined.
11497static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11498 unsigned MaxWidth,
11499 bool InConstantContext,
11500 bool Approximate) {
11501 E = E->IgnoreParens();
11502
11503 // Try a full evaluation first.
11504 Expr::EvalResult result;
11505 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11506 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11507
11508 // I think we only want to look through implicit casts here; if the
11509 // user has an explicit widening cast, we should treat the value as
11510 // being of the new, wider type.
11511 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11512 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11513 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
11514 Approximate);
11515
11516 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
11517
11518 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11519 CE->getCastKind() == CK_BooleanToSignedIntegral;
11520
11521 // Assume that non-integer casts can span the full range of the type.
11522 if (!isIntegerCast)
11523 return OutputTypeRange;
11524
11525 std::optional<IntRange> SubRange = TryGetExprRange(
11526 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
11527 InConstantContext, Approximate);
11528 if (!SubRange)
11529 return std::nullopt;
11530
11531 // Bail out if the subexpr's range is as wide as the cast type.
11532 if (SubRange->Width >= OutputTypeRange.Width)
11533 return OutputTypeRange;
11534
11535 // Otherwise, we take the smaller width, and we're non-negative if
11536 // either the output type or the subexpr is.
11537 return IntRange(SubRange->Width,
11538 SubRange->NonNegative || OutputTypeRange.NonNegative);
11539 }
11540
11541 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
11542 // If we can fold the condition, just take that operand.
11543 bool CondResult;
11544 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
11545 return TryGetExprRange(
11546 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11547 InConstantContext, Approximate);
11548
11549 // Otherwise, conservatively merge.
11550 // TryGetExprRange requires an integer expression, but a throw expression
11551 // results in a void type.
11552 Expr *TrueExpr = CO->getTrueExpr();
11553 if (TrueExpr->getType()->isVoidType())
11554 return std::nullopt;
11555
11556 std::optional<IntRange> L =
11557 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
11558 if (!L)
11559 return std::nullopt;
11560
11561 Expr *FalseExpr = CO->getFalseExpr();
11562 if (FalseExpr->getType()->isVoidType())
11563 return std::nullopt;
11564
11565 std::optional<IntRange> R =
11566 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
11567 if (!R)
11568 return std::nullopt;
11569
11570 return IntRange::join(L: *L, R: *R);
11571 }
11572
11573 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
11574 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11575
11576 switch (BO->getOpcode()) {
11577 case BO_Cmp:
11578 llvm_unreachable("builtin <=> should have class type");
11579
11580 // Boolean-valued operations are single-bit and positive.
11581 case BO_LAnd:
11582 case BO_LOr:
11583 case BO_LT:
11584 case BO_GT:
11585 case BO_LE:
11586 case BO_GE:
11587 case BO_EQ:
11588 case BO_NE:
11589 return IntRange::forBoolType();
11590
11591 // The type of the assignments is the type of the LHS, so the RHS
11592 // is not necessarily the same type.
11593 case BO_MulAssign:
11594 case BO_DivAssign:
11595 case BO_RemAssign:
11596 case BO_AddAssign:
11597 case BO_SubAssign:
11598 case BO_XorAssign:
11599 case BO_OrAssign:
11600 // TODO: bitfields?
11601 return IntRange::forValueOfType(C, T: GetExprType(E));
11602
11603 // Simple assignments just pass through the RHS, which will have
11604 // been coerced to the LHS type.
11605 case BO_Assign:
11606 // TODO: bitfields?
11607 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11608 Approximate);
11609
11610 // Operations with opaque sources are black-listed.
11611 case BO_PtrMemD:
11612 case BO_PtrMemI:
11613 return IntRange::forValueOfType(C, T: GetExprType(E));
11614
11615 // Bitwise-and uses the *infinum* of the two source ranges.
11616 case BO_And:
11617 case BO_AndAssign:
11618 Combine = IntRange::bit_and;
11619 break;
11620
11621 // Left shift gets black-listed based on a judgement call.
11622 case BO_Shl:
11623 // ...except that we want to treat '1 << (blah)' as logically
11624 // positive. It's an important idiom.
11625 if (IntegerLiteral *I
11626 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
11627 if (I->getValue() == 1) {
11628 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
11629 return IntRange(R.Width, /*NonNegative*/ true);
11630 }
11631 }
11632 [[fallthrough]];
11633
11634 case BO_ShlAssign:
11635 return IntRange::forValueOfType(C, T: GetExprType(E));
11636
11637 // Right shift by a constant can narrow its left argument.
11638 case BO_Shr:
11639 case BO_ShrAssign: {
11640 std::optional<IntRange> L = TryGetExprRange(
11641 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11642 if (!L)
11643 return std::nullopt;
11644
11645 // If the shift amount is a positive constant, drop the width by
11646 // that much.
11647 if (std::optional<llvm::APSInt> shift =
11648 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11649 if (shift->isNonNegative()) {
11650 if (shift->uge(RHS: L->Width))
11651 L->Width = (L->NonNegative ? 0 : 1);
11652 else
11653 L->Width -= shift->getZExtValue();
11654 }
11655 }
11656
11657 return L;
11658 }
11659
11660 // Comma acts as its right operand.
11661 case BO_Comma:
11662 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11663 Approximate);
11664
11665 case BO_Add:
11666 if (!Approximate)
11667 Combine = IntRange::sum;
11668 break;
11669
11670 case BO_Sub:
11671 if (BO->getLHS()->getType()->isPointerType())
11672 return IntRange::forValueOfType(C, T: GetExprType(E));
11673 if (!Approximate)
11674 Combine = IntRange::difference;
11675 break;
11676
11677 case BO_Mul:
11678 if (!Approximate)
11679 Combine = IntRange::product;
11680 break;
11681
11682 // The width of a division result is mostly determined by the size
11683 // of the LHS.
11684 case BO_Div: {
11685 // Don't 'pre-truncate' the operands.
11686 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
11687 std::optional<IntRange> L = TryGetExprRange(
11688 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11689 if (!L)
11690 return std::nullopt;
11691
11692 // If the divisor is constant, use that.
11693 if (std::optional<llvm::APSInt> divisor =
11694 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11695 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11696 if (log2 >= L->Width)
11697 L->Width = (L->NonNegative ? 0 : 1);
11698 else
11699 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
11700 return L;
11701 }
11702
11703 // Otherwise, just use the LHS's width.
11704 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11705 // could be -1.
11706 std::optional<IntRange> R = TryGetExprRange(
11707 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11708 if (!R)
11709 return std::nullopt;
11710
11711 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11712 }
11713
11714 case BO_Rem:
11715 Combine = IntRange::rem;
11716 break;
11717
11718 // The default behavior is okay for these.
11719 case BO_Xor:
11720 case BO_Or:
11721 break;
11722 }
11723
11724 // Combine the two ranges, but limit the result to the type in which we
11725 // performed the computation.
11726 QualType T = GetExprType(E);
11727 unsigned opWidth = C.getIntWidth(T);
11728 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
11729 InConstantContext, Approximate);
11730 if (!L)
11731 return std::nullopt;
11732
11733 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
11734 InConstantContext, Approximate);
11735 if (!R)
11736 return std::nullopt;
11737
11738 IntRange C = Combine(*L, *R);
11739 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11740 C.Width = std::min(a: C.Width, b: MaxWidth);
11741 return C;
11742 }
11743
11744 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
11745 switch (UO->getOpcode()) {
11746 // Boolean-valued operations are white-listed.
11747 case UO_LNot:
11748 return IntRange::forBoolType();
11749
11750 // Operations with opaque sources are black-listed.
11751 case UO_Deref:
11752 case UO_AddrOf: // should be impossible
11753 return IntRange::forValueOfType(C, T: GetExprType(E));
11754
11755 case UO_Minus: {
11756 if (E->getType()->isUnsignedIntegerType()) {
11757 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11758 Approximate);
11759 }
11760
11761 std::optional<IntRange> SubRange = TryGetExprRange(
11762 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11763
11764 if (!SubRange)
11765 return std::nullopt;
11766
11767 // If the range was previously non-negative, we need an extra bit for the
11768 // sign bit. Otherwise, we need an extra bit because the negation of the
11769 // most-negative value is one bit wider than that value.
11770 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
11771 }
11772
11773 case UO_Not: {
11774 if (E->getType()->isUnsignedIntegerType()) {
11775 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11776 Approximate);
11777 }
11778
11779 std::optional<IntRange> SubRange = TryGetExprRange(
11780 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11781
11782 if (!SubRange)
11783 return std::nullopt;
11784
11785 // The width increments by 1 if the sub-expression cannot be negative
11786 // since it now can be.
11787 return IntRange(
11788 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
11789 false);
11790 }
11791
11792 default:
11793 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11794 Approximate);
11795 }
11796 }
11797
11798 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
11799 return TryGetExprRange(C, E: OVE->getSourceExpr(), MaxWidth, InConstantContext,
11800 Approximate);
11801
11802 if (const auto *BitField = E->getSourceBitField())
11803 return IntRange(BitField->getBitWidthValue(),
11804 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11805
11806 if (GetExprType(E)->isVoidType())
11807 return std::nullopt;
11808
11809 return IntRange::forValueOfType(C, T: GetExprType(E));
11810}
11811
11812static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11813 bool InConstantContext,
11814 bool Approximate) {
11815 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
11816 Approximate);
11817}
11818
11819/// Checks whether the given value, which currently has the given
11820/// source semantics, has the same value when coerced through the
11821/// target semantics.
11822static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11823 const llvm::fltSemantics &Src,
11824 const llvm::fltSemantics &Tgt) {
11825 llvm::APFloat truncated = value;
11826
11827 bool ignored;
11828 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11829 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11830
11831 return truncated.bitwiseIsEqual(RHS: value);
11832}
11833
11834/// Checks whether the given value, which currently has the given
11835/// source semantics, has the same value when coerced through the
11836/// target semantics.
11837///
11838/// The value might be a vector of floats (or a complex number).
11839static bool IsSameFloatAfterCast(const APValue &value,
11840 const llvm::fltSemantics &Src,
11841 const llvm::fltSemantics &Tgt) {
11842 if (value.isFloat())
11843 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
11844
11845 if (value.isVector()) {
11846 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11847 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
11848 return false;
11849 return true;
11850 }
11851
11852 if (value.isMatrix()) {
11853 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
11854 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
11855 return false;
11856 return true;
11857 }
11858
11859 assert(value.isComplexFloat());
11860 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
11861 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
11862}
11863
11864static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11865 bool IsListInit = false);
11866
11867static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11868 // Suppress cases where we are comparing against an enum constant.
11869 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
11870 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
11871 return true;
11872
11873 // Suppress cases where the value is expanded from a macro, unless that macro
11874 // is how a language represents a boolean literal. This is the case in both C
11875 // and Objective-C.
11876 SourceLocation BeginLoc = E->getBeginLoc();
11877 if (BeginLoc.isMacroID()) {
11878 StringRef MacroName = Lexer::getImmediateMacroName(
11879 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
11880 return MacroName != "YES" && MacroName != "NO" &&
11881 MacroName != "true" && MacroName != "false";
11882 }
11883
11884 return false;
11885}
11886
11887static bool isKnownToHaveUnsignedValue(const Expr *E) {
11888 return E->getType()->isIntegerType() &&
11889 (!E->getType()->isSignedIntegerType() ||
11890 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11891}
11892
11893namespace {
11894/// The promoted range of values of a type. In general this has the
11895/// following structure:
11896///
11897/// |-----------| . . . |-----------|
11898/// ^ ^ ^ ^
11899/// Min HoleMin HoleMax Max
11900///
11901/// ... where there is only a hole if a signed type is promoted to unsigned
11902/// (in which case Min and Max are the smallest and largest representable
11903/// values).
11904struct PromotedRange {
11905 // Min, or HoleMax if there is a hole.
11906 llvm::APSInt PromotedMin;
11907 // Max, or HoleMin if there is a hole.
11908 llvm::APSInt PromotedMax;
11909
11910 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11911 if (R.Width == 0)
11912 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11913 else if (R.Width >= BitWidth && !Unsigned) {
11914 // Promotion made the type *narrower*. This happens when promoting
11915 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11916 // Treat all values of 'signed int' as being in range for now.
11917 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
11918 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
11919 } else {
11920 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
11921 .extOrTrunc(width: BitWidth);
11922 PromotedMin.setIsUnsigned(Unsigned);
11923
11924 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
11925 .extOrTrunc(width: BitWidth);
11926 PromotedMax.setIsUnsigned(Unsigned);
11927 }
11928 }
11929
11930 // Determine whether this range is contiguous (has no hole).
11931 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11932
11933 // Where a constant value is within the range.
11934 enum ComparisonResult {
11935 LT = 0x1,
11936 LE = 0x2,
11937 GT = 0x4,
11938 GE = 0x8,
11939 EQ = 0x10,
11940 NE = 0x20,
11941 InRangeFlag = 0x40,
11942
11943 Less = LE | LT | NE,
11944 Min = LE | InRangeFlag,
11945 InRange = InRangeFlag,
11946 Max = GE | InRangeFlag,
11947 Greater = GE | GT | NE,
11948
11949 OnlyValue = LE | GE | EQ | InRangeFlag,
11950 InHole = NE
11951 };
11952
11953 ComparisonResult compare(const llvm::APSInt &Value) const {
11954 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11955 Value.isUnsigned() == PromotedMin.isUnsigned());
11956 if (!isContiguous()) {
11957 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11958 if (Value.isMinValue()) return Min;
11959 if (Value.isMaxValue()) return Max;
11960 if (Value >= PromotedMin) return InRange;
11961 if (Value <= PromotedMax) return InRange;
11962 return InHole;
11963 }
11964
11965 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
11966 case -1: return Less;
11967 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11968 case 1:
11969 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
11970 case -1: return InRange;
11971 case 0: return Max;
11972 case 1: return Greater;
11973 }
11974 }
11975
11976 llvm_unreachable("impossible compare result");
11977 }
11978
11979 static std::optional<StringRef>
11980 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11981 if (Op == BO_Cmp) {
11982 ComparisonResult LTFlag = LT, GTFlag = GT;
11983 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
11984
11985 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11986 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11987 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11988 return std::nullopt;
11989 }
11990
11991 ComparisonResult TrueFlag, FalseFlag;
11992 if (Op == BO_EQ) {
11993 TrueFlag = EQ;
11994 FalseFlag = NE;
11995 } else if (Op == BO_NE) {
11996 TrueFlag = NE;
11997 FalseFlag = EQ;
11998 } else {
11999 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12000 TrueFlag = LT;
12001 FalseFlag = GE;
12002 } else {
12003 TrueFlag = GT;
12004 FalseFlag = LE;
12005 }
12006 if (Op == BO_GE || Op == BO_LE)
12007 std::swap(a&: TrueFlag, b&: FalseFlag);
12008 }
12009 if (R & TrueFlag)
12010 return StringRef("true");
12011 if (R & FalseFlag)
12012 return StringRef("false");
12013 return std::nullopt;
12014 }
12015};
12016}
12017
12018static bool HasEnumType(const Expr *E) {
12019 // Strip off implicit integral promotions.
12020 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12021 if (ICE->getCastKind() != CK_IntegralCast &&
12022 ICE->getCastKind() != CK_NoOp)
12023 break;
12024 E = ICE->getSubExpr();
12025 }
12026
12027 return E->getType()->isEnumeralType();
12028}
12029
12030static int classifyConstantValue(Expr *Constant) {
12031 // The values of this enumeration are used in the diagnostics
12032 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12033 enum ConstantValueKind {
12034 Miscellaneous = 0,
12035 LiteralTrue,
12036 LiteralFalse
12037 };
12038 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12039 return BL->getValue() ? ConstantValueKind::LiteralTrue
12040 : ConstantValueKind::LiteralFalse;
12041 return ConstantValueKind::Miscellaneous;
12042}
12043
12044static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12045 Expr *Constant, Expr *Other,
12046 const llvm::APSInt &Value,
12047 bool RhsConstant) {
12048 if (S.inTemplateInstantiation())
12049 return false;
12050
12051 Expr *OriginalOther = Other;
12052
12053 Constant = Constant->IgnoreParenImpCasts();
12054 Other = Other->IgnoreParenImpCasts();
12055
12056 // Suppress warnings on tautological comparisons between values of the same
12057 // enumeration type. There are only two ways we could warn on this:
12058 // - If the constant is outside the range of representable values of
12059 // the enumeration. In such a case, we should warn about the cast
12060 // to enumeration type, not about the comparison.
12061 // - If the constant is the maximum / minimum in-range value. For an
12062 // enumeratin type, such comparisons can be meaningful and useful.
12063 if (Constant->getType()->isEnumeralType() &&
12064 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12065 return false;
12066
12067 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12068 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12069 if (!OtherValueRange)
12070 return false;
12071
12072 QualType OtherT = Other->getType();
12073 if (const auto *AT = OtherT->getAs<AtomicType>())
12074 OtherT = AT->getValueType();
12075 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12076
12077 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12078 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12079 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12080 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12081 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12082
12083 // Whether we're treating Other as being a bool because of the form of
12084 // expression despite it having another type (typically 'int' in C).
12085 bool OtherIsBooleanDespiteType =
12086 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12087 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12088 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12089
12090 // Check if all values in the range of possible values of this expression
12091 // lead to the same comparison outcome.
12092 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12093 Value.isUnsigned());
12094 auto Cmp = OtherPromotedValueRange.compare(Value);
12095 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12096 if (!Result)
12097 return false;
12098
12099 // Also consider the range determined by the type alone. This allows us to
12100 // classify the warning under the proper diagnostic group.
12101 bool TautologicalTypeCompare = false;
12102 {
12103 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12104 Value.isUnsigned());
12105 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12106 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12107 ConstantOnRHS: RhsConstant)) {
12108 TautologicalTypeCompare = true;
12109 Cmp = TypeCmp;
12110 Result = TypeResult;
12111 }
12112 }
12113
12114 // Don't warn if the non-constant operand actually always evaluates to the
12115 // same value.
12116 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12117 return false;
12118
12119 // Suppress the diagnostic for an in-range comparison if the constant comes
12120 // from a macro or enumerator. We don't want to diagnose
12121 //
12122 // some_long_value <= INT_MAX
12123 //
12124 // when sizeof(int) == sizeof(long).
12125 bool InRange = Cmp & PromotedRange::InRangeFlag;
12126 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12127 return false;
12128
12129 // A comparison of an unsigned bit-field against 0 is really a type problem,
12130 // even though at the type level the bit-field might promote to 'signed int'.
12131 if (Other->refersToBitField() && InRange && Value == 0 &&
12132 Other->getType()->isUnsignedIntegerOrEnumerationType())
12133 TautologicalTypeCompare = true;
12134
12135 // If this is a comparison to an enum constant, include that
12136 // constant in the diagnostic.
12137 const EnumConstantDecl *ED = nullptr;
12138 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12139 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12140
12141 // Should be enough for uint128 (39 decimal digits)
12142 SmallString<64> PrettySourceValue;
12143 llvm::raw_svector_ostream OS(PrettySourceValue);
12144 if (ED) {
12145 OS << '\'' << *ED << "' (" << Value << ")";
12146 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12147 Val: Constant->IgnoreParenImpCasts())) {
12148 OS << (BL->getValue() ? "YES" : "NO");
12149 } else {
12150 OS << Value;
12151 }
12152
12153 if (!TautologicalTypeCompare) {
12154 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12155 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12156 << E->getOpcodeStr() << OS.str() << *Result
12157 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12158 return true;
12159 }
12160
12161 if (IsObjCSignedCharBool) {
12162 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12163 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12164 << OS.str() << *Result);
12165 return true;
12166 }
12167
12168 // FIXME: We use a somewhat different formatting for the in-range cases and
12169 // cases involving boolean values for historical reasons. We should pick a
12170 // consistent way of presenting these diagnostics.
12171 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12172
12173 S.DiagRuntimeBehavior(
12174 Loc: E->getOperatorLoc(), Statement: E,
12175 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12176 : diag::warn_tautological_bool_compare)
12177 << OS.str() << classifyConstantValue(Constant) << OtherT
12178 << OtherIsBooleanDespiteType << *Result
12179 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12180 } else {
12181 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12182 unsigned Diag =
12183 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12184 ? (HasEnumType(E: OriginalOther)
12185 ? diag::warn_unsigned_enum_always_true_comparison
12186 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12187 : diag::warn_unsigned_always_true_comparison)
12188 : diag::warn_tautological_constant_compare;
12189
12190 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12191 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12192 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12193 }
12194
12195 return true;
12196}
12197
12198/// Analyze the operands of the given comparison. Implements the
12199/// fallback case from AnalyzeComparison.
12200static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12201 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12202 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12203}
12204
12205/// Implements -Wsign-compare.
12206///
12207/// \param E the binary operator to check for warnings
12208static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12209 // The type the comparison is being performed in.
12210 QualType T = E->getLHS()->getType();
12211
12212 // Only analyze comparison operators where both sides have been converted to
12213 // the same type.
12214 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12215 return AnalyzeImpConvsInComparison(S, E);
12216
12217 // Don't analyze value-dependent comparisons directly.
12218 if (E->isValueDependent())
12219 return AnalyzeImpConvsInComparison(S, E);
12220
12221 Expr *LHS = E->getLHS();
12222 Expr *RHS = E->getRHS();
12223
12224 if (T->isIntegralType(Ctx: S.Context)) {
12225 std::optional<llvm::APSInt> RHSValue =
12226 RHS->getIntegerConstantExpr(Ctx: S.Context);
12227 std::optional<llvm::APSInt> LHSValue =
12228 LHS->getIntegerConstantExpr(Ctx: S.Context);
12229
12230 // We don't care about expressions whose result is a constant.
12231 if (RHSValue && LHSValue)
12232 return AnalyzeImpConvsInComparison(S, E);
12233
12234 // We only care about expressions where just one side is literal
12235 if ((bool)RHSValue ^ (bool)LHSValue) {
12236 // Is the constant on the RHS or LHS?
12237 const bool RhsConstant = (bool)RHSValue;
12238 Expr *Const = RhsConstant ? RHS : LHS;
12239 Expr *Other = RhsConstant ? LHS : RHS;
12240 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12241
12242 // Check whether an integer constant comparison results in a value
12243 // of 'true' or 'false'.
12244 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12245 return AnalyzeImpConvsInComparison(S, E);
12246 }
12247 }
12248
12249 if (!T->hasUnsignedIntegerRepresentation()) {
12250 // We don't do anything special if this isn't an unsigned integral
12251 // comparison: we're only interested in integral comparisons, and
12252 // signed comparisons only happen in cases we don't care to warn about.
12253 return AnalyzeImpConvsInComparison(S, E);
12254 }
12255
12256 LHS = LHS->IgnoreParenImpCasts();
12257 RHS = RHS->IgnoreParenImpCasts();
12258
12259 if (!S.getLangOpts().CPlusPlus) {
12260 // Avoid warning about comparison of integers with different signs when
12261 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12262 // the type of `E`.
12263 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12264 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12265 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12266 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12267 }
12268
12269 // Check to see if one of the (unmodified) operands is of different
12270 // signedness.
12271 Expr *signedOperand, *unsignedOperand;
12272 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12273 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12274 "unsigned comparison between two signed integer expressions?");
12275 signedOperand = LHS;
12276 unsignedOperand = RHS;
12277 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12278 signedOperand = RHS;
12279 unsignedOperand = LHS;
12280 } else {
12281 return AnalyzeImpConvsInComparison(S, E);
12282 }
12283
12284 // Otherwise, calculate the effective range of the signed operand.
12285 std::optional<IntRange> signedRange =
12286 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12287 /*Approximate=*/true);
12288 if (!signedRange)
12289 return;
12290
12291 // Go ahead and analyze implicit conversions in the operands. Note
12292 // that we skip the implicit conversions on both sides.
12293 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12294 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12295
12296 // If the signed range is non-negative, -Wsign-compare won't fire.
12297 if (signedRange->NonNegative)
12298 return;
12299
12300 // For (in)equality comparisons, if the unsigned operand is a
12301 // constant which cannot collide with a overflowed signed operand,
12302 // then reinterpreting the signed operand as unsigned will not
12303 // change the result of the comparison.
12304 if (E->isEqualityOp()) {
12305 unsigned comparisonWidth = S.Context.getIntWidth(T);
12306 std::optional<IntRange> unsignedRange = TryGetExprRange(
12307 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12308 /*Approximate=*/true);
12309 if (!unsignedRange)
12310 return;
12311
12312 // We should never be unable to prove that the unsigned operand is
12313 // non-negative.
12314 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12315
12316 if (unsignedRange->Width < comparisonWidth)
12317 return;
12318 }
12319
12320 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12321 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12322 << LHS->getType() << RHS->getType()
12323 << LHS->getSourceRange() << RHS->getSourceRange());
12324}
12325
12326/// Analyzes an attempt to assign the given value to a bitfield.
12327///
12328/// Returns true if there was something fishy about the attempt.
12329static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12330 SourceLocation InitLoc) {
12331 assert(Bitfield->isBitField());
12332 if (Bitfield->isInvalidDecl())
12333 return false;
12334
12335 // White-list bool bitfields.
12336 QualType BitfieldType = Bitfield->getType();
12337 if (BitfieldType->isBooleanType())
12338 return false;
12339
12340 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12341 // If the underlying enum type was not explicitly specified as an unsigned
12342 // type and the enum contain only positive values, MSVC++ will cause an
12343 // inconsistency by storing this as a signed type.
12344 if (S.getLangOpts().CPlusPlus11 &&
12345 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12346 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12347 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12348 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12349 << BitfieldEnumDecl;
12350 }
12351 }
12352
12353 // Ignore value- or type-dependent expressions.
12354 if (Bitfield->getBitWidth()->isValueDependent() ||
12355 Bitfield->getBitWidth()->isTypeDependent() ||
12356 Init->isValueDependent() ||
12357 Init->isTypeDependent())
12358 return false;
12359
12360 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12361 unsigned FieldWidth = Bitfield->getBitWidthValue();
12362
12363 Expr::EvalResult Result;
12364 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12365 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12366 // The RHS is not constant. If the RHS has an enum type, make sure the
12367 // bitfield is wide enough to hold all the values of the enum without
12368 // truncation.
12369 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12370 const PreferredTypeAttr *PTAttr = nullptr;
12371 if (!ED) {
12372 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12373 if (PTAttr)
12374 ED = PTAttr->getType()->getAsEnumDecl();
12375 }
12376 if (ED) {
12377 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12378
12379 // Enum types are implicitly signed on Windows, so check if there are any
12380 // negative enumerators to see if the enum was intended to be signed or
12381 // not.
12382 bool SignedEnum = ED->getNumNegativeBits() > 0;
12383
12384 // Check for surprising sign changes when assigning enum values to a
12385 // bitfield of different signedness. If the bitfield is signed and we
12386 // have exactly the right number of bits to store this unsigned enum,
12387 // suggest changing the enum to an unsigned type. This typically happens
12388 // on Windows where unfixed enums always use an underlying type of 'int'.
12389 unsigned DiagID = 0;
12390 if (SignedEnum && !SignedBitfield) {
12391 DiagID =
12392 PTAttr == nullptr
12393 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12394 : diag::
12395 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12396 } else if (SignedBitfield && !SignedEnum &&
12397 ED->getNumPositiveBits() == FieldWidth) {
12398 DiagID =
12399 PTAttr == nullptr
12400 ? diag::warn_signed_bitfield_enum_conversion
12401 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12402 }
12403 if (DiagID) {
12404 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12405 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12406 SourceRange TypeRange =
12407 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12408 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12409 << SignedEnum << TypeRange;
12410 if (PTAttr)
12411 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12412 << ED;
12413 }
12414
12415 // Compute the required bitwidth. If the enum has negative values, we need
12416 // one more bit than the normal number of positive bits to represent the
12417 // sign bit.
12418 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12419 b: ED->getNumNegativeBits())
12420 : ED->getNumPositiveBits();
12421
12422 // Check the bitwidth.
12423 if (BitsNeeded > FieldWidth) {
12424 Expr *WidthExpr = Bitfield->getBitWidth();
12425 auto DiagID =
12426 PTAttr == nullptr
12427 ? diag::warn_bitfield_too_small_for_enum
12428 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12429 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12430 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12431 << BitsNeeded << ED << WidthExpr->getSourceRange();
12432 if (PTAttr)
12433 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12434 << ED;
12435 }
12436 }
12437
12438 return false;
12439 }
12440
12441 llvm::APSInt Value = Result.Val.getInt();
12442
12443 unsigned OriginalWidth = Value.getBitWidth();
12444
12445 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12446 // false positives where the user is demonstrating they intend to use the
12447 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12448 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12449 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12450 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12451 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12452 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12453 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12454 return false;
12455 }
12456
12457 if (!Value.isSigned() || Value.isNegative())
12458 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12459 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12460 OriginalWidth = Value.getSignificantBits();
12461
12462 if (OriginalWidth <= FieldWidth)
12463 return false;
12464
12465 // Compute the value which the bitfield will contain.
12466 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12467 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12468
12469 // Check whether the stored value is equal to the original value.
12470 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12471 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12472 return false;
12473
12474 std::string PrettyValue = toString(I: Value, Radix: 10);
12475 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12476
12477 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12478 ? diag::warn_impcast_single_bit_bitield_precision_constant
12479 : diag::warn_impcast_bitfield_precision_constant)
12480 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12481 << Init->getSourceRange();
12482
12483 return true;
12484}
12485
12486/// Analyze the given simple or compound assignment for warning-worthy
12487/// operations.
12488static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12489 // Just recurse on the LHS.
12490 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12491
12492 // We want to recurse on the RHS as normal unless we're assigning to
12493 // a bitfield.
12494 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12495 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12496 InitLoc: E->getOperatorLoc())) {
12497 // Recurse, ignoring any implicit conversions on the RHS.
12498 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12499 CC: E->getOperatorLoc());
12500 }
12501 }
12502
12503 // Set context flag for overflow behavior type assignment analysis, use RAII
12504 // pattern to handle nested assignments.
12505 llvm::SaveAndRestore OBTAssignmentContext(
12506 S.InOverflowBehaviorAssignmentContext, true);
12507
12508 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12509
12510 // Diagnose implicitly sequentially-consistent atomic assignment.
12511 if (E->getLHS()->getType()->isAtomicType())
12512 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12513}
12514
12515/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12516static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12517 QualType T, SourceLocation CContext, unsigned diag,
12518 bool PruneControlFlow = false) {
12519 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12520 // address space annotations isn't really useful. The warnings aren't because
12521 // you're converting a `private int` to `unsigned int`, it is because you're
12522 // conerting `int` to `unsigned int`.
12523 if (SourceType.hasAddressSpace())
12524 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
12525 if (T.hasAddressSpace())
12526 T = S.getASTContext().removeAddrSpaceQualType(T);
12527 if (PruneControlFlow) {
12528 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12529 PD: S.PDiag(DiagID: diag)
12530 << SourceType << T << E->getSourceRange()
12531 << SourceRange(CContext));
12532 return;
12533 }
12534 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
12535 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12536}
12537
12538/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12539static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12540 SourceLocation CContext, unsigned diag,
12541 bool PruneControlFlow = false) {
12542 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
12543}
12544
12545/// Diagnose an implicit cast from a floating point value to an integer value.
12546static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12547 SourceLocation CContext) {
12548 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
12549 bool PruneWarnings = S.inTemplateInstantiation();
12550
12551 const Expr *InnerE = E->IgnoreParenImpCasts();
12552 // We also want to warn on, e.g., "int i = -1.234"
12553 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
12554 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12555 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12556
12557 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
12558
12559 llvm::APFloat Value(0.0);
12560 bool IsConstant =
12561 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
12562 if (!IsConstant) {
12563 if (S.ObjC().isSignedCharBool(Ty: T)) {
12564 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12565 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
12566 << E->getType());
12567 }
12568
12569 return DiagnoseImpCast(S, E, T, CContext,
12570 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12571 }
12572
12573 bool isExact = false;
12574
12575 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12576 T->hasUnsignedIntegerRepresentation());
12577 llvm::APFloat::opStatus Result = Value.convertToInteger(
12578 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
12579
12580 // FIXME: Force the precision of the source value down so we don't print
12581 // digits which are usually useless (we don't really care here if we
12582 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12583 // would automatically print the shortest representation, but it's a bit
12584 // tricky to implement.
12585 SmallString<16> PrettySourceValue;
12586 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12587 precision = (precision * 59 + 195) / 196;
12588 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
12589
12590 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
12591 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12592 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12593 << PrettySourceValue);
12594 }
12595
12596 if (Result == llvm::APFloat::opOK && isExact) {
12597 if (IsLiteral) return;
12598 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
12599 PruneControlFlow: PruneWarnings);
12600 }
12601
12602 // Conversion of a floating-point value to a non-bool integer where the
12603 // integral part cannot be represented by the integer type is undefined.
12604 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12605 return DiagnoseImpCast(
12606 S, E, T, CContext,
12607 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12608 : diag::warn_impcast_float_to_integer_out_of_range,
12609 PruneControlFlow: PruneWarnings);
12610
12611 unsigned DiagID = 0;
12612 if (IsLiteral) {
12613 // Warn on floating point literal to integer.
12614 DiagID = diag::warn_impcast_literal_float_to_integer;
12615 } else if (IntegerValue == 0) {
12616 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12617 return DiagnoseImpCast(S, E, T, CContext,
12618 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12619 }
12620 // Warn on non-zero to zero conversion.
12621 DiagID = diag::warn_impcast_float_to_integer_zero;
12622 } else {
12623 if (IntegerValue.isUnsigned()) {
12624 if (!IntegerValue.isMaxValue()) {
12625 return DiagnoseImpCast(S, E, T, CContext,
12626 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12627 }
12628 } else { // IntegerValue.isSigned()
12629 if (!IntegerValue.isMaxSignedValue() &&
12630 !IntegerValue.isMinSignedValue()) {
12631 return DiagnoseImpCast(S, E, T, CContext,
12632 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12633 }
12634 }
12635 // Warn on evaluatable floating point expression to integer conversion.
12636 DiagID = diag::warn_impcast_float_to_integer;
12637 }
12638
12639 SmallString<16> PrettyTargetValue;
12640 if (IsBool)
12641 PrettyTargetValue = Value.isZero() ? "false" : "true";
12642 else
12643 IntegerValue.toString(Str&: PrettyTargetValue);
12644
12645 if (PruneWarnings) {
12646 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12647 PD: S.PDiag(DiagID)
12648 << E->getType() << T.getUnqualifiedType()
12649 << PrettySourceValue << PrettyTargetValue
12650 << E->getSourceRange() << SourceRange(CContext));
12651 } else {
12652 S.Diag(Loc: E->getExprLoc(), DiagID)
12653 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12654 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12655 }
12656}
12657
12658/// Analyze the given compound assignment for the possible losing of
12659/// floating-point precision.
12660static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12661 assert(isa<CompoundAssignOperator>(E) &&
12662 "Must be compound assignment operation");
12663 // Recurse on the LHS and RHS in here
12664 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12665 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12666
12667 if (E->getLHS()->getType()->isAtomicType())
12668 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12669
12670 // Now check the outermost expression
12671 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12672 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
12673 ->getComputationResultType()
12674 ->getAs<BuiltinType>();
12675
12676 // The below checks assume source is floating point.
12677 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12678
12679 // If source is floating point but target is an integer.
12680 if (ResultBT->isInteger())
12681 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
12682 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
12683
12684 if (!ResultBT->isFloatingPoint())
12685 return;
12686
12687 // If both source and target are floating points, warn about losing precision.
12688 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12689 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
12690 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
12691 // warn about dropping FP rank.
12692 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
12693 diag: diag::warn_impcast_float_result_precision);
12694}
12695
12696static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12697 IntRange Range) {
12698 if (!Range.Width) return "0";
12699
12700 llvm::APSInt ValueInRange = Value;
12701 ValueInRange.setIsSigned(!Range.NonNegative);
12702 ValueInRange = ValueInRange.trunc(width: Range.Width);
12703 return toString(I: ValueInRange, Radix: 10);
12704}
12705
12706static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12707 bool ToBool) {
12708 if (!isa<ImplicitCastExpr>(Val: Ex))
12709 return false;
12710
12711 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12712 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
12713 const Type *Source =
12714 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
12715 if (Target->isDependentType())
12716 return false;
12717
12718 const auto *FloatCandidateBT =
12719 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
12720 const Type *BoolCandidateType = ToBool ? Target : Source;
12721
12722 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
12723 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12724}
12725
12726static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12727 SourceLocation CC) {
12728 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12729 const Expr *CurrA = TheCall->getArg(Arg: I);
12730 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
12731 continue;
12732
12733 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12734 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
12735 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12736 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
12737 if (IsSwapped) {
12738 // Warn on this floating-point to bool conversion.
12739 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
12740 T: CurrA->getType(), CContext: CC,
12741 diag: diag::warn_impcast_floating_point_to_bool);
12742 }
12743 }
12744}
12745
12746static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12747 SourceLocation CC) {
12748 // Don't warn on functions which have return type nullptr_t.
12749 if (isa<CallExpr>(Val: E))
12750 return;
12751
12752 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12753 const Expr *NewE = E->IgnoreParenImpCasts();
12754 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
12755 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12756 if (!IsGNUNullExpr && !HasNullPtrType)
12757 return;
12758
12759 // Return if target type is a safe conversion.
12760 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12761 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12762 return;
12763
12764 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
12765 Loc: E->getExprLoc()))
12766 return;
12767
12768 SourceLocation Loc = E->getSourceRange().getBegin();
12769
12770 // Venture through the macro stacks to get to the source of macro arguments.
12771 // The new location is a better location than the complete location that was
12772 // passed in.
12773 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12774 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
12775
12776 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12777 if (IsGNUNullExpr && Loc.isMacroID()) {
12778 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12779 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
12780 if (MacroName == "NULL")
12781 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12782 }
12783
12784 // Only warn if the null and context location are in the same macro expansion.
12785 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
12786 return;
12787
12788 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
12789 << HasNullPtrType << T << SourceRange(CC)
12790 << FixItHint::CreateReplacement(RemoveRange: Loc,
12791 Code: S.getFixItZeroLiteralForType(T, Loc));
12792}
12793
12794// Helper function to filter out cases for constant width constant conversion.
12795// Don't warn on char array initialization or for non-decimal values.
12796static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12797 SourceLocation CC) {
12798 // If initializing from a constant, and the constant starts with '0',
12799 // then it is a binary, octal, or hexadecimal. Allow these constants
12800 // to fill all the bits, even if there is a sign change.
12801 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
12802 const char FirstLiteralCharacter =
12803 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
12804 if (FirstLiteralCharacter == '0')
12805 return false;
12806 }
12807
12808 // If the CC location points to a '{', and the type is char, then assume
12809 // assume it is an array initialization.
12810 if (CC.isValid() && T->isCharType()) {
12811 const char FirstContextCharacter =
12812 S.getSourceManager().getCharacterData(SL: CC)[0];
12813 if (FirstContextCharacter == '{')
12814 return false;
12815 }
12816
12817 return true;
12818}
12819
12820static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12821 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
12822 if (!IL) {
12823 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12824 if (UO->getOpcode() == UO_Minus)
12825 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
12826 }
12827 }
12828
12829 return IL;
12830}
12831
12832static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12833 E = E->IgnoreParenImpCasts();
12834 SourceLocation ExprLoc = E->getExprLoc();
12835
12836 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12837 BinaryOperator::Opcode Opc = BO->getOpcode();
12838 Expr::EvalResult Result;
12839 // Do not diagnose unsigned shifts.
12840 if (Opc == BO_Shl) {
12841 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
12842 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
12843 if (LHS && LHS->getValue() == 0)
12844 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
12845 else if (!E->isValueDependent() && LHS && RHS &&
12846 RHS->getValue().isNonNegative() &&
12847 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
12848 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
12849 << (Result.Val.getInt() != 0);
12850 else if (E->getType()->isSignedIntegerType())
12851 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
12852 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
12853 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
12854 Code: ") != 0");
12855 }
12856 }
12857
12858 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12859 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
12860 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
12861 if (!LHS || !RHS)
12862 return;
12863 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12864 (RHS->getValue() == 0 || RHS->getValue() == 1))
12865 // Do not diagnose common idioms.
12866 return;
12867 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12868 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
12869 }
12870}
12871
12872static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
12873 const Type *Target, Expr *E,
12874 QualType T,
12875 SourceLocation CC) {
12876 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12877 Source != Target);
12878
12879 // Lone surrogates have a distinct representation in UTF-32.
12880 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12881 // so don't warn on such conversion.
12882 if (Source->isChar16Type() && Target->isChar32Type())
12883 return;
12884
12885 Expr::EvalResult Result;
12886 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
12887 InConstantContext: S.isConstantEvaluatedContext())) {
12888 llvm::APSInt Value(32);
12889 Value = Result.Val.getInt();
12890 bool IsASCII = Value <= 0x7F;
12891 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12892 bool ConversionPreservesSemantics =
12893 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12894
12895 if (!ConversionPreservesSemantics) {
12896 auto IsSingleCodeUnitCP = [](const QualType &T,
12897 const llvm::APSInt &Value) {
12898 if (T->isChar8Type())
12899 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12900 if (T->isChar16Type())
12901 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12902 assert(T->isChar32Type());
12903 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12904 };
12905
12906 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
12907 << E->getType() << T
12908 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12909 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
12910 }
12911 } else {
12912 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
12913 S.getASTContext().getIntWidth(T);
12914 DiagnoseImpCast(S, E, T, CContext: CC,
12915 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
12916 : diag::warn_impcast_unicode_char_type);
12917 }
12918}
12919
12920bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
12921 From = Context.getCanonicalType(T: From);
12922 To = Context.getCanonicalType(T: To);
12923 QualType MaybePointee = From->getPointeeType();
12924 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12925 From = MaybePointee;
12926 MaybePointee = To->getPointeeType();
12927 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12928 To = MaybePointee;
12929
12930 if (const auto *FromFn = From->getAs<FunctionType>()) {
12931 if (const auto *ToFn = To->getAs<FunctionType>()) {
12932 if (FromFn->getCFIUncheckedCalleeAttr() &&
12933 !ToFn->getCFIUncheckedCalleeAttr())
12934 return true;
12935 }
12936 }
12937 return false;
12938}
12939
12940void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
12941 bool *ICContext, bool IsListInit) {
12942 if (E->isTypeDependent() || E->isValueDependent()) return;
12943
12944 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
12945 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12946 if (Source == Target) return;
12947 if (Target->isDependentType()) return;
12948
12949 // If the conversion context location is invalid don't complain. We also
12950 // don't want to emit a warning if the issue occurs from the expansion of
12951 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12952 // delay this check as long as possible. Once we detect we are in that
12953 // scenario, we just return.
12954 if (CC.isInvalid())
12955 return;
12956
12957 if (Source->isAtomicType())
12958 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12959
12960 // Diagnose implicit casts to bool.
12961 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
12962 if (isa<StringLiteral>(Val: E))
12963 // Warn on string literal to bool. Checks for string literals in logical
12964 // and expressions, for instance, assert(0 && "error here"), are
12965 // prevented by a check in AnalyzeImplicitConversions().
12966 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12967 diag: diag::warn_impcast_string_literal_to_bool);
12968 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
12969 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
12970 // This covers the literal expressions that evaluate to Objective-C
12971 // objects.
12972 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12973 diag: diag::warn_impcast_objective_c_literal_to_bool);
12974 }
12975 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12976 // Warn on pointer to bool conversion that is always true.
12977 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
12978 Range: SourceRange(CC));
12979 }
12980 }
12981
12982 CheckOverflowBehaviorTypeConversion(E, T, CC);
12983
12984 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12985 // is a typedef for signed char (macOS), then that constant value has to be 1
12986 // or 0.
12987 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
12988 Expr::EvalResult Result;
12989 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
12990 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12991 ObjC().adornBoolConversionDiagWithTernaryFixit(
12992 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12993 << toString(I: Result.Val.getInt(), Radix: 10));
12994 }
12995 return;
12996 }
12997 }
12998
12999 // Check implicit casts from Objective-C collection literals to specialized
13000 // collection types, e.g., NSArray<NSString *> *.
13001 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13002 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13003 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13004 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13005
13006 // Strip complex types.
13007 if (isa<ComplexType>(Val: Source)) {
13008 if (!isa<ComplexType>(Val: Target)) {
13009 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13010 return;
13011
13012 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13013 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13014 diag: diag::err_impcast_incompatible_type);
13015 }
13016
13017 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13018 diag: getLangOpts().CPlusPlus
13019 ? diag::err_impcast_complex_scalar
13020 : diag::warn_impcast_complex_scalar);
13021 }
13022
13023 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13024 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13025 }
13026
13027 // Strip vector types.
13028 if (isa<VectorType>(Val: Source)) {
13029 if (Target->isSveVLSBuiltinType() &&
13030 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13031 SecondType: QualType(Source, 0)) ||
13032 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13033 SecondType: QualType(Source, 0))))
13034 return;
13035
13036 if (Target->isRVVVLSBuiltinType() &&
13037 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13038 SecondType: QualType(Source, 0)) ||
13039 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13040 SecondType: QualType(Source, 0))))
13041 return;
13042
13043 if (!isa<VectorType>(Val: Target)) {
13044 if (SourceMgr.isInSystemMacro(loc: CC))
13045 return;
13046 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13047 }
13048 if (getLangOpts().HLSL &&
13049 Target->castAs<VectorType>()->getNumElements() <
13050 Source->castAs<VectorType>()->getNumElements()) {
13051 // Diagnose vector truncation but don't return. We may also want to
13052 // diagnose an element conversion.
13053 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13054 diag: diag::warn_hlsl_impcast_vector_truncation);
13055 }
13056
13057 // If the vector cast is cast between two vectors of the same size, it is
13058 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13059 if (!getLangOpts().HLSL &&
13060 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13061 return;
13062
13063 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13064 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13065 }
13066 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13067 Target = VecTy->getElementType().getTypePtr();
13068
13069 // Strip matrix types.
13070 if (isa<ConstantMatrixType>(Val: Source)) {
13071 if (Target->isScalarType())
13072 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13073
13074 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13075 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13076 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13077 // Diagnose Matrix truncation but don't return. We may also want to
13078 // diagnose an element conversion.
13079 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13080 diag: diag::warn_hlsl_impcast_matrix_truncation);
13081 }
13082
13083 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13084 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13085 }
13086 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13087 Target = MatTy->getElementType().getTypePtr();
13088
13089 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13090 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13091
13092 // Strip SVE vector types
13093 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13094 // Need the original target type for vector type checks
13095 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13096 // Handle conversion from scalable to fixed when msve-vector-bits is
13097 // specified
13098 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13099 SecondType: QualType(Source, 0)) ||
13100 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13101 SecondType: QualType(Source, 0)))
13102 return;
13103
13104 // If the vector cast is cast between two vectors of the same size, it is
13105 // a bitcast, not a conversion.
13106 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13107 return;
13108
13109 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13110 }
13111
13112 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13113 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13114
13115 // If the source is floating point...
13116 if (SourceBT && SourceBT->isFloatingPoint()) {
13117 // ...and the target is floating point...
13118 if (TargetBT && TargetBT->isFloatingPoint()) {
13119 // ...then warn if we're dropping FP rank.
13120
13121 int Order = getASTContext().getFloatingTypeSemanticOrder(
13122 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13123 if (Order > 0) {
13124 // Don't warn about float constants that are precisely
13125 // representable in the target type.
13126 Expr::EvalResult result;
13127 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13128 // Value might be a float, a float vector, or a float complex.
13129 if (IsSameFloatAfterCast(
13130 value: result.Val,
13131 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13132 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13133 return;
13134 }
13135
13136 if (SourceMgr.isInSystemMacro(loc: CC))
13137 return;
13138
13139 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13140 }
13141 // ... or possibly if we're increasing rank, too
13142 else if (Order < 0) {
13143 if (SourceMgr.isInSystemMacro(loc: CC))
13144 return;
13145
13146 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13147 }
13148 return;
13149 }
13150
13151 // If the target is integral, always warn.
13152 if (TargetBT && TargetBT->isInteger()) {
13153 if (SourceMgr.isInSystemMacro(loc: CC))
13154 return;
13155
13156 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13157 }
13158
13159 // Detect the case where a call result is converted from floating-point to
13160 // to bool, and the final argument to the call is converted from bool, to
13161 // discover this typo:
13162 //
13163 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13164 //
13165 // FIXME: This is an incredibly special case; is there some more general
13166 // way to detect this class of misplaced-parentheses bug?
13167 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13168 // Check last argument of function call to see if it is an
13169 // implicit cast from a type matching the type the result
13170 // is being cast to.
13171 CallExpr *CEx = cast<CallExpr>(Val: E);
13172 if (unsigned NumArgs = CEx->getNumArgs()) {
13173 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13174 Expr *InnerE = LastA->IgnoreParenImpCasts();
13175 if (isa<ImplicitCastExpr>(Val: LastA) &&
13176 InnerE->getType()->isBooleanType()) {
13177 // Warn on this floating-point to bool conversion
13178 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13179 diag: diag::warn_impcast_floating_point_to_bool);
13180 }
13181 }
13182 }
13183 return;
13184 }
13185
13186 // Valid casts involving fixed point types should be accounted for here.
13187 if (Source->isFixedPointType()) {
13188 if (Target->isUnsaturatedFixedPointType()) {
13189 Expr::EvalResult Result;
13190 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13191 InConstantContext: isConstantEvaluatedContext())) {
13192 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13193 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13194 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13195 if (Value > MaxVal || Value < MinVal) {
13196 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13197 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13198 << Value.toString() << T
13199 << E->getSourceRange()
13200 << clang::SourceRange(CC));
13201 return;
13202 }
13203 }
13204 } else if (Target->isIntegerType()) {
13205 Expr::EvalResult Result;
13206 if (!isConstantEvaluatedContext() &&
13207 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13208 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13209
13210 bool Overflowed;
13211 llvm::APSInt IntResult = FXResult.convertToInt(
13212 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13213 Overflow: &Overflowed);
13214
13215 if (Overflowed) {
13216 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13217 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13218 << FXResult.toString() << T
13219 << E->getSourceRange()
13220 << clang::SourceRange(CC));
13221 return;
13222 }
13223 }
13224 }
13225 } else if (Target->isUnsaturatedFixedPointType()) {
13226 if (Source->isIntegerType()) {
13227 Expr::EvalResult Result;
13228 if (!isConstantEvaluatedContext() &&
13229 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13230 llvm::APSInt Value = Result.Val.getInt();
13231
13232 bool Overflowed;
13233 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13234 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13235
13236 if (Overflowed) {
13237 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13238 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13239 << toString(I: Value, /*Radix=*/10) << T
13240 << E->getSourceRange()
13241 << clang::SourceRange(CC));
13242 return;
13243 }
13244 }
13245 }
13246 }
13247
13248 // If we are casting an integer type to a floating point type without
13249 // initialization-list syntax, we might lose accuracy if the floating
13250 // point type has a narrower significand than the integer type.
13251 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13252 TargetBT->isFloatingType() && !IsListInit) {
13253 // Determine the number of precision bits in the source integer type.
13254 std::optional<IntRange> SourceRange =
13255 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13256 /*Approximate=*/true);
13257 if (!SourceRange)
13258 return;
13259 unsigned int SourcePrecision = SourceRange->Width;
13260
13261 // Determine the number of precision bits in the
13262 // target floating point type.
13263 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13264 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13265
13266 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13267 SourcePrecision > TargetPrecision) {
13268
13269 if (std::optional<llvm::APSInt> SourceInt =
13270 E->getIntegerConstantExpr(Ctx: Context)) {
13271 // If the source integer is a constant, convert it to the target
13272 // floating point type. Issue a warning if the value changes
13273 // during the whole conversion.
13274 llvm::APFloat TargetFloatValue(
13275 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13276 llvm::APFloat::opStatus ConversionStatus =
13277 TargetFloatValue.convertFromAPInt(
13278 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13279 RM: llvm::APFloat::rmNearestTiesToEven);
13280
13281 if (ConversionStatus != llvm::APFloat::opOK) {
13282 SmallString<32> PrettySourceValue;
13283 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13284 SmallString<32> PrettyTargetValue;
13285 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13286
13287 DiagRuntimeBehavior(
13288 Loc: E->getExprLoc(), Statement: E,
13289 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13290 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13291 << E->getSourceRange() << clang::SourceRange(CC));
13292 }
13293 } else {
13294 // Otherwise, the implicit conversion may lose precision.
13295 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13296 diag: diag::warn_impcast_integer_float_precision);
13297 }
13298 }
13299 }
13300
13301 DiagnoseNullConversion(S&: *this, E, T, CC);
13302
13303 DiscardMisalignedMemberAddress(T: Target, E);
13304
13305 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13306 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13307 return;
13308 }
13309
13310 if (Target->isBooleanType())
13311 DiagnoseIntInBoolContext(S&: *this, E);
13312
13313 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13314 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13315 << QualType(Source, 0) << QualType(Target, 0);
13316 }
13317
13318 if (!Source->isIntegerType() || !Target->isIntegerType())
13319 return;
13320
13321 // TODO: remove this early return once the false positives for constant->bool
13322 // in templates, macros, etc, are reduced or removed.
13323 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13324 return;
13325
13326 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13327 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13328 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13329 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13330 << E->getType());
13331 }
13332 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13333 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13334 if (!LikelySourceRange)
13335 return;
13336
13337 IntRange SourceTypeRange =
13338 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13339 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13340
13341 if (LikelySourceRange->Width > TargetRange.Width) {
13342 // Check if target is a wrapping OBT - if so, don't warn about constant
13343 // conversion as this type may be used intentionally with implicit
13344 // truncation, especially during assignments.
13345 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13346 if (TargetOBT->isWrapKind()) {
13347 return;
13348 }
13349 }
13350
13351 // Check if source expression has an explicit __ob_wrap cast because if so,
13352 // wrapping was explicitly requested and we shouldn't warn
13353 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13354 if (SourceOBT->isWrapKind()) {
13355 return;
13356 }
13357 }
13358
13359 // If the source is a constant, use a default-on diagnostic.
13360 // TODO: this should happen for bitfield stores, too.
13361 Expr::EvalResult Result;
13362 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13363 InConstantContext: isConstantEvaluatedContext())) {
13364 llvm::APSInt Value(32);
13365 Value = Result.Val.getInt();
13366
13367 if (SourceMgr.isInSystemMacro(loc: CC))
13368 return;
13369
13370 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13371 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13372
13373 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13374 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13375 << PrettySourceValue << PrettyTargetValue
13376 << E->getType() << T << E->getSourceRange()
13377 << SourceRange(CC));
13378 return;
13379 }
13380
13381 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13382 if (SourceMgr.isInSystemMacro(loc: CC))
13383 return;
13384
13385 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13386 if (UO->getOpcode() == UO_Minus)
13387 return DiagnoseImpCast(
13388 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13389 }
13390
13391 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13392 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13393 /* pruneControlFlow */ PruneControlFlow: true);
13394 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13395 diag: diag::warn_impcast_integer_precision);
13396 }
13397
13398 if (TargetRange.Width > SourceTypeRange.Width) {
13399 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13400 if (UO->getOpcode() == UO_Minus)
13401 if (Source->isUnsignedIntegerType()) {
13402 if (Target->isUnsignedIntegerType())
13403 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13404 diag: diag::warn_impcast_high_order_zero_bits);
13405 if (Target->isSignedIntegerType())
13406 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13407 diag: diag::warn_impcast_nonnegative_result);
13408 }
13409 }
13410
13411 if (TargetRange.Width == LikelySourceRange->Width &&
13412 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13413 Source->isSignedIntegerType()) {
13414 // Warn when doing a signed to signed conversion, warn if the positive
13415 // source value is exactly the width of the target type, which will
13416 // cause a negative value to be stored.
13417
13418 Expr::EvalResult Result;
13419 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13420 !SourceMgr.isInSystemMacro(loc: CC)) {
13421 llvm::APSInt Value = Result.Val.getInt();
13422 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13423 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13424 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13425
13426 Diag(Loc: E->getExprLoc(),
13427 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13428 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13429 << E->getSourceRange() << SourceRange(CC));
13430 return;
13431 }
13432 }
13433
13434 // Fall through for non-constants to give a sign conversion warning.
13435 }
13436
13437 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13438 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13439 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13440 LikelySourceRange->Width == TargetRange.Width))) {
13441 if (SourceMgr.isInSystemMacro(loc: CC))
13442 return;
13443
13444 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13445 TargetBT->isInteger() &&
13446 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13447 return;
13448 }
13449
13450 unsigned DiagID = diag::warn_impcast_integer_sign;
13451
13452 // Traditionally, gcc has warned about this under -Wsign-compare.
13453 // We also want to warn about it in -Wconversion.
13454 // So if -Wconversion is off, use a completely identical diagnostic
13455 // in the sign-compare group.
13456 // The conditional-checking code will
13457 if (ICContext) {
13458 DiagID = diag::warn_impcast_integer_sign_conditional;
13459 *ICContext = true;
13460 }
13461
13462 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13463 }
13464
13465 // If we're implicitly converting from an integer into an enumeration, that
13466 // is valid in C but invalid in C++.
13467 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13468 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13469 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13470 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13471
13472 // Diagnose conversions between different enumeration types.
13473 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13474 // type, to give us better diagnostics.
13475 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13476
13477 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13478 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13479 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13480 TargetEnum->getDecl()->hasNameForLinkage() &&
13481 SourceEnum != TargetEnum) {
13482 if (SourceMgr.isInSystemMacro(loc: CC))
13483 return;
13484
13485 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13486 diag: diag::warn_impcast_different_enum_types);
13487 }
13488}
13489
13490static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13491 SourceLocation CC, QualType T);
13492
13493static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13494 SourceLocation CC, bool &ICContext) {
13495 E = E->IgnoreParenImpCasts();
13496 // Diagnose incomplete type for second or third operand in C.
13497 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13498 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13499
13500 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13501 return CheckConditionalOperator(S, E: CO, CC, T);
13502
13503 AnalyzeImplicitConversions(S, E, CC);
13504 if (E->getType() != T)
13505 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
13506}
13507
13508static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13509 SourceLocation CC, QualType T) {
13510 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
13511
13512 Expr *TrueExpr = E->getTrueExpr();
13513 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
13514 TrueExpr = BCO->getCommon();
13515
13516 bool Suspicious = false;
13517 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
13518 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
13519
13520 if (T->isBooleanType())
13521 DiagnoseIntInBoolContext(S, E);
13522
13523 // If -Wconversion would have warned about either of the candidates
13524 // for a signedness conversion to the context type...
13525 if (!Suspicious) return;
13526
13527 // ...but it's currently ignored...
13528 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
13529 return;
13530
13531 // ...then check whether it would have warned about either of the
13532 // candidates for a signedness conversion to the condition type.
13533 if (E->getType() == T) return;
13534
13535 Suspicious = false;
13536 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
13537 ICContext: &Suspicious);
13538 if (!Suspicious)
13539 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
13540 T: E->getType(), CC, ICContext: &Suspicious);
13541}
13542
13543/// Check conversion of given expression to boolean.
13544/// Input argument E is a logical expression.
13545static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13546 // Run the bool-like conversion checks only for C since there bools are
13547 // still not used as the return type from "boolean" operators or as the input
13548 // type for conditional operators.
13549 if (S.getLangOpts().CPlusPlus)
13550 return;
13551 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13552 return;
13553 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
13554}
13555
13556namespace {
13557struct AnalyzeImplicitConversionsWorkItem {
13558 Expr *E;
13559 SourceLocation CC;
13560 bool IsListInit;
13561};
13562}
13563
13564static void CheckCommaOperand(
13565 Sema &S, Expr *E, QualType T, SourceLocation CC,
13566 bool ExtraCheckForImplicitConversion,
13567 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13568 E = E->IgnoreParenImpCasts();
13569 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
13570
13571 if (ExtraCheckForImplicitConversion && E->getType() != T)
13572 S.CheckImplicitConversion(E, T, CC);
13573}
13574
13575/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13576/// that should be visited are added to WorkList.
13577static void AnalyzeImplicitConversions(
13578 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13579 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13580 Expr *OrigE = Item.E;
13581 SourceLocation CC = Item.CC;
13582
13583 QualType T = OrigE->getType();
13584 Expr *E = OrigE->IgnoreParenImpCasts();
13585
13586 // Propagate whether we are in a C++ list initialization expression.
13587 // If so, we do not issue warnings for implicit int-float conversion
13588 // precision loss, because C++11 narrowing already handles it.
13589 //
13590 // HLSL's initialization lists are special, so they shouldn't observe the C++
13591 // behavior here.
13592 bool IsListInit =
13593 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
13594 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13595
13596 if (E->isTypeDependent() || E->isValueDependent())
13597 return;
13598
13599 Expr *SourceExpr = E;
13600 // Examine, but don't traverse into the source expression of an
13601 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13602 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13603 // evaluate it in the context of checking the specific conversion to T though.
13604 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
13605 if (auto *Src = OVE->getSourceExpr())
13606 SourceExpr = Src;
13607
13608 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
13609 if (UO->getOpcode() == UO_Not &&
13610 UO->getSubExpr()->isKnownToHaveBooleanValue())
13611 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
13612 << OrigE->getSourceRange() << T->isBooleanType()
13613 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
13614
13615 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
13616 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13617 BO->getLHS()->isKnownToHaveBooleanValue() &&
13618 BO->getRHS()->isKnownToHaveBooleanValue() &&
13619 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
13620 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
13621 SourceManager &SM = S.getSourceManager();
13622 const LangOptions &LO = S.getLangOpts();
13623 SourceLocation BLoc = BO->getOperatorLoc();
13624 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
13625 StringRef SR = clang::Lexer::getSourceText(
13626 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
13627 // To reduce false positives, only issue the diagnostic if the operator
13628 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13629 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13630 // in C, along with other macro spellings the user might invent.
13631 if (SR.str() == "&" || SR.str() == "|") {
13632
13633 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
13634 << (BO->getOpcode() == BO_And ? "&" : "|")
13635 << OrigE->getSourceRange()
13636 << FixItHint::CreateReplacement(
13637 RemoveRange: BO->getOperatorLoc(),
13638 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
13639 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
13640 }
13641 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13642 /// Analyze the given comma operator. The basic idea behind the analysis
13643 /// is to analyze the left and right operands slightly differently. The
13644 /// left operand needs to check whether the operand itself has an implicit
13645 /// conversion, but not whether the left operand induces an implicit
13646 /// conversion for the entire comma expression itself. This is similar to
13647 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13648 /// were directly used for the implicit conversion check.
13649 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
13650 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13651 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
13652 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13653 return;
13654 }
13655 }
13656
13657 // For conditional operators, we analyze the arguments as if they
13658 // were being fed directly into the output.
13659 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
13660 CheckConditionalOperator(S, E: CO, CC, T);
13661 return;
13662 }
13663
13664 // Check implicit argument conversions for function calls.
13665 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
13666 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
13667
13668 // Go ahead and check any implicit conversions we might have skipped.
13669 // The non-canonical typecheck is just an optimization;
13670 // CheckImplicitConversion will filter out dead implicit conversions.
13671 if (SourceExpr->getType() != T)
13672 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
13673
13674 // Now continue drilling into this expression.
13675
13676 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
13677 // The bound subexpressions in a PseudoObjectExpr are not reachable
13678 // as transitive children.
13679 // FIXME: Use a more uniform representation for this.
13680 for (auto *SE : POE->semantics())
13681 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
13682 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13683 }
13684
13685 // Skip past explicit casts.
13686 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
13687 E = CE->getSubExpr();
13688 // In the special case of a C++ function-style cast with braces,
13689 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13690 // initializer. This InitListExpr basically belongs to the cast itself, so
13691 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13692 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
13693 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
13694 if (InitListE->getNumInits() == 1) {
13695 E = InitListE->getInit(Init: 0);
13696 }
13697 }
13698 }
13699 E = E->IgnoreParenImpCasts();
13700 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13701 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13702 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
13703 return;
13704 }
13705
13706 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
13707 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
13708 // The base expression is only used to initialize the parameter for
13709 // arguments to `inout` parameters, so we only traverse down the base
13710 // expression for `inout` cases.
13711 if (OutArgE->isInOut())
13712 WorkList.push_back(
13713 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13714 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
13715 return;
13716 }
13717
13718 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13719 // Do a somewhat different check with comparison operators.
13720 if (BO->isComparisonOp())
13721 return AnalyzeComparison(S, E: BO);
13722
13723 // And with simple assignments.
13724 if (BO->getOpcode() == BO_Assign)
13725 return AnalyzeAssignment(S, E: BO);
13726 // And with compound assignments.
13727 if (BO->isAssignmentOp())
13728 return AnalyzeCompoundAssignment(S, E: BO);
13729 }
13730
13731 // These break the otherwise-useful invariant below. Fortunately,
13732 // we don't really need to recurse into them, because any internal
13733 // expressions should have been analyzed already when they were
13734 // built into statements.
13735 if (isa<StmtExpr>(Val: E)) return;
13736
13737 // Don't descend into unevaluated contexts.
13738 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
13739
13740 // Now just recurse over the expression's children.
13741 CC = E->getExprLoc();
13742 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
13743 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13744 for (Stmt *SubStmt : E->children()) {
13745 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
13746 if (!ChildExpr)
13747 continue;
13748
13749 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
13750 if (ChildExpr == CSE->getOperand())
13751 // Do not recurse over a CoroutineSuspendExpr's operand.
13752 // The operand is also a subexpression of getCommonExpr(), and
13753 // recursing into it directly would produce duplicate diagnostics.
13754 continue;
13755
13756 if (IsLogicalAndOperator &&
13757 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
13758 // Ignore checking string literals that are in logical and operators.
13759 // This is a common pattern for asserts.
13760 continue;
13761 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
13762 }
13763
13764 if (BO && BO->isLogicalOp()) {
13765 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13766 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13767 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13768
13769 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13770 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13771 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13772 }
13773
13774 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
13775 if (U->getOpcode() == UO_LNot) {
13776 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
13777 } else if (U->getOpcode() != UO_AddrOf) {
13778 if (U->getSubExpr()->getType()->isAtomicType())
13779 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
13780 DiagID: diag::warn_atomic_implicit_seq_cst);
13781 }
13782 }
13783}
13784
13785/// AnalyzeImplicitConversions - Find and report any interesting
13786/// implicit conversions in the given expression. There are a couple
13787/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13788static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13789 bool IsListInit/*= false*/) {
13790 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13791 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
13792 while (!WorkList.empty())
13793 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
13794}
13795
13796// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13797// Returns true when emitting a warning about taking the address of a reference.
13798static bool CheckForReference(Sema &SemaRef, const Expr *E,
13799 const PartialDiagnostic &PD) {
13800 E = E->IgnoreParenImpCasts();
13801
13802 const FunctionDecl *FD = nullptr;
13803
13804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13805 if (!DRE->getDecl()->getType()->isReferenceType())
13806 return false;
13807 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13808 if (!M->getMemberDecl()->getType()->isReferenceType())
13809 return false;
13810 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
13811 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
13812 return false;
13813 FD = Call->getDirectCallee();
13814 } else {
13815 return false;
13816 }
13817
13818 SemaRef.Diag(Loc: E->getExprLoc(), PD);
13819
13820 // If possible, point to location of function.
13821 if (FD) {
13822 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
13823 }
13824
13825 return true;
13826}
13827
13828// Returns true if the SourceLocation is expanded from any macro body.
13829// Returns false if the SourceLocation is invalid, is from not in a macro
13830// expansion, or is from expanded from a top-level macro argument.
13831static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13832 if (Loc.isInvalid())
13833 return false;
13834
13835 while (Loc.isMacroID()) {
13836 if (SM.isMacroBodyExpansion(Loc))
13837 return true;
13838 Loc = SM.getImmediateMacroCallerLoc(Loc);
13839 }
13840
13841 return false;
13842}
13843
13844void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13845 Expr::NullPointerConstantKind NullKind,
13846 bool IsEqual, SourceRange Range) {
13847 if (!E)
13848 return;
13849
13850 // Don't warn inside macros.
13851 if (E->getExprLoc().isMacroID()) {
13852 const SourceManager &SM = getSourceManager();
13853 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
13854 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
13855 return;
13856 }
13857 E = E->IgnoreImpCasts();
13858
13859 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13860
13861 if (isa<CXXThisExpr>(Val: E)) {
13862 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13863 : diag::warn_this_bool_conversion;
13864 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13865 return;
13866 }
13867
13868 bool IsAddressOf = false;
13869
13870 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
13871 if (UO->getOpcode() != UO_AddrOf)
13872 return;
13873 IsAddressOf = true;
13874 E = UO->getSubExpr();
13875 }
13876
13877 if (IsAddressOf) {
13878 unsigned DiagID = IsCompare
13879 ? diag::warn_address_of_reference_null_compare
13880 : diag::warn_address_of_reference_bool_conversion;
13881 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13882 << IsEqual;
13883 if (CheckForReference(SemaRef&: *this, E, PD)) {
13884 return;
13885 }
13886 }
13887
13888 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13889 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
13890 std::string Str;
13891 llvm::raw_string_ostream S(Str);
13892 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13893 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13894 : diag::warn_cast_nonnull_to_bool;
13895 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
13896 << E->getSourceRange() << Range << IsEqual;
13897 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
13898 };
13899
13900 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13901 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
13902 if (auto *Callee = Call->getDirectCallee()) {
13903 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13904 ComplainAboutNonnullParamOrCall(A);
13905 return;
13906 }
13907 }
13908 }
13909
13910 // Complain if we are converting a lambda expression to a boolean value
13911 // outside of instantiation.
13912 if (!inTemplateInstantiation()) {
13913 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
13914 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13915 MRecordDecl && MRecordDecl->isLambda()) {
13916 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
13917 << /*LambdaPointerConversionOperatorType=*/3
13918 << MRecordDecl->getSourceRange() << Range << IsEqual;
13919 return;
13920 }
13921 }
13922 }
13923
13924 // Expect to find a single Decl. Skip anything more complicated.
13925 ValueDecl *D = nullptr;
13926 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
13927 D = R->getDecl();
13928 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13929 D = M->getMemberDecl();
13930 }
13931
13932 // Weak Decls can be null.
13933 if (!D || D->isWeak())
13934 return;
13935
13936 // Check for parameter decl with nonnull attribute
13937 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
13938 if (getCurFunction() &&
13939 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
13940 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13941 ComplainAboutNonnullParamOrCall(A);
13942 return;
13943 }
13944
13945 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
13946 // Skip function template not specialized yet.
13947 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13948 return;
13949 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
13950 assert(ParamIter != FD->param_end());
13951 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
13952
13953 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13954 if (!NonNull->args_size()) {
13955 ComplainAboutNonnullParamOrCall(NonNull);
13956 return;
13957 }
13958
13959 for (const ParamIdx &ArgNo : NonNull->args()) {
13960 if (ArgNo.getASTIndex() == ParamNo) {
13961 ComplainAboutNonnullParamOrCall(NonNull);
13962 return;
13963 }
13964 }
13965 }
13966 }
13967 }
13968 }
13969
13970 QualType T = D->getType();
13971 const bool IsArray = T->isArrayType();
13972 const bool IsFunction = T->isFunctionType();
13973
13974 // Address of function is used to silence the function warning.
13975 if (IsAddressOf && IsFunction) {
13976 return;
13977 }
13978
13979 // Found nothing.
13980 if (!IsAddressOf && !IsFunction && !IsArray)
13981 return;
13982
13983 // Pretty print the expression for the diagnostic.
13984 std::string Str;
13985 llvm::raw_string_ostream S(Str);
13986 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13987
13988 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13989 : diag::warn_impcast_pointer_to_bool;
13990 enum {
13991 AddressOf,
13992 FunctionPointer,
13993 ArrayPointer
13994 } DiagType;
13995 if (IsAddressOf)
13996 DiagType = AddressOf;
13997 else if (IsFunction)
13998 DiagType = FunctionPointer;
13999 else if (IsArray)
14000 DiagType = ArrayPointer;
14001 else
14002 llvm_unreachable("Could not determine diagnostic.");
14003 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14004 << Range << IsEqual;
14005
14006 if (!IsFunction)
14007 return;
14008
14009 // Suggest '&' to silence the function warning.
14010 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14011 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14012
14013 // Check to see if '()' fixit should be emitted.
14014 QualType ReturnType;
14015 UnresolvedSet<4> NonTemplateOverloads;
14016 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14017 if (ReturnType.isNull())
14018 return;
14019
14020 if (IsCompare) {
14021 // There are two cases here. If there is null constant, the only suggest
14022 // for a pointer return type. If the null is 0, then suggest if the return
14023 // type is a pointer or an integer type.
14024 if (!ReturnType->isPointerType()) {
14025 if (NullKind == Expr::NPCK_ZeroExpression ||
14026 NullKind == Expr::NPCK_ZeroLiteral) {
14027 if (!ReturnType->isIntegerType())
14028 return;
14029 } else {
14030 return;
14031 }
14032 }
14033 } else { // !IsCompare
14034 // For function to bool, only suggest if the function pointer has bool
14035 // return type.
14036 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14037 return;
14038 }
14039 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14040 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14041}
14042
14043bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14044 SourceLocation CC) {
14045 QualType Source = E->getType();
14046 QualType Target = T;
14047
14048 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14049 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14050 // Overflow behavior type is being stripped - issue warning
14051 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14052 Target->isUnsignedIntegerType()) {
14053 // For unsigned wrap to unsigned conversions, use pedantic version
14054 unsigned DiagId =
14055 InOverflowBehaviorAssignmentContext
14056 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14057 : diag::warn_impcast_overflow_behavior_pedantic;
14058 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14059 } else {
14060 unsigned DiagId = InOverflowBehaviorAssignmentContext
14061 ? diag::warn_impcast_overflow_behavior_assignment
14062 : diag::warn_impcast_overflow_behavior;
14063 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14064 }
14065 }
14066 }
14067
14068 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14069 if (TargetOBT->isWrapKind()) {
14070 return true;
14071 }
14072 }
14073
14074 return false;
14075}
14076
14077void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14078 // Don't diagnose in unevaluated contexts.
14079 if (isUnevaluatedContext())
14080 return;
14081
14082 // Don't diagnose for value- or type-dependent expressions.
14083 if (E->isTypeDependent() || E->isValueDependent())
14084 return;
14085
14086 // Check for array bounds violations in cases where the check isn't triggered
14087 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14088 // ArraySubscriptExpr is on the RHS of a variable initialization.
14089 CheckArrayAccess(E);
14090
14091 // This is not the right CC for (e.g.) a variable initialization.
14092 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14093}
14094
14095void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14096 ::CheckBoolLikeConversion(S&: *this, E, CC);
14097}
14098
14099void Sema::CheckForIntOverflow (const Expr *E) {
14100 // Use a work list to deal with nested struct initializers.
14101 SmallVector<const Expr *, 2> Exprs(1, E);
14102
14103 do {
14104 const Expr *OriginalE = Exprs.pop_back_val();
14105 const Expr *E = OriginalE->IgnoreParenCasts();
14106
14107 if (isa<BinaryOperator, UnaryOperator>(Val: E)) {
14108 E->EvaluateForOverflow(Ctx: Context);
14109 continue;
14110 }
14111
14112 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14113 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14114 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14115 E->EvaluateForOverflow(Ctx: Context);
14116 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14117 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14118 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14119 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14120 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14121 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14122 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14123 Exprs.push_back(Elt: Temporary->getSubExpr());
14124 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14125 Exprs.push_back(Elt: Array->getIdx());
14126 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14127 Exprs.push_back(Elt: Compound->getInitializer());
14128 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14129 New && New->isArray()) {
14130 if (auto ArraySize = New->getArraySize())
14131 Exprs.push_back(Elt: *ArraySize);
14132 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14133 Exprs.push_back(Elt: MTE->getSubExpr());
14134 } while (!Exprs.empty());
14135}
14136
14137namespace {
14138
14139/// Visitor for expressions which looks for unsequenced operations on the
14140/// same object.
14141class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14142 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14143
14144 /// A tree of sequenced regions within an expression. Two regions are
14145 /// unsequenced if one is an ancestor or a descendent of the other. When we
14146 /// finish processing an expression with sequencing, such as a comma
14147 /// expression, we fold its tree nodes into its parent, since they are
14148 /// unsequenced with respect to nodes we will visit later.
14149 class SequenceTree {
14150 struct Value {
14151 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14152 unsigned Parent : 31;
14153 LLVM_PREFERRED_TYPE(bool)
14154 unsigned Merged : 1;
14155 };
14156 SmallVector<Value, 8> Values;
14157
14158 public:
14159 /// A region within an expression which may be sequenced with respect
14160 /// to some other region.
14161 class Seq {
14162 friend class SequenceTree;
14163
14164 unsigned Index;
14165
14166 explicit Seq(unsigned N) : Index(N) {}
14167
14168 public:
14169 Seq() : Index(0) {}
14170 };
14171
14172 SequenceTree() { Values.push_back(Elt: Value(0)); }
14173 Seq root() const { return Seq(0); }
14174
14175 /// Create a new sequence of operations, which is an unsequenced
14176 /// subset of \p Parent. This sequence of operations is sequenced with
14177 /// respect to other children of \p Parent.
14178 Seq allocate(Seq Parent) {
14179 Values.push_back(Elt: Value(Parent.Index));
14180 return Seq(Values.size() - 1);
14181 }
14182
14183 /// Merge a sequence of operations into its parent.
14184 void merge(Seq S) {
14185 Values[S.Index].Merged = true;
14186 }
14187
14188 /// Determine whether two operations are unsequenced. This operation
14189 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14190 /// should have been merged into its parent as appropriate.
14191 bool isUnsequenced(Seq Cur, Seq Old) {
14192 unsigned C = representative(K: Cur.Index);
14193 unsigned Target = representative(K: Old.Index);
14194 while (C >= Target) {
14195 if (C == Target)
14196 return true;
14197 C = Values[C].Parent;
14198 }
14199 return false;
14200 }
14201
14202 private:
14203 /// Pick a representative for a sequence.
14204 unsigned representative(unsigned K) {
14205 if (Values[K].Merged)
14206 // Perform path compression as we go.
14207 return Values[K].Parent = representative(K: Values[K].Parent);
14208 return K;
14209 }
14210 };
14211
14212 /// An object for which we can track unsequenced uses.
14213 using Object = const NamedDecl *;
14214
14215 /// Different flavors of object usage which we track. We only track the
14216 /// least-sequenced usage of each kind.
14217 enum UsageKind {
14218 /// A read of an object. Multiple unsequenced reads are OK.
14219 UK_Use,
14220
14221 /// A modification of an object which is sequenced before the value
14222 /// computation of the expression, such as ++n in C++.
14223 UK_ModAsValue,
14224
14225 /// A modification of an object which is not sequenced before the value
14226 /// computation of the expression, such as n++.
14227 UK_ModAsSideEffect,
14228
14229 UK_Count = UK_ModAsSideEffect + 1
14230 };
14231
14232 /// Bundle together a sequencing region and the expression corresponding
14233 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14234 struct Usage {
14235 const Expr *UsageExpr = nullptr;
14236 SequenceTree::Seq Seq;
14237
14238 Usage() = default;
14239 };
14240
14241 struct UsageInfo {
14242 Usage Uses[UK_Count];
14243
14244 /// Have we issued a diagnostic for this object already?
14245 bool Diagnosed = false;
14246
14247 UsageInfo();
14248 };
14249 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14250
14251 Sema &SemaRef;
14252
14253 /// Sequenced regions within the expression.
14254 SequenceTree Tree;
14255
14256 /// Declaration modifications and references which we have seen.
14257 UsageInfoMap UsageMap;
14258
14259 /// The region we are currently within.
14260 SequenceTree::Seq Region;
14261
14262 /// Filled in with declarations which were modified as a side-effect
14263 /// (that is, post-increment operations).
14264 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14265
14266 /// Expressions to check later. We defer checking these to reduce
14267 /// stack usage.
14268 SmallVectorImpl<const Expr *> &WorkList;
14269
14270 /// RAII object wrapping the visitation of a sequenced subexpression of an
14271 /// expression. At the end of this process, the side-effects of the evaluation
14272 /// become sequenced with respect to the value computation of the result, so
14273 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14274 /// UK_ModAsValue.
14275 struct SequencedSubexpression {
14276 SequencedSubexpression(SequenceChecker &Self)
14277 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14278 Self.ModAsSideEffect = &ModAsSideEffect;
14279 }
14280
14281 ~SequencedSubexpression() {
14282 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14283 // Add a new usage with usage kind UK_ModAsValue, and then restore
14284 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14285 // the previous one was empty).
14286 UsageInfo &UI = Self.UsageMap[M.first];
14287 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14288 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14289 SideEffectUsage = M.second;
14290 }
14291 Self.ModAsSideEffect = OldModAsSideEffect;
14292 }
14293
14294 SequenceChecker &Self;
14295 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14296 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14297 };
14298
14299 /// RAII object wrapping the visitation of a subexpression which we might
14300 /// choose to evaluate as a constant. If any subexpression is evaluated and
14301 /// found to be non-constant, this allows us to suppress the evaluation of
14302 /// the outer expression.
14303 class EvaluationTracker {
14304 public:
14305 EvaluationTracker(SequenceChecker &Self)
14306 : Self(Self), Prev(Self.EvalTracker) {
14307 Self.EvalTracker = this;
14308 }
14309
14310 ~EvaluationTracker() {
14311 Self.EvalTracker = Prev;
14312 if (Prev)
14313 Prev->EvalOK &= EvalOK;
14314 }
14315
14316 bool evaluate(const Expr *E, bool &Result) {
14317 if (!EvalOK || E->isValueDependent())
14318 return false;
14319 EvalOK = E->EvaluateAsBooleanCondition(
14320 Result, Ctx: Self.SemaRef.Context,
14321 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14322 return EvalOK;
14323 }
14324
14325 private:
14326 SequenceChecker &Self;
14327 EvaluationTracker *Prev;
14328 bool EvalOK = true;
14329 } *EvalTracker = nullptr;
14330
14331 /// Find the object which is produced by the specified expression,
14332 /// if any.
14333 Object getObject(const Expr *E, bool Mod) const {
14334 E = E->IgnoreParenCasts();
14335 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14336 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14337 return getObject(E: UO->getSubExpr(), Mod);
14338 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14339 if (BO->getOpcode() == BO_Comma)
14340 return getObject(E: BO->getRHS(), Mod);
14341 if (Mod && BO->isAssignmentOp())
14342 return getObject(E: BO->getLHS(), Mod);
14343 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14344 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14345 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14346 return ME->getMemberDecl();
14347 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14348 // FIXME: If this is a reference, map through to its value.
14349 return DRE->getDecl();
14350 return nullptr;
14351 }
14352
14353 /// Note that an object \p O was modified or used by an expression
14354 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14355 /// the object \p O as obtained via the \p UsageMap.
14356 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14357 // Get the old usage for the given object and usage kind.
14358 Usage &U = UI.Uses[UK];
14359 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14360 // If we have a modification as side effect and are in a sequenced
14361 // subexpression, save the old Usage so that we can restore it later
14362 // in SequencedSubexpression::~SequencedSubexpression.
14363 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14364 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14365 // Then record the new usage with the current sequencing region.
14366 U.UsageExpr = UsageExpr;
14367 U.Seq = Region;
14368 }
14369 }
14370
14371 /// Check whether a modification or use of an object \p O in an expression
14372 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14373 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14374 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14375 /// usage and false we are checking for a mod-use unsequenced usage.
14376 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14377 UsageKind OtherKind, bool IsModMod) {
14378 if (UI.Diagnosed)
14379 return;
14380
14381 const Usage &U = UI.Uses[OtherKind];
14382 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14383 return;
14384
14385 const Expr *Mod = U.UsageExpr;
14386 const Expr *ModOrUse = UsageExpr;
14387 if (OtherKind == UK_Use)
14388 std::swap(a&: Mod, b&: ModOrUse);
14389
14390 SemaRef.DiagRuntimeBehavior(
14391 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14392 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14393 : diag::warn_unsequenced_mod_use)
14394 << O << SourceRange(ModOrUse->getExprLoc()));
14395 UI.Diagnosed = true;
14396 }
14397
14398 // A note on note{Pre, Post}{Use, Mod}:
14399 //
14400 // (It helps to follow the algorithm with an expression such as
14401 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14402 // operations before C++17 and both are well-defined in C++17).
14403 //
14404 // When visiting a node which uses/modify an object we first call notePreUse
14405 // or notePreMod before visiting its sub-expression(s). At this point the
14406 // children of the current node have not yet been visited and so the eventual
14407 // uses/modifications resulting from the children of the current node have not
14408 // been recorded yet.
14409 //
14410 // We then visit the children of the current node. After that notePostUse or
14411 // notePostMod is called. These will 1) detect an unsequenced modification
14412 // as side effect (as in "k++ + k") and 2) add a new usage with the
14413 // appropriate usage kind.
14414 //
14415 // We also have to be careful that some operation sequences modification as
14416 // side effect as well (for example: || or ,). To account for this we wrap
14417 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14418 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14419 // which record usages which are modifications as side effect, and then
14420 // downgrade them (or more accurately restore the previous usage which was a
14421 // modification as side effect) when exiting the scope of the sequenced
14422 // subexpression.
14423
14424 void notePreUse(Object O, const Expr *UseExpr) {
14425 UsageInfo &UI = UsageMap[O];
14426 // Uses conflict with other modifications.
14427 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14428 }
14429
14430 void notePostUse(Object O, const Expr *UseExpr) {
14431 UsageInfo &UI = UsageMap[O];
14432 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14433 /*IsModMod=*/false);
14434 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14435 }
14436
14437 void notePreMod(Object O, const Expr *ModExpr) {
14438 UsageInfo &UI = UsageMap[O];
14439 // Modifications conflict with other modifications and with uses.
14440 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14441 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14442 }
14443
14444 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14445 UsageInfo &UI = UsageMap[O];
14446 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14447 /*IsModMod=*/true);
14448 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14449 }
14450
14451public:
14452 SequenceChecker(Sema &S, const Expr *E,
14453 SmallVectorImpl<const Expr *> &WorkList)
14454 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14455 Visit(S: E);
14456 // Silence a -Wunused-private-field since WorkList is now unused.
14457 // TODO: Evaluate if it can be used, and if not remove it.
14458 (void)this->WorkList;
14459 }
14460
14461 void VisitStmt(const Stmt *S) {
14462 // Skip all statements which aren't expressions for now.
14463 }
14464
14465 void VisitExpr(const Expr *E) {
14466 // By default, just recurse to evaluated subexpressions.
14467 Base::VisitStmt(S: E);
14468 }
14469
14470 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14471 for (auto *Sub : CSE->children()) {
14472 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14473 if (!ChildExpr)
14474 continue;
14475
14476 if (ChildExpr == CSE->getOperand())
14477 // Do not recurse over a CoroutineSuspendExpr's operand.
14478 // The operand is also a subexpression of getCommonExpr(), and
14479 // recursing into it directly could confuse object management
14480 // for the sake of sequence tracking.
14481 continue;
14482
14483 Visit(S: Sub);
14484 }
14485 }
14486
14487 void VisitCastExpr(const CastExpr *E) {
14488 Object O = Object();
14489 if (E->getCastKind() == CK_LValueToRValue)
14490 O = getObject(E: E->getSubExpr(), Mod: false);
14491
14492 if (O)
14493 notePreUse(O, UseExpr: E);
14494 VisitExpr(E);
14495 if (O)
14496 notePostUse(O, UseExpr: E);
14497 }
14498
14499 void VisitSequencedExpressions(const Expr *SequencedBefore,
14500 const Expr *SequencedAfter) {
14501 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
14502 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
14503 SequenceTree::Seq OldRegion = Region;
14504
14505 {
14506 SequencedSubexpression SeqBefore(*this);
14507 Region = BeforeRegion;
14508 Visit(S: SequencedBefore);
14509 }
14510
14511 Region = AfterRegion;
14512 Visit(S: SequencedAfter);
14513
14514 Region = OldRegion;
14515
14516 Tree.merge(S: BeforeRegion);
14517 Tree.merge(S: AfterRegion);
14518 }
14519
14520 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14521 // C++17 [expr.sub]p1:
14522 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14523 // expression E1 is sequenced before the expression E2.
14524 if (SemaRef.getLangOpts().CPlusPlus17)
14525 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
14526 else {
14527 Visit(S: ASE->getLHS());
14528 Visit(S: ASE->getRHS());
14529 }
14530 }
14531
14532 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14533 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14534 void VisitBinPtrMem(const BinaryOperator *BO) {
14535 // C++17 [expr.mptr.oper]p4:
14536 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14537 // the expression E1 is sequenced before the expression E2.
14538 if (SemaRef.getLangOpts().CPlusPlus17)
14539 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14540 else {
14541 Visit(S: BO->getLHS());
14542 Visit(S: BO->getRHS());
14543 }
14544 }
14545
14546 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14547 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14548 void VisitBinShlShr(const BinaryOperator *BO) {
14549 // C++17 [expr.shift]p4:
14550 // The expression E1 is sequenced before the expression E2.
14551 if (SemaRef.getLangOpts().CPlusPlus17)
14552 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14553 else {
14554 Visit(S: BO->getLHS());
14555 Visit(S: BO->getRHS());
14556 }
14557 }
14558
14559 void VisitBinComma(const BinaryOperator *BO) {
14560 // C++11 [expr.comma]p1:
14561 // Every value computation and side effect associated with the left
14562 // expression is sequenced before every value computation and side
14563 // effect associated with the right expression.
14564 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14565 }
14566
14567 void VisitBinAssign(const BinaryOperator *BO) {
14568 SequenceTree::Seq RHSRegion;
14569 SequenceTree::Seq LHSRegion;
14570 if (SemaRef.getLangOpts().CPlusPlus17) {
14571 RHSRegion = Tree.allocate(Parent: Region);
14572 LHSRegion = Tree.allocate(Parent: Region);
14573 } else {
14574 RHSRegion = Region;
14575 LHSRegion = Region;
14576 }
14577 SequenceTree::Seq OldRegion = Region;
14578
14579 // C++11 [expr.ass]p1:
14580 // [...] the assignment is sequenced after the value computation
14581 // of the right and left operands, [...]
14582 //
14583 // so check it before inspecting the operands and update the
14584 // map afterwards.
14585 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
14586 if (O)
14587 notePreMod(O, ModExpr: BO);
14588
14589 if (SemaRef.getLangOpts().CPlusPlus17) {
14590 // C++17 [expr.ass]p1:
14591 // [...] The right operand is sequenced before the left operand. [...]
14592 {
14593 SequencedSubexpression SeqBefore(*this);
14594 Region = RHSRegion;
14595 Visit(S: BO->getRHS());
14596 }
14597
14598 Region = LHSRegion;
14599 Visit(S: BO->getLHS());
14600
14601 if (O && isa<CompoundAssignOperator>(Val: BO))
14602 notePostUse(O, UseExpr: BO);
14603
14604 } else {
14605 // C++11 does not specify any sequencing between the LHS and RHS.
14606 Region = LHSRegion;
14607 Visit(S: BO->getLHS());
14608
14609 if (O && isa<CompoundAssignOperator>(Val: BO))
14610 notePostUse(O, UseExpr: BO);
14611
14612 Region = RHSRegion;
14613 Visit(S: BO->getRHS());
14614 }
14615
14616 // C++11 [expr.ass]p1:
14617 // the assignment is sequenced [...] before the value computation of the
14618 // assignment expression.
14619 // C11 6.5.16/3 has no such rule.
14620 Region = OldRegion;
14621 if (O)
14622 notePostMod(O, ModExpr: BO,
14623 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14624 : UK_ModAsSideEffect);
14625 if (SemaRef.getLangOpts().CPlusPlus17) {
14626 Tree.merge(S: RHSRegion);
14627 Tree.merge(S: LHSRegion);
14628 }
14629 }
14630
14631 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14632 VisitBinAssign(BO: CAO);
14633 }
14634
14635 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14636 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14637 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14638 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14639 if (!O)
14640 return VisitExpr(E: UO);
14641
14642 notePreMod(O, ModExpr: UO);
14643 Visit(S: UO->getSubExpr());
14644 // C++11 [expr.pre.incr]p1:
14645 // the expression ++x is equivalent to x+=1
14646 notePostMod(O, ModExpr: UO,
14647 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14648 : UK_ModAsSideEffect);
14649 }
14650
14651 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14652 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14653 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14654 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14655 if (!O)
14656 return VisitExpr(E: UO);
14657
14658 notePreMod(O, ModExpr: UO);
14659 Visit(S: UO->getSubExpr());
14660 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
14661 }
14662
14663 void VisitBinLOr(const BinaryOperator *BO) {
14664 // C++11 [expr.log.or]p2:
14665 // If the second expression is evaluated, every value computation and
14666 // side effect associated with the first expression is sequenced before
14667 // every value computation and side effect associated with the
14668 // second expression.
14669 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14670 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14671 SequenceTree::Seq OldRegion = Region;
14672
14673 EvaluationTracker Eval(*this);
14674 {
14675 SequencedSubexpression Sequenced(*this);
14676 Region = LHSRegion;
14677 Visit(S: BO->getLHS());
14678 }
14679
14680 // C++11 [expr.log.or]p1:
14681 // [...] the second operand is not evaluated if the first operand
14682 // evaluates to true.
14683 bool EvalResult = false;
14684 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14685 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14686 if (ShouldVisitRHS) {
14687 Region = RHSRegion;
14688 Visit(S: BO->getRHS());
14689 }
14690
14691 Region = OldRegion;
14692 Tree.merge(S: LHSRegion);
14693 Tree.merge(S: RHSRegion);
14694 }
14695
14696 void VisitBinLAnd(const BinaryOperator *BO) {
14697 // C++11 [expr.log.and]p2:
14698 // If the second expression is evaluated, every value computation and
14699 // side effect associated with the first expression is sequenced before
14700 // every value computation and side effect associated with the
14701 // second expression.
14702 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14703 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14704 SequenceTree::Seq OldRegion = Region;
14705
14706 EvaluationTracker Eval(*this);
14707 {
14708 SequencedSubexpression Sequenced(*this);
14709 Region = LHSRegion;
14710 Visit(S: BO->getLHS());
14711 }
14712
14713 // C++11 [expr.log.and]p1:
14714 // [...] the second operand is not evaluated if the first operand is false.
14715 bool EvalResult = false;
14716 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14717 bool ShouldVisitRHS = !EvalOK || EvalResult;
14718 if (ShouldVisitRHS) {
14719 Region = RHSRegion;
14720 Visit(S: BO->getRHS());
14721 }
14722
14723 Region = OldRegion;
14724 Tree.merge(S: LHSRegion);
14725 Tree.merge(S: RHSRegion);
14726 }
14727
14728 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14729 // C++11 [expr.cond]p1:
14730 // [...] Every value computation and side effect associated with the first
14731 // expression is sequenced before every value computation and side effect
14732 // associated with the second or third expression.
14733 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
14734
14735 // No sequencing is specified between the true and false expression.
14736 // However since exactly one of both is going to be evaluated we can
14737 // consider them to be sequenced. This is needed to avoid warning on
14738 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14739 // both the true and false expressions because we can't evaluate x.
14740 // This will still allow us to detect an expression like (pre C++17)
14741 // "(x ? y += 1 : y += 2) = y".
14742 //
14743 // We don't wrap the visitation of the true and false expression with
14744 // SequencedSubexpression because we don't want to downgrade modifications
14745 // as side effect in the true and false expressions after the visition
14746 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14747 // not warn between the two "y++", but we should warn between the "y++"
14748 // and the "y".
14749 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
14750 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
14751 SequenceTree::Seq OldRegion = Region;
14752
14753 EvaluationTracker Eval(*this);
14754 {
14755 SequencedSubexpression Sequenced(*this);
14756 Region = ConditionRegion;
14757 Visit(S: CO->getCond());
14758 }
14759
14760 // C++11 [expr.cond]p1:
14761 // [...] The first expression is contextually converted to bool (Clause 4).
14762 // It is evaluated and if it is true, the result of the conditional
14763 // expression is the value of the second expression, otherwise that of the
14764 // third expression. Only one of the second and third expressions is
14765 // evaluated. [...]
14766 bool EvalResult = false;
14767 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
14768 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14769 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14770 if (ShouldVisitTrueExpr) {
14771 Region = TrueRegion;
14772 Visit(S: CO->getTrueExpr());
14773 }
14774 if (ShouldVisitFalseExpr) {
14775 Region = FalseRegion;
14776 Visit(S: CO->getFalseExpr());
14777 }
14778
14779 Region = OldRegion;
14780 Tree.merge(S: ConditionRegion);
14781 Tree.merge(S: TrueRegion);
14782 Tree.merge(S: FalseRegion);
14783 }
14784
14785 void VisitCallExpr(const CallExpr *CE) {
14786 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14787
14788 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
14789 return;
14790
14791 // C++11 [intro.execution]p15:
14792 // When calling a function [...], every value computation and side effect
14793 // associated with any argument expression, or with the postfix expression
14794 // designating the called function, is sequenced before execution of every
14795 // expression or statement in the body of the function [and thus before
14796 // the value computation of its result].
14797 SequencedSubexpression Sequenced(*this);
14798 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
14799 // C++17 [expr.call]p5
14800 // The postfix-expression is sequenced before each expression in the
14801 // expression-list and any default argument. [...]
14802 SequenceTree::Seq CalleeRegion;
14803 SequenceTree::Seq OtherRegion;
14804 if (SemaRef.getLangOpts().CPlusPlus17) {
14805 CalleeRegion = Tree.allocate(Parent: Region);
14806 OtherRegion = Tree.allocate(Parent: Region);
14807 } else {
14808 CalleeRegion = Region;
14809 OtherRegion = Region;
14810 }
14811 SequenceTree::Seq OldRegion = Region;
14812
14813 // Visit the callee expression first.
14814 Region = CalleeRegion;
14815 if (SemaRef.getLangOpts().CPlusPlus17) {
14816 SequencedSubexpression Sequenced(*this);
14817 Visit(S: CE->getCallee());
14818 } else {
14819 Visit(S: CE->getCallee());
14820 }
14821
14822 // Then visit the argument expressions.
14823 Region = OtherRegion;
14824 for (const Expr *Argument : CE->arguments())
14825 Visit(S: Argument);
14826
14827 Region = OldRegion;
14828 if (SemaRef.getLangOpts().CPlusPlus17) {
14829 Tree.merge(S: CalleeRegion);
14830 Tree.merge(S: OtherRegion);
14831 }
14832 });
14833 }
14834
14835 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14836 // C++17 [over.match.oper]p2:
14837 // [...] the operator notation is first transformed to the equivalent
14838 // function-call notation as summarized in Table 12 (where @ denotes one
14839 // of the operators covered in the specified subclause). However, the
14840 // operands are sequenced in the order prescribed for the built-in
14841 // operator (Clause 8).
14842 //
14843 // From the above only overloaded binary operators and overloaded call
14844 // operators have sequencing rules in C++17 that we need to handle
14845 // separately.
14846 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14847 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14848 return VisitCallExpr(CE: CXXOCE);
14849
14850 enum {
14851 NoSequencing,
14852 LHSBeforeRHS,
14853 RHSBeforeLHS,
14854 LHSBeforeRest
14855 } SequencingKind;
14856 switch (CXXOCE->getOperator()) {
14857 case OO_Equal:
14858 case OO_PlusEqual:
14859 case OO_MinusEqual:
14860 case OO_StarEqual:
14861 case OO_SlashEqual:
14862 case OO_PercentEqual:
14863 case OO_CaretEqual:
14864 case OO_AmpEqual:
14865 case OO_PipeEqual:
14866 case OO_LessLessEqual:
14867 case OO_GreaterGreaterEqual:
14868 SequencingKind = RHSBeforeLHS;
14869 break;
14870
14871 case OO_LessLess:
14872 case OO_GreaterGreater:
14873 case OO_AmpAmp:
14874 case OO_PipePipe:
14875 case OO_Comma:
14876 case OO_ArrowStar:
14877 case OO_Subscript:
14878 SequencingKind = LHSBeforeRHS;
14879 break;
14880
14881 case OO_Call:
14882 SequencingKind = LHSBeforeRest;
14883 break;
14884
14885 default:
14886 SequencingKind = NoSequencing;
14887 break;
14888 }
14889
14890 if (SequencingKind == NoSequencing)
14891 return VisitCallExpr(CE: CXXOCE);
14892
14893 // This is a call, so all subexpressions are sequenced before the result.
14894 SequencedSubexpression Sequenced(*this);
14895
14896 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
14897 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14898 "Should only get there with C++17 and above!");
14899 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14900 "Should only get there with an overloaded binary operator"
14901 " or an overloaded call operator!");
14902
14903 if (SequencingKind == LHSBeforeRest) {
14904 assert(CXXOCE->getOperator() == OO_Call &&
14905 "We should only have an overloaded call operator here!");
14906
14907 // This is very similar to VisitCallExpr, except that we only have the
14908 // C++17 case. The postfix-expression is the first argument of the
14909 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14910 // are in the following arguments.
14911 //
14912 // Note that we intentionally do not visit the callee expression since
14913 // it is just a decayed reference to a function.
14914 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
14915 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
14916 SequenceTree::Seq OldRegion = Region;
14917
14918 assert(CXXOCE->getNumArgs() >= 1 &&
14919 "An overloaded call operator must have at least one argument"
14920 " for the postfix-expression!");
14921 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14922 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14923 CXXOCE->getNumArgs() - 1);
14924
14925 // Visit the postfix-expression first.
14926 {
14927 Region = PostfixExprRegion;
14928 SequencedSubexpression Sequenced(*this);
14929 Visit(S: PostfixExpr);
14930 }
14931
14932 // Then visit the argument expressions.
14933 Region = ArgsRegion;
14934 for (const Expr *Arg : Args)
14935 Visit(S: Arg);
14936
14937 Region = OldRegion;
14938 Tree.merge(S: PostfixExprRegion);
14939 Tree.merge(S: ArgsRegion);
14940 } else {
14941 assert(CXXOCE->getNumArgs() == 2 &&
14942 "Should only have two arguments here!");
14943 assert((SequencingKind == LHSBeforeRHS ||
14944 SequencingKind == RHSBeforeLHS) &&
14945 "Unexpected sequencing kind!");
14946
14947 // We do not visit the callee expression since it is just a decayed
14948 // reference to a function.
14949 const Expr *E1 = CXXOCE->getArg(Arg: 0);
14950 const Expr *E2 = CXXOCE->getArg(Arg: 1);
14951 if (SequencingKind == RHSBeforeLHS)
14952 std::swap(a&: E1, b&: E2);
14953
14954 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
14955 }
14956 });
14957 }
14958
14959 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14960 // This is a call, so all subexpressions are sequenced before the result.
14961 SequencedSubexpression Sequenced(*this);
14962
14963 if (!CCE->isListInitialization())
14964 return VisitExpr(E: CCE);
14965
14966 // In C++11, list initializations are sequenced.
14967 SequenceExpressionsInOrder(
14968 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14969 }
14970
14971 void VisitInitListExpr(const InitListExpr *ILE) {
14972 if (!SemaRef.getLangOpts().CPlusPlus11)
14973 return VisitExpr(E: ILE);
14974
14975 // In C++11, list initializations are sequenced.
14976 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
14977 }
14978
14979 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14980 // C++20 parenthesized list initializations are sequenced. See C++20
14981 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14982 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
14983 }
14984
14985private:
14986 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14987 SmallVector<SequenceTree::Seq, 32> Elts;
14988 SequenceTree::Seq Parent = Region;
14989 for (const Expr *E : ExpressionList) {
14990 if (!E)
14991 continue;
14992 Region = Tree.allocate(Parent);
14993 Elts.push_back(Elt: Region);
14994 Visit(S: E);
14995 }
14996
14997 // Forget that the initializers are sequenced.
14998 Region = Parent;
14999 for (unsigned I = 0; I < Elts.size(); ++I)
15000 Tree.merge(S: Elts[I]);
15001 }
15002};
15003
15004SequenceChecker::UsageInfo::UsageInfo() = default;
15005
15006} // namespace
15007
15008void Sema::CheckUnsequencedOperations(const Expr *E) {
15009 SmallVector<const Expr *, 8> WorkList;
15010 WorkList.push_back(Elt: E);
15011 while (!WorkList.empty()) {
15012 const Expr *Item = WorkList.pop_back_val();
15013 SequenceChecker(*this, Item, WorkList);
15014 }
15015}
15016
15017void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15018 bool IsConstexpr) {
15019 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15020 IsConstexpr || isa<ConstantExpr>(Val: E));
15021 CheckImplicitConversions(E, CC: CheckLoc);
15022 if (!E->isInstantiationDependent())
15023 CheckUnsequencedOperations(E);
15024 if (!IsConstexpr && !E->isValueDependent())
15025 CheckForIntOverflow(E);
15026}
15027
15028void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15029 FieldDecl *BitField,
15030 Expr *Init) {
15031 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15032}
15033
15034static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15035 SourceLocation Loc) {
15036 if (!PType->isVariablyModifiedType())
15037 return;
15038 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15039 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15040 return;
15041 }
15042 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15043 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15044 return;
15045 }
15046 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15047 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15048 return;
15049 }
15050
15051 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15052 if (!AT)
15053 return;
15054
15055 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15056 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15057 return;
15058 }
15059
15060 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15061}
15062
15063bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15064 bool CheckParameterNames) {
15065 bool HasInvalidParm = false;
15066 for (ParmVarDecl *Param : Parameters) {
15067 assert(Param && "null in a parameter list");
15068 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15069 // function declarator that is part of a function definition of
15070 // that function shall not have incomplete type.
15071 //
15072 // C++23 [dcl.fct.def.general]/p2
15073 // The type of a parameter [...] for a function definition
15074 // shall not be a (possibly cv-qualified) class type that is incomplete
15075 // or abstract within the function body unless the function is deleted.
15076 if (!Param->isInvalidDecl() &&
15077 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15078 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15079 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15080 DiagID: diag::err_abstract_type_in_decl,
15081 Args: AbstractParamType))) {
15082 Param->setInvalidDecl();
15083 HasInvalidParm = true;
15084 }
15085
15086 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15087 // declaration of each parameter shall include an identifier.
15088 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15089 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15090 // Diagnose this as an extension in C17 and earlier.
15091 if (!getLangOpts().C23)
15092 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15093 }
15094
15095 // C99 6.7.5.3p12:
15096 // If the function declarator is not part of a definition of that
15097 // function, parameters may have incomplete type and may use the [*]
15098 // notation in their sequences of declarator specifiers to specify
15099 // variable length array types.
15100 QualType PType = Param->getOriginalType();
15101 // FIXME: This diagnostic should point the '[*]' if source-location
15102 // information is added for it.
15103 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15104
15105 // If the parameter is a c++ class type and it has to be destructed in the
15106 // callee function, declare the destructor so that it can be called by the
15107 // callee function. Do not perform any direct access check on the dtor here.
15108 if (!Param->isInvalidDecl()) {
15109 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15110 if (!ClassDecl->isInvalidDecl() &&
15111 !ClassDecl->hasIrrelevantDestructor() &&
15112 !ClassDecl->isDependentContext() &&
15113 ClassDecl->isParamDestroyedInCallee()) {
15114 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15115 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15116 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15117 }
15118 }
15119 }
15120
15121 // Parameters with the pass_object_size attribute only need to be marked
15122 // constant at function definitions. Because we lack information about
15123 // whether we're on a declaration or definition when we're instantiating the
15124 // attribute, we need to check for constness here.
15125 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15126 if (!Param->getType().isConstQualified())
15127 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15128 << Attr->getSpelling() << 1;
15129
15130 // Check for parameter names shadowing fields from the class.
15131 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15132 // The owning context for the parameter should be the function, but we
15133 // want to see if this function's declaration context is a record.
15134 DeclContext *DC = Param->getDeclContext();
15135 if (DC && DC->isFunctionOrMethod()) {
15136 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15137 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15138 RD, /*DeclIsField*/ false);
15139 }
15140 }
15141
15142 if (!Param->isInvalidDecl() &&
15143 Param->getOriginalType()->isWebAssemblyTableType()) {
15144 Param->setInvalidDecl();
15145 HasInvalidParm = true;
15146 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15147 }
15148 }
15149
15150 return HasInvalidParm;
15151}
15152
15153std::optional<std::pair<
15154 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15155 *E,
15156 ASTContext
15157 &Ctx);
15158
15159/// Compute the alignment and offset of the base class object given the
15160/// derived-to-base cast expression and the alignment and offset of the derived
15161/// class object.
15162static std::pair<CharUnits, CharUnits>
15163getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15164 CharUnits BaseAlignment, CharUnits Offset,
15165 ASTContext &Ctx) {
15166 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15167 ++PathI) {
15168 const CXXBaseSpecifier *Base = *PathI;
15169 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15170 if (Base->isVirtual()) {
15171 // The complete object may have a lower alignment than the non-virtual
15172 // alignment of the base, in which case the base may be misaligned. Choose
15173 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15174 // conservative lower bound of the complete object alignment.
15175 CharUnits NonVirtualAlignment =
15176 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15177 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15178 Offset = CharUnits::Zero();
15179 } else {
15180 const ASTRecordLayout &RL =
15181 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15182 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15183 }
15184 DerivedType = Base->getType();
15185 }
15186
15187 return std::make_pair(x&: BaseAlignment, y&: Offset);
15188}
15189
15190/// Compute the alignment and offset of a binary additive operator.
15191static std::optional<std::pair<CharUnits, CharUnits>>
15192getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15193 bool IsSub, ASTContext &Ctx) {
15194 QualType PointeeType = PtrE->getType()->getPointeeType();
15195
15196 if (!PointeeType->isConstantSizeType())
15197 return std::nullopt;
15198
15199 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15200
15201 if (!P)
15202 return std::nullopt;
15203
15204 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15205 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15206 CharUnits Offset = EltSize * IdxRes->getExtValue();
15207 if (IsSub)
15208 Offset = -Offset;
15209 return std::make_pair(x&: P->first, y: P->second + Offset);
15210 }
15211
15212 // If the integer expression isn't a constant expression, compute the lower
15213 // bound of the alignment using the alignment and offset of the pointer
15214 // expression and the element size.
15215 return std::make_pair(
15216 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15217 y: CharUnits::Zero());
15218}
15219
15220/// This helper function takes an lvalue expression and returns the alignment of
15221/// a VarDecl and a constant offset from the VarDecl.
15222std::optional<std::pair<
15223 CharUnits,
15224 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15225 ASTContext &Ctx) {
15226 E = E->IgnoreParens();
15227 switch (E->getStmtClass()) {
15228 default:
15229 break;
15230 case Stmt::CStyleCastExprClass:
15231 case Stmt::CXXStaticCastExprClass:
15232 case Stmt::ImplicitCastExprClass: {
15233 auto *CE = cast<CastExpr>(Val: E);
15234 const Expr *From = CE->getSubExpr();
15235 switch (CE->getCastKind()) {
15236 default:
15237 break;
15238 case CK_NoOp:
15239 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15240 case CK_UncheckedDerivedToBase:
15241 case CK_DerivedToBase: {
15242 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15243 if (!P)
15244 break;
15245 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15246 Offset: P->second, Ctx);
15247 }
15248 }
15249 break;
15250 }
15251 case Stmt::ArraySubscriptExprClass: {
15252 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15253 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15254 IsSub: false, Ctx);
15255 }
15256 case Stmt::DeclRefExprClass: {
15257 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15258 // FIXME: If VD is captured by copy or is an escaping __block variable,
15259 // use the alignment of VD's type.
15260 if (!VD->getType()->isReferenceType()) {
15261 // Dependent alignment cannot be resolved -> bail out.
15262 if (VD->hasDependentAlignment())
15263 break;
15264 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15265 }
15266 if (VD->hasInit())
15267 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15268 }
15269 break;
15270 }
15271 case Stmt::MemberExprClass: {
15272 auto *ME = cast<MemberExpr>(Val: E);
15273 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15274 if (!FD || FD->getType()->isReferenceType() ||
15275 FD->getParent()->isInvalidDecl())
15276 break;
15277 std::optional<std::pair<CharUnits, CharUnits>> P;
15278 if (ME->isArrow())
15279 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15280 else
15281 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15282 if (!P)
15283 break;
15284 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15285 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15286 return std::make_pair(x&: P->first,
15287 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15288 }
15289 case Stmt::UnaryOperatorClass: {
15290 auto *UO = cast<UnaryOperator>(Val: E);
15291 switch (UO->getOpcode()) {
15292 default:
15293 break;
15294 case UO_Deref:
15295 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15296 }
15297 break;
15298 }
15299 case Stmt::BinaryOperatorClass: {
15300 auto *BO = cast<BinaryOperator>(Val: E);
15301 auto Opcode = BO->getOpcode();
15302 switch (Opcode) {
15303 default:
15304 break;
15305 case BO_Comma:
15306 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15307 }
15308 break;
15309 }
15310 }
15311 return std::nullopt;
15312}
15313
15314/// This helper function takes a pointer expression and returns the alignment of
15315/// a VarDecl and a constant offset from the VarDecl.
15316std::optional<std::pair<
15317 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15318 *E,
15319 ASTContext
15320 &Ctx) {
15321 E = E->IgnoreParens();
15322 switch (E->getStmtClass()) {
15323 default:
15324 break;
15325 case Stmt::CStyleCastExprClass:
15326 case Stmt::CXXStaticCastExprClass:
15327 case Stmt::ImplicitCastExprClass: {
15328 auto *CE = cast<CastExpr>(Val: E);
15329 const Expr *From = CE->getSubExpr();
15330 switch (CE->getCastKind()) {
15331 default:
15332 break;
15333 case CK_NoOp:
15334 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15335 case CK_ArrayToPointerDecay:
15336 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15337 case CK_UncheckedDerivedToBase:
15338 case CK_DerivedToBase: {
15339 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15340 if (!P)
15341 break;
15342 return getDerivedToBaseAlignmentAndOffset(
15343 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15344 }
15345 }
15346 break;
15347 }
15348 case Stmt::CXXThisExprClass: {
15349 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15350 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15351 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15352 }
15353 case Stmt::UnaryOperatorClass: {
15354 auto *UO = cast<UnaryOperator>(Val: E);
15355 if (UO->getOpcode() == UO_AddrOf)
15356 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15357 break;
15358 }
15359 case Stmt::BinaryOperatorClass: {
15360 auto *BO = cast<BinaryOperator>(Val: E);
15361 auto Opcode = BO->getOpcode();
15362 switch (Opcode) {
15363 default:
15364 break;
15365 case BO_Add:
15366 case BO_Sub: {
15367 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15368 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15369 std::swap(a&: LHS, b&: RHS);
15370 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15371 Ctx);
15372 }
15373 case BO_Comma:
15374 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15375 }
15376 break;
15377 }
15378 }
15379 return std::nullopt;
15380}
15381
15382static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15383 // See if we can compute the alignment of a VarDecl and an offset from it.
15384 std::optional<std::pair<CharUnits, CharUnits>> P =
15385 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15386
15387 if (P)
15388 return P->first.alignmentAtOffset(offset: P->second);
15389
15390 // If that failed, return the type's alignment.
15391 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15392}
15393
15394void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15395 // This is actually a lot of work to potentially be doing on every
15396 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15397 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15398 return;
15399
15400 // Ignore dependent types.
15401 if (T->isDependentType() || Op->getType()->isDependentType())
15402 return;
15403
15404 // Require that the destination be a pointer type.
15405 const PointerType *DestPtr = T->getAs<PointerType>();
15406 if (!DestPtr) return;
15407
15408 // If the destination has alignment 1, we're done.
15409 QualType DestPointee = DestPtr->getPointeeType();
15410 if (DestPointee->isIncompleteType()) return;
15411 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15412 if (DestAlign.isOne()) return;
15413
15414 // Require that the source be a pointer type.
15415 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15416 if (!SrcPtr) return;
15417 QualType SrcPointee = SrcPtr->getPointeeType();
15418
15419 // Explicitly allow casts from cv void*. We already implicitly
15420 // allowed casts to cv void*, since they have alignment 1.
15421 // Also allow casts involving incomplete types, which implicitly
15422 // includes 'void'.
15423 if (SrcPointee->isIncompleteType()) return;
15424
15425 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15426
15427 if (SrcAlign >= DestAlign) return;
15428
15429 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15430 << Op->getType() << T
15431 << static_cast<unsigned>(SrcAlign.getQuantity())
15432 << static_cast<unsigned>(DestAlign.getQuantity())
15433 << TRange << Op->getSourceRange();
15434}
15435
15436void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15437 const ArraySubscriptExpr *ASE,
15438 bool AllowOnePastEnd, bool IndexNegated) {
15439 // Already diagnosed by the constant evaluator.
15440 if (isConstantEvaluatedContext())
15441 return;
15442
15443 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15444 if (IndexExpr->isValueDependent())
15445 return;
15446
15447 const Type *EffectiveType =
15448 BaseExpr->getType()->getPointeeOrArrayElementType();
15449 BaseExpr = BaseExpr->IgnoreParenCasts();
15450 const ConstantArrayType *ArrayTy =
15451 Context.getAsConstantArrayType(T: BaseExpr->getType());
15452
15453 LangOptions::StrictFlexArraysLevelKind
15454 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15455
15456 const Type *BaseType =
15457 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15458 bool IsUnboundedArray =
15459 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15460 Context, StrictFlexArraysLevel,
15461 /*IgnoreTemplateOrMacroSubstitution=*/true);
15462 if (EffectiveType->isDependentType() ||
15463 (!IsUnboundedArray && BaseType->isDependentType()))
15464 return;
15465
15466 Expr::EvalResult Result;
15467 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15468 return;
15469
15470 llvm::APSInt index = Result.Val.getInt();
15471 if (IndexNegated) {
15472 index.setIsUnsigned(false);
15473 index = -index;
15474 }
15475
15476 if (IsUnboundedArray) {
15477 if (EffectiveType->isFunctionType())
15478 return;
15479 if (index.isUnsigned() || !index.isNegative()) {
15480 const auto &ASTC = getASTContext();
15481 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15482 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15483 if (index.getBitWidth() < AddrBits)
15484 index = index.zext(width: AddrBits);
15485 std::optional<CharUnits> ElemCharUnits =
15486 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15487 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15488 // pointer) bounds-checking isn't meaningful.
15489 if (!ElemCharUnits || ElemCharUnits->isZero())
15490 return;
15491 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15492 // If index has more active bits than address space, we already know
15493 // we have a bounds violation to warn about. Otherwise, compute
15494 // address of (index + 1)th element, and warn about bounds violation
15495 // only if that address exceeds address space.
15496 if (index.getActiveBits() <= AddrBits) {
15497 bool Overflow;
15498 llvm::APInt Product(index);
15499 Product += 1;
15500 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
15501 if (!Overflow && Product.getActiveBits() <= AddrBits)
15502 return;
15503 }
15504
15505 // Need to compute max possible elements in address space, since that
15506 // is included in diag message.
15507 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
15508 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
15509 MaxElems += 1;
15510 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
15511 MaxElems = MaxElems.udiv(RHS: ElemBytes);
15512
15513 unsigned DiagID =
15514 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15515 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15516
15517 // Diag message shows element size in bits and in "bytes" (platform-
15518 // dependent CharUnits)
15519 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15520 PD: PDiag(DiagID) << index << AddrBits
15521 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
15522 << ElemBytes << MaxElems
15523 << MaxElems.getZExtValue()
15524 << IndexExpr->getSourceRange());
15525
15526 const NamedDecl *ND = nullptr;
15527 // Try harder to find a NamedDecl to point at in the note.
15528 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15529 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15530 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15531 ND = DRE->getDecl();
15532 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15533 ND = ME->getMemberDecl();
15534
15535 if (ND)
15536 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15537 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15538 }
15539 return;
15540 }
15541
15542 if (index.isUnsigned() || !index.isNegative()) {
15543 // It is possible that the type of the base expression after
15544 // IgnoreParenCasts is incomplete, even though the type of the base
15545 // expression before IgnoreParenCasts is complete (see PR39746 for an
15546 // example). In this case we have no information about whether the array
15547 // access exceeds the array bounds. However we can still diagnose an array
15548 // access which precedes the array bounds.
15549 if (BaseType->isIncompleteType())
15550 return;
15551
15552 llvm::APInt size = ArrayTy->getSize();
15553
15554 if (BaseType != EffectiveType) {
15555 // Make sure we're comparing apples to apples when comparing index to
15556 // size.
15557 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
15558 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
15559
15560 // Handle ptrarith_typesize being zero, such as when casting to void*.
15561 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15562 if (!ptrarith_typesize)
15563 ptrarith_typesize = Context.getCharWidth();
15564
15565 if (ptrarith_typesize != array_typesize) {
15566 // There's a cast to a different size type involved.
15567 uint64_t ratio = array_typesize / ptrarith_typesize;
15568
15569 // TODO: Be smarter about handling cases where array_typesize is not a
15570 // multiple of ptrarith_typesize.
15571 if (ptrarith_typesize * ratio == array_typesize)
15572 size *= llvm::APInt(size.getBitWidth(), ratio);
15573 }
15574 }
15575
15576 if (size.getBitWidth() > index.getBitWidth())
15577 index = index.zext(width: size.getBitWidth());
15578 else if (size.getBitWidth() < index.getBitWidth())
15579 size = size.zext(width: index.getBitWidth());
15580
15581 // For array subscripting the index must be less than size, but for pointer
15582 // arithmetic also allow the index (offset) to be equal to size since
15583 // computing the next address after the end of the array is legal and
15584 // commonly done e.g. in C++ iterators and range-based for loops.
15585 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
15586 return;
15587
15588 // Suppress the warning if the subscript expression (as identified by the
15589 // ']' location) and the index expression are both from macro expansions
15590 // within a system header.
15591 if (ASE) {
15592 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15593 Loc: ASE->getRBracketLoc());
15594 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
15595 SourceLocation IndexLoc =
15596 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
15597 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
15598 return;
15599 }
15600 }
15601
15602 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15603 : diag::warn_ptr_arith_exceeds_bounds;
15604 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15605 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15606
15607 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15608 PD: PDiag(DiagID)
15609 << index << ArrayTy->desugar() << CastMsg
15610 << CastMsgTy << IndexExpr->getSourceRange());
15611 } else {
15612 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15613 if (!ASE) {
15614 DiagID = diag::warn_ptr_arith_precedes_bounds;
15615 if (index.isNegative()) index = -index;
15616 }
15617
15618 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15619 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
15620 }
15621
15622 const NamedDecl *ND = nullptr;
15623 // Try harder to find a NamedDecl to point at in the note.
15624 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15625 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15626 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15627 ND = DRE->getDecl();
15628 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15629 ND = ME->getMemberDecl();
15630
15631 if (ND)
15632 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15633 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15634}
15635
15636void Sema::CheckArrayAccess(const Expr *expr) {
15637 int AllowOnePastEnd = 0;
15638 while (expr) {
15639 expr = expr->IgnoreParenImpCasts();
15640 switch (expr->getStmtClass()) {
15641 case Stmt::ArraySubscriptExprClass: {
15642 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
15643 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
15644 AllowOnePastEnd: AllowOnePastEnd > 0);
15645 expr = ASE->getBase();
15646 break;
15647 }
15648 case Stmt::MemberExprClass: {
15649 expr = cast<MemberExpr>(Val: expr)->getBase();
15650 break;
15651 }
15652 case Stmt::CXXMemberCallExprClass: {
15653 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
15654 break;
15655 }
15656 case Stmt::ArraySectionExprClass: {
15657 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
15658 // FIXME: We should probably be checking all of the elements to the
15659 // 'length' here as well.
15660 if (ASE->getLowerBound())
15661 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
15662 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
15663 return;
15664 }
15665 case Stmt::UnaryOperatorClass: {
15666 // Only unwrap the * and & unary operators
15667 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
15668 expr = UO->getSubExpr();
15669 switch (UO->getOpcode()) {
15670 case UO_AddrOf:
15671 AllowOnePastEnd++;
15672 break;
15673 case UO_Deref:
15674 AllowOnePastEnd--;
15675 break;
15676 default:
15677 return;
15678 }
15679 break;
15680 }
15681 case Stmt::ConditionalOperatorClass: {
15682 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
15683 if (const Expr *lhs = cond->getLHS())
15684 CheckArrayAccess(expr: lhs);
15685 if (const Expr *rhs = cond->getRHS())
15686 CheckArrayAccess(expr: rhs);
15687 return;
15688 }
15689 case Stmt::CXXOperatorCallExprClass: {
15690 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
15691 for (const auto *Arg : OCE->arguments())
15692 CheckArrayAccess(expr: Arg);
15693 return;
15694 }
15695 default:
15696 return;
15697 }
15698 }
15699}
15700
15701static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15702 Expr *RHS, bool isProperty) {
15703 // Check if RHS is an Objective-C object literal, which also can get
15704 // immediately zapped in a weak reference. Note that we explicitly
15705 // allow ObjCStringLiterals, since those are designed to never really die.
15706 RHS = RHS->IgnoreParenImpCasts();
15707
15708 // This enum needs to match with the 'select' in
15709 // warn_objc_arc_literal_assign (off-by-1).
15710 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
15711 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15712 return false;
15713
15714 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
15715 << (unsigned) Kind
15716 << (isProperty ? 0 : 1)
15717 << RHS->getSourceRange();
15718
15719 return true;
15720}
15721
15722static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15723 Qualifiers::ObjCLifetime LT,
15724 Expr *RHS, bool isProperty) {
15725 // Strip off any implicit cast added to get to the one ARC-specific.
15726 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15727 if (cast->getCastKind() == CK_ARCConsumeObject) {
15728 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
15729 << (LT == Qualifiers::OCL_ExplicitNone)
15730 << (isProperty ? 0 : 1)
15731 << RHS->getSourceRange();
15732 return true;
15733 }
15734 RHS = cast->getSubExpr();
15735 }
15736
15737 if (LT == Qualifiers::OCL_Weak &&
15738 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15739 return true;
15740
15741 return false;
15742}
15743
15744bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15745 QualType LHS, Expr *RHS) {
15746 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15747
15748 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15749 return false;
15750
15751 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
15752 return true;
15753
15754 return false;
15755}
15756
15757void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15758 Expr *LHS, Expr *RHS) {
15759 QualType LHSType;
15760 // PropertyRef on LHS type need be directly obtained from
15761 // its declaration as it has a PseudoType.
15762 ObjCPropertyRefExpr *PRE
15763 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
15764 if (PRE && !PRE->isImplicitProperty()) {
15765 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15766 if (PD)
15767 LHSType = PD->getType();
15768 }
15769
15770 if (LHSType.isNull())
15771 LHSType = LHS->getType();
15772
15773 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15774
15775 if (LT == Qualifiers::OCL_Weak) {
15776 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
15777 getCurFunction()->markSafeWeakUse(E: LHS);
15778 }
15779
15780 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
15781 return;
15782
15783 // FIXME. Check for other life times.
15784 if (LT != Qualifiers::OCL_None)
15785 return;
15786
15787 if (PRE) {
15788 if (PRE->isImplicitProperty())
15789 return;
15790 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15791 if (!PD)
15792 return;
15793
15794 unsigned Attributes = PD->getPropertyAttributes();
15795 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15796 // when 'assign' attribute was not explicitly specified
15797 // by user, ignore it and rely on property type itself
15798 // for lifetime info.
15799 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15800 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15801 LHSType->isObjCRetainableType())
15802 return;
15803
15804 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15805 if (cast->getCastKind() == CK_ARCConsumeObject) {
15806 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
15807 << RHS->getSourceRange();
15808 return;
15809 }
15810 RHS = cast->getSubExpr();
15811 }
15812 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15813 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
15814 return;
15815 }
15816 }
15817}
15818
15819//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15820
15821static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15822 SourceLocation StmtLoc,
15823 const NullStmt *Body) {
15824 // Do not warn if the body is a macro that expands to nothing, e.g:
15825 //
15826 // #define CALL(x)
15827 // if (condition)
15828 // CALL(0);
15829 if (Body->hasLeadingEmptyMacro())
15830 return false;
15831
15832 // Get line numbers of statement and body.
15833 bool StmtLineInvalid;
15834 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
15835 Invalid: &StmtLineInvalid);
15836 if (StmtLineInvalid)
15837 return false;
15838
15839 bool BodyLineInvalid;
15840 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
15841 Invalid: &BodyLineInvalid);
15842 if (BodyLineInvalid)
15843 return false;
15844
15845 // Warn if null statement and body are on the same line.
15846 if (StmtLine != BodyLine)
15847 return false;
15848
15849 return true;
15850}
15851
15852void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15853 const Stmt *Body,
15854 unsigned DiagID) {
15855 // Since this is a syntactic check, don't emit diagnostic for template
15856 // instantiations, this just adds noise.
15857 if (CurrentInstantiationScope)
15858 return;
15859
15860 // The body should be a null statement.
15861 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15862 if (!NBody)
15863 return;
15864
15865 // Do the usual checks.
15866 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15867 return;
15868
15869 Diag(Loc: NBody->getSemiLoc(), DiagID);
15870 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15871}
15872
15873void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15874 const Stmt *PossibleBody) {
15875 assert(!CurrentInstantiationScope); // Ensured by caller
15876
15877 SourceLocation StmtLoc;
15878 const Stmt *Body;
15879 unsigned DiagID;
15880 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
15881 StmtLoc = FS->getRParenLoc();
15882 Body = FS->getBody();
15883 DiagID = diag::warn_empty_for_body;
15884 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
15885 StmtLoc = WS->getRParenLoc();
15886 Body = WS->getBody();
15887 DiagID = diag::warn_empty_while_body;
15888 } else
15889 return; // Neither `for' nor `while'.
15890
15891 // The body should be a null statement.
15892 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15893 if (!NBody)
15894 return;
15895
15896 // Skip expensive checks if diagnostic is disabled.
15897 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
15898 return;
15899
15900 // Do the usual checks.
15901 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15902 return;
15903
15904 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15905 // noise level low, emit diagnostics only if for/while is followed by a
15906 // CompoundStmt, e.g.:
15907 // for (int i = 0; i < n; i++);
15908 // {
15909 // a(i);
15910 // }
15911 // or if for/while is followed by a statement with more indentation
15912 // than for/while itself:
15913 // for (int i = 0; i < n; i++);
15914 // a(i);
15915 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
15916 if (!ProbableTypo) {
15917 bool BodyColInvalid;
15918 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15919 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
15920 if (BodyColInvalid)
15921 return;
15922
15923 bool StmtColInvalid;
15924 unsigned StmtCol =
15925 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
15926 if (StmtColInvalid)
15927 return;
15928
15929 if (BodyCol > StmtCol)
15930 ProbableTypo = true;
15931 }
15932
15933 if (ProbableTypo) {
15934 Diag(Loc: NBody->getSemiLoc(), DiagID);
15935 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15936 }
15937}
15938
15939//===--- CHECK: Warn on self move with std::move. -------------------------===//
15940
15941void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15942 SourceLocation OpLoc) {
15943 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
15944 return;
15945
15946 if (inTemplateInstantiation())
15947 return;
15948
15949 // Strip parens and casts away.
15950 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15951 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15952
15953 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15954 // which we can treat as an inlined std::move
15955 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
15956 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15957 RHSExpr = CE->getArg(Arg: 0);
15958 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
15959 CXXSCE && CXXSCE->isXValue())
15960 RHSExpr = CXXSCE->getSubExpr();
15961 else
15962 return;
15963
15964 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15965 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15966
15967 // Two DeclRefExpr's, check that the decls are the same.
15968 if (LHSDeclRef && RHSDeclRef) {
15969 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15970 return;
15971 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15972 RHSDeclRef->getDecl()->getCanonicalDecl())
15973 return;
15974
15975 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15976 << LHSExpr->getType() << LHSExpr->getSourceRange()
15977 << RHSExpr->getSourceRange();
15978 if (const FieldDecl *F =
15979 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
15980 D << 1 << F
15981 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15982 else
15983 D << 0;
15984 return;
15985 }
15986
15987 // Member variables require a different approach to check for self moves.
15988 // MemberExpr's are the same if every nested MemberExpr refers to the same
15989 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15990 // the base Expr's are CXXThisExpr's.
15991 const Expr *LHSBase = LHSExpr;
15992 const Expr *RHSBase = RHSExpr;
15993 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
15994 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
15995 if (!LHSME || !RHSME)
15996 return;
15997
15998 while (LHSME && RHSME) {
15999 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16000 RHSME->getMemberDecl()->getCanonicalDecl())
16001 return;
16002
16003 LHSBase = LHSME->getBase();
16004 RHSBase = RHSME->getBase();
16005 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16006 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16007 }
16008
16009 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16010 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16011 if (LHSDeclRef && RHSDeclRef) {
16012 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16013 return;
16014 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16015 RHSDeclRef->getDecl()->getCanonicalDecl())
16016 return;
16017
16018 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16019 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16020 << RHSExpr->getSourceRange();
16021 return;
16022 }
16023
16024 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16025 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16026 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16027 << RHSExpr->getSourceRange();
16028}
16029
16030//===--- Layout compatibility ----------------------------------------------//
16031
16032static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16033
16034/// Check if two enumeration types are layout-compatible.
16035static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16036 const EnumDecl *ED2) {
16037 // C++11 [dcl.enum] p8:
16038 // Two enumeration types are layout-compatible if they have the same
16039 // underlying type.
16040 return ED1->isComplete() && ED2->isComplete() &&
16041 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16042}
16043
16044/// Check if two fields are layout-compatible.
16045/// Can be used on union members, which are exempt from alignment requirement
16046/// of common initial sequence.
16047static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16048 const FieldDecl *Field2,
16049 bool AreUnionMembers = false) {
16050#ifndef NDEBUG
16051 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16052 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16053 assert(((Field1Parent->isStructureOrClassType() &&
16054 Field2Parent->isStructureOrClassType()) ||
16055 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16056 "Can't evaluate layout compatibility between a struct field and a "
16057 "union field.");
16058 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16059 (AreUnionMembers && Field1Parent->isUnionType())) &&
16060 "AreUnionMembers should be 'true' for union fields (only).");
16061#endif
16062
16063 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16064 return false;
16065
16066 if (Field1->isBitField() != Field2->isBitField())
16067 return false;
16068
16069 if (Field1->isBitField()) {
16070 // Make sure that the bit-fields are the same length.
16071 unsigned Bits1 = Field1->getBitWidthValue();
16072 unsigned Bits2 = Field2->getBitWidthValue();
16073
16074 if (Bits1 != Bits2)
16075 return false;
16076 }
16077
16078 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16079 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16080 return false;
16081
16082 if (!AreUnionMembers &&
16083 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16084 return false;
16085
16086 return true;
16087}
16088
16089/// Check if two standard-layout structs are layout-compatible.
16090/// (C++11 [class.mem] p17)
16091static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16092 const RecordDecl *RD2) {
16093 // Get to the class where the fields are declared
16094 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16095 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16096
16097 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16098 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16099
16100 // Check the fields.
16101 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16102 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16103 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16104 });
16105}
16106
16107/// Check if two standard-layout unions are layout-compatible.
16108/// (C++11 [class.mem] p18)
16109static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16110 const RecordDecl *RD2) {
16111 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16112 RD2->fields());
16113
16114 for (auto *Field1 : RD1->fields()) {
16115 auto I = UnmatchedFields.begin();
16116 auto E = UnmatchedFields.end();
16117
16118 for ( ; I != E; ++I) {
16119 if (isLayoutCompatible(C, Field1, Field2: *I, /*IsUnionMember=*/AreUnionMembers: true)) {
16120 bool Result = UnmatchedFields.erase(Ptr: *I);
16121 (void) Result;
16122 assert(Result);
16123 break;
16124 }
16125 }
16126 if (I == E)
16127 return false;
16128 }
16129
16130 return UnmatchedFields.empty();
16131}
16132
16133static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16134 const RecordDecl *RD2) {
16135 if (RD1->isUnion() != RD2->isUnion())
16136 return false;
16137
16138 if (RD1->isUnion())
16139 return isLayoutCompatibleUnion(C, RD1, RD2);
16140 else
16141 return isLayoutCompatibleStruct(C, RD1, RD2);
16142}
16143
16144/// Check if two types are layout-compatible in C++11 sense.
16145static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16146 if (T1.isNull() || T2.isNull())
16147 return false;
16148
16149 // C++20 [basic.types] p11:
16150 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16151 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16152 // or layout-compatible standard-layout class types (11.4).
16153 T1 = T1.getCanonicalType().getUnqualifiedType();
16154 T2 = T2.getCanonicalType().getUnqualifiedType();
16155
16156 if (C.hasSameType(T1, T2))
16157 return true;
16158
16159 const Type::TypeClass TC1 = T1->getTypeClass();
16160 const Type::TypeClass TC2 = T2->getTypeClass();
16161
16162 if (TC1 != TC2)
16163 return false;
16164
16165 if (TC1 == Type::Enum)
16166 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16167 if (TC1 == Type::Record) {
16168 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16169 return false;
16170
16171 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16172 RD2: T2->castAsRecordDecl());
16173 }
16174
16175 return false;
16176}
16177
16178bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16179 return isLayoutCompatible(C: getASTContext(), T1, T2);
16180}
16181
16182//===-------------- Pointer interconvertibility ----------------------------//
16183
16184bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16185 const TypeSourceInfo *Derived) {
16186 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16187 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16188
16189 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16190 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16191 return true;
16192
16193 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16194 return false;
16195
16196 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16197 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16198 return true;
16199
16200 return false;
16201}
16202
16203//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16204
16205/// Given a type tag expression find the type tag itself.
16206///
16207/// \param TypeExpr Type tag expression, as it appears in user's code.
16208///
16209/// \param VD Declaration of an identifier that appears in a type tag.
16210///
16211/// \param MagicValue Type tag magic value.
16212///
16213/// \param isConstantEvaluated whether the evalaution should be performed in
16214
16215/// constant context.
16216static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16217 const ValueDecl **VD, uint64_t *MagicValue,
16218 bool isConstantEvaluated) {
16219 while(true) {
16220 if (!TypeExpr)
16221 return false;
16222
16223 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16224
16225 switch (TypeExpr->getStmtClass()) {
16226 case Stmt::UnaryOperatorClass: {
16227 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16228 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16229 TypeExpr = UO->getSubExpr();
16230 continue;
16231 }
16232 return false;
16233 }
16234
16235 case Stmt::DeclRefExprClass: {
16236 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16237 *VD = DRE->getDecl();
16238 return true;
16239 }
16240
16241 case Stmt::IntegerLiteralClass: {
16242 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16243 llvm::APInt MagicValueAPInt = IL->getValue();
16244 if (MagicValueAPInt.getActiveBits() <= 64) {
16245 *MagicValue = MagicValueAPInt.getZExtValue();
16246 return true;
16247 } else
16248 return false;
16249 }
16250
16251 case Stmt::BinaryConditionalOperatorClass:
16252 case Stmt::ConditionalOperatorClass: {
16253 const AbstractConditionalOperator *ACO =
16254 cast<AbstractConditionalOperator>(Val: TypeExpr);
16255 bool Result;
16256 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16257 InConstantContext: isConstantEvaluated)) {
16258 if (Result)
16259 TypeExpr = ACO->getTrueExpr();
16260 else
16261 TypeExpr = ACO->getFalseExpr();
16262 continue;
16263 }
16264 return false;
16265 }
16266
16267 case Stmt::BinaryOperatorClass: {
16268 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16269 if (BO->getOpcode() == BO_Comma) {
16270 TypeExpr = BO->getRHS();
16271 continue;
16272 }
16273 return false;
16274 }
16275
16276 default:
16277 return false;
16278 }
16279 }
16280}
16281
16282/// Retrieve the C type corresponding to type tag TypeExpr.
16283///
16284/// \param TypeExpr Expression that specifies a type tag.
16285///
16286/// \param MagicValues Registered magic values.
16287///
16288/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16289/// kind.
16290///
16291/// \param TypeInfo Information about the corresponding C type.
16292///
16293/// \param isConstantEvaluated whether the evalaution should be performed in
16294/// constant context.
16295///
16296/// \returns true if the corresponding C type was found.
16297static bool GetMatchingCType(
16298 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16299 const ASTContext &Ctx,
16300 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16301 *MagicValues,
16302 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16303 bool isConstantEvaluated) {
16304 FoundWrongKind = false;
16305
16306 // Variable declaration that has type_tag_for_datatype attribute.
16307 const ValueDecl *VD = nullptr;
16308
16309 uint64_t MagicValue;
16310
16311 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16312 return false;
16313
16314 if (VD) {
16315 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16316 if (I->getArgumentKind() != ArgumentKind) {
16317 FoundWrongKind = true;
16318 return false;
16319 }
16320 TypeInfo.Type = I->getMatchingCType();
16321 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16322 TypeInfo.MustBeNull = I->getMustBeNull();
16323 return true;
16324 }
16325 return false;
16326 }
16327
16328 if (!MagicValues)
16329 return false;
16330
16331 llvm::DenseMap<Sema::TypeTagMagicValue,
16332 Sema::TypeTagData>::const_iterator I =
16333 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16334 if (I == MagicValues->end())
16335 return false;
16336
16337 TypeInfo = I->second;
16338 return true;
16339}
16340
16341void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16342 uint64_t MagicValue, QualType Type,
16343 bool LayoutCompatible,
16344 bool MustBeNull) {
16345 if (!TypeTagForDatatypeMagicValues)
16346 TypeTagForDatatypeMagicValues.reset(
16347 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16348
16349 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16350 (*TypeTagForDatatypeMagicValues)[Magic] =
16351 TypeTagData(Type, LayoutCompatible, MustBeNull);
16352}
16353
16354static bool IsSameCharType(QualType T1, QualType T2) {
16355 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16356 if (!BT1)
16357 return false;
16358
16359 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16360 if (!BT2)
16361 return false;
16362
16363 BuiltinType::Kind T1Kind = BT1->getKind();
16364 BuiltinType::Kind T2Kind = BT2->getKind();
16365
16366 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16367 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16368 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16369 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16370}
16371
16372void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16373 const ArrayRef<const Expr *> ExprArgs,
16374 SourceLocation CallSiteLoc) {
16375 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16376 bool IsPointerAttr = Attr->getIsPointer();
16377
16378 // Retrieve the argument representing the 'type_tag'.
16379 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16380 if (TypeTagIdxAST >= ExprArgs.size()) {
16381 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16382 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16383 return;
16384 }
16385 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16386 bool FoundWrongKind;
16387 TypeTagData TypeInfo;
16388 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16389 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16390 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16391 if (FoundWrongKind)
16392 Diag(Loc: TypeTagExpr->getExprLoc(),
16393 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16394 << TypeTagExpr->getSourceRange();
16395 return;
16396 }
16397
16398 // Retrieve the argument representing the 'arg_idx'.
16399 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16400 if (ArgumentIdxAST >= ExprArgs.size()) {
16401 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16402 << 1 << Attr->getArgumentIdx().getSourceIndex();
16403 return;
16404 }
16405 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16406 if (IsPointerAttr) {
16407 // Skip implicit cast of pointer to `void *' (as a function argument).
16408 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16409 if (ICE->getType()->isVoidPointerType() &&
16410 ICE->getCastKind() == CK_BitCast)
16411 ArgumentExpr = ICE->getSubExpr();
16412 }
16413 QualType ArgumentType = ArgumentExpr->getType();
16414
16415 // Passing a `void*' pointer shouldn't trigger a warning.
16416 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16417 return;
16418
16419 if (TypeInfo.MustBeNull) {
16420 // Type tag with matching void type requires a null pointer.
16421 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16422 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16423 Diag(Loc: ArgumentExpr->getExprLoc(),
16424 DiagID: diag::warn_type_safety_null_pointer_required)
16425 << ArgumentKind->getName()
16426 << ArgumentExpr->getSourceRange()
16427 << TypeTagExpr->getSourceRange();
16428 }
16429 return;
16430 }
16431
16432 QualType RequiredType = TypeInfo.Type;
16433 if (IsPointerAttr)
16434 RequiredType = Context.getPointerType(T: RequiredType);
16435
16436 bool mismatch = false;
16437 if (!TypeInfo.LayoutCompatible) {
16438 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16439
16440 // C++11 [basic.fundamental] p1:
16441 // Plain char, signed char, and unsigned char are three distinct types.
16442 //
16443 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16444 // char' depending on the current char signedness mode.
16445 if (mismatch)
16446 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16447 T2: RequiredType->getPointeeType())) ||
16448 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16449 mismatch = false;
16450 } else
16451 if (IsPointerAttr)
16452 mismatch = !isLayoutCompatible(C: Context,
16453 T1: ArgumentType->getPointeeType(),
16454 T2: RequiredType->getPointeeType());
16455 else
16456 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16457
16458 if (mismatch)
16459 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16460 << ArgumentType << ArgumentKind
16461 << TypeInfo.LayoutCompatible << RequiredType
16462 << ArgumentExpr->getSourceRange()
16463 << TypeTagExpr->getSourceRange();
16464}
16465
16466void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16467 CharUnits Alignment) {
16468 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16469 Args&: Alignment);
16470}
16471
16472void Sema::DiagnoseMisalignedMembers() {
16473 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16474 const NamedDecl *ND = m.RD;
16475 if (ND->getName().empty()) {
16476 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16477 ND = TD;
16478 }
16479 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16480 << m.MD << ND << m.E->getSourceRange();
16481 }
16482 currentEvaluationContext().MisalignedMembers.clear();
16483}
16484
16485void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16486 E = E->IgnoreParens();
16487 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16488 return;
16489 if (isa<UnaryOperator>(Val: E) &&
16490 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16491 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16492 if (isa<MemberExpr>(Val: Op)) {
16493 auto &MisalignedMembersForExpr =
16494 currentEvaluationContext().MisalignedMembers;
16495 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16496 if (MA != MisalignedMembersForExpr.end() &&
16497 (T->isDependentType() || T->isIntegerType() ||
16498 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16499 Context.getTypeAlignInChars(
16500 T: T->getPointeeType()) <= MA->Alignment))))
16501 MisalignedMembersForExpr.erase(CI: MA);
16502 }
16503 }
16504}
16505
16506void Sema::RefersToMemberWithReducedAlignment(
16507 Expr *E,
16508 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16509 Action) {
16510 const auto *ME = dyn_cast<MemberExpr>(Val: E);
16511 if (!ME)
16512 return;
16513
16514 // No need to check expressions with an __unaligned-qualified type.
16515 if (E->getType().getQualifiers().hasUnaligned())
16516 return;
16517
16518 // For a chain of MemberExpr like "a.b.c.d" this list
16519 // will keep FieldDecl's like [d, c, b].
16520 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16521 const MemberExpr *TopME = nullptr;
16522 bool AnyIsPacked = false;
16523 do {
16524 QualType BaseType = ME->getBase()->getType();
16525 if (BaseType->isDependentType())
16526 return;
16527 if (ME->isArrow())
16528 BaseType = BaseType->getPointeeType();
16529 auto *RD = BaseType->castAsRecordDecl();
16530 if (RD->isInvalidDecl())
16531 return;
16532
16533 ValueDecl *MD = ME->getMemberDecl();
16534 auto *FD = dyn_cast<FieldDecl>(Val: MD);
16535 // We do not care about non-data members.
16536 if (!FD || FD->isInvalidDecl())
16537 return;
16538
16539 AnyIsPacked =
16540 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16541 ReverseMemberChain.push_back(Elt: FD);
16542
16543 TopME = ME;
16544 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
16545 } while (ME);
16546 assert(TopME && "We did not compute a topmost MemberExpr!");
16547
16548 // Not the scope of this diagnostic.
16549 if (!AnyIsPacked)
16550 return;
16551
16552 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16553 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
16554 // TODO: The innermost base of the member expression may be too complicated.
16555 // For now, just disregard these cases. This is left for future
16556 // improvement.
16557 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
16558 return;
16559
16560 // Alignment expected by the whole expression.
16561 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
16562
16563 // No need to do anything else with this case.
16564 if (ExpectedAlignment.isOne())
16565 return;
16566
16567 // Synthesize offset of the whole access.
16568 CharUnits Offset;
16569 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
16570 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
16571
16572 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16573 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16574 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
16575
16576 // The base expression of the innermost MemberExpr may give
16577 // stronger guarantees than the class containing the member.
16578 if (DRE && !TopME->isArrow()) {
16579 const ValueDecl *VD = DRE->getDecl();
16580 if (!VD->getType()->isReferenceType())
16581 CompleteObjectAlignment =
16582 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
16583 }
16584
16585 // Check if the synthesized offset fulfills the alignment.
16586 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
16587 // It may fulfill the offset it but the effective alignment may still be
16588 // lower than the expected expression alignment.
16589 CompleteObjectAlignment < ExpectedAlignment) {
16590 // If this happens, we want to determine a sensible culprit of this.
16591 // Intuitively, watching the chain of member expressions from right to
16592 // left, we start with the required alignment (as required by the field
16593 // type) but some packed attribute in that chain has reduced the alignment.
16594 // It may happen that another packed structure increases it again. But if
16595 // we are here such increase has not been enough. So pointing the first
16596 // FieldDecl that either is packed or else its RecordDecl is,
16597 // seems reasonable.
16598 FieldDecl *FD = nullptr;
16599 CharUnits Alignment;
16600 for (FieldDecl *FDI : ReverseMemberChain) {
16601 if (FDI->hasAttr<PackedAttr>() ||
16602 FDI->getParent()->hasAttr<PackedAttr>()) {
16603 FD = FDI;
16604 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
16605 b: Context.getTypeAlignInChars(
16606 T: Context.getCanonicalTagType(TD: FD->getParent())));
16607 break;
16608 }
16609 }
16610 assert(FD && "We did not find a packed FieldDecl!");
16611 Action(E, FD->getParent(), FD, Alignment);
16612 }
16613}
16614
16615void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16616 using namespace std::placeholders;
16617
16618 RefersToMemberWithReducedAlignment(
16619 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
16620 args: _2, args: _3, args: _4));
16621}
16622
16623bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
16624 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16625 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16626 return true;
16627
16628 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
16629 if (A.isInvalid())
16630 return true;
16631
16632 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16633 QualType TyA = A.get()->getType();
16634
16635 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
16636 ArgTyRestr, ArgOrdinal: 1))
16637 return true;
16638
16639 TheCall->setType(TyA);
16640 return false;
16641}
16642
16643bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16644 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16645 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16646 TheCall->setType(*Res);
16647 return false;
16648 }
16649 return true;
16650}
16651
16652bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
16653 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16654 if (!Res)
16655 return true;
16656
16657 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16658 TheCall->setType(VecTy0->getElementType());
16659 else
16660 TheCall->setType(*Res);
16661
16662 return false;
16663}
16664
16665static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
16666 SourceLocation Loc) {
16667 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
16668 R = RHS->getEnumCoercedType(Ctx: S.Context);
16669 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16670 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
16671 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
16672 << LHS->getSourceRange() << RHS->getSourceRange()
16673 << /*Arithmetic Between*/ 0 << L << R;
16674 }
16675 return false;
16676}
16677
16678/// Check if all arguments have the same type. If the types don't match, emit an
16679/// error message and return true. Otherwise return false.
16680///
16681/// For scalars we directly compare their unqualified types. But even if we
16682/// compare unqualified vector types, a difference in qualifiers in the element
16683/// types can make the vector types be considered not equal. For example,
16684/// vector of 4 'const float' values vs vector of 4 'float' values.
16685/// So we compare unqualified types of their elements and number of elements.
16686static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
16687 ArrayRef<Expr *> Args) {
16688 assert(!Args.empty() && "Should have at least one argument.");
16689
16690 Expr *Arg0 = Args.front();
16691 QualType Ty0 = Arg0->getType();
16692
16693 auto EmitError = [&](Expr *ArgI) {
16694 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
16695 DiagID: diag::err_typecheck_call_different_arg_types)
16696 << Arg0->getType() << ArgI->getType();
16697 };
16698
16699 // Compare scalar types.
16700 if (!Ty0->isVectorType()) {
16701 for (Expr *ArgI : Args.drop_front())
16702 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
16703 EmitError(ArgI);
16704 return true;
16705 }
16706
16707 return false;
16708 }
16709
16710 // Compare vector types.
16711 const auto *Vec0 = Ty0->castAs<VectorType>();
16712 for (Expr *ArgI : Args.drop_front()) {
16713 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16714 if (!VecI ||
16715 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
16716 T2: VecI->getElementType()) ||
16717 Vec0->getNumElements() != VecI->getNumElements()) {
16718 EmitError(ArgI);
16719 return true;
16720 }
16721 }
16722
16723 return false;
16724}
16725
16726std::optional<QualType>
16727Sema::BuiltinVectorMath(CallExpr *TheCall,
16728 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16729 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
16730 return std::nullopt;
16731
16732 if (checkBuiltinVectorMathMixedEnums(
16733 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
16734 return std::nullopt;
16735
16736 Expr *Args[2];
16737 for (int I = 0; I < 2; ++I) {
16738 ExprResult Converted =
16739 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16740 if (Converted.isInvalid())
16741 return std::nullopt;
16742 Args[I] = Converted.get();
16743 }
16744
16745 SourceLocation LocA = Args[0]->getBeginLoc();
16746 QualType TyA = Args[0]->getType();
16747
16748 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
16749 return std::nullopt;
16750
16751 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16752 return std::nullopt;
16753
16754 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
16755 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
16756 return TyA;
16757}
16758
16759bool Sema::BuiltinElementwiseTernaryMath(
16760 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16761 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
16762 return true;
16763
16764 SourceLocation Loc = TheCall->getExprLoc();
16765 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
16766 RHS: TheCall->getArg(Arg: 1), Loc) ||
16767 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
16768 RHS: TheCall->getArg(Arg: 2), Loc))
16769 return true;
16770
16771 Expr *Args[3];
16772 for (int I = 0; I < 3; ++I) {
16773 ExprResult Converted =
16774 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16775 if (Converted.isInvalid())
16776 return true;
16777 Args[I] = Converted.get();
16778 }
16779
16780 int ArgOrdinal = 1;
16781 for (Expr *Arg : Args) {
16782 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
16783 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
16784 return true;
16785 }
16786
16787 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16788 return true;
16789
16790 for (int I = 0; I < 3; ++I)
16791 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
16792
16793 TheCall->setType(Args[0]->getType());
16794 return false;
16795}
16796
16797bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16798 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16799 return true;
16800
16801 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
16802 if (A.isInvalid())
16803 return true;
16804
16805 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16806 return false;
16807}
16808
16809bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16810 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16811 return true;
16812
16813 ExprResult Arg = TheCall->getArg(Arg: 0);
16814 QualType TyArg = Arg.get()->getType();
16815
16816 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16817 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
16818 DiagID: diag::err_builtin_invalid_arg_type)
16819 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16820
16821 TheCall->setType(TyArg);
16822 return false;
16823}
16824
16825ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16826 ExprResult CallResult) {
16827 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16828 return ExprError();
16829
16830 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
16831 if (MatrixArg.isInvalid())
16832 return MatrixArg;
16833 Expr *Matrix = MatrixArg.get();
16834
16835 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16836 if (!MType) {
16837 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16838 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16839 << Matrix->getType();
16840 return ExprError();
16841 }
16842
16843 // Create returned matrix type by swapping rows and columns of the argument
16844 // matrix type.
16845 QualType ResultType = Context.getConstantMatrixType(
16846 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
16847
16848 // Change the return type to the type of the returned matrix.
16849 TheCall->setType(ResultType);
16850
16851 // Update call argument to use the possibly converted matrix argument.
16852 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
16853 return CallResult;
16854}
16855
16856// Get and verify the matrix dimensions.
16857static std::optional<unsigned>
16858getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16859 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
16860 if (!Value) {
16861 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
16862 << Name;
16863 return {};
16864 }
16865 uint64_t Dim = Value->getZExtValue();
16866 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16867 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
16868 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16869 return {};
16870 }
16871 return Dim;
16872}
16873
16874ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16875 ExprResult CallResult) {
16876 if (!getLangOpts().MatrixTypes) {
16877 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16878 return ExprError();
16879 }
16880
16881 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16882 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
16883 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
16884 << /*column*/ 1 << /*load*/ 0;
16885 return ExprError();
16886 }
16887
16888 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
16889 return ExprError();
16890
16891 unsigned PtrArgIdx = 0;
16892 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
16893 Expr *RowsExpr = TheCall->getArg(Arg: 1);
16894 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
16895 Expr *StrideExpr = TheCall->getArg(Arg: 3);
16896
16897 bool ArgError = false;
16898
16899 // Check pointer argument.
16900 {
16901 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
16902 if (PtrConv.isInvalid())
16903 return PtrConv;
16904 PtrExpr = PtrConv.get();
16905 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
16906 if (PtrExpr->isTypeDependent()) {
16907 TheCall->setType(Context.DependentTy);
16908 return TheCall;
16909 }
16910 }
16911
16912 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16913 QualType ElementTy;
16914 if (!PtrTy) {
16915 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16916 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16917 << PtrExpr->getType();
16918 ArgError = true;
16919 } else {
16920 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16921
16922 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
16923 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16924 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16925 << /* no fp */ 0 << PtrExpr->getType();
16926 ArgError = true;
16927 }
16928 }
16929
16930 // Apply default Lvalue conversions and convert the expression to size_t.
16931 auto ApplyArgumentConversions = [this](Expr *E) {
16932 ExprResult Conv = DefaultLvalueConversion(E);
16933 if (Conv.isInvalid())
16934 return Conv;
16935
16936 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
16937 };
16938
16939 // Apply conversion to row and column expressions.
16940 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16941 if (!RowsConv.isInvalid()) {
16942 RowsExpr = RowsConv.get();
16943 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
16944 } else
16945 RowsExpr = nullptr;
16946
16947 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16948 if (!ColumnsConv.isInvalid()) {
16949 ColumnsExpr = ColumnsConv.get();
16950 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
16951 } else
16952 ColumnsExpr = nullptr;
16953
16954 // If any part of the result matrix type is still pending, just use
16955 // Context.DependentTy, until all parts are resolved.
16956 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16957 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16958 TheCall->setType(Context.DependentTy);
16959 return CallResult;
16960 }
16961
16962 // Check row and column dimensions.
16963 std::optional<unsigned> MaybeRows;
16964 if (RowsExpr)
16965 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
16966
16967 std::optional<unsigned> MaybeColumns;
16968 if (ColumnsExpr)
16969 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
16970
16971 // Check stride argument.
16972 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16973 if (StrideConv.isInvalid())
16974 return ExprError();
16975 StrideExpr = StrideConv.get();
16976 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
16977
16978 if (MaybeRows) {
16979 if (std::optional<llvm::APSInt> Value =
16980 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
16981 uint64_t Stride = Value->getZExtValue();
16982 if (Stride < *MaybeRows) {
16983 Diag(Loc: StrideExpr->getBeginLoc(),
16984 DiagID: diag::err_builtin_matrix_stride_too_small);
16985 ArgError = true;
16986 }
16987 }
16988 }
16989
16990 if (ArgError || !MaybeRows || !MaybeColumns)
16991 return ExprError();
16992
16993 TheCall->setType(
16994 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
16995 return CallResult;
16996}
16997
16998ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16999 ExprResult CallResult) {
17000 if (!getLangOpts().MatrixTypes) {
17001 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17002 return ExprError();
17003 }
17004
17005 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17006 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17007 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17008 << /*column*/ 1 << /*store*/ 1;
17009 return ExprError();
17010 }
17011
17012 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17013 return ExprError();
17014
17015 unsigned PtrArgIdx = 1;
17016 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17017 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17018 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17019
17020 bool ArgError = false;
17021
17022 {
17023 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17024 if (MatrixConv.isInvalid())
17025 return MatrixConv;
17026 MatrixExpr = MatrixConv.get();
17027 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17028 }
17029 if (MatrixExpr->isTypeDependent()) {
17030 TheCall->setType(Context.DependentTy);
17031 return TheCall;
17032 }
17033
17034 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17035 if (!MatrixTy) {
17036 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17037 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17038 ArgError = true;
17039 }
17040
17041 {
17042 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17043 if (PtrConv.isInvalid())
17044 return PtrConv;
17045 PtrExpr = PtrConv.get();
17046 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17047 if (PtrExpr->isTypeDependent()) {
17048 TheCall->setType(Context.DependentTy);
17049 return TheCall;
17050 }
17051 }
17052
17053 // Check pointer argument.
17054 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17055 if (!PtrTy) {
17056 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17057 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17058 << PtrExpr->getType();
17059 ArgError = true;
17060 } else {
17061 QualType ElementTy = PtrTy->getPointeeType();
17062 if (ElementTy.isConstQualified()) {
17063 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17064 ArgError = true;
17065 }
17066 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17067 if (MatrixTy &&
17068 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17069 Diag(Loc: PtrExpr->getBeginLoc(),
17070 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17071 << ElementTy << MatrixTy->getElementType();
17072 ArgError = true;
17073 }
17074 }
17075
17076 // Apply default Lvalue conversions and convert the stride expression to
17077 // size_t.
17078 {
17079 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17080 if (StrideConv.isInvalid())
17081 return StrideConv;
17082
17083 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17084 if (StrideConv.isInvalid())
17085 return StrideConv;
17086 StrideExpr = StrideConv.get();
17087 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17088 }
17089
17090 // Check stride argument.
17091 if (MatrixTy) {
17092 if (std::optional<llvm::APSInt> Value =
17093 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17094 uint64_t Stride = Value->getZExtValue();
17095 if (Stride < MatrixTy->getNumRows()) {
17096 Diag(Loc: StrideExpr->getBeginLoc(),
17097 DiagID: diag::err_builtin_matrix_stride_too_small);
17098 ArgError = true;
17099 }
17100 }
17101 }
17102
17103 if (ArgError)
17104 return ExprError();
17105
17106 return CallResult;
17107}
17108
17109void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17110 const NamedDecl *Callee) {
17111 // This warning does not make sense in code that has no runtime behavior.
17112 if (isUnevaluatedContext())
17113 return;
17114
17115 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17116
17117 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17118 return;
17119
17120 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17121 // all TCBs the callee is a part of.
17122 llvm::StringSet<> CalleeTCBs;
17123 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17124 CalleeTCBs.insert(key: A->getTCBName());
17125 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17126 CalleeTCBs.insert(key: A->getTCBName());
17127
17128 // Go through the TCBs the caller is a part of and emit warnings if Caller
17129 // is in a TCB that the Callee is not.
17130 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17131 StringRef CallerTCB = A->getTCBName();
17132 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17133 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17134 << Callee << CallerTCB;
17135 }
17136 }
17137}
17138