1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/ASTMutationListener.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DynamicRecursiveASTVisitor.h"
27#include "clang/AST/EvaluatedExprVisitor.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtVisitor.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Basic/BuiltinTraits.h"
37#include "clang/Basic/Builtins.h"
38#include "clang/Basic/DiagnosticSema.h"
39#include "clang/Basic/PartialDiagnostic.h"
40#include "clang/Basic/SourceManager.h"
41#include "clang/Basic/Specifiers.h"
42#include "clang/Basic/TargetInfo.h"
43#include "clang/Lex/LiteralSupport.h"
44#include "clang/Lex/Preprocessor.h"
45#include "clang/Sema/AnalysisBasedWarnings.h"
46#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/DelayedDiagnostic.h"
48#include "clang/Sema/Designator.h"
49#include "clang/Sema/EnterExpressionEvaluationContext.h"
50#include "clang/Sema/Initialization.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
53#include "clang/Sema/ParsedTemplate.h"
54#include "clang/Sema/Scope.h"
55#include "clang/Sema/ScopeInfo.h"
56#include "clang/Sema/SemaAMDGPU.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaBPF.h"
59#include "clang/Sema/SemaCUDA.h"
60#include "clang/Sema/SemaFixItUtils.h"
61#include "clang/Sema/SemaHLSL.h"
62#include "clang/Sema/SemaHexagon.h"
63#include "clang/Sema/SemaObjC.h"
64#include "clang/Sema/SemaOpenCL.h"
65#include "clang/Sema/SemaOpenMP.h"
66#include "clang/Sema/SemaProxy.h"
67#include "clang/Sema/SemaPseudoObject.h"
68#include "clang/Sema/Template.h"
69#include "llvm/ADT/STLExtras.h"
70#include "llvm/ADT/StringExtras.h"
71#include "llvm/IR/DerivedTypes.h"
72#include "llvm/Support/ConvertUTF.h"
73#include "llvm/Support/SaveAndRestore.h"
74#include "llvm/Support/TimeProfiler.h"
75#include "llvm/Support/TypeSize.h"
76#include <limits>
77#include <optional>
78
79using namespace clang;
80using namespace sema;
81
82bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
83 // See if this is an auto-typed variable whose initializer we are parsing.
84 if (ParsingInitForAutoVars.count(Ptr: D))
85 return false;
86
87 // See if this is a deleted function.
88 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
89 if (FD->isDeleted())
90 return false;
91
92 // If the function has a deduced return type, and we can't deduce it,
93 // then we can't use it either.
94 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
95 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
96 return false;
97
98 // See if this is an aligned allocation/deallocation function that is
99 // unavailable.
100 if (TreatUnavailableAsInvalid &&
101 isUnavailableAlignedAllocationFunction(FD: *FD))
102 return false;
103 }
104
105 // See if this function is unavailable.
106 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
107 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
108 return false;
109
110 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
111 return false;
112
113 return true;
114}
115
116static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
117 // Warn if this is used but marked unused.
118 if (const auto *A = D->getAttr<UnusedAttr>()) {
119 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
120 // should diagnose them.
121 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
122 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
123 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
124 if (DC && !DC->hasAttr<UnusedAttr>())
125 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
126 }
127 }
128}
129
130void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
131 assert(Decl && Decl->isDeleted());
132
133 if (Decl->isDefaulted()) {
134 // If the method was explicitly defaulted, point at that declaration.
135 if (!Decl->isImplicit())
136 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
137
138 // Try to diagnose why this special member function was implicitly
139 // deleted. This might fail, if that reason no longer applies.
140 DiagnoseDeletedDefaultedFunction(FD: Decl);
141 return;
142 }
143
144 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
145 if (Ctor && Ctor->isInheritingConstructor())
146 return NoteDeletedInheritingConstructor(CD: Ctor);
147
148 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
149 << Decl << 1;
150}
151
152/// Determine whether a FunctionDecl was ever declared with an
153/// explicit storage class.
154static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
155 for (auto *I : D->redecls()) {
156 if (I->getStorageClass() != SC_None)
157 return true;
158 }
159 return false;
160}
161
162/// Check whether we're in an extern inline function and referring to a
163/// variable or function with internal linkage (C11 6.7.4p3).
164///
165/// This is only a warning because we used to silently accept this code, but
166/// in many cases it will not behave correctly. This is not enabled in C++ mode
167/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
168/// and so while there may still be user mistakes, most of the time we can't
169/// prove that there are errors.
170static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
171 const NamedDecl *D,
172 SourceLocation Loc) {
173 // This is disabled under C++; there are too many ways for this to fire in
174 // contexts where the warning is a false positive, or where it is technically
175 // correct but benign.
176 //
177 // WG14 N3622 which removed the constraint entirely in C2y. It is left
178 // enabled in earlier language modes because this is a constraint in those
179 // language modes. But in C2y mode, we still want to issue the "incompatible
180 // with previous standards" diagnostic, too.
181 if (S.getLangOpts().CPlusPlus)
182 return;
183
184 // Check if this is an inlined function or method.
185 FunctionDecl *Current = S.getCurFunctionDecl();
186 if (!Current)
187 return;
188 if (!Current->isInlined())
189 return;
190 if (!Current->isExternallyVisible())
191 return;
192
193 // Check if the decl has internal linkage.
194 if (D->getFormalLinkage() != Linkage::Internal)
195 return;
196
197 // Downgrade from ExtWarn to Extension if
198 // (1) the supposedly external inline function is in the main file,
199 // and probably won't be included anywhere else.
200 // (2) the thing we're referencing is a pure function.
201 // (3) the thing we're referencing is another inline function.
202 // This last can give us false negatives, but it's better than warning on
203 // wrappers for simple C library functions.
204 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
205 unsigned DiagID;
206 if (S.getLangOpts().C2y)
207 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
208 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
209 S.getSourceManager().isInMainFile(Loc))
210 DiagID = diag::ext_internal_in_extern_inline_quiet;
211 else
212 DiagID = diag::ext_internal_in_extern_inline;
213
214 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
215 S.MaybeSuggestAddingStaticToDecl(D: Current);
216 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
217 << D;
218}
219
220void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
221 const FunctionDecl *First = Cur->getFirstDecl();
222
223 // Suggest "static" on the function, if possible.
224 if (!hasAnyExplicitStorageClass(D: First)) {
225 SourceLocation DeclBegin = First->getSourceRange().getBegin();
226 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
227 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
228 }
229}
230
231bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
232 const ObjCInterfaceDecl *UnknownObjCClass,
233 bool ObjCPropertyAccess,
234 bool AvoidPartialAvailabilityChecks,
235 ObjCInterfaceDecl *ClassReceiver,
236 bool SkipTrailingRequiresClause) {
237 SourceLocation Loc = Locs.front();
238 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
239 // If there were any diagnostics suppressed by template argument deduction,
240 // emit them now.
241 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
242 if (Pos != SuppressedDiagnostics.end()) {
243 for (const auto &[DiagLoc, PD] : Pos->second) {
244 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
245 PD.Emit(DB: Builder);
246 }
247 // Clear out the list of suppressed diagnostics, so that we don't emit
248 // them again for this specialization. However, we don't obsolete this
249 // entry from the table, because we want to avoid ever emitting these
250 // diagnostics again.
251 Pos->second.clear();
252 }
253
254 // C++ [basic.start.main]p3:
255 // The function 'main' shall not be used within a program.
256 if (cast<FunctionDecl>(Val: D)->isMain())
257 Diag(Loc, DiagID: diag::ext_main_used);
258
259 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
260 }
261
262 // See if this is an auto-typed variable whose initializer we are parsing.
263 if (ParsingInitForAutoVars.count(Ptr: D)) {
264 if (isa<BindingDecl>(Val: D)) {
265 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
266 << D->getDeclName();
267 } else {
268 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
269 << diag::ParsingInitFor::Var << D->getDeclName()
270 << cast<VarDecl>(Val: D)->getType();
271 }
272 return true;
273 }
274
275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
276 // See if this is a deleted function.
277 if (FD->isDeleted()) {
278 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
279 if (Ctor && Ctor->isInheritingConstructor())
280 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
281 << Ctor->getParent()
282 << Ctor->getInheritedConstructor().getConstructor()->getParent();
283 else {
284 StringLiteral *Msg = FD->getDeletedMessage();
285 Diag(Loc, DiagID: diag::err_deleted_function_use)
286 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
287 }
288 NoteDeletedFunction(Decl: FD);
289 return true;
290 }
291
292 // [expr.prim.id]p4
293 // A program that refers explicitly or implicitly to a function with a
294 // trailing requires-clause whose constraint-expression is not satisfied,
295 // other than to declare it, is ill-formed. [...]
296 //
297 // See if this is a function with constraints that need to be satisfied.
298 // Check this before deducing the return type, as it might instantiate the
299 // definition.
300 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
301 ConstraintSatisfaction Satisfaction;
302 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
303 /*ForOverloadResolution*/ true))
304 // A diagnostic will have already been generated (non-constant
305 // constraint expression, for example)
306 return true;
307 if (!Satisfaction.IsSatisfied) {
308 Diag(Loc,
309 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
310 << D;
311 DiagnoseUnsatisfiedConstraint(Satisfaction);
312 return true;
313 }
314 }
315
316 // If the function has a deduced return type, and we can't deduce it,
317 // then we can't use it either.
318 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
319 DeduceReturnType(FD, Loc))
320 return true;
321
322 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
323 return true;
324
325 }
326
327 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
328 Concept && CheckConceptUseInDefinition(Concept, Loc))
329 return true;
330
331 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
332 // Lambdas are only default-constructible or assignable in C++2a onwards.
333 if (MD->getParent()->isLambda() &&
334 ((isa<CXXConstructorDecl>(Val: MD) &&
335 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
336 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
337 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
338 << !isa<CXXConstructorDecl>(Val: MD);
339 }
340 }
341
342 auto getReferencedObjCProp = [](const NamedDecl *D) ->
343 const ObjCPropertyDecl * {
344 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
345 return MD->findPropertyDecl();
346 return nullptr;
347 };
348 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
349 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
350 return true;
351 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
352 return true;
353 }
354
355 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
356 // Only the variables omp_in and omp_out are allowed in the combiner.
357 // Only the variables omp_priv and omp_orig are allowed in the
358 // initializer-clause.
359 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
360 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
361 isa<VarDecl>(Val: D)) {
362 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
363 << getCurFunction()->HasOMPDeclareReductionCombiner;
364 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
365 return true;
366 }
367
368 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
369 // List-items in map clauses on this construct may only refer to the declared
370 // variable var and entities that could be referenced by a procedure defined
371 // at the same location.
372 // [OpenMP 5.2] Also allow iterator declared variables.
373 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
374 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
375 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
376 << OpenMP().getOpenMPDeclareMapperVarName();
377 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
378 return true;
379 }
380
381 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
382 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
383 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
384 return true;
385 }
386
387 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
388 AvoidPartialAvailabilityChecks, ClassReceiver);
389
390 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
391
392 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
393
394 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
395 if (getLangOpts().getFPEvalMethod() !=
396 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
397 PP.getLastFPEvalPragmaLocation().isValid() &&
398 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
399 Diag(Loc: D->getLocation(),
400 DiagID: diag::err_type_available_only_in_default_eval_method)
401 << D->getName();
402 }
403
404 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
405 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
406
407 if (LangOpts.SYCLIsDevice ||
408 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
409 if (!Context.getTargetInfo().isTLSSupported())
410 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
411 if (VD->getTLSKind() != VarDecl::TLS_None)
412 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
413 }
414
415 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
416 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
417
418 return false;
419}
420
421void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
422 ArrayRef<Expr *> Args) {
423 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
424 if (!Attr)
425 return;
426
427 // The number of formal parameters of the declaration.
428 unsigned NumFormalParams;
429
430 // The kind of declaration. This is also an index into a %select in
431 // the diagnostic.
432 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
433
434 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
435 NumFormalParams = MD->param_size();
436 CalleeKind = CK_Method;
437 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
438 NumFormalParams = FD->param_size();
439 CalleeKind = CK_Function;
440 if (FD->hasCXXExplicitFunctionObjectParameter())
441 NumFormalParams++;
442 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
443 QualType Ty = VD->getType();
444 const FunctionType *Fn = nullptr;
445 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
446 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
447 if (!Fn)
448 return;
449 CalleeKind = CK_Function;
450 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
451 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
452 CalleeKind = CK_Block;
453 } else {
454 return;
455 }
456
457 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
458 NumFormalParams = proto->getNumParams();
459 else
460 NumFormalParams = 0;
461 } else {
462 return;
463 }
464
465 // "NullPos" is the number of formal parameters at the end which
466 // effectively count as part of the variadic arguments. This is
467 // useful if you would prefer to not have *any* formal parameters,
468 // but the language forces you to have at least one.
469 unsigned NullPos = Attr->getNullPos();
470 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
471 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
472
473 // The number of arguments which should follow the sentinel.
474 unsigned NumArgsAfterSentinel = Attr->getSentinel();
475
476 // If there aren't enough arguments for all the formal parameters,
477 // the sentinel, and the args after the sentinel, complain.
478 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
479 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
480 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
481 return;
482 }
483
484 // Otherwise, find the sentinel expression.
485 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
486 if (!SentinelExpr)
487 return;
488 if (SentinelExpr->isValueDependent())
489 return;
490 if (Context.isSentinelNullExpr(E: SentinelExpr))
491 return;
492
493 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
494 // or 'NULL' if those are actually defined in the context. Only use
495 // 'nil' for ObjC methods, where it's much more likely that the
496 // variadic arguments form a list of object pointers.
497 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
498 std::string NullValue;
499 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
500 NullValue = "nil";
501 else if (getLangOpts().CPlusPlus11)
502 NullValue = "nullptr";
503 else if (PP.isMacroDefined(Id: "NULL"))
504 NullValue = "NULL";
505 else
506 NullValue = "(void*) 0";
507
508 if (MissingNilLoc.isInvalid())
509 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
510 else
511 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
512 << int(CalleeKind)
513 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
514 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
515 << int(CalleeKind) << Attr->getRange();
516}
517
518SourceRange Sema::getExprRange(Expr *E) const {
519 return E ? E->getSourceRange() : SourceRange();
520}
521
522//===----------------------------------------------------------------------===//
523// Standard Promotions and Conversions
524//===----------------------------------------------------------------------===//
525
526/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
527ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
528 // Handle any placeholder expressions which made it here.
529 if (E->hasPlaceholderType()) {
530 ExprResult result = CheckPlaceholderExpr(E);
531 if (result.isInvalid()) return ExprError();
532 E = result.get();
533 }
534
535 QualType Ty = E->getType();
536 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
537
538 if (Ty->isFunctionType()) {
539 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
540 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
541 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
542 return ExprError();
543
544 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
545 CK: CK_FunctionToPointerDecay).get();
546 } else if (Ty->isArrayType()) {
547 // In C90 mode, arrays only promote to pointers if the array expression is
548 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
549 // type 'array of type' is converted to an expression that has type 'pointer
550 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
551 // that has type 'array of type' ...". The relevant change is "an lvalue"
552 // (C90) to "an expression" (C99).
553 //
554 // C++ 4.2p1:
555 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
556 // T" can be converted to an rvalue of type "pointer to T".
557 //
558 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
559 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
560 CK: CK_ArrayToPointerDecay);
561 if (Res.isInvalid())
562 return ExprError();
563 E = Res.get();
564 }
565 }
566 return E;
567}
568
569static void CheckForNullPointerDereference(Sema &S, Expr *E) {
570 // Check to see if we are dereferencing a null pointer. If so,
571 // and if not volatile-qualified, this is undefined behavior that the
572 // optimizer will delete, so warn about it. People sometimes try to use this
573 // to get a deterministic trap and are surprised by clang's behavior. This
574 // only handles the pattern "*null", which is a very syntactic check.
575 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
576 if (UO && UO->getOpcode() == UO_Deref &&
577 UO->getSubExpr()->getType()->isPointerType()) {
578 const LangAS AS =
579 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
580 if ((!isTargetAddressSpace(AS) ||
581 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
582 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
583 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
584 !UO->getType().isVolatileQualified()) {
585 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
586 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
587 << UO->getSubExpr()->getSourceRange());
588 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
589 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
590 }
591 }
592}
593
594static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
595 SourceLocation AssignLoc,
596 const Expr* RHS) {
597 const ObjCIvarDecl *IV = OIRE->getDecl();
598 if (!IV)
599 return;
600
601 DeclarationName MemberName = IV->getDeclName();
602 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
603 if (!Member || !Member->isStr(Str: "isa"))
604 return;
605
606 const Expr *Base = OIRE->getBase();
607 QualType BaseType = Base->getType();
608 if (OIRE->isArrow())
609 BaseType = BaseType->getPointeeType();
610 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
611 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
612 ObjCInterfaceDecl *ClassDeclared = nullptr;
613 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
614 if (!ClassDeclared->getSuperClass()
615 && (*ClassDeclared->ivar_begin()) == IV) {
616 if (RHS) {
617 NamedDecl *ObjectSetClass =
618 S.LookupSingleName(S: S.TUScope,
619 Name: &S.Context.Idents.get(Name: "object_setClass"),
620 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
621 if (ObjectSetClass) {
622 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
623 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
624 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
625 Code: "object_setClass(")
626 << FixItHint::CreateReplacement(
627 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
628 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
629 }
630 else
631 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
632 } else {
633 NamedDecl *ObjectGetClass =
634 S.LookupSingleName(S: S.TUScope,
635 Name: &S.Context.Idents.get(Name: "object_getClass"),
636 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
637 if (ObjectGetClass)
638 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
639 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
640 Code: "object_getClass(")
641 << FixItHint::CreateReplacement(
642 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
643 else
644 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
645 }
646 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
647 }
648 }
649}
650
651ExprResult Sema::DefaultLvalueConversion(Expr *E) {
652 // Handle any placeholder expressions which made it here.
653 if (E->hasPlaceholderType()) {
654 ExprResult result = CheckPlaceholderExpr(E);
655 if (result.isInvalid()) return ExprError();
656 E = result.get();
657 }
658
659 // C++ [conv.lval]p1:
660 // A glvalue of a non-function, non-array type T can be
661 // converted to a prvalue.
662 if (!E->isGLValue()) return E;
663
664 QualType T = E->getType();
665 assert(!T.isNull() && "r-value conversion on typeless expression?");
666
667 // lvalue-to-rvalue conversion cannot be applied to types that decay to
668 // pointers (i.e. function or array types).
669 if (T->canDecayToPointerType())
670 return E;
671
672 // We don't want to throw lvalue-to-rvalue casts on top of
673 // expressions of certain types in C++.
674 // In HLSL LvaluetoRvalue conversion is allowed on records.
675 if (getLangOpts().CPlusPlus) {
676 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
677 (T->isDependentType() && !T->isAnyPointerType() &&
678 !T->isMemberPointerType()))
679 return E;
680 }
681
682 // The C standard is actually really unclear on this point, and
683 // DR106 tells us what the result should be but not why. It's
684 // generally best to say that void types just doesn't undergo
685 // lvalue-to-rvalue at all. Note that expressions of unqualified
686 // 'void' type are never l-values, but qualified void can be.
687 if (T->isVoidType())
688 return E;
689
690 // OpenCL usually rejects direct accesses to values of 'half' type.
691 if (getLangOpts().OpenCL &&
692 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
693 T->isHalfType()) {
694 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
695 << 0 << T;
696 return ExprError();
697 }
698
699 CheckForNullPointerDereference(S&: *this, E);
700 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
701 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
702 Name: &Context.Idents.get(Name: "object_getClass"),
703 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
704 if (ObjectGetClass)
705 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
706 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
707 << FixItHint::CreateReplacement(
708 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
709 else
710 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
711 }
712 else if (const ObjCIvarRefExpr *OIRE =
713 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
714 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
715
716 // C++ [conv.lval]p1:
717 // [...] If T is a non-class type, the type of the prvalue is the
718 // cv-unqualified version of T. Otherwise, the type of the
719 // rvalue is T.
720 //
721 // C99 6.3.2.1p2:
722 // If the lvalue has qualified type, the value has the unqualified
723 // version of the type of the lvalue; otherwise, the value has the
724 // type of the lvalue.
725 if (T.hasQualifiers())
726 T = T.getUnqualifiedType();
727
728 if (getLangOpts().HLSL)
729 if (const auto *MT = T->getAs<ConstantMatrixType>(); MT && MT->getLayout())
730 T = Context.getCanonicalType(T);
731
732 // Under the MS ABI, lock down the inheritance model now.
733 if (T->isMemberPointerType() &&
734 Context.getTargetInfo().getCXXABI().isMicrosoft())
735 (void)isCompleteType(Loc: E->getExprLoc(), T);
736
737 ExprResult Res = CheckLValueToRValueConversionOperand(E);
738 if (Res.isInvalid())
739 return Res;
740 E = Res.get();
741
742 // Loading a __weak object implicitly retains the value, so we need a cleanup to
743 // balance that.
744 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
745 Cleanup.setExprNeedsCleanups(true);
746
747 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
748 Cleanup.setExprNeedsCleanups(true);
749
750 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
751 return ExprError();
752
753 // C++ [conv.lval]p3:
754 // If T is cv std::nullptr_t, the result is a null pointer constant.
755 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
756 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
757 FPO: CurFPFeatureOverrides());
758
759 // C11 6.3.2.1p2:
760 // ... if the lvalue has atomic type, the value has the non-atomic version
761 // of the type of the lvalue ...
762 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
763 T = Atomic->getValueType().getUnqualifiedType();
764 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
765 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
766 }
767
768 return Res;
769}
770
771ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
772 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
773 if (Res.isInvalid())
774 return ExprError();
775 Res = DefaultLvalueConversion(E: Res.get());
776 if (Res.isInvalid())
777 return ExprError();
778 return Res;
779}
780
781ExprResult Sema::CallExprUnaryConversions(Expr *E) {
782 QualType Ty = E->getType();
783 ExprResult Res = E;
784 // Only do implicit cast for a function type, but not for a pointer
785 // to function type.
786 if (Ty->isFunctionType()) {
787 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
788 CK: CK_FunctionToPointerDecay);
789 if (Res.isInvalid())
790 return ExprError();
791 }
792 Res = DefaultLvalueConversion(E: Res.get());
793 if (Res.isInvalid())
794 return ExprError();
795 return Res.get();
796}
797
798/// UsualUnaryFPConversions - Promotes floating-point types according to the
799/// current language semantics.
800ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
801 QualType Ty = E->getType();
802 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
803
804 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
805 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
806 (getLangOpts().getFPEvalMethod() !=
807 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
808 PP.getLastFPEvalPragmaLocation().isValid())) {
809 switch (EvalMethod) {
810 default:
811 llvm_unreachable("Unrecognized float evaluation method");
812 break;
813 case LangOptions::FEM_UnsetOnCommandLine:
814 llvm_unreachable("Float evaluation method should be set by now");
815 break;
816 case LangOptions::FEM_Double:
817 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
818 // Widen the expression to double.
819 return Ty->isComplexType()
820 ? ImpCastExprToType(E,
821 Type: Context.getComplexType(T: Context.DoubleTy),
822 CK: CK_FloatingComplexCast)
823 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
824 break;
825 case LangOptions::FEM_Extended:
826 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
827 // Widen the expression to long double.
828 return Ty->isComplexType()
829 ? ImpCastExprToType(
830 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
831 CK: CK_FloatingComplexCast)
832 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
833 CK: CK_FloatingCast);
834 break;
835 }
836 }
837
838 // Half FP have to be promoted to float unless it is natively supported
839 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
840 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
841
842 return E;
843}
844
845/// UsualUnaryConversions - Performs various conversions that are common to most
846/// operators (C99 6.3). The conversions of array and function types are
847/// sometimes suppressed. For example, the array->pointer conversion doesn't
848/// apply if the array is an argument to the sizeof or address (&) operators.
849/// In these instances, this routine should *not* be called.
850ExprResult Sema::UsualUnaryConversions(Expr *E) {
851 // First, convert to an r-value.
852 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
853 if (Res.isInvalid())
854 return ExprError();
855
856 // Promote floating-point types.
857 Res = UsualUnaryFPConversions(E: Res.get());
858 if (Res.isInvalid())
859 return ExprError();
860 E = Res.get();
861
862 QualType Ty = E->getType();
863 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
864
865 // Try to perform integral promotions if the object has a theoretically
866 // promotable type.
867 if (Ty->isIntegralOrUnscopedEnumerationType()) {
868 // C99 6.3.1.1p2:
869 //
870 // The following may be used in an expression wherever an int or
871 // unsigned int may be used:
872 // - an object or expression with an integer type whose integer
873 // conversion rank is less than or equal to the rank of int
874 // and unsigned int.
875 // - A bit-field of type _Bool, int, signed int, or unsigned int.
876 //
877 // If an int can represent all values of the original type, the
878 // value is converted to an int; otherwise, it is converted to an
879 // unsigned int. These are called the integer promotions. All
880 // other types are unchanged by the integer promotions.
881
882 QualType PTy = Context.isPromotableBitField(E);
883 if (!PTy.isNull()) {
884 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
885 return E;
886 }
887 if (Context.isPromotableIntegerType(T: Ty)) {
888 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
889 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
890 return E;
891 }
892 }
893 return E;
894}
895
896/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
897/// do not have a prototype. Arguments that have type float or __fp16
898/// are promoted to double. All other argument types are converted by
899/// UsualUnaryConversions().
900ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
901 QualType Ty = E->getType();
902 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
903
904 ExprResult Res = UsualUnaryConversions(E);
905 if (Res.isInvalid())
906 return ExprError();
907 E = Res.get();
908
909 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
910 // promote to double.
911 // Note that default argument promotion applies only to float (and
912 // half/fp16); it does not apply to _Float16.
913 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
914 if (BTy && (BTy->getKind() == BuiltinType::Half ||
915 BTy->getKind() == BuiltinType::Float)) {
916 if (getLangOpts().OpenCL &&
917 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
918 if (BTy->getKind() == BuiltinType::Half) {
919 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
920 }
921 } else {
922 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
923 }
924 }
925 if (BTy &&
926 getLangOpts().getExtendIntArgs() ==
927 LangOptions::ExtendArgsKind::ExtendTo64 &&
928 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
929 Context.getTypeSizeInChars(T: BTy) <
930 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
931 E = (Ty->isUnsignedIntegerType())
932 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
933 .get()
934 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
935 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
936 "Unexpected typesize for LongLongTy");
937 }
938
939 // C++ performs lvalue-to-rvalue conversion as a default argument
940 // promotion, even on class types, but note:
941 // C++11 [conv.lval]p2:
942 // When an lvalue-to-rvalue conversion occurs in an unevaluated
943 // operand or a subexpression thereof the value contained in the
944 // referenced object is not accessed. Otherwise, if the glvalue
945 // has a class type, the conversion copy-initializes a temporary
946 // of type T from the glvalue and the result of the conversion
947 // is a prvalue for the temporary.
948 // FIXME: add some way to gate this entire thing for correctness in
949 // potentially potentially evaluated contexts.
950 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
951 ExprResult Temp = PerformCopyInitialization(
952 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
953 EqualLoc: E->getExprLoc(), Init: E);
954 if (Temp.isInvalid())
955 return ExprError();
956 E = Temp.get();
957 }
958
959 // C++ [expr.call]p7, per CWG722:
960 // An argument that has (possibly cv-qualified) type std::nullptr_t is
961 // converted to void* ([conv.ptr]).
962 // (This does not apply to C23 nullptr)
963 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
964 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
965
966 return E;
967}
968
969VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
970 if (Ty->isIncompleteType()) {
971 // C++11 [expr.call]p7:
972 // After these conversions, if the argument does not have arithmetic,
973 // enumeration, pointer, pointer to member, or class type, the program
974 // is ill-formed.
975 //
976 // Since we've already performed null pointer conversion, array-to-pointer
977 // decay and function-to-pointer decay, the only such type in C++ is cv
978 // void. This also handles initializer lists as variadic arguments.
979 if (Ty->isVoidType())
980 return VarArgKind::Invalid;
981
982 if (Ty->isObjCObjectType())
983 return VarArgKind::Invalid;
984 return VarArgKind::Valid;
985 }
986
987 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
988 return VarArgKind::Invalid;
989
990 if (Context.getTargetInfo().getTriple().isWasm() &&
991 Ty.isWebAssemblyReferenceType()) {
992 return VarArgKind::Invalid;
993 }
994
995 if (Ty.isCXX98PODType(Context))
996 return VarArgKind::Valid;
997
998 // C++11 [expr.call]p7:
999 // Passing a potentially-evaluated argument of class type (Clause 9)
1000 // having a non-trivial copy constructor, a non-trivial move constructor,
1001 // or a non-trivial destructor, with no corresponding parameter,
1002 // is conditionally-supported with implementation-defined semantics.
1003 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
1004 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
1005 if (!Record->hasNonTrivialCopyConstructor() &&
1006 !Record->hasNonTrivialMoveConstructor() &&
1007 !Record->hasNonTrivialDestructor())
1008 return VarArgKind::ValidInCXX11;
1009
1010 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1011 return VarArgKind::Valid;
1012
1013 if (Ty->isObjCObjectType())
1014 return VarArgKind::Invalid;
1015
1016 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1017 return VarArgKind::Valid;
1018
1019 if (getLangOpts().MSVCCompat)
1020 return VarArgKind::MSVCUndefined;
1021
1022 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1023 return VarArgKind::Valid;
1024
1025 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1026 // permitted to reject them. We should consider doing so.
1027 return VarArgKind::Undefined;
1028}
1029
1030void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1031 // Don't allow one to pass an Objective-C interface to a vararg.
1032 const QualType &Ty = E->getType();
1033 VarArgKind VAK = isValidVarArgType(Ty);
1034
1035 // Complain about passing non-POD types through varargs.
1036 switch (VAK) {
1037 case VarArgKind::ValidInCXX11:
1038 DiagRuntimeBehavior(
1039 Loc: E->getBeginLoc(), Statement: nullptr,
1040 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1041 [[fallthrough]];
1042 case VarArgKind::Valid:
1043 if (Ty->isRecordType()) {
1044 // This is unlikely to be what the user intended. If the class has a
1045 // 'c_str' member function, the user probably meant to call that.
1046 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1047 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1048 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1049 }
1050 break;
1051
1052 case VarArgKind::Undefined:
1053 case VarArgKind::MSVCUndefined:
1054 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1055 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1056 << getLangOpts().CPlusPlus11 << Ty << CT);
1057 break;
1058
1059 case VarArgKind::Invalid:
1060 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1061 Diag(Loc: E->getBeginLoc(),
1062 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1063 << Ty << CT;
1064 else if (Ty->isObjCObjectType())
1065 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1066 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1067 << Ty << CT);
1068 else
1069 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1070 << isa<InitListExpr>(Val: E) << Ty << CT;
1071 break;
1072 }
1073}
1074
1075ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1076 FunctionDecl *FDecl) {
1077 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1078 // Strip the unbridged-cast placeholder expression off, if applicable.
1079 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1080 (CT == VariadicCallType::Method ||
1081 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1082 E = ObjC().stripARCUnbridgedCast(e: E);
1083
1084 // Otherwise, do normal placeholder checking.
1085 } else {
1086 ExprResult ExprRes = CheckPlaceholderExpr(E);
1087 if (ExprRes.isInvalid())
1088 return ExprError();
1089 E = ExprRes.get();
1090 }
1091 }
1092
1093 ExprResult ExprRes = DefaultArgumentPromotion(E);
1094 if (ExprRes.isInvalid())
1095 return ExprError();
1096
1097 // Copy blocks to the heap.
1098 if (ExprRes.get()->getType()->isBlockPointerType())
1099 maybeExtendBlockObject(E&: ExprRes);
1100
1101 E = ExprRes.get();
1102
1103 // Diagnostics regarding non-POD argument types are
1104 // emitted along with format string checking in Sema::CheckFunctionCall().
1105 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1106 // Turn this into a trap.
1107 CXXScopeSpec SS;
1108 SourceLocation TemplateKWLoc;
1109 UnqualifiedId Name;
1110 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1111 IdLoc: E->getBeginLoc());
1112 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1113 /*IsCall=*/true,
1114 /*IsAddressOfOperand=*/false);
1115 if (TrapFn.isInvalid())
1116 return ExprError();
1117
1118 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1119 RParenLoc: E->getEndLoc());
1120 if (Call.isInvalid())
1121 return ExprError();
1122
1123 ExprResult Comma =
1124 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1125 if (Comma.isInvalid())
1126 return ExprError();
1127 return Comma.get();
1128 }
1129
1130 if (!getLangOpts().CPlusPlus &&
1131 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1132 DiagID: diag::err_call_incomplete_argument))
1133 return ExprError();
1134
1135 return E;
1136}
1137
1138/// Convert complex integers to complex floats and real integers to
1139/// real floats as required for complex arithmetic. Helper function of
1140/// UsualArithmeticConversions()
1141///
1142/// \return false if the integer expression is an integer type and is
1143/// successfully converted to the (complex) float type.
1144static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1145 ExprResult &ComplexExpr,
1146 QualType IntTy,
1147 QualType ComplexTy,
1148 bool SkipCast) {
1149 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1150 if (SkipCast) return false;
1151 if (IntTy->isIntegerType()) {
1152 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1153 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1154 } else {
1155 assert(IntTy->isComplexIntegerType());
1156 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1157 CK: CK_IntegralComplexToFloatingComplex);
1158 }
1159 return false;
1160}
1161
1162// This handles complex/complex, complex/float, or float/complex.
1163// When both operands are complex, the shorter operand is converted to the
1164// type of the longer, and that is the type of the result. This corresponds
1165// to what is done when combining two real floating-point operands.
1166// The fun begins when size promotion occur across type domains.
1167// From H&S 6.3.4: When one operand is complex and the other is a real
1168// floating-point type, the less precise type is converted, within it's
1169// real or complex domain, to the precision of the other type. For example,
1170// when combining a "long double" with a "double _Complex", the
1171// "double _Complex" is promoted to "long double _Complex".
1172static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1173 QualType ShorterType,
1174 QualType LongerType,
1175 bool PromotePrecision) {
1176 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1177 QualType Result =
1178 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1179
1180 if (PromotePrecision) {
1181 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1182 Shorter =
1183 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1184 } else {
1185 if (LongerIsComplex)
1186 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1187 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1188 }
1189 }
1190 return Result;
1191}
1192
1193/// Handle arithmetic conversion with complex types. Helper function of
1194/// UsualArithmeticConversions()
1195static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1196 ExprResult &RHS, QualType LHSType,
1197 QualType RHSType, bool IsCompAssign) {
1198 // Handle (complex) integer types.
1199 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1200 /*SkipCast=*/false))
1201 return LHSType;
1202 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1203 /*SkipCast=*/IsCompAssign))
1204 return RHSType;
1205
1206 // Compute the rank of the two types, regardless of whether they are complex.
1207 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1208 if (Order < 0)
1209 // Promote the precision of the LHS if not an assignment.
1210 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1211 /*PromotePrecision=*/!IsCompAssign);
1212 // Promote the precision of the RHS unless it is already the same as the LHS.
1213 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1214 /*PromotePrecision=*/Order > 0);
1215}
1216
1217/// Handle arithmetic conversion from integer to float. Helper function
1218/// of UsualArithmeticConversions()
1219static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1220 ExprResult &IntExpr,
1221 QualType FloatTy, QualType IntTy,
1222 bool ConvertFloat, bool ConvertInt) {
1223 if (IntTy->isIntegerType()) {
1224 if (ConvertInt)
1225 // Convert intExpr to the lhs floating point type.
1226 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1227 CK: CK_IntegralToFloating);
1228 return FloatTy;
1229 }
1230
1231 // Convert both sides to the appropriate complex float.
1232 assert(IntTy->isComplexIntegerType());
1233 QualType result = S.Context.getComplexType(T: FloatTy);
1234
1235 // _Complex int -> _Complex float
1236 if (ConvertInt)
1237 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1238 CK: CK_IntegralComplexToFloatingComplex);
1239
1240 // float -> _Complex float
1241 if (ConvertFloat)
1242 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1243 CK: CK_FloatingRealToComplex);
1244
1245 return result;
1246}
1247
1248/// Handle arithmethic conversion with floating point types. Helper
1249/// function of UsualArithmeticConversions()
1250static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1251 ExprResult &RHS, QualType LHSType,
1252 QualType RHSType, bool IsCompAssign) {
1253 bool LHSFloat = LHSType->isRealFloatingType();
1254 bool RHSFloat = RHSType->isRealFloatingType();
1255
1256 // N1169 4.1.4: If one of the operands has a floating type and the other
1257 // operand has a fixed-point type, the fixed-point operand
1258 // is converted to the floating type [...]
1259 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1260 if (LHSFloat)
1261 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1262 else if (!IsCompAssign)
1263 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1264 return LHSFloat ? LHSType : RHSType;
1265 }
1266
1267 // If we have two real floating types, convert the smaller operand
1268 // to the bigger result.
1269 if (LHSFloat && RHSFloat) {
1270 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1271 if (order > 0) {
1272 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1273 return LHSType;
1274 }
1275
1276 assert(order < 0 && "illegal float comparison");
1277 if (!IsCompAssign)
1278 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1279 return RHSType;
1280 }
1281
1282 if (LHSFloat) {
1283 // Half FP has to be promoted to float unless it is natively supported
1284 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1285 LHSType = S.Context.FloatTy;
1286
1287 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1288 /*ConvertFloat=*/!IsCompAssign,
1289 /*ConvertInt=*/ true);
1290 }
1291 assert(RHSFloat);
1292 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1293 /*ConvertFloat=*/ true,
1294 /*ConvertInt=*/!IsCompAssign);
1295}
1296
1297/// Diagnose attempts to convert between __float128, __ibm128 and
1298/// long double if there is no support for such conversion.
1299/// Helper function of UsualArithmeticConversions().
1300static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1301 QualType RHSType) {
1302 // No issue if either is not a floating point type.
1303 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1304 return false;
1305
1306 // No issue if both have the same 128-bit float semantics.
1307 auto *LHSComplex = LHSType->getAs<ComplexType>();
1308 auto *RHSComplex = RHSType->getAs<ComplexType>();
1309
1310 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1311 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1312
1313 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1314 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1315
1316 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1317 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1318 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1319 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1320 return false;
1321
1322 return true;
1323}
1324
1325typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1326
1327namespace {
1328/// These helper callbacks are placed in an anonymous namespace to
1329/// permit their use as function template parameters.
1330ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1331 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1332}
1333
1334ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1335 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1336 CK: CK_IntegralComplexCast);
1337}
1338}
1339
1340/// Handle integer arithmetic conversions. Helper function of
1341/// UsualArithmeticConversions()
1342template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1343static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1344 ExprResult &RHS, QualType LHSType,
1345 QualType RHSType, bool IsCompAssign) {
1346 // The rules for this case are in C99 6.3.1.8
1347 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1348 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1349 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1350 if (LHSSigned == RHSSigned) {
1351 // Same signedness; use the higher-ranked type
1352 if (order >= 0) {
1353 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1354 return LHSType;
1355 } else if (!IsCompAssign)
1356 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1357 return RHSType;
1358 } else if (order != (LHSSigned ? 1 : -1)) {
1359 // The unsigned type has greater than or equal rank to the
1360 // signed type, so use the unsigned type
1361 if (RHSSigned) {
1362 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1363 return LHSType;
1364 } else if (!IsCompAssign)
1365 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1366 return RHSType;
1367 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1368 // The two types are different widths; if we are here, that
1369 // means the signed type is larger than the unsigned type, so
1370 // use the signed type.
1371 if (LHSSigned) {
1372 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1373 return LHSType;
1374 } else if (!IsCompAssign)
1375 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1376 return RHSType;
1377 } else {
1378 // The signed type is higher-ranked than the unsigned type,
1379 // but isn't actually any bigger (like unsigned int and long
1380 // on most 32-bit systems). Use the unsigned type corresponding
1381 // to the signed type.
1382 QualType result =
1383 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1384 RHS = (*doRHSCast)(S, RHS.get(), result);
1385 if (!IsCompAssign)
1386 LHS = (*doLHSCast)(S, LHS.get(), result);
1387 return result;
1388 }
1389}
1390
1391/// Handle conversions with GCC complex int extension. Helper function
1392/// of UsualArithmeticConversions()
1393static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1394 ExprResult &RHS, QualType LHSType,
1395 QualType RHSType,
1396 bool IsCompAssign) {
1397 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1398 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1399
1400 if (LHSComplexInt && RHSComplexInt) {
1401 QualType LHSEltType = LHSComplexInt->getElementType();
1402 QualType RHSEltType = RHSComplexInt->getElementType();
1403 QualType ScalarType =
1404 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1405 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1406
1407 return S.Context.getComplexType(T: ScalarType);
1408 }
1409
1410 if (LHSComplexInt) {
1411 QualType LHSEltType = LHSComplexInt->getElementType();
1412 QualType ScalarType =
1413 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1414 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1415 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1416 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1417 CK: CK_IntegralRealToComplex);
1418
1419 return ComplexType;
1420 }
1421
1422 assert(RHSComplexInt);
1423
1424 QualType RHSEltType = RHSComplexInt->getElementType();
1425 QualType ScalarType =
1426 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1427 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1428 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1429
1430 if (!IsCompAssign)
1431 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1432 CK: CK_IntegralRealToComplex);
1433 return ComplexType;
1434}
1435
1436static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1437 ExprResult &RHS,
1438 QualType LHSType,
1439 QualType RHSType,
1440 bool IsCompAssign) {
1441
1442 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1443 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1444
1445 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1446 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1447
1448 bool LHSHasTrap =
1449 LhsOBT && LhsOBT->getBehaviorKind() ==
1450 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1451 bool RHSHasTrap =
1452 RhsOBT && RhsOBT->getBehaviorKind() ==
1453 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1454 bool LHSHasWrap =
1455 LhsOBT && LhsOBT->getBehaviorKind() ==
1456 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457 bool RHSHasWrap =
1458 RhsOBT && RhsOBT->getBehaviorKind() ==
1459 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1460
1461 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1462 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1463
1464 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1465 if (LHSHasTrap || RHSHasTrap)
1466 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1467 else if (LHSHasWrap || RHSHasWrap)
1468 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1469
1470 QualType LHSConvType = LHSUnderlyingType;
1471 QualType RHSConvType = RHSUnderlyingType;
1472 if (DominantBehavior) {
1473 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1474 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1475 Wrapped: LHSUnderlyingType);
1476 else
1477 LHSConvType = LHSType;
1478
1479 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1480 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1481 Wrapped: RHSUnderlyingType);
1482 else
1483 RHSConvType = RHSType;
1484 }
1485
1486 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1487 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1488}
1489
1490/// Return the rank of a given fixed point or integer type. The value itself
1491/// doesn't matter, but the values must be increasing with proper increasing
1492/// rank as described in N1169 4.1.1.
1493static unsigned GetFixedPointRank(QualType Ty) {
1494 const auto *BTy = Ty->getAs<BuiltinType>();
1495 assert(BTy && "Expected a builtin type.");
1496
1497 switch (BTy->getKind()) {
1498 case BuiltinType::ShortFract:
1499 case BuiltinType::UShortFract:
1500 case BuiltinType::SatShortFract:
1501 case BuiltinType::SatUShortFract:
1502 return 1;
1503 case BuiltinType::Fract:
1504 case BuiltinType::UFract:
1505 case BuiltinType::SatFract:
1506 case BuiltinType::SatUFract:
1507 return 2;
1508 case BuiltinType::LongFract:
1509 case BuiltinType::ULongFract:
1510 case BuiltinType::SatLongFract:
1511 case BuiltinType::SatULongFract:
1512 return 3;
1513 case BuiltinType::ShortAccum:
1514 case BuiltinType::UShortAccum:
1515 case BuiltinType::SatShortAccum:
1516 case BuiltinType::SatUShortAccum:
1517 return 4;
1518 case BuiltinType::Accum:
1519 case BuiltinType::UAccum:
1520 case BuiltinType::SatAccum:
1521 case BuiltinType::SatUAccum:
1522 return 5;
1523 case BuiltinType::LongAccum:
1524 case BuiltinType::ULongAccum:
1525 case BuiltinType::SatLongAccum:
1526 case BuiltinType::SatULongAccum:
1527 return 6;
1528 default:
1529 if (BTy->isInteger())
1530 return 0;
1531 llvm_unreachable("Unexpected fixed point or integer type");
1532 }
1533}
1534
1535/// handleFixedPointConversion - Fixed point operations between fixed
1536/// point types and integers or other fixed point types do not fall under
1537/// usual arithmetic conversion since these conversions could result in loss
1538/// of precsision (N1169 4.1.4). These operations should be calculated with
1539/// the full precision of their result type (N1169 4.1.6.2.1).
1540static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1541 QualType RHSTy) {
1542 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1543 "Expected at least one of the operands to be a fixed point type");
1544 assert((LHSTy->isFixedPointOrIntegerType() ||
1545 RHSTy->isFixedPointOrIntegerType()) &&
1546 "Special fixed point arithmetic operation conversions are only "
1547 "applied to ints or other fixed point types");
1548
1549 // If one operand has signed fixed-point type and the other operand has
1550 // unsigned fixed-point type, then the unsigned fixed-point operand is
1551 // converted to its corresponding signed fixed-point type and the resulting
1552 // type is the type of the converted operand.
1553 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1554 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1555 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1556 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1557
1558 // The result type is the type with the highest rank, whereby a fixed-point
1559 // conversion rank is always greater than an integer conversion rank; if the
1560 // type of either of the operands is a saturating fixedpoint type, the result
1561 // type shall be the saturating fixed-point type corresponding to the type
1562 // with the highest rank; the resulting value is converted (taking into
1563 // account rounding and overflow) to the precision of the resulting type.
1564 // Same ranks between signed and unsigned types are resolved earlier, so both
1565 // types are either signed or both unsigned at this point.
1566 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1567 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1568
1569 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1570
1571 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1572 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1573
1574 return ResultTy;
1575}
1576
1577/// Check that the usual arithmetic conversions can be performed on this pair of
1578/// expressions that might be of enumeration type.
1579void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1580 SourceLocation Loc,
1581 ArithConvKind ACK) {
1582 // C++2a [expr.arith.conv]p1:
1583 // If one operand is of enumeration type and the other operand is of a
1584 // different enumeration type or a floating-point type, this behavior is
1585 // deprecated ([depr.arith.conv.enum]).
1586 //
1587 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1588 // Eventually we will presumably reject these cases (in C++23 onwards?).
1589 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1590 R = RHS->getEnumCoercedType(Ctx: Context);
1591 bool LEnum = L->isUnscopedEnumerationType(),
1592 REnum = R->isUnscopedEnumerationType();
1593 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1594 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1595 (REnum && L->isFloatingType())) {
1596 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1597 : getLangOpts().CPlusPlus20
1598 ? diag::warn_arith_conv_enum_float_cxx20
1599 : diag::warn_arith_conv_enum_float)
1600 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1601 << L << R;
1602 } else if (!IsCompAssign && LEnum && REnum &&
1603 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1604 unsigned DiagID;
1605 // In C++ 26, usual arithmetic conversions between 2 different enum types
1606 // are ill-formed.
1607 if (getLangOpts().CPlusPlus26)
1608 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1609 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1610 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1611 // If either enumeration type is unnamed, it's less likely that the
1612 // user cares about this, but this situation is still deprecated in
1613 // C++2a. Use a different warning group.
1614 DiagID = getLangOpts().CPlusPlus20
1615 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1616 : diag::warn_arith_conv_mixed_anon_enum_types;
1617 } else if (ACK == ArithConvKind::Conditional) {
1618 // Conditional expressions are separated out because they have
1619 // historically had a different warning flag.
1620 DiagID = getLangOpts().CPlusPlus20
1621 ? diag::warn_conditional_mixed_enum_types_cxx20
1622 : diag::warn_conditional_mixed_enum_types;
1623 } else if (ACK == ArithConvKind::Comparison) {
1624 // Comparison expressions are separated out because they have
1625 // historically had a different warning flag.
1626 DiagID = getLangOpts().CPlusPlus20
1627 ? diag::warn_comparison_mixed_enum_types_cxx20
1628 : diag::warn_comparison_mixed_enum_types;
1629 } else {
1630 DiagID = getLangOpts().CPlusPlus20
1631 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1632 : diag::warn_arith_conv_mixed_enum_types;
1633 }
1634 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1635 << (int)ACK << L << R;
1636 }
1637}
1638
1639static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1640 Expr *RHS, SourceLocation Loc,
1641 ArithConvKind ACK) {
1642 QualType LHSType = LHS->getType().getUnqualifiedType();
1643 QualType RHSType = RHS->getType().getUnqualifiedType();
1644
1645 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1646 !RHSType->isUnicodeCharacterType())
1647 return;
1648
1649 if (ACK == ArithConvKind::Comparison) {
1650 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1651 return;
1652
1653 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1654 if (T->isChar8Type())
1655 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1656 if (T->isChar16Type())
1657 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1658 assert(T->isChar32Type());
1659 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1660 };
1661
1662 Expr::EvalResult LHSRes, RHSRes;
1663 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1664 AllowSideEffects: Expr::SE_AllowSideEffects,
1665 InConstantContext: SemaRef.isConstantEvaluatedContext());
1666 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1667 AllowSideEffects: Expr::SE_AllowSideEffects,
1668 InConstantContext: SemaRef.isConstantEvaluatedContext());
1669
1670 // Don't warn if the one known value is a representable
1671 // in the type of both expressions.
1672 if (LHSSuccess != RHSuccess) {
1673 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1674 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1675 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1676 return;
1677 }
1678
1679 if (!LHSSuccess || !RHSuccess) {
1680 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1681 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1682 << RHSType;
1683 return;
1684 }
1685
1686 llvm::APSInt LHSValue(32);
1687 LHSValue = LHSRes.Val.getInt();
1688 llvm::APSInt RHSValue(32);
1689 RHSValue = RHSRes.Val.getInt();
1690
1691 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1692 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1693 if (LHSSafe && RHSSafe)
1694 return;
1695
1696 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1697 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1698 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1699 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1700 return;
1701 }
1702
1703 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1704 return;
1705
1706 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1707 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1708 << RHSType;
1709}
1710
1711/// UsualArithmeticConversions - Performs various conversions that are common to
1712/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1713/// routine returns the first non-arithmetic type found. The client is
1714/// responsible for emitting appropriate error diagnostics.
1715QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1716 SourceLocation Loc,
1717 ArithConvKind ACK) {
1718
1719 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1720
1721 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1722
1723 if (ACK != ArithConvKind::CompAssign) {
1724 LHS = UsualUnaryConversions(E: LHS.get());
1725 if (LHS.isInvalid())
1726 return QualType();
1727 }
1728
1729 RHS = UsualUnaryConversions(E: RHS.get());
1730 if (RHS.isInvalid())
1731 return QualType();
1732
1733 // For conversion purposes, we ignore any qualifiers.
1734 // For example, "const float" and "float" are equivalent.
1735 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1736 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1737
1738 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1739 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1740 LHSType = AtomicLHS->getValueType();
1741
1742 // If both types are identical, no conversion is needed.
1743 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1744 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1745
1746 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1747 // The caller can deal with this (e.g. pointer + int).
1748 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1749 return QualType();
1750
1751 // Apply unary and bitfield promotions to the LHS's type.
1752 QualType LHSUnpromotedType = LHSType;
1753 if (Context.isPromotableIntegerType(T: LHSType))
1754 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1755 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1756 if (!LHSBitfieldPromoteTy.isNull())
1757 LHSType = LHSBitfieldPromoteTy;
1758 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1759 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1760
1761 // If both types are identical, no conversion is needed.
1762 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1763 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1764
1765 // At this point, we have two different arithmetic types.
1766
1767 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1768 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1769 return QualType();
1770
1771 // Diagnose attempts to convert between __ibm128, __float128 and long double
1772 // where such conversions currently can't be handled.
1773 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1774 return QualType();
1775
1776 // Handle complex types first (C99 6.3.1.8p1).
1777 if (LHSType->isComplexType() || RHSType->isComplexType())
1778 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1779 IsCompAssign: ACK == ArithConvKind::CompAssign);
1780
1781 // Now handle "real" floating types (i.e. float, double, long double).
1782 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1783 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1784 IsCompAssign: ACK == ArithConvKind::CompAssign);
1785
1786 // Handle GCC complex int extension.
1787 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1788 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1789 IsCompAssign: ACK == ArithConvKind::CompAssign);
1790
1791 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1792 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1793
1794 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1795 return handleOverflowBehaviorTypeConversion(
1796 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1797
1798 // Finally, we have two differing integer types.
1799 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1800 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1801}
1802
1803//===----------------------------------------------------------------------===//
1804// Semantic Analysis for various Expression Types
1805//===----------------------------------------------------------------------===//
1806
1807
1808ExprResult Sema::ActOnGenericSelectionExpr(
1809 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1810 bool PredicateIsExpr, void *ControllingExprOrType,
1811 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1812 unsigned NumAssocs = ArgTypes.size();
1813 assert(NumAssocs == ArgExprs.size());
1814
1815 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1816 for (unsigned i = 0; i < NumAssocs; ++i) {
1817 if (ArgTypes[i])
1818 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1819 else
1820 Types[i] = nullptr;
1821 }
1822
1823 // If we have a controlling type, we need to convert it from a parsed type
1824 // into a semantic type and then pass that along.
1825 if (!PredicateIsExpr) {
1826 TypeSourceInfo *ControllingType;
1827 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1828 TInfo: &ControllingType);
1829 assert(ControllingType && "couldn't get the type out of the parser");
1830 ControllingExprOrType = ControllingType;
1831 }
1832
1833 ExprResult ER = CreateGenericSelectionExpr(
1834 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1835 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1836 delete [] Types;
1837 return ER;
1838}
1839
1840// Helper function to determine type compatibility for C _Generic expressions.
1841// Multiple compatible types within the same _Generic expression is ambiguous
1842// and not valid.
1843static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1844 QualType U) {
1845 // Try to handle special types like OverflowBehaviorTypes
1846 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1847 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1848
1849 if (TOBT || UOBT) {
1850 if (TOBT && UOBT) {
1851 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1852 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1853 T2: UOBT->getUnderlyingType());
1854 return false;
1855 }
1856 return false;
1857 }
1858
1859 // We're dealing with types that don't require special handling.
1860 return Ctx.typesAreCompatible(T1: T, T2: U);
1861}
1862
1863ExprResult Sema::CreateGenericSelectionExpr(
1864 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1865 bool PredicateIsExpr, void *ControllingExprOrType,
1866 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1867 unsigned NumAssocs = Types.size();
1868 assert(NumAssocs == Exprs.size());
1869 assert(ControllingExprOrType &&
1870 "Must have either a controlling expression or a controlling type");
1871
1872 Expr *ControllingExpr = nullptr;
1873 TypeSourceInfo *ControllingType = nullptr;
1874 if (PredicateIsExpr) {
1875 // Decay and strip qualifiers for the controlling expression type, and
1876 // handle placeholder type replacement. See committee discussion from WG14
1877 // DR423.
1878 EnterExpressionEvaluationContext Unevaluated(
1879 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1880 ExprResult R = DefaultFunctionArrayLvalueConversion(
1881 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1882 if (R.isInvalid())
1883 return ExprError();
1884 ControllingExpr = R.get();
1885 } else {
1886 // The extension form uses the type directly rather than converting it.
1887 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1888 if (!ControllingType)
1889 return ExprError();
1890 }
1891
1892 bool TypeErrorFound = false,
1893 IsResultDependent = ControllingExpr
1894 ? ControllingExpr->isTypeDependent()
1895 : ControllingType->getType()->isDependentType(),
1896 ContainsUnexpandedParameterPack =
1897 ControllingExpr
1898 ? ControllingExpr->containsUnexpandedParameterPack()
1899 : ControllingType->getType()->containsUnexpandedParameterPack();
1900
1901 // The controlling expression is an unevaluated operand, so side effects are
1902 // likely unintended.
1903 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1904 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1905 Diag(Loc: ControllingExpr->getExprLoc(),
1906 DiagID: diag::warn_side_effects_unevaluated_context);
1907
1908 for (unsigned i = 0; i < NumAssocs; ++i) {
1909 if (Exprs[i]->containsUnexpandedParameterPack())
1910 ContainsUnexpandedParameterPack = true;
1911
1912 if (Types[i]) {
1913 if (Types[i]->getType()->containsUnexpandedParameterPack())
1914 ContainsUnexpandedParameterPack = true;
1915
1916 if (Types[i]->getType()->isDependentType()) {
1917 IsResultDependent = true;
1918 } else {
1919 // We relax the restriction on use of incomplete types and non-object
1920 // types with the type-based extension of _Generic. Allowing incomplete
1921 // objects means those can be used as "tags" for a type-safe way to map
1922 // to a value. Similarly, matching on function types rather than
1923 // function pointer types can be useful. However, the restriction on VM
1924 // types makes sense to retain as there are open questions about how
1925 // the selection can be made at compile time.
1926 //
1927 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1928 // complete object type other than a variably modified type."
1929 // C2y removed the requirement that an expression form must
1930 // use a complete type, though it's still as-if the type has undergone
1931 // lvalue conversion. We support this as an extension in C23 and
1932 // earlier because GCC does so.
1933 unsigned D = 0;
1934 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1935 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1936 : diag::compat_pre_c2y_assoc_type_incomplete;
1937 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1938 D = diag::err_assoc_type_nonobject;
1939 else if (Types[i]->getType()->isVariablyModifiedType())
1940 D = diag::err_assoc_type_variably_modified;
1941 else if (ControllingExpr) {
1942 // Because the controlling expression undergoes lvalue conversion,
1943 // array conversion, and function conversion, an association which is
1944 // of array type, function type, or is qualified can never be
1945 // reached. We will warn about this so users are less surprised by
1946 // the unreachable association. However, we don't have to handle
1947 // function types; that's not an object type, so it's handled above.
1948 //
1949 // The logic is somewhat different for C++ because C++ has different
1950 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1951 // If T is a non-class type, the type of the prvalue is the cv-
1952 // unqualified version of T. Otherwise, the type of the prvalue is T.
1953 // The result of these rules is that all qualified types in an
1954 // association in C are unreachable, and in C++, only qualified non-
1955 // class types are unreachable.
1956 //
1957 // NB: this does not apply when the first operand is a type rather
1958 // than an expression, because the type form does not undergo
1959 // conversion.
1960 unsigned Reason = 0;
1961 QualType QT = Types[i]->getType();
1962 if (QT->isArrayType())
1963 Reason = 1;
1964 else if (QT.hasQualifiers() &&
1965 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1966 Reason = 2;
1967
1968 if (Reason)
1969 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1970 DiagID: diag::warn_unreachable_association)
1971 << QT << (Reason - 1);
1972 }
1973
1974 if (D != 0) {
1975 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1976 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1977 if (getDiagnostics().getDiagnosticLevel(
1978 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1979 DiagnosticsEngine::Error)
1980 TypeErrorFound = true;
1981 }
1982
1983 // C11 6.5.1.1p2 "No two generic associations in the same generic
1984 // selection shall specify compatible types."
1985 for (unsigned j = i+1; j < NumAssocs; ++j)
1986 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1987 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1988 U: Types[j]->getType())) {
1989 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1990 DiagID: diag::err_assoc_compatible_types)
1991 << Types[j]->getTypeLoc().getSourceRange()
1992 << Types[j]->getType()
1993 << Types[i]->getType();
1994 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1995 DiagID: diag::note_compat_assoc)
1996 << Types[i]->getTypeLoc().getSourceRange()
1997 << Types[i]->getType();
1998 TypeErrorFound = true;
1999 }
2000 }
2001 }
2002 }
2003 if (TypeErrorFound)
2004 return ExprError();
2005
2006 // If we determined that the generic selection is result-dependent, don't
2007 // try to compute the result expression.
2008 if (IsResultDependent) {
2009 if (ControllingExpr)
2010 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
2011 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2012 ContainsUnexpandedParameterPack);
2013 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
2014 AssocExprs: Exprs, DefaultLoc, RParenLoc,
2015 ContainsUnexpandedParameterPack);
2016 }
2017
2018 SmallVector<unsigned, 1> CompatIndices;
2019 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2020 // Look at the canonical type of the controlling expression in case it was a
2021 // deduced type like __auto_type. However, when issuing diagnostics, use the
2022 // type the user wrote in source rather than the canonical one.
2023 for (unsigned i = 0; i < NumAssocs; ++i) {
2024 if (!Types[i])
2025 DefaultIndex = i;
2026 else {
2027 bool Compatible;
2028 QualType ControllingQT =
2029 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2030 : ControllingType->getType().getCanonicalType();
2031 QualType AssocQT = Types[i]->getType();
2032
2033 Compatible =
2034 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2035
2036 if (Compatible)
2037 CompatIndices.push_back(Elt: i);
2038 }
2039 }
2040
2041 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2042 TypeSourceInfo *ControllingType) {
2043 // We strip parens here because the controlling expression is typically
2044 // parenthesized in macro definitions.
2045 if (ControllingExpr)
2046 ControllingExpr = ControllingExpr->IgnoreParens();
2047
2048 SourceRange SR = ControllingExpr
2049 ? ControllingExpr->getSourceRange()
2050 : ControllingType->getTypeLoc().getSourceRange();
2051 QualType QT = ControllingExpr ? ControllingExpr->getType()
2052 : ControllingType->getType();
2053
2054 return std::make_pair(x&: SR, y&: QT);
2055 };
2056
2057 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2058 // type compatible with at most one of the types named in its generic
2059 // association list."
2060 if (CompatIndices.size() > 1) {
2061 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2062 SourceRange SR = P.first;
2063 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2064 << SR << P.second << (unsigned)CompatIndices.size();
2065 for (unsigned I : CompatIndices) {
2066 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2067 DiagID: diag::note_compat_assoc)
2068 << Types[I]->getTypeLoc().getSourceRange()
2069 << Types[I]->getType();
2070 }
2071 return ExprError();
2072 }
2073
2074 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2075 // its controlling expression shall have type compatible with exactly one of
2076 // the types named in its generic association list."
2077 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2078 CompatIndices.size() == 0) {
2079 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2080 SourceRange SR = P.first;
2081 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2082 return ExprError();
2083 }
2084
2085 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2086 // type name that is compatible with the type of the controlling expression,
2087 // then the result expression of the generic selection is the expression
2088 // in that generic association. Otherwise, the result expression of the
2089 // generic selection is the expression in the default generic association."
2090 unsigned ResultIndex =
2091 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2092
2093 if (ControllingExpr) {
2094 return GenericSelectionExpr::Create(
2095 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2096 ContainsUnexpandedParameterPack, ResultIndex);
2097 }
2098 return GenericSelectionExpr::Create(
2099 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2100 ContainsUnexpandedParameterPack, ResultIndex);
2101}
2102
2103static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2104 switch (Kind) {
2105 default:
2106 llvm_unreachable("unexpected TokenKind");
2107 case tok::kw___func__:
2108 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2109 case tok::kw___FUNCTION__:
2110 return PredefinedIdentKind::Function;
2111 case tok::kw___FUNCDNAME__:
2112 return PredefinedIdentKind::FuncDName; // [MS]
2113 case tok::kw___FUNCSIG__:
2114 return PredefinedIdentKind::FuncSig; // [MS]
2115 case tok::kw_L__FUNCTION__:
2116 return PredefinedIdentKind::LFunction; // [MS]
2117 case tok::kw_L__FUNCSIG__:
2118 return PredefinedIdentKind::LFuncSig; // [MS]
2119 case tok::kw___PRETTY_FUNCTION__:
2120 return PredefinedIdentKind::PrettyFunction; // [GNU]
2121 }
2122}
2123
2124/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2125/// to determine the value of a PredefinedExpr. This can be either a
2126/// block, lambda, captured statement, function, otherwise a nullptr.
2127static Decl *getPredefinedExprDecl(Sema &S, DeclContext *DC) {
2128 auto LSI = S.FunctionScopes.rbegin();
2129
2130 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2131 if (isLambdaCallOperator(DC)) {
2132 auto E = S.FunctionScopes.rend();
2133 while (LSI != E && !isa<LambdaScopeInfo>(Val: *LSI))
2134 ++LSI;
2135 assert(LSI != E && "Should be in a lambda scope info");
2136 if (dyn_cast<LambdaScopeInfo>(Val: *LSI)->BeforeCompoundStatement)
2137 DC = DC->getParent();
2138 ++LSI;
2139 }
2140 };
2141
2142 tryAdjustLambdaContext(DC);
2143 while (DC &&
2144 !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) {
2145 DC = DC->getParent();
2146 tryAdjustLambdaContext(DC);
2147 }
2148
2149 return cast_or_null<Decl>(Val: DC);
2150}
2151
2152/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2153/// location of the token and the offset of the ud-suffix within it.
2154static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2155 unsigned Offset) {
2156 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2157 LangOpts: S.getLangOpts());
2158}
2159
2160/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2161/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2162static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2163 IdentifierInfo *UDSuffix,
2164 SourceLocation UDSuffixLoc,
2165 ArrayRef<Expr*> Args,
2166 SourceLocation LitEndLoc) {
2167 assert(Args.size() <= 2 && "too many arguments for literal operator");
2168
2169 QualType ArgTy[2];
2170 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2171 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2172 if (ArgTy[ArgIdx]->isArrayType())
2173 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2174 }
2175
2176 DeclarationName OpName =
2177 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2178 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2179 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2180
2181 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2182 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2183 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2184 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2185 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2186 return ExprError();
2187
2188 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2189}
2190
2191ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2192 // StringToks needs backing storage as it doesn't hold array elements itself
2193 std::vector<Token> ExpandedToks;
2194 if (getLangOpts().MicrosoftExt)
2195 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2196
2197 StringLiteralParser Literal(StringToks, PP,
2198 StringLiteralEvalMethod::Unevaluated);
2199 if (Literal.hadError)
2200 return ExprError();
2201
2202 SmallVector<SourceLocation, 4> StringTokLocs;
2203 for (const Token &Tok : StringToks)
2204 StringTokLocs.push_back(Elt: Tok.getLocation());
2205
2206 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2207 Kind: StringLiteralKind::Unevaluated,
2208 Pascal: false, Ty: {}, Locs: StringTokLocs);
2209
2210 if (!Literal.getUDSuffix().empty()) {
2211 SourceLocation UDSuffixLoc =
2212 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2213 Offset: Literal.getUDSuffixOffset());
2214 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2215 }
2216
2217 return Lit;
2218}
2219
2220std::vector<Token>
2221Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2222 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2223 // local macros that expand to string literals that may be concatenated.
2224 // These macros are expanded here (in Sema), because StringLiteralParser
2225 // (in Lex) doesn't know the enclosing function (because it hasn't been
2226 // parsed yet).
2227 assert(getLangOpts().MicrosoftExt);
2228
2229 // Note: Although function local macros are defined only inside functions,
2230 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2231 // expansion of macros into empty string literals without additional checks.
2232 Decl *CurrentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
2233 if (!CurrentDecl)
2234 CurrentDecl = Context.getTranslationUnitDecl();
2235
2236 std::vector<Token> ExpandedToks;
2237 ExpandedToks.reserve(n: Toks.size());
2238 for (const Token &Tok : Toks) {
2239 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2240 assert(tok::isStringLiteral(Tok.getKind()));
2241 ExpandedToks.emplace_back(args: Tok);
2242 continue;
2243 }
2244 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2245 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2246 // Stringify predefined expression
2247 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2248 << Tok.getKind();
2249 SmallString<64> Str;
2250 llvm::raw_svector_ostream OS(Str);
2251 Token &Exp = ExpandedToks.emplace_back();
2252 Exp.startToken();
2253 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2254 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2255 OS << 'L';
2256 Exp.setKind(tok::wide_string_literal);
2257 } else {
2258 Exp.setKind(tok::string_literal);
2259 }
2260 OS << '"'
2261 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2262 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2263 << '"';
2264 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2265 }
2266 return ExpandedToks;
2267}
2268
2269ExprResult Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope,
2270 ConversionAction Action) {
2271 assert(!StringToks.empty() && "Must have at least one string!");
2272
2273 // StringToks needs backing storage as it doesn't hold array elements itself
2274 std::vector<Token> ExpandedToks;
2275 if (getLangOpts().MicrosoftExt)
2276 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2277
2278 StringLiteralParser Literal(StringToks, PP,
2279 StringLiteralEvalMethod::Evaluated, Action);
2280 if (Literal.hadError)
2281 return ExprError();
2282
2283 SmallVector<SourceLocation, 4> StringTokLocs;
2284 for (const Token &Tok : StringToks)
2285 StringTokLocs.push_back(Elt: Tok.getLocation());
2286
2287 QualType CharTy = Context.CharTy;
2288 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2289 if (Literal.isWide()) {
2290 CharTy = Context.getWideCharType();
2291 Kind = StringLiteralKind::Wide;
2292 } else if (Literal.isUTF8()) {
2293 if (getLangOpts().Char8)
2294 CharTy = Context.Char8Ty;
2295 else if (getLangOpts().C23)
2296 CharTy = Context.UnsignedCharTy;
2297 Kind = StringLiteralKind::UTF8;
2298 } else if (Literal.isUTF16()) {
2299 CharTy = Context.Char16Ty;
2300 Kind = StringLiteralKind::UTF16;
2301 } else if (Literal.isUTF32()) {
2302 CharTy = Context.Char32Ty;
2303 Kind = StringLiteralKind::UTF32;
2304 } else if (Literal.isPascal()) {
2305 CharTy = Context.UnsignedCharTy;
2306 }
2307
2308 // Warn on u8 string literals before C++20 and C23, whose type
2309 // was an array of char before but becomes an array of char8_t.
2310 // In C++20, it cannot be used where a pointer to char is expected.
2311 // In C23, it might have an unexpected value if char was signed.
2312 if (Kind == StringLiteralKind::UTF8 &&
2313 (getLangOpts().CPlusPlus
2314 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2315 : !getLangOpts().C23)) {
2316 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2317 ? diag::warn_cxx20_compat_utf8_string
2318 : diag::warn_c23_compat_utf8_string);
2319
2320 // Create removals for all 'u8' prefixes in the string literal(s). This
2321 // ensures C++20/C23 compatibility (but may change the program behavior when
2322 // built by non-Clang compilers for which the execution character set is
2323 // not always UTF-8).
2324 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2325 SourceLocation RemovalDiagLoc;
2326 for (const Token &Tok : StringToks) {
2327 if (Tok.getKind() == tok::utf8_string_literal) {
2328 if (RemovalDiagLoc.isInvalid())
2329 RemovalDiagLoc = Tok.getLocation();
2330 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2331 B: Tok.getLocation(),
2332 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2333 SM: getSourceManager(), LangOpts: getLangOpts())));
2334 }
2335 }
2336 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2337 }
2338
2339 QualType StrTy =
2340 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2341
2342 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2343 StringLiteral *Lit = StringLiteral::Create(
2344 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2345 if (Literal.getUDSuffix().empty())
2346 return Lit;
2347
2348 // We're building a user-defined literal.
2349 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2350 SourceLocation UDSuffixLoc =
2351 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2352 Offset: Literal.getUDSuffixOffset());
2353
2354 // Make sure we're allowed user-defined literals here.
2355 if (!UDLScope)
2356 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2357
2358 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2359 // operator "" X (str, len)
2360 QualType SizeType = Context.getSizeType();
2361
2362 DeclarationName OpName =
2363 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2364 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2365 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2366
2367 QualType ArgTy[] = {
2368 Context.getArrayDecayedType(T: StrTy), SizeType
2369 };
2370
2371 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2372 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2373 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2374 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2375 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2376
2377 case LOLR_Cooked: {
2378 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2379 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2380 l: StringTokLocs[0]);
2381 Expr *Args[] = { Lit, LenArg };
2382
2383 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2384 }
2385
2386 case LOLR_Template: {
2387 TemplateArgumentListInfo ExplicitArgs;
2388 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2389 TemplateArgumentLocInfo ArgInfo(Lit);
2390 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2391 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2392 ExplicitTemplateArgs: &ExplicitArgs);
2393 }
2394
2395 case LOLR_StringTemplatePack: {
2396 TemplateArgumentListInfo ExplicitArgs;
2397
2398 unsigned CharBits = Context.getIntWidth(T: CharTy);
2399 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2400 llvm::APSInt Value(CharBits, CharIsUnsigned);
2401
2402 TemplateArgument TypeArg(CharTy);
2403 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2404 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2405
2406 SourceLocation Loc = StringTokLocs.back();
2407 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2408 Value = Lit->getCodeUnit(I);
2409 TemplateArgument Arg(Context, Value, CharTy);
2410 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2411 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2412 }
2413 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2414 }
2415 case LOLR_Raw:
2416 case LOLR_ErrorNoDiagnostic:
2417 llvm_unreachable("unexpected literal operator lookup result");
2418 case LOLR_Error:
2419 return ExprError();
2420 }
2421 llvm_unreachable("unexpected literal operator lookup result");
2422}
2423
2424DeclRefExpr *
2425Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2426 SourceLocation Loc,
2427 const CXXScopeSpec *SS) {
2428 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2429 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2430}
2431
2432DeclRefExpr *
2433Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2434 const DeclarationNameInfo &NameInfo,
2435 const CXXScopeSpec *SS, NamedDecl *FoundD,
2436 SourceLocation TemplateKWLoc,
2437 const TemplateArgumentListInfo *TemplateArgs) {
2438 NestedNameSpecifierLoc NNS =
2439 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2440 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2441 TemplateArgs);
2442}
2443
2444// CUDA/HIP: Check whether a captured reference variable is referencing a
2445// host variable in a device or host device lambda.
2446static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2447 VarDecl *VD) {
2448 if (!S.getLangOpts().CUDA || !VD->hasInit())
2449 return false;
2450 assert(VD->getType()->isReferenceType());
2451
2452 // Check whether the reference variable is referencing a host variable.
2453 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2454 if (!DRE)
2455 return false;
2456 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2457 if (!Referee || !Referee->hasGlobalStorage() ||
2458 Referee->hasAttr<CUDADeviceAttr>())
2459 return false;
2460
2461 // Check whether the current function is a device or host device lambda.
2462 // Check whether the reference variable is a capture by getDeclContext()
2463 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2464 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2465 if (MD && MD->getParent()->isLambda() &&
2466 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2467 VD->getDeclContext() != MD)
2468 return true;
2469
2470 return false;
2471}
2472
2473NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2474 // A declaration named in an unevaluated operand never constitutes an odr-use.
2475 if (isUnevaluatedContext())
2476 return NOUR_Unevaluated;
2477
2478 // C++2a [basic.def.odr]p4:
2479 // A variable x whose name appears as a potentially-evaluated expression e
2480 // is odr-used by e unless [...] x is a reference that is usable in
2481 // constant expressions.
2482 // CUDA/HIP:
2483 // If a reference variable referencing a host variable is captured in a
2484 // device or host device lambda, the value of the referee must be copied
2485 // to the capture and the reference variable must be treated as odr-use
2486 // since the value of the referee is not known at compile time and must
2487 // be loaded from the captured.
2488 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2489 if (VD->getType()->isReferenceType() &&
2490 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2491 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2492 VD->isUsableInConstantExpressions(C: Context))
2493 return NOUR_Constant;
2494 }
2495
2496 // All remaining non-variable cases constitute an odr-use. For variables, we
2497 // need to wait and see how the expression is used.
2498 return NOUR_None;
2499}
2500
2501DeclRefExpr *
2502Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2503 const DeclarationNameInfo &NameInfo,
2504 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2505 SourceLocation TemplateKWLoc,
2506 const TemplateArgumentListInfo *TemplateArgs) {
2507 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2508 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2509
2510 DeclRefExpr *E = DeclRefExpr::Create(
2511 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2512 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2513 MarkDeclRefReferenced(E);
2514
2515 // C++ [except.spec]p17:
2516 // An exception-specification is considered to be needed when:
2517 // - in an expression, the function is the unique lookup result or
2518 // the selected member of a set of overloaded functions.
2519 //
2520 // We delay doing this until after we've built the function reference and
2521 // marked it as used so that:
2522 // a) if the function is defaulted, we get errors from defining it before /
2523 // instead of errors from computing its exception specification, and
2524 // b) if the function is a defaulted comparison, we can use the body we
2525 // build when defining it as input to the exception specification
2526 // computation rather than computing a new body.
2527 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2528 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2529 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2530 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2531 }
2532 }
2533
2534 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2535 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2536 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2537 getCurFunction()->recordUseOfWeak(E);
2538
2539 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2540 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2541 FD = IFD->getAnonField();
2542 if (FD) {
2543 UnusedPrivateFields.remove(X: FD);
2544 // Just in case we're building an illegal pointer-to-member.
2545 if (FD->isBitField())
2546 E->setObjectKind(OK_BitField);
2547 }
2548
2549 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2550 // designates a bit-field.
2551 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2552 if (const auto *BE = BD->getBinding())
2553 E->setObjectKind(BE->getObjectKind());
2554
2555 return E;
2556}
2557
2558// Diagnose when a macro cannot be expanded because it's a function-like macro
2559// being used as a function-like macro. Returns true if a diagnostic is emitted.
2560static bool diagnoseFunctionLikeMacro(Sema &SemaRef, DeclarationName Name,
2561 SourceLocation TypoLoc) {
2562
2563 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2564 if (II->hasMacroDefinition()) {
2565 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2566 if (MI && MI->isFunctionLike()) {
2567 // If the identifier is immediately followed by '(', the user did
2568 // attempt to invoke it as a function-like macro; the failure is
2569 // for some other reason (e.g. wrong argument count), which the
2570 // preprocessor already diagnosed separately. Don't suggest adding
2571 // parens in that case, since they're already there.
2572 SourceManager &SM = SemaRef.getSourceManager();
2573 const LangOptions &LangOpts = SemaRef.getLangOpts();
2574 std::optional<Token> NextTok =
2575 Lexer::findNextToken(Loc: TypoLoc, SM, LangOpts);
2576 if (NextTok && NextTok->is(K: tok::l_paren))
2577 return false;
2578 SemaRef.Diag(Loc: TypoLoc,
2579 DiagID: diag::err_undeclared_var_use_suggest_func_like_macro)
2580 << II->getName();
2581 SemaRef.Diag(Loc: MI->getDefinitionLoc(),
2582 DiagID: diag::note_function_like_macro_requires_parens)
2583 << II->getName();
2584 return true;
2585 }
2586 }
2587 }
2588 return false;
2589}
2590
2591void
2592Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2593 TemplateArgumentListInfo &Buffer,
2594 DeclarationNameInfo &NameInfo,
2595 const TemplateArgumentListInfo *&TemplateArgs) {
2596 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2597 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2598 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2599
2600 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2601 Id.TemplateId->NumArgs);
2602 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2603
2604 TemplateName TName = Id.TemplateId->Template.get();
2605 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2606 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2607 TemplateArgs = &Buffer;
2608 } else {
2609 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2610 TemplateArgs = nullptr;
2611 }
2612}
2613
2614bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2615 // During a default argument instantiation the CurContext points
2616 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2617 // function parameter list, hence add an explicit check.
2618 bool isDefaultArgument =
2619 !CodeSynthesisContexts.empty() &&
2620 CodeSynthesisContexts.back().Kind ==
2621 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2622 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2623 bool isInstance = CurMethod && CurMethod->isInstance() &&
2624 R.getNamingClass() == CurMethod->getParent() &&
2625 !isDefaultArgument;
2626
2627 // There are two ways we can find a class-scope declaration during template
2628 // instantiation that we did not find in the template definition: if it is a
2629 // member of a dependent base class, or if it is declared after the point of
2630 // use in the same class. Distinguish these by comparing the class in which
2631 // the member was found to the naming class of the lookup.
2632 unsigned DiagID = diag::err_found_in_dependent_base;
2633 unsigned NoteID = diag::note_member_declared_at;
2634 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2635 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2636 : diag::err_found_later_in_class;
2637 } else if (getLangOpts().MSVCCompat) {
2638 DiagID = diag::ext_found_in_dependent_base;
2639 NoteID = diag::note_dependent_member_use;
2640 }
2641
2642 if (isInstance) {
2643 // Give a code modification hint to insert 'this->'.
2644 Diag(Loc: R.getNameLoc(), DiagID)
2645 << R.getLookupName()
2646 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2647 CheckCXXThisCapture(Loc: R.getNameLoc());
2648 } else {
2649 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2650 // they're not shadowed).
2651 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2652 }
2653
2654 for (const NamedDecl *D : R)
2655 Diag(Loc: D->getLocation(), DiagID: NoteID);
2656
2657 // Return true if we are inside a default argument instantiation
2658 // and the found name refers to an instance member function, otherwise
2659 // the caller will try to create an implicit member call and this is wrong
2660 // for default arguments.
2661 //
2662 // FIXME: Is this special case necessary? We could allow the caller to
2663 // diagnose this.
2664 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2665 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2666 return true;
2667 }
2668
2669 // Tell the callee to try to recover.
2670 return false;
2671}
2672
2673bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2674 CorrectionCandidateCallback &CCC,
2675 TemplateArgumentListInfo *ExplicitTemplateArgs,
2676 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2677 DeclarationName Name = R.getLookupName();
2678 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2679
2680 unsigned diagnostic = diag::err_undeclared_var_use;
2681 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2682 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2683 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2684 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2685 diagnostic = diag::err_undeclared_use;
2686 diagnostic_suggest = diag::err_undeclared_use_suggest;
2687 }
2688
2689 // If the original lookup was an unqualified lookup, fake an
2690 // unqualified lookup. This is useful when (for example) the
2691 // original lookup would not have found something because it was a
2692 // dependent name.
2693 DeclContext *DC =
2694 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2695 while (DC) {
2696 if (isa<CXXRecordDecl>(Val: DC)) {
2697 if (ExplicitTemplateArgs) {
2698 if (LookupTemplateName(
2699 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2700 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2701 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2702 return true;
2703 } else {
2704 LookupQualifiedName(R, LookupCtx: DC);
2705 }
2706
2707 if (!R.empty()) {
2708 // Don't give errors about ambiguities in this lookup.
2709 R.suppressDiagnostics();
2710
2711 // If there's a best viable function among the results, only mention
2712 // that one in the notes.
2713 OverloadCandidateSet Candidates(R.getNameLoc(),
2714 OverloadCandidateSet::CSK_Normal);
2715 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2716 OverloadCandidateSet::iterator Best;
2717 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2718 OR_Success) {
2719 R.clear();
2720 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2721 R.resolveKind();
2722 }
2723
2724 return DiagnoseDependentMemberLookup(R);
2725 }
2726
2727 R.clear();
2728 }
2729
2730 DC = DC->getLookupParent();
2731 }
2732
2733 // We didn't find anything, so try to correct for a typo.
2734 TypoCorrection Corrected;
2735 if (S && (Corrected =
2736 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2737 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2738 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2739 bool DroppedSpecifier =
2740 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2741 R.setLookupName(Corrected.getCorrection());
2742
2743 bool AcceptableWithRecovery = false;
2744 bool AcceptableWithoutRecovery = false;
2745 NamedDecl *ND = Corrected.getFoundDecl();
2746 if (ND) {
2747 if (Corrected.isOverloaded()) {
2748 OverloadCandidateSet OCS(R.getNameLoc(),
2749 OverloadCandidateSet::CSK_Normal);
2750 OverloadCandidateSet::iterator Best;
2751 for (NamedDecl *CD : Corrected) {
2752 if (FunctionTemplateDecl *FTD =
2753 dyn_cast<FunctionTemplateDecl>(Val: CD))
2754 AddTemplateOverloadCandidate(
2755 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2756 Args, CandidateSet&: OCS);
2757 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2758 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2759 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2760 Args, CandidateSet&: OCS);
2761 }
2762 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2763 case OR_Success:
2764 ND = Best->FoundDecl;
2765 Corrected.setCorrectionDecl(ND);
2766 break;
2767 default:
2768 // FIXME: Arbitrarily pick the first declaration for the note.
2769 Corrected.setCorrectionDecl(ND);
2770 break;
2771 }
2772 }
2773 R.addDecl(D: ND);
2774 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2775 CXXRecordDecl *Record =
2776 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2777 if (!Record)
2778 Record = cast<CXXRecordDecl>(
2779 Val: ND->getDeclContext()->getRedeclContext());
2780 R.setNamingClass(Record);
2781 }
2782
2783 auto *UnderlyingND = ND->getUnderlyingDecl();
2784 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2785 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2786 // FIXME: If we ended up with a typo for a type name or
2787 // Objective-C class name, we're in trouble because the parser
2788 // is in the wrong place to recover. Suggest the typo
2789 // correction, but don't make it a fix-it since we're not going
2790 // to recover well anyway.
2791 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2792 getAsTypeTemplateDecl(D: UnderlyingND) ||
2793 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2794 } else {
2795 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2796 // because we aren't able to recover.
2797 AcceptableWithoutRecovery = true;
2798 }
2799
2800 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2801 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2802 ? diag::note_implicit_param_decl
2803 : diag::note_previous_decl;
2804 if (SS.isEmpty())
2805 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2806 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2807 else
2808 diagnoseTypo(Correction: Corrected,
2809 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2810 << Name << computeDeclContext(SS, EnteringContext: false)
2811 << DroppedSpecifier << NameRange,
2812 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2813
2814 if (Corrected.WillReplaceSpecifier()) {
2815 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2816 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2817 SS.MakeTrivial(Context, Qualifier: NNS,
2818 R: NNS ? NameRange.getBegin() : SourceRange());
2819 }
2820
2821 // Tell the callee whether to try to recover.
2822 return !AcceptableWithRecovery;
2823 }
2824 }
2825 R.clear();
2826
2827 if (diagnoseFunctionLikeMacro(SemaRef, Name, TypoLoc: R.getNameLoc()))
2828 return true;
2829
2830 // Emit a special diagnostic for failed member lookups.
2831 // FIXME: computing the declaration context might fail here (?)
2832 if (!SS.isEmpty()) {
2833 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2834 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2835 return true;
2836 }
2837
2838 // Give up, we can't recover.
2839 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2840 return true;
2841}
2842
2843/// In Microsoft mode, if we are inside a template class whose parent class has
2844/// dependent base classes, and we can't resolve an unqualified identifier, then
2845/// assume the identifier is a member of a dependent base class. We can only
2846/// recover successfully in static methods, instance methods, and other contexts
2847/// where 'this' is available. This doesn't precisely match MSVC's
2848/// instantiation model, but it's close enough.
2849static Expr *
2850recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2851 DeclarationNameInfo &NameInfo,
2852 SourceLocation TemplateKWLoc,
2853 const TemplateArgumentListInfo *TemplateArgs) {
2854 // Only try to recover from lookup into dependent bases in static methods or
2855 // contexts where 'this' is available.
2856 QualType ThisType = S.getCurrentThisType();
2857 const CXXRecordDecl *RD = nullptr;
2858 if (!ThisType.isNull())
2859 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2860 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2861 RD = MD->getParent();
2862 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2863 return nullptr;
2864
2865 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2866 // is available, suggest inserting 'this->' as a fixit.
2867 SourceLocation Loc = NameInfo.getLoc();
2868 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2869 DB << NameInfo.getName() << RD;
2870
2871 if (!ThisType.isNull()) {
2872 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2873 return CXXDependentScopeMemberExpr::Create(
2874 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2875 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2876 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2877 }
2878
2879 // Synthesize a fake NNS that points to the derived class. This will
2880 // perform name lookup during template instantiation.
2881 CXXScopeSpec SS;
2882 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2883 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2884 return DependentScopeDeclRefExpr::Create(
2885 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2886 TemplateArgs);
2887}
2888
2889ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2890 SourceLocation TemplateKWLoc,
2891 UnqualifiedId &Id, bool IsCall,
2892 bool IsAddressOfOperand,
2893 CorrectionCandidateCallback *CCC,
2894 bool IsInlineAsmIdentifier) {
2895 assert(!(IsAddressOfOperand && IsCall) &&
2896 "cannot be direct & operand and a function call");
2897 if (SS.isInvalid())
2898 return ExprError();
2899
2900 TemplateArgumentListInfo TemplateArgsBuffer;
2901
2902 // Decompose the UnqualifiedId into the following data.
2903 DeclarationNameInfo NameInfo;
2904 const TemplateArgumentListInfo *TemplateArgs;
2905 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2906
2907 DeclarationName Name = NameInfo.getName();
2908 IdentifierInfo *II = Name.getAsIdentifierInfo();
2909 SourceLocation NameLoc = NameInfo.getLoc();
2910
2911 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId &&
2912 Id.TemplateId->Template)
2913 if (TemplateName TN = Id.TemplateId->Template.get();
2914 TN.getAsPackIndexingTemplate())
2915 return CheckVarOrConceptTemplateTemplateId(NameInfo, Template: TN, TemplateArgs);
2916
2917 if (II && II->isEditorPlaceholder()) {
2918 // FIXME: When typed placeholders are supported we can create a typed
2919 // placeholder expression node.
2920 return ExprError();
2921 }
2922
2923 // This specially handles arguments of attributes appertains to a type of C
2924 // struct field such that the name lookup within a struct finds the member
2925 // name, which is not the case for other contexts in C.
2926 // A late-parsed attribute on a function pointer field has the pointee's
2927 // parameters in the struct's scope too; as when the attribute was written, a
2928 // parameter shadows a field of the same name.
2929 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope() &&
2930 llvm::none_of(Range: S->decls(), P: [&](Decl *D) {
2931 return isa<ParmVarDecl>(Val: D) &&
2932 cast<ParmVarDecl>(Val: D)->getDeclName() == NameInfo.getName();
2933 })) {
2934 // See if this is reference to a field of struct.
2935 LookupResult R(*this, NameInfo, LookupMemberName);
2936 // LookupName handles a name lookup from within anonymous struct.
2937 if (LookupName(R, S)) {
2938 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2939 QualType type = VD->getType().getNonReferenceType();
2940 // This will eventually be translated into MemberExpr upon
2941 // the use of instantiated struct fields.
2942 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2943 }
2944 }
2945 }
2946
2947 // Perform the required lookup.
2948 LookupResult R(*this, NameInfo,
2949 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2950 ? LookupObjCImplicitSelfParam
2951 : LookupOrdinaryName);
2952 if (TemplateKWLoc.isValid() || TemplateArgs) {
2953 // Lookup the template name again to correctly establish the context in
2954 // which it was found. This is really unfortunate as we already did the
2955 // lookup to determine that it was a template name in the first place. If
2956 // this becomes a performance hit, we can work harder to preserve those
2957 // results until we get here but it's likely not worth it.
2958 AssumedTemplateKind AssumedTemplate;
2959 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2960 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2961 ATK: &AssumedTemplate))
2962 return ExprError();
2963
2964 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2965 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2966 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2967 } else {
2968 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2969 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2970 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2971
2972 // If the result might be in a dependent base class, this is a dependent
2973 // id-expression.
2974 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2975 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2976 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2977
2978 // If this reference is in an Objective-C method, then we need to do
2979 // some special Objective-C lookup, too.
2980 if (IvarLookupFollowUp) {
2981 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2982 if (E.isInvalid())
2983 return ExprError();
2984
2985 if (Expr *Ex = E.getAs<Expr>())
2986 return Ex;
2987 }
2988 }
2989
2990 if (R.isAmbiguous())
2991 return ExprError();
2992
2993 // This could be an implicitly declared function reference if the language
2994 // mode allows it as a feature.
2995 if (R.empty() && IsCall && II && getLangOpts().implicitFunctionsAllowed()) {
2996 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2997 if (D) R.addDecl(D);
2998 }
2999
3000 // Determine whether this name might be a candidate for
3001 // argument-dependent lookup.
3002 bool ADL = UseArgumentDependentLookup(SS, R, IsCall);
3003
3004 if (R.empty() && !ADL) {
3005 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
3006 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
3007 TemplateKWLoc, TemplateArgs))
3008 return E;
3009 }
3010
3011 // Don't diagnose an empty lookup for inline assembly.
3012 if (IsInlineAsmIdentifier)
3013 return ExprError();
3014
3015 // If this name wasn't predeclared and if this is not a function
3016 // call, diagnose the problem.
3017 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3018 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3019 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3020 "Typo correction callback misconfigured");
3021 if (CCC) {
3022 // Make sure the callback knows what the typo being diagnosed is.
3023 CCC->setTypoName(II);
3024 if (SS.isValid())
3025 CCC->setTypoNNS(SS.getScopeRep());
3026 }
3027 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3028 // a template name, but we happen to have always already looked up the name
3029 // before we get here if it must be a template name.
3030 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
3031 Args: {}, LookupCtx: nullptr))
3032 return ExprError();
3033
3034 assert(!R.empty() &&
3035 "DiagnoseEmptyLookup returned false but added no results");
3036
3037 // If we found an Objective-C instance variable, let
3038 // LookupInObjCMethod build the appropriate expression to
3039 // reference the ivar.
3040 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3041 R.clear();
3042 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
3043 // In a hopelessly buggy code, Objective-C instance variable
3044 // lookup fails and no expression will be built to reference it.
3045 if (!E.isInvalid() && !E.get())
3046 return ExprError();
3047 return E;
3048 }
3049 }
3050
3051 // This is guaranteed from this point on.
3052 assert(!R.empty() || ADL);
3053
3054 // Check whether this might be a C++ implicit instance member access.
3055 // C++ [class.mfct.non-static]p3:
3056 // When an id-expression that is not part of a class member access
3057 // syntax and not used to form a pointer to member is used in the
3058 // body of a non-static member function of class X, if name lookup
3059 // resolves the name in the id-expression to a non-static non-type
3060 // member of some class C, the id-expression is transformed into a
3061 // class member access expression using (*this) as the
3062 // postfix-expression to the left of the . operator.
3063 //
3064 // But we don't actually need to do this for '&' operands if R
3065 // resolved to a function or overloaded function set, because the
3066 // expression is ill-formed if it actually works out to be a
3067 // non-static member function:
3068 //
3069 // C++ [expr.ref]p4:
3070 // Otherwise, if E1.E2 refers to a non-static member function. . .
3071 // [t]he expression can be used only as the left-hand operand of a
3072 // member function call.
3073 //
3074 // There are other safeguards against such uses, but it's important
3075 // to get this right here so that we don't end up making a
3076 // spuriously dependent expression if we're inside a dependent
3077 // instance method.
3078 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3079 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3080 S);
3081
3082 if (TemplateArgs || TemplateKWLoc.isValid()) {
3083
3084 // In C++1y, if this is a variable template id, then check it
3085 // in BuildTemplateIdExpr().
3086 // The single lookup result must be a variable template declaration.
3087 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3088 (Id.TemplateId->Kind == TNK_Var_template ||
3089 Id.TemplateId->Kind == TNK_Concept_template)) {
3090 assert(R.getAsSingle<TemplateDecl>() &&
3091 "There should only be one declaration found.");
3092 }
3093
3094 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3095 }
3096
3097 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3098}
3099
3100ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3101 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3102 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3103 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3104 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3105
3106 if (R.isAmbiguous())
3107 return ExprError();
3108
3109 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3110 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3111 NameInfo, /*TemplateArgs=*/nullptr);
3112
3113 if (R.empty()) {
3114 // Don't diagnose problems with invalid record decl, the secondary no_member
3115 // diagnostic during template instantiation is likely bogus, e.g. if a class
3116 // is invalid because it's derived from an invalid base class, then missing
3117 // members were likely supposed to be inherited.
3118 DeclContext *DC = computeDeclContext(SS);
3119 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3120 if (CD->isInvalidDecl() || CD->isBeingDefined())
3121 return ExprError();
3122 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3123 << NameInfo.getName() << DC << SS.getRange();
3124 return ExprError();
3125 }
3126
3127 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3128 QualType ET;
3129 TypeLocBuilder TLB;
3130 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3131 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3132 Qualifier: SS.getScopeRep(), TD: TagD,
3133 /*OwnsTag=*/false);
3134 auto TL = TLB.push<TagTypeLoc>(T: ET);
3135 TL.setElaboratedKeywordLoc(SourceLocation());
3136 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3137 TL.setNameLoc(NameInfo.getLoc());
3138 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3139 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3140 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3141 TLB.push<TypedefTypeLoc>(T: ET).set(
3142 /*ElaboratedKeywordLoc=*/SourceLocation(),
3143 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3144 } else {
3145 // FIXME: What else can appear here?
3146 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3147 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3148 assert(SS.isEmpty());
3149 }
3150
3151 // Diagnose a missing typename if this resolved unambiguously to a type in
3152 // a dependent context. If we can recover with a type, downgrade this to
3153 // a warning in Microsoft compatibility mode.
3154 unsigned DiagID = diag::err_typename_missing;
3155 if (RecoveryTSI && getLangOpts().MSVCCompat)
3156 DiagID = diag::ext_typename_missing;
3157 SourceLocation Loc = SS.getBeginLoc();
3158 auto D = Diag(Loc, DiagID);
3159 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3160
3161 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3162 // context.
3163 if (!RecoveryTSI)
3164 return ExprError();
3165
3166 // Only issue the fixit if we're prepared to recover.
3167 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3168
3169 // Recover by pretending this was an elaborated type.
3170 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3171
3172 return ExprEmpty();
3173 }
3174
3175 // If necessary, build an implicit class member access.
3176 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3177 return BuildPossibleImplicitMemberExpr(SS,
3178 /*TemplateKWLoc=*/SourceLocation(),
3179 R, /*TemplateArgs=*/nullptr,
3180 /*S=*/nullptr);
3181
3182 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3183}
3184
3185ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3186 NestedNameSpecifier Qualifier,
3187 NamedDecl *FoundDecl,
3188 NamedDecl *Member) {
3189 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3190 if (!RD)
3191 return From;
3192
3193 QualType DestRecordType;
3194 QualType DestType;
3195 QualType FromRecordType;
3196 QualType FromType = From->getType();
3197 bool PointerConversions = false;
3198 if (isa<FieldDecl>(Val: Member)) {
3199 DestRecordType = Context.getCanonicalTagType(TD: RD);
3200 auto FromPtrType = FromType->getAs<PointerType>();
3201 DestRecordType = Context.getAddrSpaceQualType(
3202 T: DestRecordType, AddressSpace: FromPtrType
3203 ? FromType->getPointeeType().getAddressSpace()
3204 : FromType.getAddressSpace());
3205
3206 if (FromPtrType) {
3207 DestType = Context.getPointerType(T: DestRecordType);
3208 FromRecordType = FromPtrType->getPointeeType();
3209 PointerConversions = true;
3210 } else {
3211 DestType = DestRecordType;
3212 FromRecordType = FromType;
3213 }
3214 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3215 if (!Method->isImplicitObjectMemberFunction())
3216 return From;
3217
3218 DestType = Method->getThisType().getNonReferenceType();
3219 DestRecordType = Method->getFunctionObjectParameterType();
3220
3221 if (FromType->getAs<PointerType>()) {
3222 FromRecordType = FromType->getPointeeType();
3223 PointerConversions = true;
3224 } else {
3225 FromRecordType = FromType;
3226 DestType = DestRecordType;
3227 }
3228
3229 LangAS FromAS = FromRecordType.getAddressSpace();
3230 LangAS DestAS = DestRecordType.getAddressSpace();
3231 if (FromAS != DestAS) {
3232 QualType FromRecordTypeWithoutAS =
3233 Context.removeAddrSpaceQualType(T: FromRecordType);
3234 QualType FromTypeWithDestAS =
3235 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3236 if (PointerConversions)
3237 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3238 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3239 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3240 .get();
3241 }
3242 } else {
3243 // No conversion necessary.
3244 return From;
3245 }
3246
3247 if (DestType->isDependentType() || FromType->isDependentType())
3248 return From;
3249
3250 // If the unqualified types are the same, no conversion is necessary.
3251 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3252 return From;
3253
3254 SourceRange FromRange = From->getSourceRange();
3255 SourceLocation FromLoc = FromRange.getBegin();
3256
3257 ExprValueKind VK = From->getValueKind();
3258
3259 // C++ [class.member.lookup]p8:
3260 // [...] Ambiguities can often be resolved by qualifying a name with its
3261 // class name.
3262 //
3263 // If the member was a qualified name and the qualified referred to a
3264 // specific base subobject type, we'll cast to that intermediate type
3265 // first and then to the object in which the member is declared. That allows
3266 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3267 //
3268 // class Base { public: int x; };
3269 // class Derived1 : public Base { };
3270 // class Derived2 : public Base { };
3271 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3272 //
3273 // void VeryDerived::f() {
3274 // x = 17; // error: ambiguous base subobjects
3275 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3276 // }
3277 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3278 QualType QType = QualType(Qualifier.getAsType(), 0);
3279 assert(QType->isRecordType() && "lookup done with non-record type");
3280
3281 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3282
3283 // In C++98, the qualifier type doesn't actually have to be a base
3284 // type of the object type, in which case we just ignore it.
3285 // Otherwise build the appropriate casts.
3286 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3287 CXXCastPath BasePath;
3288 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3289 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3290 return ExprError();
3291
3292 if (PointerConversions)
3293 QType = Context.getPointerType(T: QType);
3294 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3295 VK, BasePath: &BasePath).get();
3296
3297 FromType = QType;
3298 FromRecordType = QRecordType;
3299
3300 // If the qualifier type was the same as the destination type,
3301 // we're done.
3302 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3303 return From;
3304 }
3305 }
3306
3307 CXXCastPath BasePath;
3308 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3309 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3310 /*IgnoreAccess=*/true))
3311 return ExprError();
3312
3313 // Propagate qualifiers to base subobjects as per:
3314 // C++ [basic.type.qualifier]p1.2:
3315 // A volatile object is [...] a subobject of a volatile object.
3316 Qualifiers FromTypeQuals = FromType.getQualifiers();
3317 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3318 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3319
3320 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3321 BasePath: &BasePath);
3322}
3323
3324bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3325 const LookupResult &R, bool IsCall) {
3326 // Only when used directly as the postfix-expression of a call.
3327 if (!IsCall)
3328 return false;
3329
3330 // Never if a scope specifier was provided.
3331 if (SS.isNotEmpty())
3332 return false;
3333
3334 // Only in C++ or ObjC++.
3335 if (!getLangOpts().CPlusPlus)
3336 return false;
3337
3338 // Turn off ADL when we find certain kinds of declarations during
3339 // normal lookup:
3340 for (const NamedDecl *D : R) {
3341 // C++0x [basic.lookup.argdep]p3:
3342 // -- a declaration of a class member
3343 // Since using decls preserve this property, we check this on the
3344 // original decl.
3345 if (D->isCXXClassMember())
3346 return false;
3347
3348 // C++0x [basic.lookup.argdep]p3:
3349 // -- a block-scope function declaration that is not a
3350 // using-declaration
3351 // NOTE: we also trigger this for function templates (in fact, we
3352 // don't check the decl type at all, since all other decl types
3353 // turn off ADL anyway).
3354 if (isa<UsingShadowDecl>(Val: D))
3355 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3356 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3357 return false;
3358
3359 // C++0x [basic.lookup.argdep]p3:
3360 // -- a declaration that is neither a function or a function
3361 // template
3362 // And also for builtin functions.
3363 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3364 // But also builtin functions.
3365 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3366 return false;
3367 } else if (!isa<FunctionTemplateDecl>(Val: D))
3368 return false;
3369 }
3370
3371 return true;
3372}
3373
3374/// Diagnoses obvious problems with the use of the given declaration
3375/// as an expression. This is only actually called for lookups that
3376/// were not overloaded, and it doesn't promise that the declaration
3377/// will in fact be used.
3378static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3379 bool AcceptInvalid) {
3380 if (D->isInvalidDecl() && !AcceptInvalid)
3381 return true;
3382
3383 if (isa<TypedefNameDecl>(Val: D)) {
3384 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3385 return true;
3386 }
3387
3388 if (isa<ObjCInterfaceDecl>(Val: D)) {
3389 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3390 return true;
3391 }
3392
3393 if (isa<NamespaceDecl>(Val: D)) {
3394 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3395 return true;
3396 }
3397
3398 return false;
3399}
3400
3401// Certain multiversion types should be treated as overloaded even when there is
3402// only one result.
3403static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3404 assert(R.isSingleResult() && "Expected only a single result");
3405 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3406 return FD &&
3407 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3408}
3409
3410ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3411 LookupResult &R, bool NeedsADL,
3412 bool AcceptInvalidDecl) {
3413 // If this is a single, fully-resolved result and we don't need ADL,
3414 // just build an ordinary singleton decl ref.
3415 if (!NeedsADL && R.isSingleResult() &&
3416 !R.getAsSingle<FunctionTemplateDecl>() &&
3417 !ShouldLookupResultBeMultiVersionOverload(R))
3418 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3419 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3420 AcceptInvalidDecl);
3421
3422 // We only need to check the declaration if there's exactly one
3423 // result, because in the overloaded case the results can only be
3424 // functions and function templates.
3425 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3426 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3427 AcceptInvalid: AcceptInvalidDecl))
3428 return ExprError();
3429
3430 // Otherwise, just build an unresolved lookup expression. Suppress
3431 // any lookup-related diagnostics; we'll hash these out later, when
3432 // we've picked a target.
3433 R.suppressDiagnostics();
3434
3435 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3436 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3437 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3438 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3439
3440 return ULE;
3441}
3442
3443ExprResult Sema::BuildDeclarationNameExpr(
3444 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3445 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3446 bool AcceptInvalidDecl) {
3447 assert(D && "Cannot refer to a NULL declaration");
3448 assert(!isa<FunctionTemplateDecl>(D) &&
3449 "Cannot refer unambiguously to a function template");
3450
3451 SourceLocation Loc = NameInfo.getLoc();
3452 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3453 // Recovery from invalid cases (e.g. D is an invalid Decl).
3454 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3455 // diagnostics, as invalid decls use int as a fallback type.
3456 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3457 }
3458
3459 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3460 // Specifically diagnose references to class templates that are missing
3461 // a template argument list.
3462 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3463 return ExprError();
3464 }
3465
3466 // Make sure that we're referring to a value.
3467 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3468 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3469 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3470 return ExprError();
3471 }
3472
3473 // Check whether this declaration can be used. Note that we suppress
3474 // this check when we're going to perform argument-dependent lookup
3475 // on this function name, because this might not be the function
3476 // that overload resolution actually selects.
3477 if (DiagnoseUseOfDecl(D, Locs: Loc))
3478 return ExprError();
3479
3480 auto *VD = cast<ValueDecl>(Val: D);
3481
3482 // Only create DeclRefExpr's for valid Decl's.
3483 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3484 return ExprError();
3485
3486 // Handle members of anonymous structs and unions. If we got here,
3487 // and the reference is to a class member indirect field, then this
3488 // must be the subject of a pointer-to-member expression.
3489 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3490 IndirectField && !IndirectField->isCXXClassMember())
3491 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3492 indirectField: IndirectField);
3493
3494 QualType type = VD->getType();
3495 if (type.isNull())
3496 return ExprError();
3497 ExprValueKind valueKind = VK_PRValue;
3498
3499 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3500 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3501 // is expanded by some outer '...' in the context of the use.
3502 type = type.getNonPackExpansionType();
3503
3504 switch (D->getKind()) {
3505 // Ignore all the non-ValueDecl kinds.
3506#define ABSTRACT_DECL(kind)
3507#define VALUE(type, base)
3508#define DECL(type, base) case Decl::type:
3509#include "clang/AST/DeclNodes.inc"
3510 llvm_unreachable("invalid value decl kind");
3511
3512 // These shouldn't make it here.
3513 case Decl::ObjCAtDefsField:
3514 llvm_unreachable("forming non-member reference to ivar?");
3515
3516 // Enum constants are always r-values and never references.
3517 // Unresolved using declarations are dependent.
3518 case Decl::EnumConstant:
3519 case Decl::UnresolvedUsingValue:
3520 case Decl::OMPDeclareReduction:
3521 case Decl::OMPDeclareMapper:
3522 valueKind = VK_PRValue;
3523 break;
3524
3525 // Fields and indirect fields that got here must be for
3526 // pointer-to-member expressions; we just call them l-values for
3527 // internal consistency, because this subexpression doesn't really
3528 // exist in the high-level semantics.
3529 case Decl::Field:
3530 case Decl::IndirectField:
3531 case Decl::ObjCIvar:
3532 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3533 "building reference to field in C?");
3534
3535 // These can't have reference type in well-formed programs, but
3536 // for internal consistency we do this anyway.
3537 type = type.getNonReferenceType();
3538 valueKind = VK_LValue;
3539 break;
3540
3541 // Non-type template parameters are either l-values or r-values
3542 // depending on the type.
3543 case Decl::NonTypeTemplateParm: {
3544 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3545 type = reftype->getPointeeType();
3546 valueKind = VK_LValue; // even if the parameter is an r-value reference
3547 break;
3548 }
3549
3550 // [expr.prim.id.unqual]p2:
3551 // If the entity is a template parameter object for a template
3552 // parameter of type T, the type of the expression is const T.
3553 // [...] The expression is an lvalue if the entity is a [...] template
3554 // parameter object.
3555 if (type->isRecordType()) {
3556 type = type.getUnqualifiedType().withConst();
3557 valueKind = VK_LValue;
3558 break;
3559 }
3560
3561 // For non-references, we need to strip qualifiers just in case
3562 // the template parameter was declared as 'const int' or whatever.
3563 valueKind = VK_PRValue;
3564 type = type.getUnqualifiedType();
3565 break;
3566 }
3567
3568 case Decl::Var:
3569 case Decl::VarTemplateSpecialization:
3570 case Decl::VarTemplatePartialSpecialization:
3571 case Decl::Decomposition:
3572 case Decl::Binding:
3573 case Decl::OMPCapturedExpr:
3574 // In C, "extern void blah;" is valid and is an r-value.
3575 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3576 type->isVoidType()) {
3577 valueKind = VK_PRValue;
3578 break;
3579 }
3580 [[fallthrough]];
3581
3582 case Decl::ImplicitParam:
3583 case Decl::ParmVar: {
3584 // These are always l-values.
3585 valueKind = VK_LValue;
3586 type = type.getNonReferenceType();
3587
3588 // FIXME: Does the addition of const really only apply in
3589 // potentially-evaluated contexts? Since the variable isn't actually
3590 // captured in an unevaluated context, it seems that the answer is no.
3591 if (!isUnevaluatedContext()) {
3592 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3593 if (!CapturedType.isNull())
3594 type = CapturedType;
3595 }
3596 break;
3597 }
3598
3599 case Decl::Function: {
3600 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3601 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3602 type = Context.BuiltinFnTy;
3603 valueKind = VK_PRValue;
3604 break;
3605 }
3606 }
3607
3608 const FunctionType *fty = type->castAs<FunctionType>();
3609
3610 // If we're referring to a function with an __unknown_anytype
3611 // result type, make the entire expression __unknown_anytype.
3612 if (fty->getReturnType() == Context.UnknownAnyTy) {
3613 type = Context.UnknownAnyTy;
3614 valueKind = VK_PRValue;
3615 break;
3616 }
3617
3618 // Functions are l-values in C++.
3619 if (getLangOpts().CPlusPlus) {
3620 valueKind = VK_LValue;
3621 break;
3622 }
3623
3624 // C99 DR 316 says that, if a function type comes from a
3625 // function definition (without a prototype), that type is only
3626 // used for checking compatibility. Therefore, when referencing
3627 // the function, we pretend that we don't have the full function
3628 // type.
3629 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3630 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3631 Info: fty->getExtInfo());
3632
3633 // Functions are r-values in C.
3634 valueKind = VK_PRValue;
3635 break;
3636 }
3637
3638 case Decl::CXXDeductionGuide:
3639 llvm_unreachable("building reference to deduction guide");
3640
3641 case Decl::MSProperty:
3642 case Decl::MSGuid:
3643 case Decl::TemplateParamObject:
3644 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3645 // capture in OpenMP, or duplicated between host and device?
3646 valueKind = VK_LValue;
3647 break;
3648
3649 case Decl::UnnamedGlobalConstant:
3650 valueKind = VK_LValue;
3651 break;
3652
3653 case Decl::CXXMethod:
3654 // If we're referring to a method with an __unknown_anytype
3655 // result type, make the entire expression __unknown_anytype.
3656 // This should only be possible with a type written directly.
3657 if (const FunctionProtoType *proto =
3658 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3659 if (proto->getReturnType() == Context.UnknownAnyTy) {
3660 type = Context.UnknownAnyTy;
3661 valueKind = VK_PRValue;
3662 break;
3663 }
3664
3665 // C++ methods are l-values if static, r-values if non-static.
3666 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3667 valueKind = VK_LValue;
3668 break;
3669 }
3670 [[fallthrough]];
3671
3672 case Decl::CXXConversion:
3673 case Decl::CXXDestructor:
3674 case Decl::CXXConstructor:
3675 valueKind = VK_PRValue;
3676 break;
3677 }
3678
3679 auto *E =
3680 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3681 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3682 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3683 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3684 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3685 // diagnostics).
3686 if (VD->isInvalidDecl() && E)
3687 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3688 if (isa<EnumConstantDecl>(Val: VD) && Context.getTargetInfo().getTriple().isBPF())
3689 return BPF().BuildPreserveAIEnumeratorRef(E);
3690 return E;
3691}
3692
3693static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3694 SmallString<32> &Target) {
3695 Target.resize(N: CharByteWidth * (Source.size() + 1));
3696 char *ResultPtr = &Target[0];
3697 const llvm::UTF8 *ErrorPtr;
3698 bool success =
3699 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3700 (void)success;
3701 assert(success);
3702 Target.resize(N: ResultPtr - &Target[0]);
3703}
3704
3705ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3706 PredefinedIdentKind IK) {
3707 Decl *currentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
3708 if (!currentDecl) {
3709 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3710 currentDecl = Context.getTranslationUnitDecl();
3711 }
3712
3713 QualType ResTy;
3714 StringLiteral *SL = nullptr;
3715 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3716 ResTy = Context.DependentTy;
3717 else {
3718 // Pre-defined identifiers are of type char[x], where x is the length of
3719 // the string.
3720 bool ForceElaboratedPrinting =
3721 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3722 auto Str =
3723 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3724 unsigned Length = Str.length();
3725
3726 llvm::APInt LengthI(32, Length + 1);
3727 if (IK == PredefinedIdentKind::LFunction ||
3728 IK == PredefinedIdentKind::LFuncSig) {
3729 ResTy =
3730 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3731 SmallString<32> RawChars;
3732 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3733 Source: Str, Target&: RawChars);
3734 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3735 ASM: ArraySizeModifier::Normal,
3736 /*IndexTypeQuals*/ 0);
3737 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3738 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3739 } else {
3740 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3741 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3742 ASM: ArraySizeModifier::Normal,
3743 /*IndexTypeQuals*/ 0);
3744 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3745 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3746 }
3747 }
3748
3749 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3750 SL);
3751}
3752
3753ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3754 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3755}
3756
3757ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3758 SmallString<16> CharBuffer;
3759 bool Invalid = false;
3760 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3761 if (Invalid)
3762 return ExprError();
3763
3764 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3765 PP, Tok.getKind());
3766 if (Literal.hadError())
3767 return ExprError();
3768
3769 QualType Ty;
3770 if (Literal.isWide())
3771 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3772 else if (Literal.isUTF8() && getLangOpts().C23)
3773 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3774 else if (Literal.isUTF8() && getLangOpts().Char8)
3775 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3776 else if (Literal.isUTF16())
3777 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3778 else if (Literal.isUTF32())
3779 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3780 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3781 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3782 else
3783 Ty = Context.CharTy; // 'x' -> char in C++;
3784 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3785
3786 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3787 if (Literal.isWide())
3788 Kind = CharacterLiteralKind::Wide;
3789 else if (Literal.isUTF16())
3790 Kind = CharacterLiteralKind::UTF16;
3791 else if (Literal.isUTF32())
3792 Kind = CharacterLiteralKind::UTF32;
3793 else if (Literal.isUTF8())
3794 Kind = CharacterLiteralKind::UTF8;
3795
3796 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3797 Tok.getLocation());
3798
3799 if (Literal.getUDSuffix().empty())
3800 return Lit;
3801
3802 // We're building a user-defined literal.
3803 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3804 SourceLocation UDSuffixLoc =
3805 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3806
3807 // Make sure we're allowed user-defined literals here.
3808 if (!UDLScope)
3809 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3810
3811 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3812 // operator "" X (ch)
3813 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3814 Args: Lit, LitEndLoc: Tok.getLocation());
3815}
3816
3817ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3818 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3819 return IntegerLiteral::Create(C: Context,
3820 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3821 type: Context.IntTy, l: Loc);
3822}
3823
3824ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3825 ExprResult Inner;
3826 if (getLangOpts().CPlusPlus) {
3827 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3828 } else {
3829 // C doesn't actually have a way to represent literal values of type
3830 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3831 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3832 Inner =
3833 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3834 }
3835 return Inner;
3836}
3837
3838static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3839 QualType Ty, SourceLocation Loc) {
3840 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3841
3842 using llvm::APFloat;
3843 APFloat Val(Format);
3844
3845 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3846 if (RM == llvm::RoundingMode::Dynamic)
3847 RM = llvm::RoundingMode::NearestTiesToEven;
3848 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3849
3850 // Overflow is always an error, but underflow is only an error if
3851 // we underflowed to zero (APFloat reports denormals as underflow).
3852 if ((result & APFloat::opOverflow) ||
3853 ((result & APFloat::opUnderflow) && Val.isZero())) {
3854 unsigned diagnostic;
3855 SmallString<20> buffer;
3856 if (result & APFloat::opOverflow) {
3857 diagnostic = diag::warn_float_overflow;
3858 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3859 } else {
3860 diagnostic = diag::warn_float_underflow;
3861 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3862 }
3863
3864 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3865 }
3866
3867 bool isExact = (result == APFloat::opOK);
3868 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3869}
3870
3871bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3872 assert(E && "Invalid expression");
3873
3874 if (E->isValueDependent())
3875 return false;
3876
3877 QualType QT = E->getType();
3878 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3879 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3880 return true;
3881 }
3882
3883 llvm::APSInt ValueAPS;
3884 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3885
3886 if (R.isInvalid())
3887 return true;
3888
3889 // GCC allows the value of unroll count to be 0.
3890 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3891 // "The values of 0 and 1 block any unrolling of the loop."
3892 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3893 // '#pragma unroll' cases.
3894 bool ValueIsPositive =
3895 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3896 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3897 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3898 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3899 return true;
3900 }
3901
3902 return false;
3903}
3904
3905ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3906 // Fast path for a single digit (which is quite common). A single digit
3907 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3908 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3909 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3910 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3911 }
3912
3913 SmallString<128> SpellingBuffer;
3914 // NumericLiteralParser wants to overread by one character. Add padding to
3915 // the buffer in case the token is copied to the buffer. If getSpelling()
3916 // returns a StringRef to the memory buffer, it should have a null char at
3917 // the EOF, so it is also safe.
3918 SpellingBuffer.resize(N: Tok.getLength() + 1);
3919
3920 // Get the spelling of the token, which eliminates trigraphs, etc.
3921 bool Invalid = false;
3922 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3923 if (Invalid)
3924 return ExprError();
3925
3926 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3927 PP.getSourceManager(), PP.getLangOpts(),
3928 PP.getTargetInfo(), PP.getDiagnostics());
3929 if (Literal.hadError)
3930 return ExprError();
3931
3932 if (Literal.hasUDSuffix()) {
3933 // We're building a user-defined literal.
3934 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3935 SourceLocation UDSuffixLoc =
3936 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3937
3938 // Make sure we're allowed user-defined literals here.
3939 if (!UDLScope)
3940 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3941
3942 QualType CookedTy;
3943 if (Literal.isFloatingLiteral()) {
3944 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3945 // long double, the literal is treated as a call of the form
3946 // operator "" X (f L)
3947 CookedTy = Context.LongDoubleTy;
3948 } else {
3949 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3950 // unsigned long long, the literal is treated as a call of the form
3951 // operator "" X (n ULL)
3952 CookedTy = Context.UnsignedLongLongTy;
3953 }
3954
3955 DeclarationName OpName =
3956 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3957 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3958 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3959
3960 SourceLocation TokLoc = Tok.getLocation();
3961
3962 // Perform literal operator lookup to determine if we're building a raw
3963 // literal or a cooked one.
3964 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3965 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3966 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3967 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3968 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3969 case LOLR_ErrorNoDiagnostic:
3970 // Lookup failure for imaginary constants isn't fatal, there's still the
3971 // GNU extension producing _Complex types.
3972 break;
3973 case LOLR_Error:
3974 return ExprError();
3975 case LOLR_Cooked: {
3976 Expr *Lit;
3977 if (Literal.isFloatingLiteral()) {
3978 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3979 } else {
3980 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3981 if (Literal.GetIntegerValue(Val&: ResultVal))
3982 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3983 << /* Unsigned */ 1;
3984 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3985 l: Tok.getLocation());
3986 }
3987 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3988 }
3989
3990 case LOLR_Raw: {
3991 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3992 // literal is treated as a call of the form
3993 // operator "" X ("n")
3994 unsigned Length = Literal.getUDSuffixOffset();
3995 QualType StrTy = Context.getConstantArrayType(
3996 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3997 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3998 Expr *Lit =
3999 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
4000 Kind: StringLiteralKind::Ordinary,
4001 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
4002 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
4003 }
4004
4005 case LOLR_Template: {
4006 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4007 // template), L is treated as a call fo the form
4008 // operator "" X <'c1', 'c2', ... 'ck'>()
4009 // where n is the source character sequence c1 c2 ... ck.
4010 TemplateArgumentListInfo ExplicitArgs;
4011 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
4012 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4013 llvm::APSInt Value(CharBits, CharIsUnsigned);
4014 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4015 Value = TokSpelling[I];
4016 TemplateArgument Arg(Context, Value, Context.CharTy);
4017 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
4018 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
4019 }
4020 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
4021 }
4022 case LOLR_StringTemplatePack:
4023 llvm_unreachable("unexpected literal operator lookup result");
4024 }
4025 }
4026
4027 Expr *Res;
4028
4029 if (Literal.isFixedPointLiteral()) {
4030 QualType Ty;
4031
4032 if (Literal.isAccum) {
4033 if (Literal.isHalf) {
4034 Ty = Context.ShortAccumTy;
4035 } else if (Literal.isLong) {
4036 Ty = Context.LongAccumTy;
4037 } else {
4038 Ty = Context.AccumTy;
4039 }
4040 } else if (Literal.isFract) {
4041 if (Literal.isHalf) {
4042 Ty = Context.ShortFractTy;
4043 } else if (Literal.isLong) {
4044 Ty = Context.LongFractTy;
4045 } else {
4046 Ty = Context.FractTy;
4047 }
4048 }
4049
4050 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
4051
4052 bool isSigned = !Literal.isUnsigned;
4053 unsigned scale = Context.getFixedPointScale(Ty);
4054 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4055
4056 llvm::APInt Val(bit_width, 0, isSigned);
4057 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
4058 bool ValIsZero = Val.isZero() && !Overflowed;
4059
4060 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4061 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4062 // Clause 6.4.4 - The value of a constant shall be in the range of
4063 // representable values for its type, with exception for constants of a
4064 // fract type with a value of exactly 1; such a constant shall denote
4065 // the maximal value for the type.
4066 --Val;
4067 else if (Val.ugt(RHS: MaxVal) || Overflowed)
4068 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
4069
4070 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4071 l: Tok.getLocation(), Scale: scale);
4072 } else if (Literal.isFloatingLiteral()) {
4073 QualType Ty;
4074 if (Literal.isHalf){
4075 if (getLangOpts().HLSL ||
4076 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4077 Ty = Context.HalfTy;
4078 else {
4079 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4080 return ExprError();
4081 }
4082 } else if (Literal.isFloat)
4083 Ty = Context.FloatTy;
4084 else if (Literal.isLong)
4085 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4086 else if (Literal.isFloat16)
4087 Ty = Context.Float16Ty;
4088 else if (Literal.isFloat128)
4089 Ty = Context.Float128Ty;
4090 else if (getLangOpts().HLSL)
4091 Ty = Context.FloatTy;
4092 else
4093 Ty = Context.DoubleTy;
4094
4095 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4096
4097 if (Ty == Context.DoubleTy) {
4098 if (getLangOpts().SinglePrecisionConstants) {
4099 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4100 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4101 }
4102 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4103 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4104 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4105 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4106 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4107 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4108 }
4109 }
4110 } else if (!Literal.isIntegerLiteral()) {
4111 return ExprError();
4112 } else {
4113 QualType Ty;
4114
4115 // 'z/uz' literals are a C++23 feature.
4116 if (Literal.isSizeT) {
4117 if (getLangOpts().CPlusPlus)
4118 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::size_t_suffix);
4119 else
4120 Diag(Loc: Tok.getLocation(), DiagID: diag::err_cxx23_size_t_suffix);
4121 }
4122
4123 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4124 // but we do not currently support the suffix in C++ mode because it's not
4125 // entirely clear whether WG21 will prefer this suffix to return a library
4126 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4127 // literals are a C++ extension.
4128 if (Literal.isBitInt)
4129 PP.Diag(Loc: Tok.getLocation(),
4130 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4131 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4132 : diag::ext_c23_bitint_suffix);
4133
4134 // Get the value in the widest-possible width. What is "widest" depends on
4135 // whether the literal is a bit-precise integer or not. For a bit-precise
4136 // integer type, try to scan the source to determine how many bits are
4137 // needed to represent the value. This may seem a bit expensive, but trying
4138 // to get the integer value from an overly-wide APInt is *extremely*
4139 // expensive, so the naive approach of assuming
4140 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4141 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4142 if (Literal.isBitInt)
4143 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4144 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4145 if (Literal.MicrosoftInteger) {
4146 if (Literal.MicrosoftInteger == 128 &&
4147 !Context.getTargetInfo().hasInt128Type())
4148 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4149 << Literal.isUnsigned;
4150 BitsNeeded = std::max<unsigned>(a: BitsNeeded, b: Literal.MicrosoftInteger);
4151 }
4152
4153 llvm::APInt ResultVal(BitsNeeded, 0);
4154
4155 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4156 // If this value didn't fit into uintmax_t, error and force to ull.
4157 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4158 << /* Unsigned */ 1;
4159 Ty = Context.UnsignedLongLongTy;
4160 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4161 "long long is not intmax_t?");
4162 } else {
4163 // If this value fits into a ULL, try to figure out what else it fits into
4164 // according to the rules of C99 6.4.4.1p5.
4165
4166 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4167 // be an unsigned int.
4168 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4169
4170 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4171 // suffix for portability of code with C++, but both `l` and `ll` are
4172 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4173 // same.
4174 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4175 Literal.isLong = true;
4176 Literal.isLongLong = false;
4177 }
4178
4179 // Check from smallest to largest, picking the smallest type we can.
4180 unsigned Width = 0;
4181
4182 // Microsoft specific integer suffixes are explicitly sized.
4183 if (Literal.MicrosoftInteger) {
4184 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4185 Width = 8;
4186 Ty = Context.CharTy;
4187 } else {
4188 Width = Literal.MicrosoftInteger;
4189 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4190 /*Signed=*/!Literal.isUnsigned);
4191 }
4192 // To maintain consistency with MSVC, we chose to truncate directly
4193 // without issuing any warnings.
4194 ResultVal = ResultVal.zextOrTrunc(width: Width);
4195 }
4196
4197 // Bit-precise integer literals are automagically-sized based on the
4198 // width required by the literal.
4199 if (Literal.isBitInt) {
4200 // The signed version has one more bit for the sign value. There are no
4201 // zero-width bit-precise integers, even if the literal value is 0.
4202 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4203 (Literal.isUnsigned ? 0u : 1u);
4204
4205 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4206 // and reset the type to the largest supported width.
4207 unsigned int MaxBitIntWidth =
4208 Context.getTargetInfo().getMaxBitIntWidth();
4209 if (Width > MaxBitIntWidth) {
4210 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4211 << Literal.isUnsigned;
4212 Width = MaxBitIntWidth;
4213 }
4214
4215 // Reset the result value to the smaller APInt and select the correct
4216 // type to be used. Note, we zext even for signed values because the
4217 // literal itself is always an unsigned value (a preceeding - is a
4218 // unary operator, not part of the literal).
4219 ResultVal = ResultVal.zextOrTrunc(width: Width);
4220 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4221 }
4222
4223 // Check C++23 size_t literals.
4224 if (Literal.isSizeT) {
4225 assert(!Literal.MicrosoftInteger &&
4226 "size_t literals can't be Microsoft literals");
4227 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4228 T: Context.getTargetInfo().getSizeType());
4229
4230 // Does it fit in size_t?
4231 if (ResultVal.isIntN(N: SizeTSize)) {
4232 // Does it fit in ssize_t?
4233 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4234 Ty = Context.getSignedSizeType();
4235 else if (AllowUnsigned)
4236 Ty = Context.getSizeType();
4237 Width = SizeTSize;
4238 }
4239 }
4240
4241 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4242 !Literal.isSizeT) {
4243 // Are int/unsigned possibilities?
4244 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4245
4246 // Does it fit in a unsigned int?
4247 if (ResultVal.isIntN(N: IntSize)) {
4248 // Does it fit in a signed int?
4249 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4250 Ty = Context.IntTy;
4251 else if (AllowUnsigned)
4252 Ty = Context.UnsignedIntTy;
4253 Width = IntSize;
4254 }
4255 }
4256
4257 // Are long/unsigned long possibilities?
4258 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4259 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4260
4261 // Does it fit in a unsigned long?
4262 if (ResultVal.isIntN(N: LongSize)) {
4263 // Does it fit in a signed long?
4264 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4265 Ty = Context.LongTy;
4266 else if (AllowUnsigned)
4267 Ty = Context.UnsignedLongTy;
4268 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4269 // is compatible.
4270 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4271 const unsigned LongLongSize =
4272 Context.getTargetInfo().getLongLongWidth();
4273 Diag(Loc: Tok.getLocation(),
4274 DiagID: getLangOpts().CPlusPlus
4275 ? Literal.isLong
4276 ? diag::warn_old_implicitly_unsigned_long_cxx
4277 : /*C++98 UB*/ diag::
4278 ext_old_implicitly_unsigned_long_cxx
4279 : diag::warn_old_implicitly_unsigned_long)
4280 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4281 : /*will be ill-formed*/ 1);
4282 Ty = Context.UnsignedLongTy;
4283 }
4284 Width = LongSize;
4285 }
4286 }
4287
4288 // Check long long if needed.
4289 if (Ty.isNull() && !Literal.isSizeT) {
4290 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4291
4292 // Does it fit in a unsigned long long?
4293 if (ResultVal.isIntN(N: LongLongSize)) {
4294 // Does it fit in a signed long long?
4295 // To be compatible with MSVC, hex integer literals ending with the
4296 // LL or i64 suffix are always signed in Microsoft mode.
4297 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4298 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4299 Ty = Context.LongLongTy;
4300 else if (AllowUnsigned)
4301 Ty = Context.UnsignedLongLongTy;
4302 Width = LongLongSize;
4303
4304 // 'long long' is a C99 or C++11 feature, whether the literal
4305 // explicitly specified 'long long' or we needed the extra width.
4306 if (getLangOpts().CPlusPlus)
4307 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4308 ? diag::warn_cxx98_compat_longlong
4309 : diag::ext_cxx11_longlong);
4310 else if (!getLangOpts().C99)
4311 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4312 }
4313 }
4314
4315 // If we still couldn't decide a type, we either have 'size_t' literal
4316 // that is out of range, or a decimal literal that does not fit in a
4317 // signed long long and has no U suffix.
4318 if (Ty.isNull()) {
4319 if (Literal.isSizeT)
4320 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4321 << Literal.isUnsigned;
4322 else
4323 Diag(Loc: Tok.getLocation(),
4324 DiagID: diag::ext_integer_literal_too_large_for_signed);
4325 Ty = Context.UnsignedLongLongTy;
4326 Width = Context.getTargetInfo().getLongLongWidth();
4327 }
4328
4329 if (ResultVal.getBitWidth() != Width)
4330 ResultVal = ResultVal.trunc(width: Width);
4331 }
4332 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4333 }
4334
4335 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4336 if (Literal.isImaginary) {
4337 Res = new (Context) ImaginaryLiteral(Res,
4338 Context.getComplexType(T: Res->getType()));
4339
4340 // In C++, this is a GNU extension. In C, it's a C2y extension.
4341 if (getLangOpts().CPlusPlus)
4342 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_gnu_imaginary_constant);
4343 else
4344 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::imaginary_constant);
4345 }
4346 return Res;
4347}
4348
4349ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4350 assert(E && "ActOnParenExpr() missing expr");
4351 QualType ExprTy = E->getType();
4352 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4353 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4354 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4355 return new (Context) ParenExpr(L, R, E);
4356}
4357
4358static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4359 SourceLocation Loc,
4360 SourceRange ArgRange) {
4361 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4362 // scalar or vector data type argument..."
4363 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4364 // type (C99 6.2.5p18) or void.
4365 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4366 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4367 << T << ArgRange;
4368 return true;
4369 }
4370
4371 assert((T->isVoidType() || !T->isIncompleteType()) &&
4372 "Scalar types should always be complete");
4373 return false;
4374}
4375
4376static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4377 SourceLocation Loc,
4378 SourceRange ArgRange) {
4379 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4380 if (!T->isVectorType() && !T->isSizelessVectorType())
4381 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4382 << ""
4383 << "__builtin_vectorelements" << T << ArgRange;
4384
4385 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4386 if (T->isSVESizelessBuiltinType()) {
4387 llvm::StringMap<bool> CallerFeatureMap;
4388 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4389 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4390 }
4391 }
4392
4393 return false;
4394}
4395
4396static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4397 SourceLocation Loc,
4398 SourceRange ArgRange) {
4399 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4400 return true;
4401
4402 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4403 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4404 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4405 return true;
4406 }
4407
4408 return false;
4409}
4410
4411static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4412 SourceLocation Loc,
4413 SourceRange ArgRange,
4414 UnaryExprOrTypeTrait TraitKind) {
4415 // Invalid types must be hard errors for SFINAE in C++.
4416 if (S.LangOpts.CPlusPlus)
4417 return true;
4418
4419 // C99 6.5.3.4p1:
4420 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4421 TraitKind == UETT_PreferredAlignOf) {
4422
4423 // sizeof(function)/alignof(function) is allowed as an extension.
4424 if (T->isFunctionType()) {
4425 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4426 << getTraitSpelling(T: TraitKind) << ArgRange;
4427 return false;
4428 }
4429
4430 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4431 // this is an error (OpenCL v1.1 s6.3.k)
4432 if (T->isVoidType()) {
4433 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4434 : diag::ext_sizeof_alignof_void_type;
4435 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4436 return false;
4437 }
4438 }
4439 return true;
4440}
4441
4442static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4443 SourceLocation Loc,
4444 SourceRange ArgRange,
4445 UnaryExprOrTypeTrait TraitKind) {
4446 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4447 // runtime doesn't allow it.
4448 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4449 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4450 << T << (TraitKind == UETT_SizeOf)
4451 << ArgRange;
4452 return true;
4453 }
4454
4455 return false;
4456}
4457
4458/// Check whether E is a pointer from a decayed array type (the decayed
4459/// pointer type is equal to T) and emit a warning if it is.
4460static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4461 const Expr *E) {
4462 // Don't warn if the operation changed the type.
4463 if (T != E->getType())
4464 return;
4465
4466 // Now look for array decays.
4467 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4468 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4469 return;
4470
4471 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4472 << ICE->getType()
4473 << ICE->getSubExpr()->getType();
4474}
4475
4476bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4477 UnaryExprOrTypeTrait ExprKind) {
4478 QualType ExprTy = E->getType();
4479 assert(!ExprTy->isReferenceType());
4480
4481 bool IsUnevaluatedOperand =
4482 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4483 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4484 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4485 if (IsUnevaluatedOperand) {
4486 ExprResult Result = CheckUnevaluatedOperand(E);
4487 if (Result.isInvalid())
4488 return true;
4489 E = Result.get();
4490 }
4491
4492 // The operand for sizeof and alignof is in an unevaluated expression context,
4493 // so side effects could result in unintended consequences.
4494 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4495 // used to build SFINAE gadgets.
4496 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4497 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4498 !E->isInstantiationDependent() &&
4499 !E->getType()->isVariableArrayType() &&
4500 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4501 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4502
4503 if (ExprKind == UETT_VecStep)
4504 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4505 ArgRange: E->getSourceRange());
4506
4507 if (ExprKind == UETT_VectorElements)
4508 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4509 ArgRange: E->getSourceRange());
4510
4511 // Explicitly list some types as extensions.
4512 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4513 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4514 return false;
4515
4516 // WebAssembly tables are always illegal operands to unary expressions and
4517 // type traits.
4518 if (Context.getTargetInfo().getTriple().isWasm() &&
4519 E->getType()->isWebAssemblyTableType()) {
4520 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4521 << getTraitSpelling(T: ExprKind);
4522 return true;
4523 }
4524
4525 // 'alignof' applied to an expression only requires the base element type of
4526 // the expression to be complete. 'sizeof' requires the expression's type to
4527 // be complete (and will attempt to complete it if it's an array of unknown
4528 // bound).
4529 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4530 if (RequireCompleteSizedType(
4531 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4532 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4533 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4534 return true;
4535 } else {
4536 if (RequireCompleteSizedExprType(
4537 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4538 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4539 return true;
4540 }
4541
4542 // Completing the expression's type may have changed it.
4543 ExprTy = E->getType();
4544 assert(!ExprTy->isReferenceType());
4545
4546 if (ExprTy->isFunctionType()) {
4547 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4548 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4549 return true;
4550 }
4551
4552 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4553 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4554 return true;
4555
4556 if (ExprKind == UETT_CountOf) {
4557 // The type has to be an array type. We already checked for incomplete
4558 // types above.
4559 QualType ExprType = E->IgnoreParens()->getType();
4560 if (!ExprType->isArrayType()) {
4561 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4562 return true;
4563 }
4564 // FIXME: warn on _Countof on an array parameter. Not warning on it
4565 // currently because there are papers in WG14 about array types which do
4566 // not decay that could impact this behavior, so we want to see if anything
4567 // changes here before coming up with a warning group for _Countof-related
4568 // diagnostics.
4569 }
4570
4571 if (ExprKind == UETT_SizeOf) {
4572 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4573 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4574 QualType OType = PVD->getOriginalType();
4575 QualType Type = PVD->getType();
4576 if (Type->isPointerType() && OType->isArrayType()) {
4577 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4578 << Type << OType;
4579 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4580 }
4581 }
4582 }
4583
4584 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4585 // decays into a pointer and returns an unintended result. This is most
4586 // likely a typo for "sizeof(array) op x".
4587 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4588 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4589 E: BO->getLHS());
4590 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4591 E: BO->getRHS());
4592 }
4593 }
4594
4595 return false;
4596}
4597
4598static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4599 // Cannot know anything else if the expression is dependent.
4600 if (E->isTypeDependent())
4601 return false;
4602
4603 if (E->getObjectKind() == OK_BitField) {
4604 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4605 << 1 << E->getSourceRange();
4606 return true;
4607 }
4608
4609 ValueDecl *D = nullptr;
4610 Expr *Inner = E->IgnoreParens();
4611 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4612 D = DRE->getDecl();
4613 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4614 D = ME->getMemberDecl();
4615 }
4616
4617 // If it's a field, require the containing struct to have a
4618 // complete definition so that we can compute the layout.
4619 //
4620 // This can happen in C++11 onwards, either by naming the member
4621 // in a way that is not transformed into a member access expression
4622 // (in an unevaluated operand, for instance), or by naming the member
4623 // in a trailing-return-type.
4624 //
4625 // For the record, since __alignof__ on expressions is a GCC
4626 // extension, GCC seems to permit this but always gives the
4627 // nonsensical answer 0.
4628 //
4629 // We don't really need the layout here --- we could instead just
4630 // directly check for all the appropriate alignment-lowing
4631 // attributes --- but that would require duplicating a lot of
4632 // logic that just isn't worth duplicating for such a marginal
4633 // use-case.
4634 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4635 // Fast path this check, since we at least know the record has a
4636 // definition if we can find a member of it.
4637 if (!FD->getParent()->isCompleteDefinition()) {
4638 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4639 << E->getSourceRange();
4640 return true;
4641 }
4642
4643 // Otherwise, if it's a field, and the field doesn't have
4644 // reference type, then it must have a complete type (or be a
4645 // flexible array member, which we explicitly want to
4646 // white-list anyway), which makes the following checks trivial.
4647 if (!FD->getType()->isReferenceType())
4648 return false;
4649 }
4650
4651 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4652}
4653
4654bool Sema::CheckVecStepExpr(Expr *E) {
4655 E = E->IgnoreParens();
4656
4657 // Cannot know anything else if the expression is dependent.
4658 if (E->isTypeDependent())
4659 return false;
4660
4661 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4662}
4663
4664/// Walk down into the variably modified type \p T and call \p Fn for each
4665/// variable length array type in it.
4666static void forEachVariableArrayType(
4667 ASTContext &Context, QualType T,
4668 llvm::function_ref<void(const VariableArrayType *)> Fn) {
4669 assert(T->isVariablyModifiedType());
4670
4671 // We're going to walk down into the type and look for VLA expressions.
4672 do {
4673 const Type *Ty = T.getTypePtr();
4674 switch (Ty->getTypeClass()) {
4675#define TYPE(Class, Base)
4676#define ABSTRACT_TYPE(Class, Base)
4677#define NON_CANONICAL_TYPE(Class, Base)
4678#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4679#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4680#include "clang/AST/TypeNodes.inc"
4681 T = QualType();
4682 break;
4683 // These types are never variably-modified.
4684 case Type::Builtin:
4685 case Type::Complex:
4686 case Type::Vector:
4687 case Type::ExtVector:
4688 case Type::ConstantMatrix:
4689 case Type::Record:
4690 case Type::Enum:
4691 case Type::TemplateSpecialization:
4692 case Type::ObjCObject:
4693 case Type::ObjCInterface:
4694 case Type::ObjCObjectPointer:
4695 case Type::ObjCTypeParam:
4696 case Type::Pipe:
4697 case Type::BitInt:
4698 case Type::HLSLInlineSpirv:
4699 llvm_unreachable("type class is never variably-modified!");
4700 case Type::Adjusted:
4701 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4702 break;
4703 case Type::Decayed:
4704 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4705 break;
4706 case Type::ArrayParameter:
4707 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4708 break;
4709 case Type::Pointer:
4710 T = cast<PointerType>(Val: Ty)->getPointeeType();
4711 break;
4712 case Type::BlockPointer:
4713 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4714 break;
4715 case Type::LValueReference:
4716 case Type::RValueReference:
4717 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4718 break;
4719 case Type::MemberPointer:
4720 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4721 break;
4722 case Type::ConstantArray:
4723 case Type::IncompleteArray:
4724 // Losing element qualification here is fine.
4725 T = cast<ArrayType>(Val: Ty)->getElementType();
4726 break;
4727 case Type::VariableArray: {
4728 // Losing element qualification here is fine.
4729 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4730 Fn(VAT);
4731 T = VAT->getElementType();
4732 break;
4733 }
4734 case Type::FunctionProto:
4735 case Type::FunctionNoProto:
4736 T = cast<FunctionType>(Val: Ty)->getReturnType();
4737 break;
4738 case Type::Paren:
4739 case Type::TypeOf:
4740 case Type::UnaryTransform:
4741 case Type::Attributed:
4742 case Type::BTFTagAttributed:
4743 case Type::OverflowBehavior:
4744 case Type::HLSLAttributedResource:
4745 case Type::SubstTemplateTypeParm:
4746 case Type::MacroQualified:
4747 case Type::CountAttributed:
4748 case Type::LateParsedAttr:
4749 // Keep walking after single level desugaring.
4750 T = T.getSingleStepDesugaredType(Context);
4751 break;
4752 case Type::Typedef:
4753 T = cast<TypedefType>(Val: Ty)->desugar();
4754 break;
4755 case Type::Decltype:
4756 T = cast<DecltypeType>(Val: Ty)->desugar();
4757 break;
4758 case Type::PackIndexing:
4759 T = cast<PackIndexingType>(Val: Ty)->desugar();
4760 break;
4761 case Type::Using:
4762 T = cast<UsingType>(Val: Ty)->desugar();
4763 break;
4764 case Type::Auto:
4765 case Type::DeducedTemplateSpecialization:
4766 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4767 break;
4768 case Type::TypeOfExpr:
4769 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4770 break;
4771 case Type::Atomic:
4772 T = cast<AtomicType>(Val: Ty)->getValueType();
4773 break;
4774 case Type::PredefinedSugar:
4775 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4776 break;
4777 }
4778 } while (!T.isNull() && T->isVariablyModifiedType());
4779}
4780
4781static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4782 CapturingScopeInfo *CSI) {
4783 assert(CSI != nullptr);
4784 forEachVariableArrayType(Context, T, Fn: [&](const VariableArrayType *VAT) {
4785 // Unknown size indication requires no size computation.
4786 // Otherwise, evaluate and record it.
4787 auto Size = VAT->getSizeExpr();
4788 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4789 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4790 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4791 });
4792}
4793
4794/// Find the capturing scope that is being built for the lambda call operator
4795/// or captured declaration \p DC, if any.
4796static CapturingScopeInfo *
4797findCapturingScope(ArrayRef<FunctionScopeInfo *> Scopes,
4798 const DeclContext *DC) {
4799 for (FunctionScopeInfo *FSI : llvm::reverse(C&: Scopes)) {
4800 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI);
4801 LSI && LSI->CallOperator == DC)
4802 return LSI;
4803 if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: FSI);
4804 CRSI && CRSI->TheCapturedDecl == DC)
4805 return CRSI;
4806 }
4807 return nullptr;
4808}
4809
4810bool Sema::CheckVariablyModifiedTypeUse(QualType T, SourceLocation Loc) {
4811 if (VLASizeExprOwners.empty() || T.isNull())
4812 return true;
4813 // Default arguments and default member initializers are evaluated where
4814 // they are used, and unevaluated operands are not evaluated at all.
4815 if (isUnevaluatedContext() || isCheckingDefaultArgumentOrInitializer())
4816 return true;
4817 // FIXME: DeducedType drops the variably modified bit of the deduced type
4818 // (auto, __auto_type), so look at the canonical type.
4819 QualType CanonT = T.getCanonicalType();
4820 if (!CanonT->isVariablyModifiedType())
4821 return true;
4822
4823 const Expr *BadSize = nullptr;
4824 unsigned BadKind = 0;
4825 forEachVariableArrayType(Context, T: CanonT, Fn: [&](const VariableArrayType *VAT) {
4826 const Expr *Size = VAT->getSizeExpr();
4827 if (BadSize || !Size)
4828 return;
4829 auto It = VLASizeExprOwners.find(Val: Size);
4830 if (It == VLASizeExprOwners.end())
4831 return;
4832
4833 // Walk from the use to the context in which the bound is evaluated.
4834 // Lambdas and captured regions on the way capture the bound; a local
4835 // class or a block cannot see it.
4836 SmallVector<CapturingScopeInfo *, 2> Capturers;
4837 std::optional<unsigned> Barrier;
4838 const DeclContext *DC = CurContext;
4839 for (; DC && DC != It->second; DC = DC->getParent()) {
4840 if (isLambdaCallOperator(DC) || isa<CapturedDecl>(Val: DC)) {
4841 if (CapturingScopeInfo *CSI = findCapturingScope(Scopes: FunctionScopes, DC))
4842 Capturers.push_back(Elt: CSI);
4843 } else if (isa<BlockDecl>(Val: DC)) {
4844 Barrier = Barrier.value_or(u: 1);
4845 } else if (const auto *RD = dyn_cast<RecordDecl>(Val: DC)) {
4846 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: RD);
4847 !CRD || !CRD->isLambda())
4848 Barrier = Barrier.value_or(u: 0);
4849 }
4850 }
4851 // Nothing to do if the bound is not evaluated in an enclosing context.
4852 if (!DC)
4853 return;
4854 if (Barrier) {
4855 BadSize = Size;
4856 BadKind = *Barrier;
4857 return;
4858 }
4859 // VAT is a canonical type; the bound may already have been captured
4860 // through a different type node with the same size expression.
4861 for (CapturingScopeInfo *CSI : Capturers)
4862 if (llvm::none_of(Range&: CSI->Captures, P: [&](const Capture &C) {
4863 return C.isVLATypeCapture() &&
4864 C.getCapturedVLAType()->getSizeExpr() == Size;
4865 }))
4866 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4867 });
4868 if (!BadSize)
4869 return true;
4870
4871 // A typedef naming such a type has already been diagnosed.
4872 if (const auto *TT = T->getAs<TypedefType>();
4873 TT && TT->getDecl()->isInvalidDecl())
4874 return false;
4875
4876 Diag(Loc, DiagID: diag::err_vm_type_from_enclosing_function) << T << BadKind;
4877 Diag(Loc: BadSize->getBeginLoc(), DiagID: diag::note_vm_type_size_evaluated_here);
4878 return false;
4879}
4880
4881bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4882 SourceLocation OpLoc,
4883 SourceRange ExprRange,
4884 UnaryExprOrTypeTrait ExprKind,
4885 StringRef KWName) {
4886 if (ExprType->isDependentType())
4887 return false;
4888
4889 // These builtins evaluate with the operand type as written; a reference is
4890 // not looked through.
4891 if (ExprKind == UETT_VectorElements)
4892 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4893 ArgRange: ExprRange);
4894 if (ExprKind == UETT_VecStep)
4895 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4896 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4897 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4898 ArgRange: ExprRange);
4899
4900 // C++ [expr.sizeof]p2:
4901 // When applied to a reference or a reference type, the result
4902 // is the size of the referenced type.
4903 // C++11 [expr.alignof]p3:
4904 // When alignof is applied to a reference type, the result
4905 // shall be the alignment of the referenced type.
4906 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4907 ExprType = Ref->getPointeeType();
4908
4909 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4910 // When alignof or _Alignof is applied to an array type, the result
4911 // is the alignment of the element type.
4912 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4913 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4914 // If the trait is 'alignof' in C before C2y, the ability to apply the
4915 // trait to an incomplete array is an extension.
4916 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4917 ExprType->isIncompleteArrayType())
4918 DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::alignof_incomplete_array);
4919 ExprType = Context.getBaseElementType(QT: ExprType);
4920 }
4921
4922 // Explicitly list some types as extensions.
4923 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4924 TraitKind: ExprKind))
4925 return false;
4926
4927 if (RequireCompleteSizedType(
4928 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4929 Args: KWName, Args: ExprRange))
4930 return true;
4931
4932 if (ExprType->isFunctionType()) {
4933 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4934 return true;
4935 }
4936
4937 if (ExprKind == UETT_CountOf) {
4938 // The type has to be an array type. We already checked for incomplete
4939 // types above.
4940 if (!ExprType->isArrayType()) {
4941 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4942 return true;
4943 }
4944 }
4945
4946 // WebAssembly tables are always illegal operands to unary expressions and
4947 // type traits.
4948 if (Context.getTargetInfo().getTriple().isWasm() &&
4949 ExprType->isWebAssemblyTableType()) {
4950 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4951 << getTraitSpelling(T: ExprKind);
4952 return true;
4953 }
4954
4955 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4956 TraitKind: ExprKind))
4957 return true;
4958
4959 return false;
4960}
4961
4962ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4963 SourceLocation OpLoc,
4964 UnaryExprOrTypeTrait ExprKind,
4965 SourceRange R) {
4966 if (!TInfo)
4967 return ExprError();
4968
4969 QualType T = TInfo->getType();
4970
4971 if (!T->isDependentType() &&
4972 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4973 KWName: getTraitSpelling(T: ExprKind)))
4974 return ExprError();
4975
4976 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4977 // properly deal with VLAs in nested calls of sizeof and typeof.
4978 if (currentEvaluationContext().isUnevaluated() &&
4979 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4980 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4981 TInfo->getType()->isVariablyModifiedType())
4982 TInfo = TransformToPotentiallyEvaluated(TInfo);
4983
4984 // It's possible that the transformation above failed.
4985 if (!TInfo)
4986 return ExprError();
4987
4988 if (!TInfo->getType()->isDependentType()) {
4989 // The operand of sizeof is parsed in an unevaluated context, but a
4990 // variably modified operand is evaluated if the sizeof itself is.
4991 // FIXME: TransformToPotentiallyEvaluated() above should take care of this,
4992 // but it only runs if an array bound is written inside the sizeof, not
4993 // whenever the sizeof is potentially evaluated.
4994 std::optional<EnterExpressionEvaluationContext> Evaluated;
4995 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4996 isUnevaluatedContext())
4997 Evaluated.emplace(args&: *this, args&: parentEvaluationContext().Context);
4998 if (!CheckVariablyModifiedTypeUse(T: TInfo->getType(), Loc: OpLoc))
4999 return ExprError();
5000 }
5001
5002 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
5003 return new (Context) UnaryExprOrTypeTraitExpr(
5004 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
5005}
5006
5007ExprResult
5008Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5009 UnaryExprOrTypeTrait ExprKind) {
5010 ExprResult PE = CheckPlaceholderExpr(E);
5011 if (PE.isInvalid())
5012 return ExprError();
5013
5014 E = PE.get();
5015
5016 // Verify that the operand is valid.
5017 bool isInvalid = false;
5018 if (E->isTypeDependent()) {
5019 // Delay type-checking for type-dependent expressions.
5020 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
5021 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
5022 } else if (ExprKind == UETT_VecStep) {
5023 isInvalid = CheckVecStepExpr(E);
5024 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
5025 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
5026 isInvalid = true;
5027 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
5028 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
5029 isInvalid = true;
5030 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
5031 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
5032 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
5033 }
5034
5035 if (isInvalid)
5036 return ExprError();
5037
5038 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
5039 E->getType()->isVariableArrayType()) {
5040 PE = TransformToPotentiallyEvaluated(E);
5041 if (PE.isInvalid()) return ExprError();
5042 E = PE.get();
5043 }
5044
5045 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
5046 return new (Context) UnaryExprOrTypeTraitExpr(
5047 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
5048}
5049
5050ExprResult
5051Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5052 UnaryExprOrTypeTrait ExprKind, bool IsType,
5053 void *TyOrEx, SourceRange ArgRange) {
5054 // If error parsing type, ignore.
5055 if (!TyOrEx) return ExprError();
5056
5057 if (IsType) {
5058 TypeSourceInfo *TInfo;
5059 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
5060 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
5061 }
5062
5063 Expr *ArgEx = (Expr *)TyOrEx;
5064 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
5065 return Result;
5066}
5067
5068bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
5069 SourceLocation OpLoc, SourceRange R) {
5070 if (!TInfo)
5071 return true;
5072 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
5073 ExprKind: UETT_AlignOf, KWName);
5074}
5075
5076bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
5077 SourceLocation OpLoc, SourceRange R) {
5078 TypeSourceInfo *TInfo;
5079 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
5080 TInfo: &TInfo);
5081 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
5082}
5083
5084static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
5085 bool IsReal) {
5086 if (V.get()->isTypeDependent())
5087 return S.Context.DependentTy;
5088
5089 // _Real and _Imag are only l-values for normal l-values.
5090 if (V.get()->getObjectKind() != OK_Ordinary) {
5091 V = S.DefaultLvalueConversion(E: V.get());
5092 if (V.isInvalid())
5093 return QualType();
5094 }
5095
5096 // These operators return the element type of a complex type.
5097 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5098 return CT->getElementType();
5099
5100 // Otherwise they pass through real integer and floating point types here.
5101 if (V.get()->getType()->isArithmeticType())
5102 return V.get()->getType();
5103
5104 // Test for placeholders.
5105 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
5106 if (PR.isInvalid()) return QualType();
5107 if (PR.get() != V.get()) {
5108 V = PR;
5109 return CheckRealImagOperand(S, V, Loc, IsReal);
5110 }
5111
5112 // Reject anything else.
5113 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
5114 << (IsReal ? "__real" : "__imag");
5115 return QualType();
5116}
5117
5118
5119
5120ExprResult
5121Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5122 tok::TokenKind Kind, Expr *Input) {
5123 UnaryOperatorKind Opc;
5124 switch (Kind) {
5125 default: llvm_unreachable("Unknown unary op!");
5126 case tok::plusplus: Opc = UO_PostInc; break;
5127 case tok::minusminus: Opc = UO_PostDec; break;
5128 }
5129
5130 // Since this might is a postfix expression, get rid of ParenListExprs.
5131 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
5132 if (Result.isInvalid()) return ExprError();
5133 Input = Result.get();
5134
5135 return BuildUnaryOp(S, OpLoc, Opc, Input);
5136}
5137
5138/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5139///
5140/// \return true on error
5141static bool checkArithmeticOnObjCPointer(Sema &S,
5142 SourceLocation opLoc,
5143 Expr *op) {
5144 assert(op->getType()->isObjCObjectPointerType());
5145 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5146 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5147 return false;
5148
5149 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
5150 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5151 << op->getSourceRange();
5152 return true;
5153}
5154
5155static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5156 auto *BaseNoParens = Base->IgnoreParens();
5157 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5158 return MSProp->getPropertyDecl()->getType()->isArrayType();
5159 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
5160}
5161
5162// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5163// Typically this is DependentTy, but can sometimes be more precise.
5164//
5165// There are cases when we could determine a non-dependent type:
5166// - LHS and RHS may have non-dependent types despite being type-dependent
5167// (e.g. unbounded array static members of the current instantiation)
5168// - one may be a dependent-sized array with known element type
5169// - one may be a dependent-typed valid index (enum in current instantiation)
5170//
5171// We *always* return a dependent type, in such cases it is DependentTy.
5172// This avoids creating type-dependent expressions with non-dependent types.
5173// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5174static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5175 const ASTContext &Ctx) {
5176 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5177 QualType LTy = LHS->getType(), RTy = RHS->getType();
5178 QualType Result = Ctx.DependentTy;
5179 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5180 if (const PointerType *PT = LTy->getAs<PointerType>())
5181 Result = PT->getPointeeType();
5182 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5183 Result = AT->getElementType();
5184 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5185 if (const PointerType *PT = RTy->getAs<PointerType>())
5186 Result = PT->getPointeeType();
5187 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5188 Result = AT->getElementType();
5189 }
5190 // Ensure we return a dependent type.
5191 return Result->isDependentType() ? Result : Ctx.DependentTy;
5192}
5193
5194ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5195 SourceLocation lbLoc,
5196 MultiExprArg ArgExprs,
5197 SourceLocation rbLoc) {
5198
5199 if (base && !base->getType().isNull() &&
5200 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5201 auto *AS = cast<ArraySectionExpr>(Val: base);
5202 if (AS->isOMPArraySection())
5203 return OpenMP().ActOnOMPArraySectionExpr(
5204 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5205 /*Length*/ nullptr,
5206 /*Stride=*/nullptr, RBLoc: rbLoc);
5207
5208 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5209 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5210 RBLoc: rbLoc);
5211 }
5212
5213 // Since this might be a postfix expression, get rid of ParenListExprs.
5214 if (isa<ParenListExpr>(Val: base)) {
5215 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5216 if (result.isInvalid())
5217 return ExprError();
5218 base = result.get();
5219 }
5220
5221 // Check if base and idx form a MatrixSubscriptExpr.
5222 //
5223 // Helper to check for comma expressions, which are not allowed as indices for
5224 // matrix subscript expressions.
5225 //
5226 // In C++23, we get multiple arguments instead of a comma expression.
5227 auto CheckAndReportCommaError = [&](Expr *E) {
5228 if (ArgExprs.size() > 1 ||
5229 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5230 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5231 << SourceRange(base->getBeginLoc(), rbLoc);
5232 return true;
5233 }
5234 return false;
5235 };
5236 // The matrix subscript operator ([][])is considered a single operator.
5237 // Separating the index expressions by parenthesis is not allowed.
5238 if (base && !base->getType().isNull() &&
5239 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5240 !isa<MatrixSubscriptExpr>(Val: base)) {
5241 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5242 << SourceRange(base->getBeginLoc(), rbLoc);
5243 return ExprError();
5244 }
5245 // If the base is a MatrixSubscriptExpr, try to create a new
5246 // MatrixSubscriptExpr.
5247 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5248 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5249 if (CheckAndReportCommaError(ArgExprs.front()))
5250 return ExprError();
5251
5252 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5253 RowIdx: matSubscriptE->getRowIdx(),
5254 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5255 }
5256 if (base->getType()->isWebAssemblyTableType()) {
5257 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5258 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5259 return ExprError();
5260 }
5261
5262 CheckInvalidBuiltinCountedByRef(E: base,
5263 K: BuiltinCountedByRefKind::ArraySubscript);
5264
5265 // Handle any non-overload placeholder types in the base and index
5266 // expressions. We can't handle overloads here because the other
5267 // operand might be an overloadable type, in which case the overload
5268 // resolution for the operator overload should get the first crack
5269 // at the overload.
5270 bool IsMSPropertySubscript = false;
5271 if (base->getType()->isNonOverloadPlaceholderType()) {
5272 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5273 if (!IsMSPropertySubscript) {
5274 ExprResult result = CheckPlaceholderExpr(E: base);
5275 if (result.isInvalid())
5276 return ExprError();
5277 base = result.get();
5278 }
5279 }
5280
5281 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5282 if (base->getType()->isMatrixType()) {
5283 if (CheckAndReportCommaError(ArgExprs.front()))
5284 return ExprError();
5285
5286 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5287 RBLoc: rbLoc);
5288 }
5289
5290 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5291 Expr *idx = ArgExprs[0];
5292 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5293 (isa<CXXOperatorCallExpr>(Val: idx) &&
5294 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5295 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5296 << SourceRange(base->getBeginLoc(), rbLoc);
5297 }
5298 }
5299
5300 if (ArgExprs.size() == 1 &&
5301 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5302 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5303 if (result.isInvalid())
5304 return ExprError();
5305 ArgExprs[0] = result.get();
5306 } else {
5307 if (CheckArgsForPlaceholders(args: ArgExprs))
5308 return ExprError();
5309 }
5310
5311 // Build an unanalyzed expression if either operand is type-dependent.
5312 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5313 (base->isTypeDependent() ||
5314 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5315 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5316 return new (Context) ArraySubscriptExpr(
5317 base, ArgExprs.front(),
5318 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5319 VK_LValue, OK_Ordinary, rbLoc);
5320 }
5321
5322 // MSDN, property (C++)
5323 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5324 // This attribute can also be used in the declaration of an empty array in a
5325 // class or structure definition. For example:
5326 // __declspec(property(get=GetX, put=PutX)) int x[];
5327 // The above statement indicates that x[] can be used with one or more array
5328 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5329 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5330 if (IsMSPropertySubscript) {
5331 if (ArgExprs.size() > 1) {
5332 Diag(Loc: base->getExprLoc(),
5333 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5334 return ExprError();
5335 }
5336
5337 // Build MS property subscript expression if base is MS property reference
5338 // or MS property subscript.
5339 return new (Context)
5340 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5341 VK_LValue, OK_Ordinary, rbLoc);
5342 }
5343
5344 // Use C++ overloaded-operator rules if either operand has record
5345 // type. The spec says to do this if either type is *overloadable*,
5346 // but enum types can't declare subscript operators or conversion
5347 // operators, so there's nothing interesting for overload resolution
5348 // to do if there aren't any record types involved.
5349 //
5350 // ObjC pointers have their own subscripting logic that is not tied
5351 // to overload resolution and so should not take this path.
5352 //
5353 // Issue a better diagnostic if we tried to pass multiple arguments to
5354 // a builtin subscript operator rather than diagnosing this as a generic
5355 // overload resolution failure.
5356 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5357 !base->getType()->isRecordType() &&
5358 !base->getType()->isObjCObjectPointerType()) {
5359 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5360 << base->getType() << base->getSourceRange();
5361 return ExprError();
5362 }
5363
5364 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5365 ((base->getType()->isRecordType() ||
5366 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5367 ArgExprs[0]->getType()->isRecordType())))) {
5368 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5369 }
5370
5371 ExprResult Res =
5372 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5373
5374 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5375 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5376
5377 return Res;
5378}
5379
5380ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5381 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5382 InitializationKind Kind =
5383 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5384 InitializationSequence InitSeq(*this, Entity, Kind, E);
5385 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5386}
5387
5388ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5389 Expr *RowIdx,
5390 SourceLocation RBLoc) {
5391 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5392 if (BaseR.isInvalid())
5393 return BaseR;
5394 Base = BaseR.get();
5395
5396 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5397 if (RowR.isInvalid())
5398 return RowR;
5399 RowIdx = RowR.get();
5400
5401 // Build an unanalyzed expression if any of the operands is type-dependent.
5402 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5403 return new (Context)
5404 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5405
5406 // Check that IndexExpr is an integer expression. If it is a constant
5407 // expression, check that it is less than Dim (= the number of elements in the
5408 // corresponding dimension).
5409 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5410 bool IsColumnIdx) -> Expr * {
5411 if (!IndexExpr->getType()->isIntegerType() &&
5412 !IndexExpr->isTypeDependent()) {
5413 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5414 << IsColumnIdx;
5415 return nullptr;
5416 }
5417
5418 if (std::optional<llvm::APSInt> Idx =
5419 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5420 if ((*Idx < 0 || *Idx >= Dim)) {
5421 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5422 << IsColumnIdx << Dim;
5423 return nullptr;
5424 }
5425 }
5426
5427 ExprResult ConvExpr = IndexExpr;
5428 assert(!ConvExpr.isInvalid() &&
5429 "should be able to convert any integer type to size type");
5430 return ConvExpr.get();
5431 };
5432
5433 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5434 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5435 if (!RowIdx)
5436 return ExprError();
5437
5438 QualType RowVecQT =
5439 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5440
5441 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5442}
5443
5444ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5445 Expr *ColumnIdx,
5446 SourceLocation RBLoc) {
5447 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5448 if (BaseR.isInvalid())
5449 return BaseR;
5450 Base = BaseR.get();
5451
5452 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5453 if (RowR.isInvalid())
5454 return RowR;
5455 RowIdx = RowR.get();
5456
5457 if (!ColumnIdx)
5458 return new (Context) MatrixSubscriptExpr(
5459 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5460
5461 // Build an unanalyzed expression if any of the operands is type-dependent.
5462 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5463 ColumnIdx->isTypeDependent())
5464 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5465 Context.DependentTy, RBLoc);
5466
5467 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5468 if (ColumnR.isInvalid())
5469 return ColumnR;
5470 ColumnIdx = ColumnR.get();
5471
5472 // Check that IndexExpr is an integer expression. If it is a constant
5473 // expression, check that it is less than Dim (= the number of elements in the
5474 // corresponding dimension).
5475 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5476 bool IsColumnIdx) -> Expr * {
5477 if (!IndexExpr->getType()->isIntegerType() &&
5478 !IndexExpr->isTypeDependent()) {
5479 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5480 << IsColumnIdx;
5481 return nullptr;
5482 }
5483
5484 if (std::optional<llvm::APSInt> Idx =
5485 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5486 if ((*Idx < 0 || *Idx >= Dim)) {
5487 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5488 << IsColumnIdx << Dim;
5489 return nullptr;
5490 }
5491 }
5492
5493 ExprResult ConvExpr = IndexExpr;
5494 assert(!ConvExpr.isInvalid() &&
5495 "should be able to convert any integer type to size type");
5496 return ConvExpr.get();
5497 };
5498
5499 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5500 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5501 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5502 if (!RowIdx || !ColumnIdx)
5503 return ExprError();
5504
5505 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5506 MTy->getElementType(), RBLoc);
5507}
5508
5509void Sema::CheckAddressOfNoDeref(const Expr *E) {
5510 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5511 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5512
5513 // For expressions like `&(*s).b`, the base is recorded and what should be
5514 // checked.
5515 const MemberExpr *Member = nullptr;
5516 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5517 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5518
5519 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5520}
5521
5522void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5523 if (isUnevaluatedContext())
5524 return;
5525
5526 QualType ResultTy = E->getType();
5527 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5528
5529 // Bail if the element is an array since it is not memory access.
5530 if (isa<ArrayType>(Val: ResultTy))
5531 return;
5532
5533 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5534 LastRecord.PossibleDerefs.insert(Ptr: E);
5535 return;
5536 }
5537
5538 // Check if the base type is a pointer to a member access of a struct
5539 // marked with noderef.
5540 const Expr *Base = E->getBase();
5541 QualType BaseTy = Base->getType();
5542 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5543 // Not a pointer access
5544 return;
5545
5546 const MemberExpr *Member = nullptr;
5547 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5548 Member->isArrow())
5549 Base = Member->getBase();
5550
5551 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5552 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5553 LastRecord.PossibleDerefs.insert(Ptr: E);
5554 }
5555}
5556
5557ExprResult
5558Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5559 Expr *Idx, SourceLocation RLoc) {
5560 Expr *LHSExp = Base;
5561 Expr *RHSExp = Idx;
5562
5563 ExprValueKind VK = VK_LValue;
5564 ExprObjectKind OK = OK_Ordinary;
5565
5566 // Per C++ core issue 1213, the result is an xvalue if either operand is
5567 // a non-lvalue array, and an lvalue otherwise.
5568 if (getLangOpts().CPlusPlus11) {
5569 for (auto *Op : {LHSExp, RHSExp}) {
5570 Op = Op->IgnoreImplicit();
5571 if (Op->getType()->isArrayType() && !Op->isLValue())
5572 VK = VK_XValue;
5573 }
5574 }
5575
5576 // Perform default conversions.
5577 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5578 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5579 if (Result.isInvalid())
5580 return ExprError();
5581 LHSExp = Result.get();
5582 }
5583 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5584 if (Result.isInvalid())
5585 return ExprError();
5586 RHSExp = Result.get();
5587
5588 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5589
5590 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5591 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5592 // in the subscript position. As a result, we need to derive the array base
5593 // and index from the expression types.
5594 Expr *BaseExpr, *IndexExpr;
5595 QualType ResultType;
5596 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5597 BaseExpr = LHSExp;
5598 IndexExpr = RHSExp;
5599 ResultType =
5600 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5601 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5602 BaseExpr = LHSExp;
5603 IndexExpr = RHSExp;
5604 ResultType = PTy->getPointeeType();
5605 } else if (const ObjCObjectPointerType *PTy =
5606 LHSTy->getAs<ObjCObjectPointerType>()) {
5607 BaseExpr = LHSExp;
5608 IndexExpr = RHSExp;
5609
5610 // Use custom logic if this should be the pseudo-object subscript
5611 // expression.
5612 if (!LangOpts.isSubscriptPointerArithmetic())
5613 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5614 getterMethod: nullptr, setterMethod: nullptr);
5615
5616 ResultType = PTy->getPointeeType();
5617 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5618 // Handle the uncommon case of "123[Ptr]".
5619 BaseExpr = RHSExp;
5620 IndexExpr = LHSExp;
5621 ResultType = PTy->getPointeeType();
5622 } else if (const ObjCObjectPointerType *PTy =
5623 RHSTy->getAs<ObjCObjectPointerType>()) {
5624 // Handle the uncommon case of "123[Ptr]".
5625 BaseExpr = RHSExp;
5626 IndexExpr = LHSExp;
5627 ResultType = PTy->getPointeeType();
5628 if (!LangOpts.isSubscriptPointerArithmetic()) {
5629 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5630 << ResultType << BaseExpr->getSourceRange();
5631 return ExprError();
5632 }
5633 } else if (LHSTy->isSubscriptableVectorType()) {
5634 if (LHSTy->isBuiltinType() &&
5635 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5636 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5637 if (BTy->isSVEBool())
5638 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5639 << LHSExp->getSourceRange()
5640 << RHSExp->getSourceRange());
5641 ResultType = BTy->getSveEltType(Ctx: Context);
5642 } else if (Hexagon().isHLXVectorType(T: LHSTy)) {
5643 // There is no HLX vector element extract.
5644 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_hlx)
5645 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5646 } else {
5647 const VectorType *VTy = LHSTy->getAs<VectorType>();
5648 ResultType = VTy->getElementType();
5649 }
5650 BaseExpr = LHSExp; // vectors: V[123]
5651 IndexExpr = RHSExp;
5652 // We apply C++ DR1213 to vector subscripting too.
5653 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5654 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5655 if (Materialized.isInvalid())
5656 return ExprError();
5657 LHSExp = Materialized.get();
5658 }
5659 VK = LHSExp->getValueKind();
5660 if (VK != VK_PRValue)
5661 OK = OK_VectorComponent;
5662
5663 QualType BaseType = BaseExpr->getType();
5664 Qualifiers BaseQuals = BaseType.getQualifiers();
5665 Qualifiers MemberQuals = ResultType.getQualifiers();
5666 Qualifiers Combined = BaseQuals + MemberQuals;
5667 if (Combined != MemberQuals)
5668 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5669 } else if (LHSTy->isArrayType()) {
5670 // If we see an array that wasn't promoted by
5671 // DefaultFunctionArrayLvalueConversion, it must be an array that
5672 // wasn't promoted because of the C90 rule that doesn't
5673 // allow promoting non-lvalue arrays. Warn, then
5674 // force the promotion here.
5675 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5676 << LHSExp->getSourceRange();
5677 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5678 CK: CK_ArrayToPointerDecay).get();
5679 LHSTy = LHSExp->getType();
5680
5681 BaseExpr = LHSExp;
5682 IndexExpr = RHSExp;
5683 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5684 } else if (RHSTy->isArrayType()) {
5685 // Same as previous, except for 123[f().a] case
5686 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5687 << RHSExp->getSourceRange();
5688 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5689 CK: CK_ArrayToPointerDecay).get();
5690 RHSTy = RHSExp->getType();
5691
5692 BaseExpr = RHSExp;
5693 IndexExpr = LHSExp;
5694 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5695 } else {
5696 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5697 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5698 }
5699 // C99 6.5.2.1p1
5700 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5701 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5702 << IndexExpr->getSourceRange());
5703
5704 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5705 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5706 !IndexExpr->isTypeDependent()) {
5707 std::optional<llvm::APSInt> IntegerContantExpr =
5708 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5709 if (!IntegerContantExpr.has_value() ||
5710 IntegerContantExpr.value().isNegative())
5711 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5712 }
5713
5714 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5715 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5716 // type. Note that Functions are not objects, and that (in C99 parlance)
5717 // incomplete types are not object types.
5718 if (ResultType->isFunctionType()) {
5719 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5720 << ResultType << BaseExpr->getSourceRange();
5721 return ExprError();
5722 }
5723
5724 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5725 // GNU extension: subscripting on pointer to void
5726 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5727 << BaseExpr->getSourceRange();
5728
5729 // C forbids expressions of unqualified void type from being l-values.
5730 // See IsCForbiddenLValueType.
5731 if (!ResultType.hasQualifiers())
5732 VK = VK_PRValue;
5733 } else if (!ResultType->isDependentType() &&
5734 !ResultType.isWebAssemblyReferenceType() &&
5735 RequireCompleteSizedType(
5736 Loc: LLoc, T: ResultType,
5737 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5738 return ExprError();
5739
5740 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5741 !ResultType.isCForbiddenLValueType());
5742
5743 return new (Context)
5744 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5745}
5746
5747bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5748 ParmVarDecl *Param, Expr *RewrittenInit,
5749 bool SkipImmediateInvocations) {
5750 if (Param->hasUnparsedDefaultArg()) {
5751 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5752 // If we've already cleared out the location for the default argument,
5753 // that means we're parsing it right now.
5754 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5755 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5756 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5757 Param->setInvalidDecl();
5758 return true;
5759 }
5760
5761 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5762 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5763 Diag(Loc: UnparsedDefaultArgLocs[Param],
5764 DiagID: diag::note_default_argument_declared_here);
5765 return true;
5766 }
5767
5768 if (Param->hasUninstantiatedDefaultArg()) {
5769 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5770 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5771 return true;
5772 }
5773
5774 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5775 assert(Init && "default argument but no initializer?");
5776
5777 // If the default expression creates temporaries, we need to
5778 // push them to the current stack of expression temporaries so they'll
5779 // be properly destroyed.
5780 // FIXME: We should really be rebuilding the default argument with new
5781 // bound temporaries; see the comment in PR5810.
5782 // We don't need to do that with block decls, though, because
5783 // blocks in default argument expression can never capture anything.
5784 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5785 // Set the "needs cleanups" bit regardless of whether there are
5786 // any explicit objects.
5787 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5788 // Append all the objects to the cleanup list. Right now, this
5789 // should always be a no-op, because blocks in default argument
5790 // expressions should never be able to capture anything.
5791 assert(!InitWithCleanup->getNumObjects() &&
5792 "default argument expression has capturing blocks?");
5793 }
5794 // C++ [expr.const]p15.1:
5795 // An expression or conversion is in an immediate function context if it is
5796 // potentially evaluated and [...] its innermost enclosing non-block scope
5797 // is a function parameter scope of an immediate function.
5798 EnterExpressionEvaluationContext EvalContext(
5799 *this,
5800 FD->isImmediateFunction()
5801 ? ExpressionEvaluationContext::ImmediateFunctionContext
5802 : ExpressionEvaluationContext::PotentiallyEvaluated,
5803 Param);
5804 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5805 SkipImmediateInvocations;
5806 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5807 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5808 });
5809 return false;
5810}
5811
5812struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5813 const ASTContext &Context;
5814 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5815 ShouldVisitImplicitCode = true;
5816 }
5817
5818 bool HasImmediateCalls = false;
5819
5820 bool VisitCallExpr(CallExpr *E) override {
5821 if (const FunctionDecl *FD = E->getDirectCallee())
5822 HasImmediateCalls |= FD->isImmediateFunction();
5823 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5824 }
5825
5826 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5827 if (const FunctionDecl *FD = E->getConstructor())
5828 HasImmediateCalls |= FD->isImmediateFunction();
5829 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5830 }
5831
5832 // SourceLocExpr are not immediate invocations
5833 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5834 // need to be rebuilt so that they refer to the correct SourceLocation and
5835 // DeclContext.
5836 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5837 HasImmediateCalls = true;
5838 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5839 }
5840
5841 // A nested lambda might have parameters with immediate invocations
5842 // in their default arguments, or init-captures that are evaluated in the
5843 // enclosing context.
5844 // The compound statement is not visited (as it does not constitute a
5845 // subexpression).
5846 bool VisitLambdaExpr(LambdaExpr *E) override {
5847 auto Init = E->capture_init_begin();
5848 for (auto C = E->capture_begin(), CEnd = E->capture_end(); C != CEnd;
5849 ++C, ++Init) {
5850 if (E->isInitCapture(Capture: C) && !TraverseLambdaCapture(LE: E, C, Init: *Init))
5851 return false;
5852 }
5853 return VisitCXXMethodDecl(D: E->getCallOperator());
5854 }
5855
5856 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5857 return TraverseStmt(S: E->getExpr());
5858 }
5859
5860 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5861 return TraverseStmt(S: E->getExpr());
5862 }
5863};
5864
5865struct EnsureImmediateInvocationInDefaultArgs
5866 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5867 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5868 : TreeTransform(SemaRef) {}
5869
5870 bool AlwaysRebuild() { return true; }
5871
5872 // Lambda bodies are not subexpressions of the enclosing default initializer,
5873 // but init-capture expressions are evaluated in the enclosing context. Keep
5874 // the existing closure type and capture declarations so the existing body
5875 // still refers to the right declarations.
5876 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5877 SmallVector<Expr *, 4> CaptureInits(E->capture_inits());
5878
5879 bool Changed = false;
5880 for (unsigned I = 0, N = E->capture_size(); I != N; ++I) {
5881 const LambdaCapture *C = E->capture_begin() + I;
5882 if (!E->isInitCapture(Capture: C))
5883 continue;
5884
5885 auto *VD = cast<VarDecl>(Val: C->getCapturedVar());
5886 // Default initializers are rebuilt at their point of use, where the
5887 // lambda is no longer dependent, so init-capture packs have already been
5888 // expanded into separate captures.
5889 assert(!VD->isParameterPack() &&
5890 "unexpanded init-capture pack while rebuilding a default member "
5891 "initializer");
5892
5893 Expr *Init = CaptureInits[I];
5894 ExprResult NewInit =
5895 TransformInitializer(Init, NotCopyInit: VD->getInitStyle() == VarDecl::CallInit);
5896 if (NewInit.isInvalid())
5897 return ExprError();
5898
5899 // TransformInitializer strips the CXXConstructExpr that a copy or move
5900 // initialization produces, expecting the enclosing context to rebuild the
5901 // initialization. Rebuild the capture's initialization sequence here so
5902 // the closure still constructs its captured member; otherwise CodeGen is
5903 // left with a bare initializer for a non-trivially copyable capture and
5904 // crashes.
5905 Expr *NewInitE = NewInit.get();
5906 QualType CaptureType = SemaRef.buildLambdaInitCaptureInitialization(
5907 Loc: C->getLocation(), ByRef: C->getCaptureKind() == LCK_ByRef,
5908 /*EllipsisLoc=*/SourceLocation(), /*NumExpansions=*/std::nullopt,
5909 Id: VD->getIdentifier(), DirectInit: VD->getInitStyle() != VarDecl::CInit, Init&: NewInitE);
5910 if (CaptureType.isNull() || !NewInitE)
5911 return ExprError();
5912
5913 Changed |= NewInitE != Init;
5914 CaptureInits[I] = NewInitE;
5915 }
5916
5917 LambdaExpr *Lambda = E;
5918 if (Changed) {
5919 // Reuse the existing closure class: it owns the capture declarations,
5920 // fields, and call operator body. Only the LambdaExpr's capture
5921 // initializer list is replaced.
5922 Lambda = LambdaExpr::Create(
5923 C: SemaRef.Context, Class: E->getLambdaClass(), IntroducerRange: E->getIntroducerRange(),
5924 CaptureDefault: E->getCaptureDefault(), CaptureDefaultLoc: E->getCaptureDefaultLoc(),
5925 ExplicitParams: E->hasExplicitParameters(), ExplicitResultType: E->hasExplicitResultType(), CaptureInits,
5926 ClosingBrace: E->getEndLoc(), ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack());
5927 }
5928
5929 return SemaRef.MaybeBindToTemporary(E: Lambda);
5930 }
5931 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5932
5933 // Make sure we don't rebuild the this pointer as it would
5934 // cause it to incorrectly point it to the outermost class
5935 // in the case of nested struct initialization.
5936 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5937
5938 // Rewrite to source location to refer to the context in which they are used.
5939 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5940 DeclContext *DC = E->getParentContext();
5941 if (DC == SemaRef.CurContext)
5942 return E;
5943
5944 // FIXME: During instantiation, because the rebuild of defaults arguments
5945 // is not always done in the context of the template instantiator,
5946 // we run the risk of producing a dependent source location
5947 // that would never be rebuilt.
5948 // This usually happens during overload resolution, or in contexts
5949 // where the value of the source location does not matter.
5950 // However, we should find a better way to deal with source location
5951 // of function templates.
5952 if (!SemaRef.CurrentInstantiationScope ||
5953 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5954 DC = SemaRef.CurContext;
5955
5956 return getDerived().RebuildSourceLocExpr(
5957 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5958 }
5959};
5960
5961ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5962 FunctionDecl *FD, ParmVarDecl *Param,
5963 Expr *Init) {
5964 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5965
5966 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5967 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5968 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5969 InitializationContext =
5970 OutermostDeclarationWithDelayedImmediateInvocations();
5971 if (!InitializationContext.has_value())
5972 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5973
5974 if (!Init && !Param->hasUnparsedDefaultArg()) {
5975 // Mark that we are replacing a default argument first.
5976 // If we are instantiating a template we won't have to
5977 // retransform immediate calls.
5978 // C++ [expr.const]p15.1:
5979 // An expression or conversion is in an immediate function context if it
5980 // is potentially evaluated and [...] its innermost enclosing non-block
5981 // scope is a function parameter scope of an immediate function.
5982 EnterExpressionEvaluationContext EvalContext(
5983 *this,
5984 FD->isImmediateFunction()
5985 ? ExpressionEvaluationContext::ImmediateFunctionContext
5986 : ExpressionEvaluationContext::PotentiallyEvaluated,
5987 Param);
5988
5989 if (Param->hasUninstantiatedDefaultArg()) {
5990 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5991 return ExprError();
5992 }
5993 // CWG2631
5994 // An immediate invocation that is not evaluated where it appears is
5995 // evaluated and checked for whether it is a constant expression at the
5996 // point where the enclosing initializer is used in a function call.
5997 ImmediateCallVisitor V(getASTContext());
5998 if (!NestedDefaultChecking)
5999 V.TraverseDecl(D: Param);
6000
6001 // Rewrite the call argument that was created from the corresponding
6002 // parameter's default argument.
6003 if (V.HasImmediateCalls ||
6004 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
6005 if (V.HasImmediateCalls)
6006 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6007 CallLoc, Param, CurContext};
6008 // Pass down lifetime extending flag, and collect temporaries in
6009 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
6010 currentEvaluationContext().InLifetimeExtendingContext =
6011 parentEvaluationContext().InLifetimeExtendingContext;
6012 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6013 ExprResult Res;
6014 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
6015 Res = Immediate.TransformInitializer(Init: Param->getInit(),
6016 /*NotCopy=*/NotCopyInit: false);
6017 });
6018 if (Res.isInvalid())
6019 return ExprError();
6020 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
6021 EqualLoc: Res.get()->getBeginLoc());
6022 if (Res.isInvalid())
6023 return ExprError();
6024 Init = Res.get();
6025 }
6026 }
6027
6028 if (CheckCXXDefaultArgExpr(
6029 CallLoc, FD, Param, RewrittenInit: Init,
6030 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6031 return ExprError();
6032
6033 if (getLangOpts().CUDA)
6034 CUDA().checkRTTIInDefaultInit(D: Param, Init: Init ? Init : Param->getDefaultArg(),
6035 UseLoc: CallLoc);
6036
6037 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
6038 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
6039}
6040
6041static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
6042 FieldDecl *Field) {
6043 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
6044 return Pattern;
6045 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
6046 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6047 DeclContext::lookup_result Lookup =
6048 ClassPattern->lookup(Name: Field->getDeclName());
6049 auto Rng = llvm::make_filter_range(
6050 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
6051 if (Rng.empty())
6052 return nullptr;
6053 // FIXME: this breaks clang/test/Modules/pr28812.cpp
6054 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
6055 // && "Duplicated instantiation pattern for field decl");
6056 return cast<FieldDecl>(Val: *Rng.begin());
6057}
6058
6059ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
6060 FieldDecl *Field,
6061 const InitializedEntity &Entity,
6062 bool NestedDefaultChecking,
6063 bool NeedRebuild) {
6064 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
6065
6066 if (!Field->getInClassInitializer() &&
6067 isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
6068 // Maybe we haven't instantiated the in-class initializer. Go check the
6069 // pattern FieldDecl to see if it has one.
6070 FieldDecl *Pattern =
6071 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
6072 assert(Pattern && "We must have set the Pattern!");
6073 if (!Pattern->hasInClassInitializer() ||
6074 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
6075 TemplateArgs: getTemplateInstantiationArgs(D: Field)))
6076 return ExprError();
6077 }
6078
6079 Expr *InClassInit = Field->getInClassInitializer();
6080 if (!InClassInit) {
6081 // DR1351:
6082 // If the brace-or-equal-initializer of a non-static data member
6083 // invokes a defaulted default constructor of its class or of an
6084 // enclosing class in a potentially evaluated subexpression, the
6085 // program is ill-formed.
6086 //
6087 // This resolution is unworkable: the exception specification of the
6088 // default constructor can be needed in an unevaluated context, in
6089 // particular, in the operand of a noexcept-expression, and we can be
6090 // unable to compute an exception specification for an enclosed class.
6091 //
6092 // Any attempt to resolve the exception specification of a defaulted default
6093 // constructor before the initializer is lexically complete will ultimately
6094 // come here at which point we can diagnose it.
6095 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6096 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
6097 << OutermostClass << Field;
6098 Diag(Loc: Field->getEndLoc(),
6099 DiagID: diag::note_default_member_initializer_not_yet_parsed);
6100 // Recover by marking the field invalid, unless we're in a SFINAE context.
6101 if (!isSFINAEContext())
6102 Field->setInvalidDecl();
6103 return ExprError();
6104 }
6105
6106 if (getLangOpts().CUDA)
6107 CUDA().checkRTTIInDefaultInit(D: Field, Init: InClassInit, UseLoc: Loc);
6108
6109 // CWG2631
6110 // An immediate invocation that is not evaluated where it appears is
6111 // evaluated and checked for whether it is a constant expression at the
6112 // point where the enclosing initializer is used in a [...] a constructor
6113 // definition, or an aggregate initialization.
6114 ImmediateCallVisitor V(getASTContext());
6115 if (!NestedDefaultChecking)
6116 V.TraverseDecl(D: Field);
6117
6118 // CWG1815
6119 // Support lifetime extension of temporary created by aggregate
6120 // initialization using a default member initializer. We should rebuild
6121 // the initializer in a lifetime extension context if the initializer
6122 // expression is an ExprWithCleanups. Then make sure the normal lifetime
6123 // extension code recurses into the default initializer and does lifetime
6124 // extension when warranted.
6125 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(Val: InClassInit);
6126 Expr *Init = InClassInit;
6127 if (!InClassInit->containsErrors() &&
6128 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
6129 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6130 CurContext};
6131 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6132 NestedDefaultChecking;
6133 // Pass down lifetime extending flag, and collect temporaries in
6134 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
6135 currentEvaluationContext().InLifetimeExtendingContext =
6136 parentEvaluationContext().InLifetimeExtendingContext;
6137
6138 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6139 ExprResult Res;
6140 runWithSufficientStackSpace(Loc, Fn: [&] {
6141 Res = Immediate.TransformInitializer(Init: InClassInit,
6142 /*CXXDirectInit=*/NotCopyInit: false);
6143 });
6144 if (!Res.isInvalid())
6145 Res = ConvertMemberDefaultInitExpression(FD: Field, Entity, InitExpr: Res.get(), InitLoc: Loc);
6146 if (Res.isInvalid()) {
6147 Field->setInvalidDecl();
6148 return ExprError();
6149 }
6150 Init = Res.get();
6151 }
6152
6153 if (!NestedDefaultChecking)
6154 runWithSufficientStackSpace(Loc, Fn: [&] {
6155 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/false);
6156 });
6157 return Init;
6158}
6159
6160ExprResult Sema::BuildCXXCtorDefaultInitExpr(SourceLocation Loc,
6161 FieldDecl *Field) {
6162 assert(Field->hasInClassInitializer());
6163
6164 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6165
6166 // C++11 [class.base.init]p7:
6167 // The initialization of each base and member constitutes a
6168 // full-expression.
6169 // So this initializer gets an evaluation context of its own, and is finished
6170 // as a full-expression below.
6171 EnterExpressionEvaluationContext EvalContext(
6172 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6173 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6174
6175 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6176 if (!InitContext)
6177 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6178
6179 // [class.temporary]/p7:
6180 // If such a temporary object would otherwise be destroyed at the end of the
6181 // for-range-initializer full-expression, the object persists for the lifetime
6182 // of the reference initialized by the for-range-initializer.
6183 //
6184 // A default member initializer used by a constructor is a separate
6185 // full-expression, we don't need extend temporaries lifetime in this
6186 // situation, the NeedRebuild will always false.
6187 ExprResult Init = BuildCXXDefaultInitInternal(
6188 Loc, Field,
6189 Entity: InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: Field),
6190 NestedDefaultChecking, /*NeedRebuild=*/false);
6191 if (Init.isInvalid())
6192 return ExprError();
6193
6194 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscardedValue=*/false);
6195 if (Init.isInvalid()) {
6196 Field->setInvalidDecl();
6197 return ExprError();
6198 }
6199
6200 return CXXDefaultInitExpr::Create(
6201 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6202 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6203}
6204
6205ExprResult
6206Sema::BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
6207 const InitializedEntity &MemberEntity) {
6208 assert(Field->hasInClassInitializer());
6209
6210 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6211
6212 // Unlike a mem-initializer, this initializer is a subexpression of the
6213 // full-expression containing the aggregate initialization. It is evaluated
6214 // exactly as that full-expression is, so inherit the enclosing context kind
6215 // rather than forcing a potentially evaluated one.
6216 EnterExpressionEvaluationContext EvalContext(
6217 *this, currentEvaluationContext().Context, Field);
6218 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6219
6220 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6221 if (!InitContext)
6222 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6223
6224 // [class.temporary]/p7:
6225 // If such a temporary object would otherwise be destroyed at the end of the
6226 // for-range-initializer full-expression, the object persists for the lifetime
6227 // of the reference initialized by the for-range-initializer.
6228 //
6229 // A default member initializer used by an aggregate initialization belongs to
6230 // the full-expression containing the aggregate initialization. we need extend
6231 // temporaries lifetime in this situation, the NeedRebuild will always true.
6232
6233 // CWG1815: always rebuild, never share the AST built when the field was
6234 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6235 // collected in this context, which is what lets the aggregate initialization
6236 // lifetime-extend them; sharing one AST would also make several uses of the
6237 // same field fight over its extension. A mem-initializer has no such need,
6238 // as its temporaries die at the end of the initializer itself.
6239 ExprResult Init = BuildCXXDefaultInitInternal(
6240 Loc, Field, Entity: MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6241 if (Init.isInvalid())
6242 return ExprError();
6243
6244 // Deliberately not finished as a full-expression: leaving the temporaries it
6245 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6246 // them into the enclosing context, which eventually wraps them all in a
6247 // single ExprWithCleanups. They are then destroyed at the end of the
6248 // containing full-expression, in reverse construction order.
6249
6250 return CXXDefaultInitExpr::Create(
6251 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6252 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6253}
6254
6255VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
6256 const FunctionProtoType *Proto,
6257 Expr *Fn) {
6258 if (Proto && Proto->isVariadic()) {
6259 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6260 return VariadicCallType::Constructor;
6261 else if (Fn && Fn->getType()->isBlockPointerType())
6262 return VariadicCallType::Block;
6263 else if (FDecl) {
6264 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6265 if (Method->isInstance())
6266 return VariadicCallType::Method;
6267 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6268 return VariadicCallType::Method;
6269 return VariadicCallType::Function;
6270 }
6271 return VariadicCallType::DoesNotApply;
6272}
6273
6274namespace {
6275class FunctionCallCCC final : public FunctionCallFilterCCC {
6276public:
6277 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6278 unsigned NumArgs, MemberExpr *ME)
6279 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6280 FunctionName(FuncName) {}
6281
6282 bool ValidateCandidate(const TypoCorrection &candidate) override {
6283 if (!candidate.getCorrectionSpecifier() ||
6284 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6285 return false;
6286 }
6287
6288 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6289 }
6290
6291 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6292 return std::make_unique<FunctionCallCCC>(args&: *this);
6293 }
6294
6295private:
6296 const IdentifierInfo *const FunctionName;
6297};
6298}
6299
6300static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6301 FunctionDecl *FDecl,
6302 ArrayRef<Expr *> Args) {
6303 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6304 DeclarationName FuncName = FDecl->getDeclName();
6305 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6306
6307 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6308 if (TypoCorrection Corrected = S.CorrectTypo(
6309 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6310 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6311 Mode: CorrectTypoKind::ErrorRecovery)) {
6312 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6313 if (Corrected.isOverloaded()) {
6314 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6315 OverloadCandidateSet::iterator Best;
6316 for (NamedDecl *CD : Corrected) {
6317 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6318 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6319 CandidateSet&: OCS);
6320 }
6321 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6322 case OR_Success:
6323 ND = Best->FoundDecl;
6324 Corrected.setCorrectionDecl(ND);
6325 break;
6326 default:
6327 break;
6328 }
6329 }
6330 ND = ND->getUnderlyingDecl();
6331 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6332 return Corrected;
6333 }
6334 }
6335 return TypoCorrection();
6336}
6337
6338// [C++26][[expr.unary.op]/p4
6339// A pointer to member is only formed when an explicit &
6340// is used and its operand is a qualified-id not enclosed in parentheses.
6341static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6342 if (!isa<ParenExpr>(Val: Fn))
6343 return false;
6344
6345 Fn = Fn->IgnoreParens();
6346
6347 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6348 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6349 return false;
6350 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6351 return DRE->hasQualifier();
6352 }
6353 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6354 return bool(OVL->getQualifier());
6355 return false;
6356}
6357
6358bool
6359Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6360 FunctionDecl *FDecl,
6361 const FunctionProtoType *Proto,
6362 ArrayRef<Expr *> Args,
6363 SourceLocation RParenLoc,
6364 bool IsExecConfig) {
6365 // Bail out early if calling a builtin with custom typechecking.
6366 // For HLSL builtin aliases, argument conversion is still needed because
6367 // overload resolution may have selected a conversion sequence (e.g.,
6368 // vector-to-scalar truncation) that must be applied before the custom
6369 // type checker runs.
6370 if (FDecl)
6371 if (unsigned ID = FDecl->getBuiltinID())
6372 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6373 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6374 return false;
6375
6376 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6377 // assignment, to the types of the corresponding parameter, ...
6378
6379 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6380 bool HasExplicitObjectParameter =
6381 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6382 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6383 unsigned NumParams = Proto->getNumParams();
6384 bool Invalid = false;
6385 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6386 unsigned FnKind = Fn->getType()->isBlockPointerType()
6387 ? 1 /* block */
6388 : (IsExecConfig ? 3 /* kernel function (exec config) */
6389 : 0 /* function */);
6390
6391 // If too few arguments are available (and we don't have default
6392 // arguments for the remaining parameters), don't make the call.
6393 if (Args.size() < NumParams) {
6394 if (Args.size() < MinArgs) {
6395 TypoCorrection TC;
6396 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6397 unsigned diag_id =
6398 MinArgs == NumParams && !Proto->isVariadic()
6399 ? diag::err_typecheck_call_too_few_args_suggest
6400 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6401 diagnoseTypo(
6402 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6403 << FnKind << MinArgs - ExplicitObjectParameterOffset
6404 << static_cast<unsigned>(Args.size()) -
6405 ExplicitObjectParameterOffset
6406 << HasExplicitObjectParameter << TC.getCorrectionRange());
6407 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6408 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6409 ->getDeclName())
6410 Diag(Loc: RParenLoc,
6411 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6412 ? diag::err_typecheck_call_too_few_args_one
6413 : diag::err_typecheck_call_too_few_args_at_least_one)
6414 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6415 << HasExplicitObjectParameter << Fn->getSourceRange();
6416 else
6417 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6418 ? diag::err_typecheck_call_too_few_args
6419 : diag::err_typecheck_call_too_few_args_at_least)
6420 << FnKind << MinArgs - ExplicitObjectParameterOffset
6421 << static_cast<unsigned>(Args.size()) -
6422 ExplicitObjectParameterOffset
6423 << HasExplicitObjectParameter << Fn->getSourceRange();
6424
6425 // Emit the location of the prototype.
6426 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6427 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6428 << FDecl << FDecl->getParametersSourceRange();
6429
6430 return true;
6431 }
6432 // We reserve space for the default arguments when we create
6433 // the call expression, before calling ConvertArgumentsForCall.
6434 assert((Call->getNumArgs() == NumParams) &&
6435 "We should have reserved space for the default arguments before!");
6436 }
6437
6438 // If too many are passed and not variadic, error on the extras and drop
6439 // them.
6440 if (Args.size() > NumParams) {
6441 if (!Proto->isVariadic()) {
6442 TypoCorrection TC;
6443 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6444 unsigned diag_id =
6445 MinArgs == NumParams && !Proto->isVariadic()
6446 ? diag::err_typecheck_call_too_many_args_suggest
6447 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6448 diagnoseTypo(
6449 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6450 << FnKind << NumParams - ExplicitObjectParameterOffset
6451 << static_cast<unsigned>(Args.size()) -
6452 ExplicitObjectParameterOffset
6453 << HasExplicitObjectParameter << TC.getCorrectionRange());
6454 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6455 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6456 ->getDeclName())
6457 Diag(Loc: Args[NumParams]->getBeginLoc(),
6458 DiagID: MinArgs == NumParams
6459 ? diag::err_typecheck_call_too_many_args_one
6460 : diag::err_typecheck_call_too_many_args_at_most_one)
6461 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6462 << static_cast<unsigned>(Args.size()) -
6463 ExplicitObjectParameterOffset
6464 << HasExplicitObjectParameter << Fn->getSourceRange()
6465 << SourceRange(Args[NumParams]->getBeginLoc(),
6466 Args.back()->getEndLoc());
6467 else
6468 Diag(Loc: Args[NumParams]->getBeginLoc(),
6469 DiagID: MinArgs == NumParams
6470 ? diag::err_typecheck_call_too_many_args
6471 : diag::err_typecheck_call_too_many_args_at_most)
6472 << FnKind << NumParams - ExplicitObjectParameterOffset
6473 << static_cast<unsigned>(Args.size()) -
6474 ExplicitObjectParameterOffset
6475 << HasExplicitObjectParameter << Fn->getSourceRange()
6476 << SourceRange(Args[NumParams]->getBeginLoc(),
6477 Args.back()->getEndLoc());
6478
6479 // Emit the location of the prototype.
6480 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6481 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6482 << FDecl << FDecl->getParametersSourceRange();
6483
6484 // This deletes the extra arguments.
6485 Call->shrinkNumArgs(NewNumArgs: NumParams);
6486 return true;
6487 }
6488 }
6489 SmallVector<Expr *, 8> AllArgs;
6490 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6491
6492 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6493 AllArgs, CallType);
6494 if (Invalid)
6495 return true;
6496 unsigned TotalNumArgs = AllArgs.size();
6497 for (unsigned i = 0; i < TotalNumArgs; ++i)
6498 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6499
6500 Call->computeDependence();
6501 return false;
6502}
6503
6504bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6505 const FunctionProtoType *Proto,
6506 unsigned FirstParam, ArrayRef<Expr *> Args,
6507 SmallVectorImpl<Expr *> &AllArgs,
6508 VariadicCallType CallType, bool AllowExplicit,
6509 bool IsListInitialization) {
6510 unsigned NumParams = Proto->getNumParams();
6511 bool Invalid = false;
6512 size_t ArgIx = 0;
6513 // Continue to check argument types (even if we have too few/many args).
6514 for (unsigned i = FirstParam; i < NumParams; i++) {
6515 QualType ProtoArgType = Proto->getParamType(i);
6516
6517 Expr *Arg;
6518 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6519 if (ArgIx < Args.size()) {
6520 Arg = Args[ArgIx++];
6521
6522 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6523 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6524 return true;
6525
6526 // Strip the unbridged-cast placeholder expression off, if applicable.
6527 bool CFAudited = false;
6528 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6529 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6530 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6531 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6532 else if (getLangOpts().ObjCAutoRefCount &&
6533 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6534 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6535 CFAudited = true;
6536
6537 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6538 ProtoArgType->isBlockPointerType())
6539 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6540 BE->getBlockDecl()->setDoesNotEscape();
6541 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6542 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6543 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6544 if (ArgExpr.isInvalid())
6545 return true;
6546 Arg = ArgExpr.getAs<Expr>();
6547 }
6548
6549 InitializedEntity Entity =
6550 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6551 Type: ProtoArgType)
6552 : InitializedEntity::InitializeParameter(
6553 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6554
6555 // Remember that parameter belongs to a CF audited API.
6556 if (CFAudited)
6557 Entity.setParameterCFAudited();
6558
6559 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6560 // function boundaries is a common oversight.
6561 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6562 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6563 bool isPedantic =
6564 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6565 Diag(Loc: Arg->getExprLoc(),
6566 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6567 : diag::warn_obt_discarded_at_function_boundary)
6568 << Arg->getType() << ProtoArgType;
6569 }
6570
6571 ExprResult ArgE = PerformCopyInitialization(
6572 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6573 if (ArgE.isInvalid())
6574 return true;
6575
6576 Arg = ArgE.getAs<Expr>();
6577 } else {
6578 assert(Param && "can't use default arguments without a known callee");
6579
6580 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6581 if (ArgExpr.isInvalid())
6582 return true;
6583
6584 Arg = ArgExpr.getAs<Expr>();
6585 }
6586
6587 // Check for array bounds violations for each argument to the call. This
6588 // check only triggers warnings when the argument isn't a more complex Expr
6589 // with its own checking, such as a BinaryOperator.
6590 CheckArrayAccess(E: Arg);
6591
6592 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6593 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6594
6595 AllArgs.push_back(Elt: Arg);
6596 }
6597
6598 // If this is a variadic call, handle args passed through "...".
6599 if (CallType != VariadicCallType::DoesNotApply) {
6600 // Assume that extern "C" functions with variadic arguments that
6601 // return __unknown_anytype aren't *really* variadic.
6602 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6603 FDecl->isExternC()) {
6604 for (Expr *A : Args.slice(N: ArgIx)) {
6605 QualType paramType; // ignored
6606 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6607 Invalid |= arg.isInvalid();
6608 AllArgs.push_back(Elt: arg.get());
6609 }
6610
6611 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6612 } else {
6613 for (Expr *A : Args.slice(N: ArgIx)) {
6614 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6615 Invalid |= Arg.isInvalid();
6616 AllArgs.push_back(Elt: Arg.get());
6617 }
6618 }
6619
6620 // Check for array bounds violations.
6621 for (Expr *A : Args.slice(N: ArgIx))
6622 CheckArrayAccess(E: A);
6623 }
6624 return Invalid;
6625}
6626
6627static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6628 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6629 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6630 TL = DTL.getOriginalLoc();
6631 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6632 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6633 << ATL.getLocalSourceRange();
6634}
6635
6636void
6637Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6638 ParmVarDecl *Param,
6639 const Expr *ArgExpr) {
6640 // Static array parameters are not supported in C++.
6641 if (!Param || getLangOpts().CPlusPlus)
6642 return;
6643
6644 QualType OrigTy = Param->getOriginalType();
6645
6646 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6647 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6648 return;
6649
6650 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6651 NPC: Expr::NPC_NeverValueDependent)) {
6652 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6653 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6654 return;
6655 }
6656
6657 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6658 if (!CAT)
6659 return;
6660
6661 const ConstantArrayType *ArgCAT =
6662 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6663 if (!ArgCAT)
6664 return;
6665
6666 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6667 T2: ArgCAT->getElementType())) {
6668 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6669 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6670 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6671 << (unsigned)CAT->getZExtSize() << 0;
6672 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6673 }
6674 return;
6675 }
6676
6677 std::optional<CharUnits> ArgSize =
6678 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6679 std::optional<CharUnits> ParmSize =
6680 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6681 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6682 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6683 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6684 << (unsigned)ParmSize->getQuantity() << 1;
6685 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6686 }
6687}
6688
6689/// Given a function expression of unknown-any type, try to rebuild it
6690/// to have a function type.
6691static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6692
6693/// Is the given type a placeholder that we need to lower out
6694/// immediately during argument processing?
6695static bool isPlaceholderToRemoveAsArg(QualType type) {
6696 // Placeholders are never sugared.
6697 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6698 if (!placeholder) return false;
6699
6700 switch (placeholder->getKind()) {
6701 // Ignore all the non-placeholder types.
6702#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6703 case BuiltinType::Id:
6704#include "clang/Basic/OpenCLImageTypes.def"
6705#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6706 case BuiltinType::Id:
6707#include "clang/Basic/OpenCLExtensionTypes.def"
6708 // In practice we'll never use this, since all SVE types are sugared
6709 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6710#define SVE_TYPE(Name, Id, SingletonId) \
6711 case BuiltinType::Id:
6712#include "clang/Basic/AArch64ACLETypes.def"
6713#define PPC_VECTOR_TYPE(Name, Id, Size) \
6714 case BuiltinType::Id:
6715#include "clang/Basic/PPCTypes.def"
6716#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6717#include "clang/Basic/RISCVVTypes.def"
6718#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6719#include "clang/Basic/WebAssemblyReferenceTypes.def"
6720#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6721#include "clang/Basic/AMDGPUTypes.def"
6722#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6723#include "clang/Basic/HLSLIntangibleTypes.def"
6724#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6725#include "clang/Basic/HLSLPackedTypes.def"
6726#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6727#include "clang/Basic/SPIRVTypes.def"
6728#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6729#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6730#include "clang/AST/BuiltinTypes.def"
6731 return false;
6732
6733 case BuiltinType::UnresolvedTemplate:
6734 // We cannot lower out overload sets; they might validly be resolved
6735 // by the call machinery.
6736 case BuiltinType::Overload:
6737 return false;
6738
6739 // Unbridged casts in ARC can be handled in some call positions and
6740 // should be left in place.
6741 case BuiltinType::ARCUnbridgedCast:
6742 return false;
6743
6744 // Pseudo-objects should be converted as soon as possible.
6745 case BuiltinType::PseudoObject:
6746 return true;
6747
6748 // The debugger mode could theoretically but currently does not try
6749 // to resolve unknown-typed arguments based on known parameter types.
6750 case BuiltinType::UnknownAny:
6751 return true;
6752
6753 // These are always invalid as call arguments and should be reported.
6754 case BuiltinType::BoundMember:
6755 case BuiltinType::BuiltinFn:
6756 case BuiltinType::IncompleteMatrixIdx:
6757 case BuiltinType::ArraySection:
6758 case BuiltinType::OMPArrayShaping:
6759 case BuiltinType::OMPIterator:
6760 return true;
6761
6762 }
6763 llvm_unreachable("bad builtin type kind");
6764}
6765
6766bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6767 // Apply this processing to all the arguments at once instead of
6768 // dying at the first failure.
6769 bool hasInvalid = false;
6770 for (size_t i = 0, e = args.size(); i != e; i++) {
6771 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6772 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6773 if (result.isInvalid()) hasInvalid = true;
6774 else args[i] = result.get();
6775 }
6776 }
6777 return hasInvalid;
6778}
6779
6780/// If a builtin function has a pointer argument with no explicit address
6781/// space, then it should be able to accept a pointer to any address
6782/// space as input. In order to do this, we need to replace the
6783/// standard builtin declaration with one that uses the same address space
6784/// as the call.
6785///
6786/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6787/// it does not contain any pointer arguments without
6788/// an address space qualifer. Otherwise the rewritten
6789/// FunctionDecl is returned.
6790/// TODO: Handle pointer return types.
6791static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6792 FunctionDecl *FDecl,
6793 MultiExprArg ArgExprs) {
6794
6795 QualType DeclType = FDecl->getType();
6796 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6797
6798 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6799 ArgExprs.size() < FT->getNumParams())
6800 return nullptr;
6801
6802 bool NeedsNewDecl = false;
6803 unsigned i = 0;
6804 SmallVector<QualType, 8> OverloadParams;
6805
6806 {
6807 // The lvalue conversions in this loop are only for type resolution and
6808 // don't actually occur.
6809 EnterExpressionEvaluationContext Unevaluated(
6810 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6811 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6812
6813 for (QualType ParamType : FT->param_types()) {
6814
6815 // Convert array arguments to pointer to simplify type lookup.
6816 ExprResult ArgRes =
6817 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6818 if (ArgRes.isInvalid())
6819 return nullptr;
6820 Expr *Arg = ArgRes.get();
6821 QualType ArgType = Arg->getType();
6822 if (!ParamType->isPointerType() ||
6823 ParamType->getPointeeType().hasAddressSpace() ||
6824 !ArgType->isPointerType() ||
6825 !ArgType->getPointeeType().hasAddressSpace() ||
6826 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6827 OverloadParams.push_back(Elt: ParamType);
6828 continue;
6829 }
6830
6831 QualType PointeeType = ParamType->getPointeeType();
6832 NeedsNewDecl = true;
6833 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6834
6835 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6836 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6837 }
6838 }
6839
6840 if (!NeedsNewDecl)
6841 return nullptr;
6842
6843 FunctionProtoType::ExtProtoInfo EPI;
6844 EPI.Variadic = FT->isVariadic();
6845 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6846 Args: OverloadParams, EPI);
6847 DeclContext *Parent = FDecl->getParent();
6848 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6849 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6850 N: FDecl->getIdentifier(), T: OverloadTy,
6851 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6852 isInlineSpecified: false,
6853 /*hasPrototype=*/hasWrittenPrototype: true);
6854 SmallVector<ParmVarDecl*, 16> Params;
6855 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6856 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6857 QualType ParamType = FT->getParamType(i);
6858 ParmVarDecl *Parm =
6859 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6860 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6861 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6862 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6863 Params.push_back(Elt: Parm);
6864 }
6865 OverloadDecl->setParams(Params);
6866 // We cannot merge host/device attributes of redeclarations. They have to
6867 // be consistent when created.
6868 if (Sema->LangOpts.CUDA) {
6869 if (FDecl->hasAttr<CUDAHostAttr>())
6870 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6871 if (FDecl->hasAttr<CUDADeviceAttr>())
6872 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6873 }
6874 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6875 return OverloadDecl;
6876}
6877
6878static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6879 FunctionDecl *Callee,
6880 MultiExprArg ArgExprs) {
6881 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6882 // similar attributes) really don't like it when functions are called with an
6883 // invalid number of args.
6884 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6885 /*PartialOverloading=*/false) &&
6886 !Callee->isVariadic())
6887 return;
6888 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6889 return;
6890
6891 if (const EnableIfAttr *Attr =
6892 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6893 S.Diag(Loc: Fn->getBeginLoc(),
6894 DiagID: isa<CXXMethodDecl>(Val: Callee)
6895 ? diag::err_ovl_no_viable_member_function_in_call
6896 : diag::err_ovl_no_viable_function_in_call)
6897 << Callee << Callee->getSourceRange();
6898 S.Diag(Loc: Callee->getLocation(),
6899 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6900 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6901 return;
6902 }
6903}
6904
6905static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6906 const UnresolvedMemberExpr *const UME, Sema &S) {
6907
6908 const auto GetFunctionLevelDCIfCXXClass =
6909 [](Sema &S) -> const CXXRecordDecl * {
6910 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6911 if (!DC || !DC->getParent())
6912 return nullptr;
6913
6914 // If the call to some member function was made from within a member
6915 // function body 'M' return return 'M's parent.
6916 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6917 return MD->getParent()->getCanonicalDecl();
6918 // else the call was made from within a default member initializer of a
6919 // class, so return the class.
6920 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6921 return RD->getCanonicalDecl();
6922 return nullptr;
6923 };
6924 // If our DeclContext is neither a member function nor a class (in the
6925 // case of a lambda in a default member initializer), we can't have an
6926 // enclosing 'this'.
6927
6928 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6929 if (!CurParentClass)
6930 return false;
6931
6932 // The naming class for implicit member functions call is the class in which
6933 // name lookup starts.
6934 const CXXRecordDecl *const NamingClass =
6935 UME->getNamingClass()->getCanonicalDecl();
6936 assert(NamingClass && "Must have naming class even for implicit access");
6937
6938 // If the unresolved member functions were found in a 'naming class' that is
6939 // related (either the same or derived from) to the class that contains the
6940 // member function that itself contained the implicit member access.
6941
6942 return CurParentClass == NamingClass ||
6943 CurParentClass->isDerivedFrom(Base: NamingClass);
6944}
6945
6946static void
6947tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6948 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6949
6950 if (!UME)
6951 return;
6952
6953 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6954 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6955 // already been captured, or if this is an implicit member function call (if
6956 // it isn't, an attempt to capture 'this' should already have been made).
6957 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6958 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6959 return;
6960
6961 // Check if the naming class in which the unresolved members were found is
6962 // related (same as or is a base of) to the enclosing class.
6963
6964 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6965 return;
6966
6967
6968 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6969 // If the enclosing function is not dependent, then this lambda is
6970 // capture ready, so if we can capture this, do so.
6971 if (!EnclosingFunctionCtx->isDependentContext()) {
6972 // If the current lambda and all enclosing lambdas can capture 'this' -
6973 // then go ahead and capture 'this' (since our unresolved overload set
6974 // contains at least one non-static member function).
6975 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6976 S.CheckCXXThisCapture(Loc: CallLoc);
6977 } else if (S.CurContext->isDependentContext()) {
6978 // ... since this is an implicit member reference, that might potentially
6979 // involve a 'this' capture, mark 'this' for potential capture in
6980 // enclosing lambdas.
6981 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6982 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6983 }
6984}
6985
6986// Once a call is fully resolved, warn for unqualified calls to specific
6987// C++ standard functions, like move and forward.
6988static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6989 const CallExpr *Call) {
6990 // We are only checking unary move and forward so exit early here.
6991 if (Call->getNumArgs() != 1)
6992 return;
6993
6994 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6995 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6996 return;
6997 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6998 if (!DRE || !DRE->getLocation().isValid())
6999 return;
7000
7001 if (DRE->getQualifier())
7002 return;
7003
7004 const FunctionDecl *FD = Call->getDirectCallee();
7005 if (!FD)
7006 return;
7007
7008 // Only warn for some functions deemed more frequent or problematic.
7009 unsigned BuiltinID = FD->getBuiltinID();
7010 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
7011 return;
7012
7013 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
7014 << FD->getQualifiedNameAsString()
7015 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
7016}
7017
7018ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7019 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7020 Expr *ExecConfig) {
7021 ExprResult Call =
7022 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7023 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7024 if (Call.isInvalid())
7025 return Call;
7026
7027 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7028 // language modes.
7029 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
7030 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
7031 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
7032 << ULE->getName();
7033 }
7034
7035 if (LangOpts.OpenMP)
7036 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
7037 ExecConfig);
7038 if (LangOpts.CPlusPlus) {
7039 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
7040 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
7041
7042 // If we previously found that the id-expression of this call refers to a
7043 // consteval function but the call is dependent, we should not treat is an
7044 // an invalid immediate call.
7045 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
7046 DRE && Call.get()->isValueDependent()) {
7047 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
7048 }
7049 }
7050 return Call;
7051}
7052
7053// Any type that could be used to form a callable expression
7054static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
7055 QualType T = E->getType();
7056 if (T->isDependentType())
7057 return true;
7058
7059 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
7060 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
7061 T->isFunctionType() || T->isFunctionReferenceType() ||
7062 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
7063 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
7064 return true;
7065
7066 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
7067 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
7068}
7069
7070ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7071 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7072 Expr *ExecConfig, bool IsExecConfig,
7073 bool AllowRecovery) {
7074 // Since this might be a postfix expression, get rid of ParenListExprs.
7075 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
7076 if (Result.isInvalid()) return ExprError();
7077 Fn = Result.get();
7078
7079 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
7080 // later, when we check boolean conditions, for now we merely forward it
7081 // without any additional checking.
7082 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
7083 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
7084 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
7085
7086 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
7087 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
7088 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7089 return CallExpr::Create(
7090 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
7091 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
7092 }
7093 }
7094
7095 if (CheckArgsForPlaceholders(args: ArgExprs))
7096 return ExprError();
7097
7098 // The result of __builtin_counted_by_ref cannot be used as a function
7099 // argument. It allows leaking and modification of bounds safety information.
7100 for (const Expr *Arg : ArgExprs)
7101 if (CheckInvalidBuiltinCountedByRef(E: Arg,
7102 K: BuiltinCountedByRefKind::FunctionArg))
7103 return ExprError();
7104
7105 if (getLangOpts().CPlusPlus) {
7106 // If this is a pseudo-destructor expression, build the call immediately.
7107 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
7108 if (!ArgExprs.empty()) {
7109 // Pseudo-destructor calls should not have any arguments.
7110 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
7111 << FixItHint::CreateRemoval(
7112 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
7113 ArgExprs.back()->getEndLoc()));
7114 }
7115
7116 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
7117 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7118 }
7119 if (Fn->getType() == Context.PseudoObjectTy) {
7120 ExprResult result = CheckPlaceholderExpr(E: Fn);
7121 if (result.isInvalid()) return ExprError();
7122 Fn = result.get();
7123 }
7124
7125 // Determine whether this is a dependent call inside a C++ template,
7126 // in which case we won't do any semantic analysis now.
7127 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
7128 if (ExecConfig) {
7129 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
7130 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
7131 Ty: Context.DependentTy, VK: VK_PRValue,
7132 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
7133 } else {
7134
7135 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7136 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
7137 CallLoc: Fn->getBeginLoc());
7138
7139 // If the type of the function itself is not dependent
7140 // check that it is a reasonable as a function, as type deduction
7141 // later assume the CallExpr has a sensible TYPE.
7142 if (!MayBeFunctionType(Context, E: Fn))
7143 return ExprError(
7144 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7145 << Fn->getType() << Fn->getSourceRange());
7146
7147 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7148 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7149 }
7150 }
7151
7152 // Determine whether this is a call to an object (C++ [over.call.object]).
7153 if (Fn->getType()->isRecordType())
7154 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
7155 RParenLoc);
7156
7157 if (Fn->getType() == Context.UnknownAnyTy) {
7158 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7159 if (result.isInvalid()) return ExprError();
7160 Fn = result.get();
7161 }
7162
7163 if (Fn->getType() == Context.BoundMemberTy) {
7164 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7165 RParenLoc, ExecConfig, IsExecConfig,
7166 AllowRecovery);
7167 }
7168 }
7169
7170 // Check for overloaded calls. This can happen even in C due to extensions.
7171 if (Fn->getType() == Context.OverloadTy) {
7172 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
7173
7174 // We aren't supposed to apply this logic if there's an '&' involved.
7175 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
7176 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
7177 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7178 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7179 OverloadExpr *ovl = find.Expression;
7180 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
7181 return BuildOverloadedCallExpr(
7182 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
7183 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
7184 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7185 RParenLoc, ExecConfig, IsExecConfig,
7186 AllowRecovery);
7187 }
7188 }
7189
7190 // If we're directly calling a function, get the appropriate declaration.
7191 if (Fn->getType() == Context.UnknownAnyTy) {
7192 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7193 if (result.isInvalid()) return ExprError();
7194 Fn = result.get();
7195 }
7196
7197 Expr *NakedFn = Fn->IgnoreParens();
7198
7199 bool CallingNDeclIndirectly = false;
7200 NamedDecl *NDecl = nullptr;
7201 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
7202 if (UnOp->getOpcode() == UO_AddrOf) {
7203 CallingNDeclIndirectly = true;
7204 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7205 }
7206 }
7207
7208 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
7209 NDecl = DRE->getDecl();
7210
7211 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
7212 if (FDecl && FDecl->getBuiltinID()) {
7213 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7214 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7215 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
7216 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
7217 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
7218 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7219 }
7220 }
7221
7222 // Rewrite the function decl for this builtin by replacing parameters
7223 // with no explicit address space with the address space of the arguments
7224 // in ArgExprs.
7225 if ((FDecl =
7226 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
7227 NDecl = FDecl;
7228 Fn = DeclRefExpr::Create(
7229 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
7230 NameLoc: DRE->getLocation(), T: Fn->getType() /* BuiltinFnTy */,
7231 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
7232 }
7233 }
7234 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
7235 NDecl = ME->getMemberDecl();
7236
7237 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
7238 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7239 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
7240 return ExprError();
7241
7242 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
7243
7244 // If this expression is a call to a builtin function in HIP compilation,
7245 // allow a pointer-type argument to default address space to be passed as a
7246 // pointer-type parameter to a non-default address space. If Arg is declared
7247 // in the default address space and Param is declared in a non-default
7248 // address space, perform an implicit address space cast to the parameter
7249 // type.
7250 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7251 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7252 ++Idx) {
7253 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7254 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7255 !ArgExprs[Idx]->getType()->isPointerType())
7256 continue;
7257
7258 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7259 auto ArgTy = ArgExprs[Idx]->getType();
7260 auto ArgPtTy = ArgTy->getPointeeType();
7261 auto ArgAS = ArgPtTy.getAddressSpace();
7262
7263 // Add address space cast if target address spaces are different
7264 bool NeedImplicitASC =
7265 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7266 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7267 // or from specific AS which has target AS matching that of Param.
7268 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7269 if (!NeedImplicitASC)
7270 continue;
7271
7272 // First, ensure that the Arg is an RValue.
7273 if (ArgExprs[Idx]->isGLValue()) {
7274 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7275 if (Res.isInvalid())
7276 return ExprError();
7277 ArgExprs[Idx] = Res.get();
7278 }
7279
7280 // Construct a new arg type with address space of Param
7281 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7282 ArgPtQuals.setAddressSpace(ParamAS);
7283 auto NewArgPtTy =
7284 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7285 auto NewArgTy =
7286 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7287 Qs: ArgTy.getQualifiers());
7288
7289 // Finally perform an implicit address space cast
7290 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7291 CK: CK_AddressSpaceConversion)
7292 .get();
7293 }
7294 }
7295 }
7296
7297 if (Context.isDependenceAllowed() &&
7298 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7299 assert(!getLangOpts().CPlusPlus);
7300 assert((Fn->containsErrors() ||
7301 llvm::any_of(ArgExprs,
7302 [](clang::Expr *E) { return E->containsErrors(); })) &&
7303 "should only occur in error-recovery path.");
7304 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7305 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7306 }
7307 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7308 Config: ExecConfig, IsExecConfig);
7309}
7310
7311Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, unsigned Id,
7312 MultiExprArg CallArgs) {
7313 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7314 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7315 Sema::LookupOrdinaryName);
7316 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7317
7318 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7319 assert(BuiltInDecl && "failed to find builtin declaration");
7320
7321 ExprResult DeclRef =
7322 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7323 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7324
7325 ExprResult Call =
7326 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7327
7328 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7329 return Call.get();
7330}
7331
7332ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7333 SourceLocation BuiltinLoc,
7334 SourceLocation RParenLoc) {
7335 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7336 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7337}
7338
7339ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7340 SourceLocation BuiltinLoc,
7341 SourceLocation RParenLoc) {
7342 ExprValueKind VK = VK_PRValue;
7343 ExprObjectKind OK = OK_Ordinary;
7344 QualType SrcTy = E->getType();
7345 if (!SrcTy->isDependentType() &&
7346 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7347 return ExprError(
7348 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7349 << DestTy << SrcTy << E->getSourceRange());
7350 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7351}
7352
7353ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7354 SourceLocation BuiltinLoc,
7355 SourceLocation RParenLoc) {
7356 TypeSourceInfo *TInfo;
7357 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7358 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7359}
7360
7361ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7362 SourceLocation LParenLoc,
7363 ArrayRef<Expr *> Args,
7364 SourceLocation RParenLoc, Expr *Config,
7365 bool IsExecConfig, ADLCallKind UsesADL) {
7366 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7367 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7368
7369 auto IsSJLJ = [&] {
7370 switch (BuiltinID) {
7371 case Builtin::BI__builtin_longjmp:
7372 case Builtin::BI__builtin_setjmp:
7373 case Builtin::BI__sigsetjmp:
7374 case Builtin::BI_longjmp:
7375 case Builtin::BI_setjmp:
7376 case Builtin::BIlongjmp:
7377 case Builtin::BIsetjmp:
7378 case Builtin::BIsiglongjmp:
7379 case Builtin::BIsigsetjmp:
7380 return true;
7381 default:
7382 return false;
7383 }
7384 };
7385
7386 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7387 if (!CurrentDefer.empty() && IsSJLJ()) {
7388 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7389 // for more than just blocks (e.g. lambdas, nested classes...).
7390 Scope *DeferParent = CurrentDefer.back().first;
7391 Scope *Block = CurScope->getBlockParent();
7392 if (DeferParent->Contains(rhs: *CurScope) &&
7393 (!Block || !DeferParent->Contains(rhs: *Block)))
7394 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7395 }
7396
7397 // Functions with 'interrupt' attribute cannot be called directly.
7398 if (FDecl) {
7399 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7400 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7401 return ExprError();
7402 }
7403 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7404 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7405 return ExprError();
7406 }
7407 }
7408
7409 // X86 interrupt handlers may only call routines with attribute
7410 // no_caller_saved_registers since there is no efficient way to
7411 // save and restore the non-GPR state.
7412 if (auto *Caller = getCurFunctionDecl()) {
7413 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7414 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7415 const TargetInfo &TI = Context.getTargetInfo();
7416 bool HasNonGPRRegisters =
7417 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7418 if (HasNonGPRRegisters &&
7419 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7420 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7421 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7422 if (FDecl)
7423 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7424 }
7425 }
7426 }
7427
7428 // Extract the return type from the builtin function pointer type.
7429 QualType ResultTy;
7430 if (BuiltinID)
7431 ResultTy = FDecl->getCallResultType();
7432 else
7433 ResultTy = Context.BoolTy;
7434
7435 // Promote the function operand.
7436 // We special-case function promotion here because we only allow promoting
7437 // builtin functions to function pointers in the callee of a call.
7438 ExprResult Result;
7439 if (BuiltinID &&
7440 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7441 // FIXME Several builtins still have setType in
7442 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7443 // Builtins.td to ensure they are correct before removing setType calls.
7444 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7445 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7446 } else
7447 Result = CallExprUnaryConversions(E: Fn);
7448 if (Result.isInvalid())
7449 return ExprError();
7450 Fn = Result.get();
7451
7452 // Check for a valid function type, but only if it is not a builtin which
7453 // requires custom type checking. These will be handled by
7454 // CheckBuiltinFunctionCall below just after creation of the call expression.
7455 const FunctionType *FuncT = nullptr;
7456 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7457 retry:
7458 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7459 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7460 // have type pointer to function".
7461 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7462 if (!FuncT)
7463 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7464 << Fn->getType() << Fn->getSourceRange());
7465 } else if (const BlockPointerType *BPT =
7466 Fn->getType()->getAs<BlockPointerType>()) {
7467 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7468 } else {
7469 // Handle calls to expressions of unknown-any type.
7470 if (Fn->getType() == Context.UnknownAnyTy) {
7471 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7472 if (rewrite.isInvalid())
7473 return ExprError();
7474 Fn = rewrite.get();
7475 goto retry;
7476 }
7477
7478 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7479 << Fn->getType() << Fn->getSourceRange());
7480 }
7481 }
7482
7483 // Get the number of parameters in the function prototype, if any.
7484 // We will allocate space for max(Args.size(), NumParams) arguments
7485 // in the call expression.
7486 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7487 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7488
7489 CallExpr *TheCall;
7490 if (Config) {
7491 TheCall = CUDAKernelCallExpr::Create(
7492 Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), Args, Ty: ResultTy, VK: VK_PRValue,
7493 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7494 } else {
7495 TheCall =
7496 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7497 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7498 }
7499
7500 // Bail out early if calling a builtin with custom type checking.
7501 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7502 // For HLSL builtin aliases, the call was resolved via overload resolution
7503 // which may have selected a conversion sequence (e.g., vector-to-scalar
7504 // truncation). Convert arguments to match the declared prototype before
7505 // the custom type checker runs, otherwise the builtin will operate on
7506 // the unconverted argument types.
7507 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7508 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7509 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7510 IsExecConfig))
7511 return ExprError();
7512 }
7513 }
7514 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7515 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7516 E = CheckForImmediateInvocation(E, Decl: FDecl);
7517 return E;
7518 }
7519
7520 if (getLangOpts().CUDA) {
7521 if (Config) {
7522 // CUDA: Kernel calls must be to global functions
7523 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7524 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7525 << FDecl << Fn->getSourceRange());
7526
7527 // CUDA: Kernel function must have 'void' return type
7528 if (!FuncT->getReturnType()->isVoidType() &&
7529 !FuncT->getReturnType()->getAs<AutoType>() &&
7530 !FuncT->getReturnType()->isInstantiationDependentType())
7531 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7532 << Fn->getType() << Fn->getSourceRange());
7533 } else {
7534 // CUDA: Calls to global functions must be configured
7535 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7536 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7537 << FDecl << Fn->getSourceRange());
7538 }
7539 }
7540
7541 // Check for a valid return type
7542 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7543 FD: FDecl))
7544 return ExprError();
7545
7546 // We know the result type of the call, set it.
7547 TheCall->setType(FuncT->getCallResultType(Context));
7548 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7549
7550 // WebAssembly tables can't be used as arguments.
7551 if (Context.getTargetInfo().getTriple().isWasm()) {
7552 for (const Expr *Arg : Args) {
7553 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7554 return ExprError(Diag(Loc: Arg->getExprLoc(),
7555 DiagID: diag::err_wasm_table_as_function_parameter));
7556 }
7557 }
7558 }
7559
7560 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7561 // replaces sampler DeclRefExprs with their integer initializers.
7562 if (getLangOpts().OpenCL && FDecl) {
7563 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7564 }
7565
7566 if (Proto) {
7567 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7568 IsExecConfig))
7569 return ExprError();
7570 } else {
7571 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7572
7573 if (FDecl) {
7574 // Check if we have too few/too many template arguments, based
7575 // on our knowledge of the function definition.
7576 const FunctionDecl *Def = nullptr;
7577 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7578 Proto = Def->getType()->getAs<FunctionProtoType>();
7579 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7580 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7581 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7582 }
7583
7584 // If the function we're calling isn't a function prototype, but we have
7585 // a function prototype from a prior declaratiom, use that prototype.
7586 if (!FDecl->hasPrototype())
7587 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7588 }
7589
7590 // If we still haven't found a prototype to use but there are arguments to
7591 // the call, diagnose this as calling a function without a prototype.
7592 // However, if we found a function declaration, check to see if
7593 // -Wdeprecated-non-prototype was disabled where the function was declared.
7594 // If so, we will silence the diagnostic here on the assumption that this
7595 // interface is intentional and the user knows what they're doing. We will
7596 // also silence the diagnostic if there is a function declaration but it
7597 // was implicitly defined (the user already gets diagnostics about the
7598 // creation of the implicit function declaration, so the additional warning
7599 // is not helpful).
7600 if (!Proto && !Args.empty() &&
7601 (!FDecl || (!FDecl->isImplicit() &&
7602 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7603 Loc: FDecl->getLocation()))))
7604 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7605 << (FDecl != nullptr) << FDecl;
7606
7607 // Promote the arguments (C99 6.5.2.2p6).
7608 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7609 Expr *Arg = Args[i];
7610
7611 if (Proto && i < Proto->getNumParams()) {
7612 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7613 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7614 ExprResult ArgE =
7615 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7616 if (ArgE.isInvalid())
7617 return true;
7618
7619 Arg = ArgE.getAs<Expr>();
7620
7621 } else {
7622 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7623
7624 if (ArgE.isInvalid())
7625 return true;
7626
7627 Arg = ArgE.getAs<Expr>();
7628 }
7629
7630 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7631 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7632 return ExprError();
7633
7634 TheCall->setArg(Arg: i, ArgExpr: Arg);
7635 }
7636 TheCall->computeDependence();
7637 }
7638
7639 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7640 if (Method->isImplicitObjectMemberFunction())
7641 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7642 << Fn->getSourceRange() << 0);
7643
7644 // Check for sentinels
7645 if (NDecl)
7646 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7647
7648 // Warn for unions passing across security boundary (CMSE).
7649 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7650 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7651 if (const auto *RT =
7652 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7653 if (RT->getDecl()->isOrContainsUnion())
7654 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7655 << 0 << i;
7656 }
7657 }
7658 }
7659
7660 // Do special checking on direct calls to functions.
7661 if (FDecl) {
7662 if (CheckFunctionCall(FDecl, TheCall, Proto))
7663 return ExprError();
7664
7665 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7666 checkFortifiedLibcArgument(FD: FDecl, TheCall);
7667
7668 if (BuiltinID)
7669 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7670 } else if (NDecl) {
7671 if (CheckPointerCall(NDecl, TheCall, Proto))
7672 return ExprError();
7673 } else {
7674 if (CheckOtherCall(TheCall, Proto))
7675 return ExprError();
7676 }
7677
7678 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7679}
7680
7681ExprResult
7682Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7683 SourceLocation RParenLoc, Expr *InitExpr) {
7684 assert(Ty && "ActOnCompoundLiteral(): missing type");
7685 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7686
7687 TypeSourceInfo *TInfo;
7688 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7689 if (!TInfo)
7690 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7691
7692 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7693}
7694
7695ExprResult
7696Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7697 SourceLocation RParenLoc, Expr *LiteralExpr) {
7698 QualType literalType = TInfo->getType();
7699
7700 if (literalType->isArrayType()) {
7701 if (RequireCompleteSizedType(
7702 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7703 DiagID: diag::err_array_incomplete_or_sizeless_type,
7704 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7705 return ExprError();
7706 if (literalType->isVariableArrayType()) {
7707 // C23 6.7.10p4: An entity of variable length array type shall not be
7708 // initialized except by an empty initializer.
7709 //
7710 // The C extension warnings are issued from ParseBraceInitializer() and
7711 // do not need to be issued here. However, we continue to issue an error
7712 // in the case there are initializers or we are compiling C++. We allow
7713 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7714 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7715 // FIXME: should we allow this construct in C++ when it makes sense to do
7716 // so?
7717 //
7718 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7719 // shall specify an object type or an array of unknown size, but not a
7720 // variable length array type. This seems odd, as it allows 'int a[size] =
7721 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7722 // says, this is what's implemented here for C (except for the extension
7723 // that permits constant foldable size arrays)
7724
7725 auto diagID = LangOpts.CPlusPlus
7726 ? diag::err_variable_object_no_init
7727 : diag::err_compound_literal_with_vla_type;
7728 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7729 FailedFoldDiagID: diagID))
7730 return ExprError();
7731 }
7732 } else if (!literalType->isDependentType() &&
7733 RequireCompleteType(Loc: LParenLoc, T: literalType,
7734 DiagID: diag::err_typecheck_decl_incomplete_type,
7735 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7736 return ExprError();
7737
7738 InitializedEntity Entity
7739 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7740 InitializationKind Kind
7741 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7742 TypeRange: SourceRange(LParenLoc, RParenLoc),
7743 /*InitList=*/true);
7744 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7745 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7746 ResultType: &literalType);
7747 if (Result.isInvalid())
7748 return ExprError();
7749 LiteralExpr = Result.get();
7750
7751 // We treat the compound literal as being at file scope if it's not in a
7752 // function or method body, or within the function's prototype scope. This
7753 // means the following compound literal is not at file scope:
7754 // void func(char *para[(int [1]){ 0 }[0]);
7755 const Scope *S = getCurScope();
7756 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7757 !S->isInCFunctionScope() &&
7758 (!S || !S->isFunctionPrototypeScope());
7759
7760 // In C, compound literals are l-values for some reason.
7761 // For GCC compatibility, in C++, file-scope array compound literals with
7762 // constant initializers are also l-values, and compound literals are
7763 // otherwise prvalues.
7764 //
7765 // (GCC also treats C++ list-initialized file-scope array prvalues with
7766 // constant initializers as l-values, but that's non-conforming, so we don't
7767 // follow it there.)
7768 //
7769 // FIXME: It would be better to handle the lvalue cases as materializing and
7770 // lifetime-extending a temporary object, but our materialized temporaries
7771 // representation only supports lifetime extension from a variable, not "out
7772 // of thin air".
7773 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7774 // is bound to the result of applying array-to-pointer decay to the compound
7775 // literal.
7776 // FIXME: GCC supports compound literals of reference type, which should
7777 // obviously have a value kind derived from the kind of reference involved.
7778 ExprValueKind VK =
7779 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7780 ? VK_PRValue
7781 : VK_LValue;
7782
7783 // C99 6.5.2.5
7784 // "If the compound literal occurs outside the body of a function, the
7785 // initializer list shall consist of constant expressions."
7786 if (IsFileScope) {
7787 // An element with an immediate call or source_location is left for the
7788 // use site, and for its rebuild too when the rebuilt default arguments
7789 // could not be given the use-site location.
7790 bool DeferImmediate =
7791 isCheckingDefaultArgumentOrInitializer() ||
7792 (currentEvaluationContext().DelayedDefaultInitializationContext &&
7793 !OutermostDeclarationWithDelayedImmediateInvocations());
7794 // Store the element's value so CodeGen does not re-evaluate it outside a
7795 // constant context.
7796 auto CheckElement = [&](Expr *Init) -> Expr * {
7797 if (Init->isTypeDependent() || Init->isValueDependent())
7798 return Init;
7799 if (DeferImmediate) {
7800 ImmediateCallVisitor V(Context);
7801 V.TraverseStmt(S: Init);
7802 if (V.HasImmediateCalls)
7803 return Init;
7804 }
7805 Expr::EvalResult Eval;
7806 if (!Init->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context,
7807 Kind: ConstantExprKind::Initializer)) {
7808 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7809 << Init->getSourceBitField();
7810 return nullptr;
7811 }
7812 // An immediate invocation already is a ConstantExpr.
7813 if (isa<ConstantExpr>(Val: Init))
7814 return Init;
7815 return ConstantExpr::Create(Context, E: Init, Result: Eval.Val);
7816 };
7817 if (auto *ILE = dyn_cast<InitListExpr>(Val: LiteralExpr)) {
7818 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7819 Expr *Init = CheckElement(ILE->getInit(Init: i));
7820 if (!Init)
7821 return ExprError();
7822 ILE->setInit(Init: i, expr: Init);
7823 }
7824 } else {
7825 LiteralExpr = CheckElement(LiteralExpr);
7826 if (!LiteralExpr)
7827 return ExprError();
7828 }
7829 }
7830
7831 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7832 LiteralExpr, IsFileScope);
7833 if (!IsFileScope && literalType.getAddressSpace() != LangAS::opencl_private &&
7834 literalType.getAddressSpace() != LangAS::Default) {
7835 // Embedded-C extensions to C99 6.5.2.5:
7836 // "If the compound literal occurs inside the body of a function, the
7837 // type name shall not be qualified by an address-space qualifier."
7838 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7839 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7840 return ExprError();
7841 }
7842
7843 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7844 // Compound literals that have automatic storage duration are destroyed at
7845 // the end of the scope in C; in C++, they're just temporaries.
7846
7847 // Emit diagnostics if it is or contains a C union type that is non-trivial
7848 // to destruct.
7849 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7850 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7851 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7852 NonTrivialKind: NTCUK_Destruct);
7853
7854 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7855 Cleanup.setExprNeedsCleanups(true);
7856 ExprCleanupObjects.push_back(Elt: E);
7857 if (literalType.isDestructedType()) {
7858 getCurFunction()->setHasBranchProtectedScope();
7859 }
7860 }
7861
7862 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7863 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7864 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7865 Loc: E->getInitializer()->getExprLoc());
7866
7867 return MaybeBindToTemporary(E);
7868}
7869
7870ExprResult
7871Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7872 SourceLocation RBraceLoc) {
7873 // Only produce each kind of designated initialization diagnostic once.
7874 SourceLocation FirstDesignator;
7875 bool DiagnosedArrayDesignator = false;
7876 bool DiagnosedNestedDesignator = false;
7877 bool DiagnosedMixedDesignator = false;
7878
7879 // Check that any designated initializers are syntactically valid in the
7880 // current language mode.
7881 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7882 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7883 if (FirstDesignator.isInvalid())
7884 FirstDesignator = DIE->getBeginLoc();
7885
7886 if (!getLangOpts().CPlusPlus)
7887 break;
7888
7889 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7890 DiagnosedNestedDesignator = true;
7891 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7892 << DIE->getDesignatorsSourceRange();
7893 }
7894
7895 for (auto &Desig : DIE->designators()) {
7896 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7897 DiagnosedArrayDesignator = true;
7898 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7899 << Desig.getSourceRange();
7900 }
7901 }
7902
7903 if (!DiagnosedMixedDesignator &&
7904 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7905 DiagnosedMixedDesignator = true;
7906 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7907 << DIE->getSourceRange();
7908 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7909 << InitArgList[0]->getSourceRange();
7910 }
7911 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7912 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7913 DiagnosedMixedDesignator = true;
7914 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7915 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7916 << DIE->getSourceRange();
7917 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7918 << InitArgList[I]->getSourceRange();
7919 }
7920 }
7921
7922 if (FirstDesignator.isValid()) {
7923 // Only diagnose designated initiaization as a C++20 extension if we didn't
7924 // already diagnose use of (non-C++20) C99 designator syntax.
7925 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7926 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7927 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7928 ? diag::warn_cxx17_compat_designated_init
7929 : diag::ext_cxx_designated_init);
7930 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7931 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7932 }
7933 }
7934
7935 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7936}
7937
7938ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7939 MultiExprArg InitArgList,
7940 SourceLocation RBraceLoc, bool IsExplicit) {
7941 // Semantic analysis for initializers is done by ActOnDeclarator() and
7942 // CheckInitializer() - it requires knowledge of the object being initialized.
7943
7944 // Immediately handle non-overload placeholders. Overloads can be
7945 // resolved contextually, but everything else here can't.
7946 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7947 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7948 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7949
7950 // Ignore failures; dropping the entire initializer list because
7951 // of one failure would be terrible for indexing/etc.
7952 if (result.isInvalid()) continue;
7953
7954 InitArgList[I] = result.get();
7955 }
7956 }
7957
7958 InitListExpr *E = new (Context)
7959 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7960 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7961 return E;
7962}
7963
7964void Sema::maybeExtendBlockObject(ExprResult &E) {
7965 assert(E.get()->getType()->isBlockPointerType());
7966 assert(E.get()->isPRValue());
7967
7968 // Only do this in an r-value context.
7969 if (!getLangOpts().ObjCAutoRefCount) return;
7970
7971 E = ImplicitCastExpr::Create(
7972 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7973 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7974 Cleanup.setExprNeedsCleanups(true);
7975}
7976
7977CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7978 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7979 // Also, callers should have filtered out the invalid cases with
7980 // pointers. Everything else should be possible.
7981
7982 QualType SrcTy = Src.get()->getType();
7983 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7984 return CK_NoOp;
7985
7986 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7987 case Type::STK_MemberPointer:
7988 llvm_unreachable("member pointer type in C");
7989
7990 case Type::STK_CPointer:
7991 case Type::STK_BlockPointer:
7992 case Type::STK_ObjCObjectPointer:
7993 switch (DestTy->getScalarTypeKind()) {
7994 case Type::STK_CPointer: {
7995 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7996 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7997 if (SrcAS != DestAS)
7998 return CK_AddressSpaceConversion;
7999 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
8000 return CK_NoOp;
8001 return CK_BitCast;
8002 }
8003 case Type::STK_BlockPointer:
8004 return (SrcKind == Type::STK_BlockPointer
8005 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
8006 case Type::STK_ObjCObjectPointer:
8007 if (SrcKind == Type::STK_ObjCObjectPointer)
8008 return CK_BitCast;
8009 if (SrcKind == Type::STK_CPointer)
8010 return CK_CPointerToObjCPointerCast;
8011 maybeExtendBlockObject(E&: Src);
8012 return CK_BlockPointerToObjCPointerCast;
8013 case Type::STK_Bool:
8014 return CK_PointerToBoolean;
8015 case Type::STK_Integral:
8016 return CK_PointerToIntegral;
8017 case Type::STK_Floating:
8018 case Type::STK_FloatingComplex:
8019 case Type::STK_IntegralComplex:
8020 case Type::STK_MemberPointer:
8021 case Type::STK_FixedPoint:
8022 llvm_unreachable("illegal cast from pointer");
8023 }
8024 llvm_unreachable("Should have returned before this");
8025
8026 case Type::STK_FixedPoint:
8027 switch (DestTy->getScalarTypeKind()) {
8028 case Type::STK_FixedPoint:
8029 return CK_FixedPointCast;
8030 case Type::STK_Bool:
8031 return CK_FixedPointToBoolean;
8032 case Type::STK_Integral:
8033 return CK_FixedPointToIntegral;
8034 case Type::STK_Floating:
8035 return CK_FixedPointToFloating;
8036 case Type::STK_IntegralComplex:
8037 case Type::STK_FloatingComplex:
8038 Diag(Loc: Src.get()->getExprLoc(),
8039 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8040 << DestTy;
8041 return CK_IntegralCast;
8042 case Type::STK_CPointer:
8043 case Type::STK_ObjCObjectPointer:
8044 case Type::STK_BlockPointer:
8045 case Type::STK_MemberPointer:
8046 llvm_unreachable("illegal cast to pointer type");
8047 }
8048 llvm_unreachable("Should have returned before this");
8049
8050 case Type::STK_Bool: // casting from bool is like casting from an integer
8051 case Type::STK_Integral:
8052 switch (DestTy->getScalarTypeKind()) {
8053 case Type::STK_CPointer:
8054 case Type::STK_ObjCObjectPointer:
8055 case Type::STK_BlockPointer:
8056 if (Src.get()->isNullPointerConstant(Ctx&: Context,
8057 NPC: Expr::NPC_ValueDependentIsNull))
8058 return CK_NullToPointer;
8059 return CK_IntegralToPointer;
8060 case Type::STK_Bool:
8061 return CK_IntegralToBoolean;
8062 case Type::STK_Integral:
8063 return CK_IntegralCast;
8064 case Type::STK_Floating:
8065 return CK_IntegralToFloating;
8066 case Type::STK_IntegralComplex:
8067 Src = ImpCastExprToType(E: Src.get(),
8068 Type: DestTy->castAs<ComplexType>()->getElementType(),
8069 CK: CK_IntegralCast);
8070 return CK_IntegralRealToComplex;
8071 case Type::STK_FloatingComplex:
8072 Src = ImpCastExprToType(E: Src.get(),
8073 Type: DestTy->castAs<ComplexType>()->getElementType(),
8074 CK: CK_IntegralToFloating);
8075 return CK_FloatingRealToComplex;
8076 case Type::STK_MemberPointer:
8077 llvm_unreachable("member pointer type in C");
8078 case Type::STK_FixedPoint:
8079 return CK_IntegralToFixedPoint;
8080 }
8081 llvm_unreachable("Should have returned before this");
8082
8083 case Type::STK_Floating:
8084 switch (DestTy->getScalarTypeKind()) {
8085 case Type::STK_Floating:
8086 return CK_FloatingCast;
8087 case Type::STK_Bool:
8088 return CK_FloatingToBoolean;
8089 case Type::STK_Integral:
8090 return CK_FloatingToIntegral;
8091 case Type::STK_FloatingComplex:
8092 Src = ImpCastExprToType(E: Src.get(),
8093 Type: DestTy->castAs<ComplexType>()->getElementType(),
8094 CK: CK_FloatingCast);
8095 return CK_FloatingRealToComplex;
8096 case Type::STK_IntegralComplex:
8097 Src = ImpCastExprToType(E: Src.get(),
8098 Type: DestTy->castAs<ComplexType>()->getElementType(),
8099 CK: CK_FloatingToIntegral);
8100 return CK_IntegralRealToComplex;
8101 case Type::STK_CPointer:
8102 case Type::STK_ObjCObjectPointer:
8103 case Type::STK_BlockPointer:
8104 llvm_unreachable("valid float->pointer cast?");
8105 case Type::STK_MemberPointer:
8106 llvm_unreachable("member pointer type in C");
8107 case Type::STK_FixedPoint:
8108 return CK_FloatingToFixedPoint;
8109 }
8110 llvm_unreachable("Should have returned before this");
8111
8112 case Type::STK_FloatingComplex:
8113 switch (DestTy->getScalarTypeKind()) {
8114 case Type::STK_FloatingComplex:
8115 return CK_FloatingComplexCast;
8116 case Type::STK_IntegralComplex:
8117 return CK_FloatingComplexToIntegralComplex;
8118 case Type::STK_Floating: {
8119 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8120 if (Context.hasSameType(T1: ET, T2: DestTy))
8121 return CK_FloatingComplexToReal;
8122 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
8123 return CK_FloatingCast;
8124 }
8125 case Type::STK_Bool:
8126 return CK_FloatingComplexToBoolean;
8127 case Type::STK_Integral:
8128 Src = ImpCastExprToType(E: Src.get(),
8129 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8130 CK: CK_FloatingComplexToReal);
8131 return CK_FloatingToIntegral;
8132 case Type::STK_CPointer:
8133 case Type::STK_ObjCObjectPointer:
8134 case Type::STK_BlockPointer:
8135 llvm_unreachable("valid complex float->pointer cast?");
8136 case Type::STK_MemberPointer:
8137 llvm_unreachable("member pointer type in C");
8138 case Type::STK_FixedPoint:
8139 Diag(Loc: Src.get()->getExprLoc(),
8140 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8141 << SrcTy;
8142 return CK_IntegralCast;
8143 }
8144 llvm_unreachable("Should have returned before this");
8145
8146 case Type::STK_IntegralComplex:
8147 switch (DestTy->getScalarTypeKind()) {
8148 case Type::STK_FloatingComplex:
8149 return CK_IntegralComplexToFloatingComplex;
8150 case Type::STK_IntegralComplex:
8151 return CK_IntegralComplexCast;
8152 case Type::STK_Integral: {
8153 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8154 if (Context.hasSameType(T1: ET, T2: DestTy))
8155 return CK_IntegralComplexToReal;
8156 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
8157 return CK_IntegralCast;
8158 }
8159 case Type::STK_Bool:
8160 return CK_IntegralComplexToBoolean;
8161 case Type::STK_Floating:
8162 Src = ImpCastExprToType(E: Src.get(),
8163 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8164 CK: CK_IntegralComplexToReal);
8165 return CK_IntegralToFloating;
8166 case Type::STK_CPointer:
8167 case Type::STK_ObjCObjectPointer:
8168 case Type::STK_BlockPointer:
8169 llvm_unreachable("valid complex int->pointer cast?");
8170 case Type::STK_MemberPointer:
8171 llvm_unreachable("member pointer type in C");
8172 case Type::STK_FixedPoint:
8173 Diag(Loc: Src.get()->getExprLoc(),
8174 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8175 << SrcTy;
8176 return CK_IntegralCast;
8177 }
8178 llvm_unreachable("Should have returned before this");
8179 }
8180
8181 llvm_unreachable("Unhandled scalar cast");
8182}
8183
8184static bool breakDownVectorType(QualType type, uint64_t &len,
8185 QualType &eltType) {
8186 // Vectors are simple.
8187 if (const VectorType *vecType = type->getAs<VectorType>()) {
8188 len = vecType->getNumElements();
8189 eltType = vecType->getElementType();
8190 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8191 return true;
8192 }
8193
8194 // We allow lax conversion to and from non-vector types, but only if
8195 // they're real types (i.e. non-complex, non-pointer scalar types).
8196 if (!type->isRealType()) return false;
8197
8198 len = 1;
8199 eltType = type;
8200 return true;
8201}
8202
8203bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8204 assert(srcTy->isVectorType() || destTy->isVectorType());
8205
8206 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8207 if (!FirstType->isSVESizelessBuiltinType())
8208 return false;
8209
8210 const auto *VecTy = SecondType->getAs<VectorType>();
8211 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8212 };
8213
8214 return ValidScalableConversion(srcTy, destTy) ||
8215 ValidScalableConversion(destTy, srcTy);
8216}
8217
8218bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8219 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8220 return false;
8221
8222 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8223 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8224
8225 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8226 matSrcType->getNumColumns() == matDestType->getNumColumns();
8227}
8228
8229bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8230 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8231
8232 uint64_t SrcLen, DestLen;
8233 QualType SrcEltTy, DestEltTy;
8234 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
8235 return false;
8236 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
8237 return false;
8238
8239 // x87 long double has padding bits, so it cannot be bitcast to another type.
8240 auto IsX87LongDouble = [&](QualType T) {
8241 return T->isRealFloatingType() && &Context.getFloatTypeSemantics(T) ==
8242 &llvm::APFloat::x87DoubleExtended();
8243 };
8244 if (IsX87LongDouble(SrcEltTy) != IsX87LongDouble(DestEltTy))
8245 return false;
8246
8247 // ASTContext::getTypeSize will return the size rounded up to a
8248 // power of 2, so instead of using that, we need to use the raw
8249 // element size multiplied by the element count.
8250 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
8251 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
8252
8253 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8254}
8255
8256bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8257 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8258 "expected at least one type to be a vector here");
8259
8260 bool IsSrcTyAltivec =
8261 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8262 VectorKind::AltiVecVector) ||
8263 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8264 VectorKind::AltiVecBool) ||
8265 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8266 VectorKind::AltiVecPixel));
8267
8268 bool IsDestTyAltivec = DestTy->isVectorType() &&
8269 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8270 VectorKind::AltiVecVector) ||
8271 (DestTy->castAs<VectorType>()->getVectorKind() ==
8272 VectorKind::AltiVecBool) ||
8273 (DestTy->castAs<VectorType>()->getVectorKind() ==
8274 VectorKind::AltiVecPixel));
8275
8276 return (IsSrcTyAltivec || IsDestTyAltivec);
8277}
8278
8279bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8280 assert(destTy->isVectorType() || srcTy->isVectorType());
8281
8282 // Disallow lax conversions between scalars and ExtVectors (these
8283 // conversions are allowed for other vector types because common headers
8284 // depend on them). Most scalar OP ExtVector cases are handled by the
8285 // splat path anyway, which does what we want (convert, not bitcast).
8286 // What this rules out for ExtVectors is crazy things like char4*float.
8287 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8288 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8289
8290 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8291}
8292
8293bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8294 assert(destTy->isVectorType() || srcTy->isVectorType());
8295
8296 switch (Context.getLangOpts().getLaxVectorConversions()) {
8297 case LangOptions::LaxVectorConversionKind::None:
8298 return false;
8299
8300 case LangOptions::LaxVectorConversionKind::Integer:
8301 if (!srcTy->isIntegralOrEnumerationType()) {
8302 auto *Vec = srcTy->getAs<VectorType>();
8303 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8304 return false;
8305 }
8306 if (!destTy->isIntegralOrEnumerationType()) {
8307 auto *Vec = destTy->getAs<VectorType>();
8308 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8309 return false;
8310 }
8311 // OK, integer (vector) -> integer (vector) bitcast.
8312 break;
8313
8314 case LangOptions::LaxVectorConversionKind::All:
8315 break;
8316 }
8317
8318 return areLaxCompatibleVectorTypes(srcTy, destTy);
8319}
8320
8321bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8322 CastKind &Kind) {
8323 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8324 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8325 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8326 << DestTy << SrcTy << R;
8327 }
8328 } else if (SrcTy->isMatrixType()) {
8329 return Diag(Loc: R.getBegin(),
8330 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8331 << SrcTy << DestTy << R;
8332 } else if (DestTy->isMatrixType()) {
8333 return Diag(Loc: R.getBegin(),
8334 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8335 << DestTy << SrcTy << R;
8336 }
8337
8338 Kind = CK_MatrixCast;
8339 return false;
8340}
8341
8342bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8343 CastKind &Kind) {
8344 assert(VectorTy->isVectorType() && "Not a vector type!");
8345
8346 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8347 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8348 return Diag(Loc: R.getBegin(),
8349 DiagID: Ty->isVectorType() ?
8350 diag::err_invalid_conversion_between_vectors :
8351 diag::err_invalid_conversion_between_vector_and_integer)
8352 << VectorTy << Ty << R;
8353 } else
8354 return Diag(Loc: R.getBegin(),
8355 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8356 << VectorTy << Ty << R;
8357
8358 Kind = CK_BitCast;
8359 return false;
8360}
8361
8362ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8363 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8364
8365 if (DestElemTy == SplattedExpr->getType())
8366 return SplattedExpr;
8367
8368 assert(DestElemTy->isFloatingType() ||
8369 DestElemTy->isIntegralOrEnumerationType());
8370
8371 CastKind CK;
8372 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8373 // OpenCL requires that we convert `true` boolean expressions to -1, but
8374 // only when splatting vectors.
8375 if (DestElemTy->isFloatingType()) {
8376 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8377 // in two steps: boolean to signed integral, then to floating.
8378 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8379 CK: CK_BooleanToSignedIntegral);
8380 SplattedExpr = CastExprRes.get();
8381 CK = CK_IntegralToFloating;
8382 } else {
8383 CK = CK_BooleanToSignedIntegral;
8384 }
8385 } else {
8386 ExprResult CastExprRes = SplattedExpr;
8387 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8388 if (CastExprRes.isInvalid())
8389 return ExprError();
8390 SplattedExpr = CastExprRes.get();
8391 }
8392 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8393}
8394
8395ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8396 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8397
8398 if (DestElemTy == SplattedExpr->getType())
8399 return SplattedExpr;
8400
8401 assert(DestElemTy->isFloatingType() ||
8402 DestElemTy->isIntegralOrEnumerationType());
8403
8404 ExprResult CastExprRes = SplattedExpr;
8405 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8406 if (CastExprRes.isInvalid())
8407 return ExprError();
8408 SplattedExpr = CastExprRes.get();
8409
8410 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8411}
8412
8413ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8414 Expr *CastExpr, CastKind &Kind) {
8415 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8416
8417 QualType SrcTy = CastExpr->getType();
8418
8419 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8420 // an ExtVectorType.
8421 // In OpenCL, casts between vectors of different types are not allowed.
8422 // (See OpenCL 6.2).
8423 if (SrcTy->isVectorType()) {
8424 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8425 (getLangOpts().OpenCL &&
8426 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8427 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8428 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8429 << DestTy << SrcTy << R;
8430 return ExprError();
8431 }
8432 Kind = CK_BitCast;
8433 return CastExpr;
8434 }
8435
8436 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8437 // conversion will take place first from scalar to elt type, and then
8438 // splat from elt type to vector.
8439 if (SrcTy->isPointerType())
8440 return Diag(Loc: R.getBegin(),
8441 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8442 << DestTy << SrcTy << R;
8443
8444 Kind = CK_VectorSplat;
8445 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8446}
8447
8448/// Check that a call to alloc_size function specifies sufficient space for the
8449/// destination type.
8450static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8451 const Expr *E) {
8452 QualType SourceType = E->getType();
8453 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8454 DestType == SourceType)
8455 return;
8456
8457 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8458 if (!CE)
8459 return;
8460
8461 // Find the total size allocated by the function call.
8462 if (!CE->getCalleeAllocSizeAttr())
8463 return;
8464 std::optional<llvm::APInt> AllocSize =
8465 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8466 // Allocations of size zero are permitted as a special case. They are usually
8467 // done intentionally.
8468 if (!AllocSize || AllocSize->isZero())
8469 return;
8470 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8471
8472 QualType TargetType = DestType->getPointeeType();
8473 // Find the destination size. As a special case function types have size of
8474 // one byte to match the sizeof operator behavior.
8475 auto LhsSize = TargetType->isFunctionType()
8476 ? CharUnits::One()
8477 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8478 if (LhsSize && Size < LhsSize)
8479 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8480 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8481}
8482
8483ExprResult
8484Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8485 Declarator &D, ParsedType &Ty,
8486 SourceLocation RParenLoc, Expr *CastExpr) {
8487 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8488 "ActOnCastExpr(): missing type or expr");
8489
8490 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8491 if (D.isInvalidType())
8492 return ExprError();
8493
8494 if (getLangOpts().CPlusPlus) {
8495 // Check that there are no default arguments (C++ only).
8496 CheckExtraCXXDefaultArguments(D);
8497 }
8498
8499 checkUnusedDeclAttributes(D);
8500
8501 QualType castType = castTInfo->getType();
8502 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8503
8504 bool isVectorLiteral = false;
8505
8506 // Check for an altivec or OpenCL literal,
8507 // i.e. all the elements are integer constants.
8508 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8509 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8510 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8511 && castType->isVectorType() && (PE || PLE)) {
8512 if (PLE && PLE->getNumExprs() == 0) {
8513 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8514 return ExprError();
8515 }
8516 if (PE || PLE->getNumExprs() == 1) {
8517 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8518 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8519 isVectorLiteral = true;
8520 }
8521 else
8522 isVectorLiteral = true;
8523 }
8524
8525 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8526 // then handle it as such.
8527 if (isVectorLiteral)
8528 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8529
8530 // If the Expr being casted is a ParenListExpr, handle it specially.
8531 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8532 // sequence of BinOp comma operators.
8533 if (isa<ParenListExpr>(Val: CastExpr)) {
8534 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8535 if (Result.isInvalid()) return ExprError();
8536 CastExpr = Result.get();
8537 }
8538
8539 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8540 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8541
8542 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8543
8544 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8545
8546 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8547
8548 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8549
8550 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8551}
8552
8553ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8554 SourceLocation RParenLoc, Expr *E,
8555 TypeSourceInfo *TInfo) {
8556 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8557 "Expected paren or paren list expression");
8558
8559 Expr **exprs;
8560 unsigned numExprs;
8561 Expr *subExpr;
8562 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8563 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8564 LiteralLParenLoc = PE->getLParenLoc();
8565 LiteralRParenLoc = PE->getRParenLoc();
8566 exprs = PE->getExprs();
8567 numExprs = PE->getNumExprs();
8568 } else { // isa<ParenExpr> by assertion at function entrance
8569 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8570 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8571 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8572 exprs = &subExpr;
8573 numExprs = 1;
8574 }
8575
8576 QualType Ty = TInfo->getType();
8577 assert(Ty->isVectorType() && "Expected vector type");
8578
8579 SmallVector<Expr *, 8> initExprs;
8580 const VectorType *VTy = Ty->castAs<VectorType>();
8581 unsigned numElems = VTy->getNumElements();
8582
8583 // '(...)' form of vector initialization in AltiVec: the number of
8584 // initializers must be one or must match the size of the vector.
8585 // If a single value is specified in the initializer then it will be
8586 // replicated to all the components of the vector
8587 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8588 SrcTy: VTy->getElementType()))
8589 return ExprError();
8590 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8591 // The number of initializers must be one or must match the size of the
8592 // vector. If a single value is specified in the initializer then it will
8593 // be replicated to all the components of the vector
8594 if (numExprs == 1) {
8595 QualType ElemTy = VTy->getElementType();
8596 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8597 if (Literal.isInvalid())
8598 return ExprError();
8599 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8600 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8601 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8602 }
8603 else if (numExprs < numElems) {
8604 Diag(Loc: E->getExprLoc(),
8605 DiagID: diag::err_incorrect_number_of_vector_initializers);
8606 return ExprError();
8607 }
8608 else
8609 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8610 }
8611 else {
8612 // For OpenCL, when the number of initializers is a single value,
8613 // it will be replicated to all components of the vector.
8614 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8615 numExprs == 1) {
8616 QualType SrcTy = exprs[0]->getType();
8617 if (!SrcTy->isArithmeticType()) {
8618 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8619 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8620 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8621 return ExprError();
8622 }
8623 QualType ElemTy = VTy->getElementType();
8624 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8625 if (Literal.isInvalid())
8626 return ExprError();
8627 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8628 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8629 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8630 }
8631
8632 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8633 }
8634 // FIXME: This means that pretty-printing the final AST will produce curly
8635 // braces instead of the original commas.
8636 InitListExpr *initE =
8637 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8638 LiteralRParenLoc, /*isExplicit=*/false);
8639 initE->setType(Ty);
8640 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8641}
8642
8643ExprResult
8644Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8645 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8646 if (!E)
8647 return OrigExpr;
8648
8649 ExprResult Result(E->getExpr(Init: 0));
8650
8651 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8652 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8653 RHSExpr: E->getExpr(Init: i));
8654
8655 if (Result.isInvalid()) return ExprError();
8656
8657 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8658}
8659
8660ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8661 SourceLocation R,
8662 MultiExprArg Val) {
8663 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8664}
8665
8666ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8667 unsigned NumUserSpecifiedExprs,
8668 SourceLocation InitLoc,
8669 SourceLocation LParenLoc,
8670 SourceLocation RParenLoc) {
8671 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8672 InitLoc, LParenLoc, RParenLoc);
8673}
8674
8675bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8676 SourceLocation QuestionLoc) {
8677 const Expr *NullExpr = LHSExpr;
8678 const Expr *NonPointerExpr = RHSExpr;
8679 Expr::NullPointerConstantKind NullKind =
8680 NullExpr->isNullPointerConstant(Ctx&: Context,
8681 NPC: Expr::NPC_ValueDependentIsNotNull);
8682
8683 if (NullKind == Expr::NPCK_NotNull) {
8684 NullExpr = RHSExpr;
8685 NonPointerExpr = LHSExpr;
8686 NullKind =
8687 NullExpr->isNullPointerConstant(Ctx&: Context,
8688 NPC: Expr::NPC_ValueDependentIsNotNull);
8689 }
8690
8691 if (NullKind == Expr::NPCK_NotNull)
8692 return false;
8693
8694 if (NullKind == Expr::NPCK_ZeroExpression)
8695 return false;
8696
8697 if (NullKind == Expr::NPCK_ZeroLiteral) {
8698 // In this case, check to make sure that we got here from a "NULL"
8699 // string in the source code.
8700 NullExpr = NullExpr->IgnoreParenImpCasts();
8701 SourceLocation loc = NullExpr->getExprLoc();
8702 if (!findMacroSpelling(loc, name: "NULL"))
8703 return false;
8704 }
8705
8706 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8707 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8708 << NonPointerExpr->getType() << DiagType
8709 << NonPointerExpr->getSourceRange();
8710 return true;
8711}
8712
8713/// Return false if the condition expression is valid, true otherwise.
8714static bool checkCondition(Sema &S, const Expr *Cond,
8715 SourceLocation QuestionLoc) {
8716 QualType CondTy = Cond->getType();
8717
8718 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8719 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8720 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8721 << CondTy << Cond->getSourceRange();
8722 return true;
8723 }
8724
8725 // C99 6.5.15p2
8726 if (CondTy->isScalarType()) return false;
8727
8728 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8729 << CondTy << Cond->getSourceRange();
8730 return true;
8731}
8732
8733/// Return false if the NullExpr can be promoted to PointerTy,
8734/// true otherwise.
8735static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8736 QualType PointerTy) {
8737 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8738 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8739 NPC: Expr::NPC_ValueDependentIsNull))
8740 return true;
8741
8742 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8743 return false;
8744}
8745
8746/// Checks compatibility between two pointers and return the resulting
8747/// type.
8748static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8749 ExprResult &RHS,
8750 SourceLocation Loc) {
8751 QualType LHSTy = LHS.get()->getType();
8752 QualType RHSTy = RHS.get()->getType();
8753
8754 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8755 // Two identical pointers types are always compatible.
8756 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8757 }
8758
8759 QualType lhptee, rhptee;
8760
8761 // Get the pointee types.
8762 bool IsBlockPointer = false;
8763 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8764 lhptee = LHSBTy->getPointeeType();
8765 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8766 IsBlockPointer = true;
8767 } else {
8768 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8769 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8770 }
8771
8772 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8773 // differently qualified versions of compatible types, the result type is
8774 // a pointer to an appropriately qualified version of the composite
8775 // type.
8776
8777 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8778 // clause doesn't make sense for our extensions. E.g. address space 2 should
8779 // be incompatible with address space 3: they may live on different devices or
8780 // anything.
8781 Qualifiers lhQual = lhptee.getQualifiers();
8782 Qualifiers rhQual = rhptee.getQualifiers();
8783
8784 LangAS ResultAddrSpace = LangAS::Default;
8785 LangAS LAddrSpace = lhQual.getAddressSpace();
8786 LangAS RAddrSpace = rhQual.getAddressSpace();
8787
8788 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8789 // spaces is disallowed.
8790 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8791 ResultAddrSpace = LAddrSpace;
8792 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8793 ResultAddrSpace = RAddrSpace;
8794 else {
8795 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8796 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8797 << RHS.get()->getSourceRange();
8798 return QualType();
8799 }
8800
8801 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8802 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8803 lhQual.removeCVRQualifiers();
8804 rhQual.removeCVRQualifiers();
8805
8806 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8807 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8808 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8809 << RHS.get()->getSourceRange();
8810 return QualType();
8811 }
8812
8813 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8814 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8815 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8816 // qual types are compatible iff
8817 // * corresponded types are compatible
8818 // * CVR qualifiers are equal
8819 // * address spaces are equal
8820 // Thus for conditional operator we merge CVR and address space unqualified
8821 // pointees and if there is a composite type we return a pointer to it with
8822 // merged qualifiers.
8823 LHSCastKind =
8824 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8825 RHSCastKind =
8826 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8827 lhQual.removeAddressSpace();
8828 rhQual.removeAddressSpace();
8829
8830 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8831 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8832
8833 QualType CompositeTy = S.Context.mergeTypes(
8834 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8835 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8836
8837 if (CompositeTy.isNull()) {
8838 // In this situation, we assume void* type. No especially good
8839 // reason, but this is what gcc does, and we do have to pick
8840 // to get a consistent AST.
8841 QualType incompatTy;
8842 incompatTy = S.Context.getPointerType(
8843 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8844 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8845 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8846
8847 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8848 // for casts between types with incompatible address space qualifiers.
8849 // For the following code the compiler produces casts between global and
8850 // local address spaces of the corresponded innermost pointees:
8851 // local int *global *a;
8852 // global int *global *b;
8853 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8854 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8855 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8856 << RHS.get()->getSourceRange();
8857
8858 return incompatTy;
8859 }
8860
8861 // The pointer types are compatible.
8862 // In case of OpenCL ResultTy should have the address space qualifier
8863 // which is a superset of address spaces of both the 2nd and the 3rd
8864 // operands of the conditional operator.
8865 QualType ResultTy = [&, ResultAddrSpace]() {
8866 if (S.getLangOpts().OpenCL) {
8867 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8868 CompositeQuals.setAddressSpace(ResultAddrSpace);
8869 return S.Context
8870 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8871 .withCVRQualifiers(CVR: MergedCVRQual);
8872 }
8873 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8874 }();
8875 if (IsBlockPointer)
8876 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8877 else
8878 ResultTy = S.Context.getPointerType(T: ResultTy);
8879
8880 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8881 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8882 return ResultTy;
8883}
8884
8885/// Return the resulting type when the operands are both block pointers.
8886static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8887 ExprResult &LHS,
8888 ExprResult &RHS,
8889 SourceLocation Loc) {
8890 QualType LHSTy = LHS.get()->getType();
8891 QualType RHSTy = RHS.get()->getType();
8892
8893 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8894 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8895 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8896 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8897 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8898 return destType;
8899 }
8900 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8901 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8902 << RHS.get()->getSourceRange();
8903 return QualType();
8904 }
8905
8906 // We have 2 block pointer types.
8907 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8908}
8909
8910/// Return the resulting type when the operands are both pointers.
8911static QualType
8912checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8913 ExprResult &RHS,
8914 SourceLocation Loc) {
8915 // get the pointer types
8916 QualType LHSTy = LHS.get()->getType();
8917 QualType RHSTy = RHS.get()->getType();
8918
8919 // get the "pointed to" types
8920 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8921 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8922
8923 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8924 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8925 // Figure out necessary qualifiers (C99 6.5.15p6)
8926 QualType destPointee
8927 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8928 QualType destType = S.Context.getPointerType(T: destPointee);
8929 // Add qualifiers if necessary.
8930 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8931 // Promote to void*.
8932 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8933 return destType;
8934 }
8935 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8936 QualType destPointee
8937 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8938 QualType destType = S.Context.getPointerType(T: destPointee);
8939 // Add qualifiers if necessary.
8940 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8941 // Promote to void*.
8942 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8943 return destType;
8944 }
8945
8946 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8947}
8948
8949/// Return false if the first expression is not an integer and the second
8950/// expression is not a pointer, true otherwise.
8951static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8952 Expr* PointerExpr, SourceLocation Loc,
8953 bool IsIntFirstExpr) {
8954 if (!PointerExpr->getType()->isPointerType() ||
8955 !Int.get()->getType()->isIntegerType())
8956 return false;
8957
8958 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8959 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8960
8961 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8962 << Expr1->getType() << Expr2->getType()
8963 << Expr1->getSourceRange() << Expr2->getSourceRange();
8964 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8965 CK: CK_IntegralToPointer);
8966 return true;
8967}
8968
8969/// Simple conversion between integer and floating point types.
8970///
8971/// Used when handling the OpenCL conditional operator where the
8972/// condition is a vector while the other operands are scalar.
8973///
8974/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8975/// types are either integer or floating type. Between the two
8976/// operands, the type with the higher rank is defined as the "result
8977/// type". The other operand needs to be promoted to the same type. No
8978/// other type promotion is allowed. We cannot use
8979/// UsualArithmeticConversions() for this purpose, since it always
8980/// promotes promotable types.
8981static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8982 ExprResult &RHS,
8983 SourceLocation QuestionLoc) {
8984 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8985 if (LHS.isInvalid())
8986 return QualType();
8987 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8988 if (RHS.isInvalid())
8989 return QualType();
8990
8991 // For conversion purposes, we ignore any qualifiers.
8992 // For example, "const float" and "float" are equivalent.
8993 QualType LHSType =
8994 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8995 QualType RHSType =
8996 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8997
8998 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8999 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
9000 << LHSType << LHS.get()->getSourceRange();
9001 return QualType();
9002 }
9003
9004 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
9005 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
9006 << RHSType << RHS.get()->getSourceRange();
9007 return QualType();
9008 }
9009
9010 // If both types are identical, no conversion is needed.
9011 if (LHSType == RHSType)
9012 return LHSType;
9013
9014 // Now handle "real" floating types (i.e. float, double, long double).
9015 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
9016 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
9017 /*IsCompAssign = */ false);
9018
9019 // Finally, we have two differing integer types.
9020 return handleIntegerConversion<doIntegralCast, doIntegralCast>
9021 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
9022}
9023
9024/// Convert scalar operands to a vector that matches the
9025/// condition in length.
9026///
9027/// Used when handling the OpenCL conditional operator where the
9028/// condition is a vector while the other operands are scalar.
9029///
9030/// We first compute the "result type" for the scalar operands
9031/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
9032/// into a vector of that type where the length matches the condition
9033/// vector type. s6.11.6 requires that the element types of the result
9034/// and the condition must have the same number of bits.
9035static QualType
9036OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
9037 QualType CondTy, SourceLocation QuestionLoc) {
9038 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
9039 if (ResTy.isNull()) return QualType();
9040
9041 const VectorType *CV = CondTy->getAs<VectorType>();
9042 assert(CV);
9043
9044 // Determine the vector result type
9045 unsigned NumElements = CV->getNumElements();
9046 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
9047
9048 // Ensure that all types have the same number of bits
9049 if (S.Context.getTypeSize(T: CV->getElementType())
9050 != S.Context.getTypeSize(T: ResTy)) {
9051 // Since VectorTy is created internally, it does not pretty print
9052 // with an OpenCL name. Instead, we just print a description.
9053 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
9054 SmallString<64> Str;
9055 llvm::raw_svector_ostream OS(Str);
9056 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
9057 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
9058 << CondTy << OS.str();
9059 return QualType();
9060 }
9061
9062 // Convert operands to the vector result type
9063 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
9064 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
9065
9066 return VectorTy;
9067}
9068
9069/// Return false if this is a valid OpenCL condition vector
9070static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
9071 SourceLocation QuestionLoc) {
9072 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9073 // integral type.
9074 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
9075 assert(CondTy);
9076 QualType EleTy = CondTy->getElementType();
9077 if (EleTy->isIntegerType()) return false;
9078
9079 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
9080 << Cond->getType() << Cond->getSourceRange();
9081 return true;
9082}
9083
9084/// Return false if the vector condition type and the vector
9085/// result type are compatible.
9086///
9087/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9088/// number of elements, and their element types have the same number
9089/// of bits.
9090static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
9091 SourceLocation QuestionLoc) {
9092 const VectorType *CV = CondTy->getAs<VectorType>();
9093 const VectorType *RV = VecResTy->getAs<VectorType>();
9094 assert(CV && RV);
9095
9096 if (CV->getNumElements() != RV->getNumElements()) {
9097 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
9098 << CondTy << VecResTy;
9099 return true;
9100 }
9101
9102 QualType CVE = CV->getElementType();
9103 QualType RVE = RV->getElementType();
9104
9105 // Boolean vectors are permitted outside of OpenCL mode.
9106 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
9107 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
9108 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
9109 << CondTy << VecResTy;
9110 return true;
9111 }
9112
9113 return false;
9114}
9115
9116/// Return the resulting type for the conditional operator in
9117/// OpenCL (aka "ternary selection operator", OpenCL v1.1
9118/// s6.3.i) when the condition is a vector type.
9119static QualType
9120OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9121 ExprResult &LHS, ExprResult &RHS,
9122 SourceLocation QuestionLoc) {
9123 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
9124 if (Cond.isInvalid())
9125 return QualType();
9126 QualType CondTy = Cond.get()->getType();
9127
9128 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
9129 return QualType();
9130
9131 // If either operand is a vector then find the vector type of the
9132 // result as specified in OpenCL v1.1 s6.3.i.
9133 if (LHS.get()->getType()->isVectorType() ||
9134 RHS.get()->getType()->isVectorType()) {
9135 bool IsBoolVecLang =
9136 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9137 QualType VecResTy =
9138 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
9139 /*isCompAssign*/ IsCompAssign: false,
9140 /*AllowBothBool*/ true,
9141 /*AllowBoolConversions*/ AllowBoolConversion: false,
9142 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang);
9143 if (VecResTy.isNull())
9144 return QualType();
9145 // The result type must match the condition type as specified in
9146 // OpenCL v1.1 s6.11.6.
9147 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9148 return QualType();
9149 return VecResTy;
9150 }
9151
9152 // Both operands are scalar.
9153 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9154}
9155
9156/// Return true if the Expr is block type
9157static bool checkBlockType(Sema &S, const Expr *E) {
9158 if (E->getType()->isBlockPointerType()) {
9159 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
9160 return true;
9161 }
9162
9163 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
9164 QualType Ty = CE->getCallee()->getType();
9165 if (Ty->isBlockPointerType()) {
9166 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
9167 return true;
9168 }
9169 }
9170 return false;
9171}
9172
9173/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9174/// In that case, LHS = cond.
9175/// C99 6.5.15
9176QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9177 ExprResult &RHS, ExprValueKind &VK,
9178 ExprObjectKind &OK,
9179 SourceLocation QuestionLoc) {
9180
9181 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
9182 if (!LHSResult.isUsable()) return QualType();
9183 LHS = LHSResult;
9184
9185 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
9186 if (!RHSResult.isUsable()) return QualType();
9187 RHS = RHSResult;
9188
9189 // C++ is sufficiently different to merit its own checker.
9190 if (getLangOpts().CPlusPlus)
9191 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
9192
9193 VK = VK_PRValue;
9194 OK = OK_Ordinary;
9195
9196 if (Context.isDependenceAllowed() &&
9197 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9198 RHS.get()->isTypeDependent())) {
9199 assert(!getLangOpts().CPlusPlus);
9200 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9201 RHS.get()->containsErrors()) &&
9202 "should only occur in error-recovery path.");
9203 return Context.DependentTy;
9204 }
9205
9206 // The OpenCL operator with a vector condition is sufficiently
9207 // different to merit its own checker.
9208 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9209 Cond.get()->getType()->isExtVectorType())
9210 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
9211
9212 // First, check the condition.
9213 Cond = UsualUnaryConversions(E: Cond.get());
9214 if (Cond.isInvalid())
9215 return QualType();
9216 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
9217 return QualType();
9218
9219 // Handle vectors.
9220 if (LHS.get()->getType()->isVectorType() ||
9221 RHS.get()->getType()->isVectorType())
9222 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
9223 /*AllowBothBool*/ true,
9224 /*AllowBoolConversions*/ AllowBoolConversion: false,
9225 /*AllowBooleanOperation*/ AllowBoolOperation: false);
9226
9227 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
9228 ACK: ArithConvKind::Conditional);
9229 if (LHS.isInvalid() || RHS.isInvalid())
9230 return QualType();
9231
9232 // WebAssembly tables are not allowed as conditional LHS or RHS.
9233 QualType LHSTy = LHS.get()->getType();
9234 QualType RHSTy = RHS.get()->getType();
9235 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9236 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
9237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9238 return QualType();
9239 }
9240
9241 // Diagnose attempts to convert between __ibm128, __float128 and long double
9242 // where such conversions currently can't be handled.
9243 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
9244 Diag(Loc: QuestionLoc,
9245 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9246 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9247 return QualType();
9248 }
9249
9250 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9251 // selection operator (?:).
9252 if (getLangOpts().OpenCL &&
9253 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
9254 return QualType();
9255 }
9256
9257 // If both operands have arithmetic type, do the usual arithmetic conversions
9258 // to find a common type: C99 6.5.15p3,5.
9259 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9260 // Disallow invalid arithmetic conversions, such as those between bit-
9261 // precise integers types of different sizes, or between a bit-precise
9262 // integer and another type.
9263 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9264 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9265 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9266 << RHS.get()->getSourceRange();
9267 return QualType();
9268 }
9269
9270 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
9271 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
9272
9273 return ResTy;
9274 }
9275
9276 // If both operands are the same structure or union type, the result is that
9277 // type.
9278 // FIXME: Type of conditional expression must be complete in C mode.
9279 if (LHSTy->isRecordType() &&
9280 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
9281 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9282 Y: RHSTy.getUnqualifiedType());
9283
9284 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9285 // The following || allows only one side to be void (a GCC-ism).
9286 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9287 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9288 // UsualArithmeticConversions already handled the case where both sides
9289 // are the same type.
9290 } else if (RHSTy->isVoidType()) {
9291 ResTy = RHSTy;
9292 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9293 << RHS.get()->getSourceRange();
9294 } else {
9295 ResTy = LHSTy;
9296 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9297 << LHS.get()->getSourceRange();
9298 }
9299 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9300 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9301 return ResTy;
9302 }
9303
9304 // C23 6.5.15p7:
9305 // ... if both the second and third operands have nullptr_t type, the
9306 // result also has that type.
9307 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9308 return ResTy;
9309
9310 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9311 // the type of the other operand."
9312 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9313 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9314
9315 // All objective-c pointer type analysis is done here.
9316 QualType compositeType =
9317 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9318 if (LHS.isInvalid() || RHS.isInvalid())
9319 return QualType();
9320 if (!compositeType.isNull())
9321 return compositeType;
9322
9323
9324 // Handle block pointer types.
9325 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9326 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9327 Loc: QuestionLoc);
9328
9329 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9330 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9331 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9332 Loc: QuestionLoc);
9333
9334 // GCC compatibility: soften pointer/integer mismatch. Note that
9335 // null pointers have been filtered out by this point.
9336 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9337 /*IsIntFirstExpr=*/true))
9338 return RHSTy;
9339 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9340 /*IsIntFirstExpr=*/false))
9341 return LHSTy;
9342
9343 // Emit a better diagnostic if one of the expressions is a null pointer
9344 // constant and the other is not a pointer type. In this case, the user most
9345 // likely forgot to take the address of the other expression.
9346 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9347 return QualType();
9348
9349 // Finally, if the LHS and RHS types are canonically the same type, we can
9350 // use the common sugared type.
9351 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9352 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9353
9354 // Otherwise, the operands are not compatible.
9355 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9356 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9357 << RHS.get()->getSourceRange();
9358 return QualType();
9359}
9360
9361/// SuggestParentheses - Emit a note with a fixit hint that wraps
9362/// ParenRange in parentheses.
9363static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9364 const PartialDiagnostic &Note,
9365 SourceRange ParenRange) {
9366 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9367 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9368 EndLoc.isValid()) {
9369 Self.Diag(Loc, PD: Note)
9370 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9371 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9372 } else {
9373 // We can't display the parentheses, so just show the bare note.
9374 Self.Diag(Loc, PD: Note) << ParenRange;
9375 }
9376}
9377
9378static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9379 return BinaryOperator::isAdditiveOp(Opc) ||
9380 BinaryOperator::isMultiplicativeOp(Opc) ||
9381 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9382 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9383 // not any of the logical operators. Bitwise-xor is commonly used as a
9384 // logical-xor because there is no logical-xor operator. The logical
9385 // operators, including uses of xor, have a high false positive rate for
9386 // precedence warnings.
9387}
9388
9389/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9390/// expression, either using a built-in or overloaded operator,
9391/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9392/// expression.
9393static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9394 const Expr **RHSExprs) {
9395 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9396 E = E->IgnoreImpCasts();
9397 E = E->IgnoreConversionOperatorSingleStep();
9398 E = E->IgnoreImpCasts();
9399 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9400 E = MTE->getSubExpr();
9401 E = E->IgnoreImpCasts();
9402 }
9403
9404 // Built-in binary operator.
9405 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9406 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9407 *Opcode = OP->getOpcode();
9408 *RHSExprs = OP->getRHS();
9409 return true;
9410 }
9411
9412 // Overloaded operator.
9413 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9414 if (Call->getNumArgs() != 2)
9415 return false;
9416
9417 // Make sure this is really a binary operator that is safe to pass into
9418 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9419 OverloadedOperatorKind OO = Call->getOperator();
9420 if (OO < OO_Plus || OO > OO_Arrow ||
9421 OO == OO_PlusPlus || OO == OO_MinusMinus)
9422 return false;
9423
9424 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9425 if (IsArithmeticOp(Opc: OpKind)) {
9426 *Opcode = OpKind;
9427 *RHSExprs = Call->getArg(Arg: 1);
9428 return true;
9429 }
9430 }
9431
9432 return false;
9433}
9434
9435/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9436/// or is a logical expression such as (x==y) which has int type, but is
9437/// commonly interpreted as boolean.
9438static bool ExprLooksBoolean(const Expr *E) {
9439 E = E->IgnoreParenImpCasts();
9440
9441 if (E->getType()->isBooleanType())
9442 return true;
9443 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9444 return OP->isComparisonOp() || OP->isLogicalOp();
9445 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9446 return OP->getOpcode() == UO_LNot;
9447 if (E->getType()->isPointerType())
9448 return true;
9449 // FIXME: What about overloaded operator calls returning "unspecified boolean
9450 // type"s (commonly pointer-to-members)?
9451
9452 return false;
9453}
9454
9455/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9456/// and binary operator are mixed in a way that suggests the programmer assumed
9457/// the conditional operator has higher precedence, for example:
9458/// "int x = a + someBinaryCondition ? 1 : 2".
9459static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9460 Expr *Condition, const Expr *LHSExpr,
9461 const Expr *RHSExpr) {
9462 BinaryOperatorKind CondOpcode;
9463 const Expr *CondRHS;
9464
9465 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9466 return;
9467 if (!ExprLooksBoolean(E: CondRHS))
9468 return;
9469
9470 // The condition is an arithmetic binary expression, with a right-
9471 // hand side that looks boolean, so warn.
9472
9473 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9474 ? diag::warn_precedence_bitwise_conditional
9475 : diag::warn_precedence_conditional;
9476
9477 Self.Diag(Loc: OpLoc, DiagID)
9478 << Condition->getSourceRange()
9479 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9480
9481 SuggestParentheses(
9482 Self, Loc: OpLoc,
9483 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9484 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9485 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9486
9487 SuggestParentheses(Self, Loc: OpLoc,
9488 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9489 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9490}
9491
9492/// Compute the nullability of a conditional expression.
9493static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9494 QualType LHSTy, QualType RHSTy,
9495 ASTContext &Ctx) {
9496 if (!ResTy->isAnyPointerType())
9497 return ResTy;
9498
9499 auto GetNullability = [](QualType Ty) {
9500 NullabilityKindOrNone Kind = Ty->getNullability();
9501 if (Kind) {
9502 // For our purposes, treat _Nullable_result as _Nullable.
9503 if (*Kind == NullabilityKind::NullableResult)
9504 return NullabilityKind::Nullable;
9505 return *Kind;
9506 }
9507 return NullabilityKind::Unspecified;
9508 };
9509
9510 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9511 NullabilityKind MergedKind;
9512
9513 // Compute nullability of a binary conditional expression.
9514 if (IsBin) {
9515 if (LHSKind == NullabilityKind::NonNull)
9516 MergedKind = NullabilityKind::NonNull;
9517 else
9518 MergedKind = RHSKind;
9519 // Compute nullability of a normal conditional expression.
9520 } else {
9521 if (LHSKind == NullabilityKind::Nullable ||
9522 RHSKind == NullabilityKind::Nullable)
9523 MergedKind = NullabilityKind::Nullable;
9524 else if (LHSKind == NullabilityKind::NonNull)
9525 MergedKind = RHSKind;
9526 else if (RHSKind == NullabilityKind::NonNull)
9527 MergedKind = LHSKind;
9528 else
9529 MergedKind = NullabilityKind::Unspecified;
9530 }
9531
9532 // Return if ResTy already has the correct nullability.
9533 if (GetNullability(ResTy) == MergedKind)
9534 return ResTy;
9535
9536 // Strip all nullability from ResTy.
9537 while (ResTy->getNullability())
9538 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9539
9540 // Create a new AttributedType with the new nullability kind.
9541 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9542}
9543
9544ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9545 SourceLocation ColonLoc,
9546 Expr *CondExpr, Expr *LHSExpr,
9547 Expr *RHSExpr) {
9548 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9549 // was the condition.
9550 OpaqueValueExpr *opaqueValue = nullptr;
9551 Expr *commonExpr = nullptr;
9552 if (!LHSExpr) {
9553 commonExpr = CondExpr;
9554 // Lower out placeholder types first. This is important so that we don't
9555 // try to capture a placeholder. This happens in few cases in C++; such
9556 // as Objective-C++'s dictionary subscripting syntax.
9557 if (commonExpr->hasPlaceholderType()) {
9558 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9559 if (!result.isUsable()) return ExprError();
9560 commonExpr = result.get();
9561 }
9562 // We usually want to apply unary conversions *before* saving, except
9563 // in the special case of a C++ l-value conditional.
9564 if (!(getLangOpts().CPlusPlus
9565 && !commonExpr->isTypeDependent()
9566 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9567 && commonExpr->isGLValue()
9568 && commonExpr->isOrdinaryOrBitFieldObject()
9569 && RHSExpr->isOrdinaryOrBitFieldObject()
9570 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9571 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9572 if (commonRes.isInvalid())
9573 return ExprError();
9574 commonExpr = commonRes.get();
9575 }
9576
9577 // If the common expression is a class or array prvalue, materialize it
9578 // so that we can safely refer to it multiple times.
9579 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9580 commonExpr->getType()->isArrayType())) {
9581 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9582 if (MatExpr.isInvalid())
9583 return ExprError();
9584 commonExpr = MatExpr.get();
9585 }
9586
9587 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9588 commonExpr->getType(),
9589 commonExpr->getValueKind(),
9590 commonExpr->getObjectKind(),
9591 commonExpr);
9592 LHSExpr = CondExpr = opaqueValue;
9593 }
9594
9595 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9596 ExprValueKind VK = VK_PRValue;
9597 ExprObjectKind OK = OK_Ordinary;
9598 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9599 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9600 VK, OK, QuestionLoc);
9601 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9602 RHS.isInvalid())
9603 return ExprError();
9604
9605 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9606 RHSExpr: RHS.get());
9607
9608 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9609
9610 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9611 Ctx&: Context);
9612
9613 if (!commonExpr)
9614 return new (Context)
9615 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9616 RHS.get(), result, VK, OK);
9617
9618 return new (Context) BinaryConditionalOperator(
9619 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9620 ColonLoc, result, VK, OK);
9621}
9622
9623bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9624 unsigned FromAttributes = 0, ToAttributes = 0;
9625 if (const auto *FromFn =
9626 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9627 FromAttributes =
9628 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9629 if (const auto *ToFn =
9630 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9631 ToAttributes =
9632 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9633
9634 return FromAttributes != ToAttributes;
9635}
9636
9637// checkPointerTypesForAssignment - This is a very tricky routine (despite
9638// being closely modeled after the C99 spec:-). The odd characteristic of this
9639// routine is it effectively iqnores the qualifiers on the top level pointee.
9640// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9641// FIXME: add a couple examples in this comment.
9642static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9643 QualType LHSType,
9644 QualType RHSType,
9645 SourceLocation Loc) {
9646 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9647 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9648
9649 // get the "pointed to" type (ignoring qualifiers at the top level)
9650 const Type *lhptee, *rhptee;
9651 Qualifiers lhq, rhq;
9652 std::tie(args&: lhptee, args&: lhq) =
9653 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9654 std::tie(args&: rhptee, args&: rhq) =
9655 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9656
9657 AssignConvertType ConvTy = AssignConvertType::Compatible;
9658
9659 // C99 6.5.16.1p1: This following citation is common to constraints
9660 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9661 // qualifiers of the type *pointed to* by the right;
9662
9663 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9664 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9665 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9666 // Ignore lifetime for further calculation.
9667 lhq.removeObjCLifetime();
9668 rhq.removeObjCLifetime();
9669 }
9670
9671 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9672 // Treat address-space mismatches as fatal.
9673 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9674 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9675
9676 // It's okay to add or remove GC or lifetime qualifiers when converting to
9677 // and from void*.
9678 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9679 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9680 Ctx: S.getASTContext()) &&
9681 (lhptee->isVoidType() || rhptee->isVoidType()))
9682 ; // keep old
9683
9684 // Treat lifetime mismatches as fatal.
9685 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9686 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9687
9688 // Treat pointer-auth mismatches as fatal.
9689 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9690 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9691
9692 // For GCC/MS compatibility, other qualifier mismatches are treated
9693 // as still compatible in C.
9694 else
9695 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9696 }
9697
9698 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9699 // incomplete type and the other is a pointer to a qualified or unqualified
9700 // version of void...
9701 if (lhptee->isVoidType()) {
9702 if (rhptee->isIncompleteOrObjectType())
9703 return ConvTy;
9704
9705 // As an extension, we allow cast to/from void* to function pointer.
9706 assert(rhptee->isFunctionType());
9707 return AssignConvertType::FunctionVoidPointer;
9708 }
9709
9710 if (rhptee->isVoidType()) {
9711 // In C, void * to another pointer type is compatible, but we want to note
9712 // that there will be an implicit conversion happening here.
9713 if (lhptee->isIncompleteOrObjectType())
9714 return ConvTy == AssignConvertType::Compatible &&
9715 !S.getLangOpts().CPlusPlus
9716 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9717 : ConvTy;
9718
9719 // As an extension, we allow cast to/from void* to function pointer.
9720 assert(lhptee->isFunctionType());
9721 return AssignConvertType::FunctionVoidPointer;
9722 }
9723
9724 if (!S.Diags.isIgnored(
9725 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9726 Loc) &&
9727 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9728 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9729 return AssignConvertType::IncompatibleFunctionPointerStrict;
9730
9731 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9732 // unqualified versions of compatible types, ...
9733 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9734
9735 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9736 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9737 QualType LUnderlying =
9738 ltrans->isOverflowBehaviorType()
9739 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9740 : ltrans;
9741 QualType RUnderlying =
9742 rtrans->isOverflowBehaviorType()
9743 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9744 : rtrans;
9745
9746 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9747 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9748
9749 ltrans = LUnderlying;
9750 rtrans = RUnderlying;
9751 }
9752 }
9753
9754 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9755 // Check if the pointee types are compatible ignoring the sign.
9756 // We explicitly check for char so that we catch "char" vs
9757 // "unsigned char" on systems where "char" is unsigned.
9758 if (lhptee->isCharType())
9759 ltrans = S.Context.UnsignedCharTy;
9760 else if (lhptee->hasSignedIntegerRepresentation())
9761 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9762
9763 if (rhptee->isCharType())
9764 rtrans = S.Context.UnsignedCharTy;
9765 else if (rhptee->hasSignedIntegerRepresentation())
9766 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9767
9768 if (ltrans == rtrans) {
9769 // Types are compatible ignoring the sign. Qualifier incompatibility
9770 // takes priority over sign incompatibility because the sign
9771 // warning can be disabled.
9772 if (!S.IsAssignConvertCompatible(ConvTy))
9773 return ConvTy;
9774
9775 return AssignConvertType::IncompatiblePointerSign;
9776 }
9777
9778 // If we are a multi-level pointer, it's possible that our issue is simply
9779 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9780 // the eventual target type is the same and the pointers have the same
9781 // level of indirection, this must be the issue.
9782 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9783 do {
9784 std::tie(args&: lhptee, args&: lhq) =
9785 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9786 std::tie(args&: rhptee, args&: rhq) =
9787 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9788
9789 // Inconsistent address spaces at this point is invalid, even if the
9790 // address spaces would be compatible.
9791 // FIXME: This doesn't catch address space mismatches for pointers of
9792 // different nesting levels, like:
9793 // __local int *** a;
9794 // int ** b = a;
9795 // It's not clear how to actually determine when such pointers are
9796 // invalidly incompatible.
9797 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9798 return AssignConvertType::
9799 IncompatibleNestedPointerAddressSpaceMismatch;
9800
9801 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9802
9803 if (lhptee == rhptee)
9804 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9805 }
9806
9807 // General pointer incompatibility takes priority over qualifiers.
9808 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9809 return AssignConvertType::IncompatibleFunctionPointer;
9810 return AssignConvertType::IncompatiblePointer;
9811 }
9812 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9813 // hasSameType, so we can skip further checks.
9814 const auto *LFT = ltrans->getAs<FunctionType>();
9815 const auto *RFT = rtrans->getAs<FunctionType>();
9816 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9817 // The invocation of IsFunctionConversion below will try to transform rtrans
9818 // to obtain an exact match for ltrans. This should not fail because of
9819 // mismatches in result type and parameter types, they were already checked
9820 // by typesAreCompatible above. So we will recreate rtrans (or where
9821 // appropriate ltrans) using the result type and parameter types from ltrans
9822 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9823 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9824 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9825 if (LFPT && RFPT) {
9826 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9827 Args: LFPT->getParamTypes(),
9828 EPI: RFPT->getExtProtoInfo());
9829 } else if (LFPT) {
9830 FunctionProtoType::ExtProtoInfo EPI;
9831 EPI.ExtInfo = RFT->getExtInfo();
9832 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9833 Args: LFPT->getParamTypes(), EPI);
9834 } else if (RFPT) {
9835 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9836 // all of its ExtProtoInfo. Transform ltrans instead.
9837 FunctionProtoType::ExtProtoInfo EPI;
9838 EPI.ExtInfo = LFT->getExtInfo();
9839 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9840 Args: RFPT->getParamTypes(), EPI);
9841 } else {
9842 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9843 Info: RFT->getExtInfo());
9844 }
9845 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9846 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9847 return AssignConvertType::IncompatibleFunctionPointer;
9848 }
9849 return ConvTy;
9850}
9851
9852/// checkBlockPointerTypesForAssignment - This routine determines whether two
9853/// block pointer types are compatible or whether a block and normal pointer
9854/// are compatible. It is more restrict than comparing two function pointer
9855// types.
9856static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9857 QualType LHSType,
9858 QualType RHSType) {
9859 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9860 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9861
9862 QualType lhptee, rhptee;
9863
9864 // get the "pointed to" type (ignoring qualifiers at the top level)
9865 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9866 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9867
9868 // In C++, the types have to match exactly.
9869 if (S.getLangOpts().CPlusPlus)
9870 return AssignConvertType::IncompatibleBlockPointer;
9871
9872 AssignConvertType ConvTy = AssignConvertType::Compatible;
9873
9874 // For blocks we enforce that qualifiers are identical.
9875 Qualifiers LQuals = lhptee.getLocalQualifiers();
9876 Qualifiers RQuals = rhptee.getLocalQualifiers();
9877 if (S.getLangOpts().OpenCL) {
9878 LQuals.removeAddressSpace();
9879 RQuals.removeAddressSpace();
9880 }
9881 if (LQuals != RQuals)
9882 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9883
9884 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9885 // assignment.
9886 // The current behavior is similar to C++ lambdas. A block might be
9887 // assigned to a variable iff its return type and parameters are compatible
9888 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9889 // an assignment. Presumably it should behave in way that a function pointer
9890 // assignment does in C, so for each parameter and return type:
9891 // * CVR and address space of LHS should be a superset of CVR and address
9892 // space of RHS.
9893 // * unqualified types should be compatible.
9894 if (S.getLangOpts().OpenCL) {
9895 if (!S.Context.typesAreBlockPointerCompatible(
9896 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9897 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9898 return AssignConvertType::IncompatibleBlockPointer;
9899 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9900 return AssignConvertType::IncompatibleBlockPointer;
9901
9902 return ConvTy;
9903}
9904
9905/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9906/// for assignment compatibility.
9907static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9908 QualType LHSType,
9909 QualType RHSType) {
9910 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9911 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9912
9913 if (LHSType->isObjCBuiltinType()) {
9914 // Class is not compatible with ObjC object pointers.
9915 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9916 !RHSType->isObjCQualifiedClassType())
9917 return AssignConvertType::IncompatiblePointer;
9918 return AssignConvertType::Compatible;
9919 }
9920 if (RHSType->isObjCBuiltinType()) {
9921 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9922 !LHSType->isObjCQualifiedClassType())
9923 return AssignConvertType::IncompatiblePointer;
9924 return AssignConvertType::Compatible;
9925 }
9926 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9927 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9928
9929 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9930 // make an exception for id<P>
9931 !LHSType->isObjCQualifiedIdType())
9932 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9933
9934 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9935 return AssignConvertType::Compatible;
9936 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9937 return AssignConvertType::IncompatibleObjCQualifiedId;
9938 return AssignConvertType::IncompatiblePointer;
9939}
9940
9941AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9942 QualType LHSType,
9943 QualType RHSType) {
9944 // Fake up an opaque expression. We don't actually care about what
9945 // cast operations are required, so if CheckAssignmentConstraints
9946 // adds casts to this they'll be wasted, but fortunately that doesn't
9947 // usually happen on valid code.
9948 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9949 ExprResult RHSPtr = &RHSExpr;
9950 CastKind K;
9951
9952 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9953}
9954
9955/// This helper function returns true if QT is a vector type that has element
9956/// type ElementType.
9957static bool isVector(QualType QT, QualType ElementType) {
9958 if (const VectorType *VT = QT->getAs<VectorType>())
9959 return VT->getElementType().getCanonicalType() == ElementType;
9960 return false;
9961}
9962
9963/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9964/// has code to accommodate several GCC extensions when type checking
9965/// pointers. Here are some objectionable examples that GCC considers warnings:
9966///
9967/// int a, *pint;
9968/// short *pshort;
9969/// struct foo *pfoo;
9970///
9971/// pint = pshort; // warning: assignment from incompatible pointer type
9972/// a = pint; // warning: assignment makes integer from pointer without a cast
9973/// pint = a; // warning: assignment makes pointer from integer without a cast
9974/// pint = pfoo; // warning: assignment from incompatible pointer type
9975///
9976/// As a result, the code for dealing with pointers is more complex than the
9977/// C99 spec dictates.
9978///
9979/// Sets 'Kind' for any result kind except Incompatible.
9980AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9981 ExprResult &RHS,
9982 CastKind &Kind,
9983 bool ConvertRHS) {
9984 QualType RHSType = RHS.get()->getType();
9985 QualType OrigLHSType = LHSType;
9986
9987 // Get canonical types. We're not formatting these types, just comparing
9988 // them.
9989 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9990 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9991
9992 // Common case: no conversion required.
9993 if (LHSType == RHSType) {
9994 Kind = CK_NoOp;
9995 return AssignConvertType::Compatible;
9996 }
9997
9998 // If the LHS has an __auto_type, there are no additional type constraints
9999 // to be worried about.
10000 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
10001 if (AT->isGNUAutoType()) {
10002 Kind = CK_NoOp;
10003 return AssignConvertType::Compatible;
10004 }
10005 }
10006
10007 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
10008 switch (OBTResult) {
10009 case ASTContext::OBTAssignResult::IncompatibleKinds:
10010 Kind = CK_NoOp;
10011 return AssignConvertType::IncompatibleOBTKinds;
10012 case ASTContext::OBTAssignResult::Discards:
10013 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
10014 return AssignConvertType::CompatibleOBTDiscards;
10015 case ASTContext::OBTAssignResult::Compatible:
10016 case ASTContext::OBTAssignResult::NotApplicable:
10017 break;
10018 }
10019
10020 // Check for incompatible OBT types in pointer pointee types
10021 if (LHSType->isPointerType() && RHSType->isPointerType()) {
10022 QualType LHSPointee = LHSType->getPointeeType();
10023 QualType RHSPointee = RHSType->getPointeeType();
10024 if ((LHSPointee->isOverflowBehaviorType() ||
10025 RHSPointee->isOverflowBehaviorType()) &&
10026 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
10027 Kind = CK_NoOp;
10028 return AssignConvertType::IncompatibleOBTKinds;
10029 }
10030 }
10031
10032 // If we have an atomic type, try a non-atomic assignment, then just add an
10033 // atomic qualification step.
10034 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
10035 AssignConvertType Result =
10036 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
10037 if (!IsAssignConvertCompatible(ConvTy: Result))
10038 return Result;
10039 if (Kind != CK_NoOp && ConvertRHS)
10040 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
10041 Kind = CK_NonAtomicToAtomic;
10042 return Result;
10043 }
10044
10045 // If the left-hand side is a reference type, then we are in a
10046 // (rare!) case where we've allowed the use of references in C,
10047 // e.g., as a parameter type in a built-in function. In this case,
10048 // just make sure that the type referenced is compatible with the
10049 // right-hand side type. The caller is responsible for adjusting
10050 // LHSType so that the resulting expression does not have reference
10051 // type.
10052 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
10053 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
10054 Kind = CK_LValueBitCast;
10055 return AssignConvertType::Compatible;
10056 }
10057 return AssignConvertType::Incompatible;
10058 }
10059
10060 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
10061 // of an ExtVector type to the same ExtVector type.
10062 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
10063 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
10064 // Implicit conversions require the same number of elements.
10065 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
10066 return AssignConvertType::Incompatible;
10067
10068 if (LHSType->isExtVectorBoolType() &&
10069 RHSExtType->getElementType()->isIntegerType()) {
10070 Kind = CK_IntegralToBoolean;
10071 return AssignConvertType::Compatible;
10072 }
10073 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
10074 if (Context.getLangOpts().OpenCL &&
10075 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10076 Kind = CK_BitCast;
10077 return AssignConvertType::Compatible;
10078 }
10079 return AssignConvertType::Incompatible;
10080 }
10081 if (RHSType->isArithmeticType()) {
10082 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10083 if (ConvertRHS)
10084 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
10085 Kind = CK_VectorSplat;
10086 return AssignConvertType::Compatible;
10087 }
10088 }
10089
10090 // Conversions to or from vector type.
10091 if (LHSType->isVectorType() || RHSType->isVectorType()) {
10092 if (LHSType->isVectorType() && RHSType->isVectorType()) {
10093 // Allow assignments of an AltiVec vector type to an equivalent GCC
10094 // vector type and vice versa
10095 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10096 Kind = CK_BitCast;
10097 return AssignConvertType::Compatible;
10098 }
10099
10100 // If we are allowing lax vector conversions, and LHS and RHS are both
10101 // vectors, the total size only needs to be the same. This is a bitcast;
10102 // no bits are changed but the result type is different.
10103 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
10104 // The default for lax vector conversions with Altivec vectors will
10105 // change, so if we are converting between vector types where
10106 // at least one is an Altivec vector, emit a warning.
10107 if (Context.getTargetInfo().getTriple().isPPC() &&
10108 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10109 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10110 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
10111 << RHSType << LHSType;
10112 Kind = CK_BitCast;
10113 return AssignConvertType::IncompatibleVectors;
10114 }
10115 }
10116
10117 // When the RHS comes from another lax conversion (e.g. binops between
10118 // scalars and vectors) the result is canonicalized as a vector. When the
10119 // LHS is also a vector, the lax is allowed by the condition above. Handle
10120 // the case where LHS is a scalar.
10121 if (LHSType->isScalarType()) {
10122 const VectorType *VecType = RHSType->getAs<VectorType>();
10123 if (VecType && VecType->getNumElements() == 1 &&
10124 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
10125 if (Context.getTargetInfo().getTriple().isPPC() &&
10126 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
10127 VecType->getVectorKind() == VectorKind::AltiVecBool ||
10128 VecType->getVectorKind() == VectorKind::AltiVecPixel))
10129 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
10130 << RHSType << LHSType;
10131 ExprResult *VecExpr = &RHS;
10132 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
10133 Kind = CK_BitCast;
10134 return AssignConvertType::Compatible;
10135 }
10136 }
10137
10138 // Allow assignments between fixed-length and sizeless SVE vectors.
10139 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10140 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10141 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
10142 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
10143 Kind = CK_BitCast;
10144 return AssignConvertType::Compatible;
10145 }
10146
10147 // Allow assignments between fixed-length and sizeless RVV vectors.
10148 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10149 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10150 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
10151 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
10152 Kind = CK_BitCast;
10153 return AssignConvertType::Compatible;
10154 }
10155 }
10156
10157 return AssignConvertType::Incompatible;
10158 }
10159
10160 // Diagnose attempts to convert between __ibm128, __float128 and long double
10161 // where such conversions currently can't be handled.
10162 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
10163 return AssignConvertType::Incompatible;
10164
10165 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10166 // discards the imaginary part.
10167 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10168 !LHSType->getAs<ComplexType>())
10169 return AssignConvertType::Incompatible;
10170
10171 // Arithmetic conversions.
10172 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10173 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10174 if (ConvertRHS)
10175 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
10176 return AssignConvertType::Compatible;
10177 }
10178
10179 // Conversions to normal pointers.
10180 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
10181 // U* -> T*
10182 if (isa<PointerType>(Val: RHSType)) {
10183 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10184 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10185 if (AddrSpaceL != AddrSpaceR)
10186 Kind = CK_AddressSpaceConversion;
10187 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
10188 Kind = CK_NoOp;
10189 else
10190 Kind = CK_BitCast;
10191 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
10192 Loc: RHS.get()->getBeginLoc());
10193 }
10194
10195 // int -> T*
10196 if (RHSType->isIntegerType()) {
10197 Kind = CK_IntegralToPointer; // FIXME: null?
10198 return AssignConvertType::IntToPointer;
10199 }
10200
10201 // C pointers are not compatible with ObjC object pointers,
10202 // with two exceptions:
10203 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10204 // - conversions to void*
10205 if (LHSPointer->getPointeeType()->isVoidType()) {
10206 Kind = CK_BitCast;
10207 return AssignConvertType::Compatible;
10208 }
10209
10210 // - conversions from 'Class' to the redefinition type
10211 if (RHSType->isObjCClassType() &&
10212 Context.hasSameType(T1: LHSType,
10213 T2: Context.getObjCClassRedefinitionType())) {
10214 Kind = CK_BitCast;
10215 return AssignConvertType::Compatible;
10216 }
10217
10218 Kind = CK_BitCast;
10219 return AssignConvertType::IncompatiblePointer;
10220 }
10221
10222 // U^ -> void*
10223 if (RHSType->getAs<BlockPointerType>()) {
10224 if (LHSPointer->getPointeeType()->isVoidType()) {
10225 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10226 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10227 ->getPointeeType()
10228 .getAddressSpace();
10229 Kind =
10230 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10231 return AssignConvertType::Compatible;
10232 }
10233 }
10234
10235 return AssignConvertType::Incompatible;
10236 }
10237
10238 // Conversions to block pointers.
10239 if (isa<BlockPointerType>(Val: LHSType)) {
10240 // U^ -> T^
10241 if (RHSType->isBlockPointerType()) {
10242 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10243 ->getPointeeType()
10244 .getAddressSpace();
10245 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10246 ->getPointeeType()
10247 .getAddressSpace();
10248 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10249 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10250 }
10251
10252 // int or null -> T^
10253 if (RHSType->isIntegerType()) {
10254 Kind = CK_IntegralToPointer; // FIXME: null
10255 return AssignConvertType::IntToBlockPointer;
10256 }
10257
10258 // id -> T^
10259 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10260 Kind = CK_AnyPointerToBlockPointerCast;
10261 return AssignConvertType::Compatible;
10262 }
10263
10264 // void* -> T^
10265 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10266 if (RHSPT->getPointeeType()->isVoidType()) {
10267 Kind = CK_AnyPointerToBlockPointerCast;
10268 return AssignConvertType::Compatible;
10269 }
10270
10271 return AssignConvertType::Incompatible;
10272 }
10273
10274 // Conversions to Objective-C pointers.
10275 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10276 // A* -> B*
10277 if (RHSType->isObjCObjectPointerType()) {
10278 Kind = CK_BitCast;
10279 AssignConvertType result =
10280 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10281 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10282 result == AssignConvertType::Compatible &&
10283 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10284 result = AssignConvertType::IncompatibleObjCWeakRef;
10285 return result;
10286 }
10287
10288 // int or null -> A*
10289 if (RHSType->isIntegerType()) {
10290 Kind = CK_IntegralToPointer; // FIXME: null
10291 return AssignConvertType::IntToPointer;
10292 }
10293
10294 // In general, C pointers are not compatible with ObjC object pointers,
10295 // with two exceptions:
10296 if (isa<PointerType>(Val: RHSType)) {
10297 Kind = CK_CPointerToObjCPointerCast;
10298
10299 // - conversions from 'void*'
10300 if (RHSType->isVoidPointerType()) {
10301 return AssignConvertType::Compatible;
10302 }
10303
10304 // - conversions to 'Class' from its redefinition type
10305 if (LHSType->isObjCClassType() &&
10306 Context.hasSameType(T1: RHSType,
10307 T2: Context.getObjCClassRedefinitionType())) {
10308 return AssignConvertType::Compatible;
10309 }
10310
10311 return AssignConvertType::IncompatiblePointer;
10312 }
10313
10314 // Only under strict condition T^ is compatible with an Objective-C pointer.
10315 if (RHSType->isBlockPointerType() &&
10316 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10317 if (ConvertRHS)
10318 maybeExtendBlockObject(E&: RHS);
10319 Kind = CK_BlockPointerToObjCPointerCast;
10320 return AssignConvertType::Compatible;
10321 }
10322
10323 return AssignConvertType::Incompatible;
10324 }
10325
10326 // Conversion to nullptr_t (C23 only)
10327 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10328 RHS.get()->isNullPointerConstant(Ctx&: Context,
10329 NPC: Expr::NPC_ValueDependentIsNull)) {
10330 // null -> nullptr_t
10331 Kind = CK_NullToPointer;
10332 return AssignConvertType::Compatible;
10333 }
10334
10335 // Conversions from pointers that are not covered by the above.
10336 if (isa<PointerType>(Val: RHSType)) {
10337 // T* -> _Bool
10338 if (LHSType == Context.BoolTy) {
10339 Kind = CK_PointerToBoolean;
10340 return AssignConvertType::Compatible;
10341 }
10342
10343 // T* -> int
10344 if (LHSType->isIntegerType()) {
10345 Kind = CK_PointerToIntegral;
10346 return AssignConvertType::PointerToInt;
10347 }
10348
10349 return AssignConvertType::Incompatible;
10350 }
10351
10352 // Conversions from Objective-C pointers that are not covered by the above.
10353 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10354 // T* -> _Bool
10355 if (LHSType == Context.BoolTy) {
10356 Kind = CK_PointerToBoolean;
10357 return AssignConvertType::Compatible;
10358 }
10359
10360 // T* -> int
10361 if (LHSType->isIntegerType()) {
10362 Kind = CK_PointerToIntegral;
10363 return AssignConvertType::PointerToInt;
10364 }
10365
10366 return AssignConvertType::Incompatible;
10367 }
10368
10369 // struct A -> struct B
10370 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10371 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10372 Kind = CK_NoOp;
10373 return AssignConvertType::Compatible;
10374 }
10375 }
10376
10377 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10378 Kind = CK_IntToOCLSampler;
10379 return AssignConvertType::Compatible;
10380 }
10381
10382 return AssignConvertType::Incompatible;
10383}
10384
10385/// Constructs a transparent union from an expression that is
10386/// used to initialize the transparent union.
10387static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10388 ExprResult &EResult, QualType UnionType,
10389 FieldDecl *Field) {
10390 // Build an initializer list that designates the appropriate member
10391 // of the transparent union.
10392 Expr *E = EResult.get();
10393 InitListExpr *Initializer = new (C) InitListExpr(
10394 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10395 Initializer->setType(UnionType);
10396 Initializer->setInitializedFieldInUnion(Field);
10397
10398 // Build a compound literal constructing a value of the transparent
10399 // union type from this initializer list.
10400 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10401 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10402 VK_PRValue, Initializer, false);
10403}
10404
10405AssignConvertType
10406Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10407 ExprResult &RHS) {
10408 QualType RHSType = RHS.get()->getType();
10409
10410 // If the ArgType is a Union type, we want to handle a potential
10411 // transparent_union GCC extension.
10412 const RecordType *UT = ArgType->getAsUnionType();
10413 if (!UT)
10414 return AssignConvertType::Incompatible;
10415
10416 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10417 if (!UD->hasAttr<TransparentUnionAttr>())
10418 return AssignConvertType::Incompatible;
10419
10420 // The field to initialize within the transparent union.
10421 FieldDecl *InitField = nullptr;
10422 // It's compatible if the expression matches any of the fields.
10423 for (auto *it : UD->fields()) {
10424 if (it->getType()->isPointerType()) {
10425 // If the transparent union contains a pointer type, we allow:
10426 // 1) void pointer
10427 // 2) null pointer constant
10428 if (RHSType->isPointerType())
10429 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10430 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10431 InitField = it;
10432 break;
10433 }
10434
10435 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10436 NPC: Expr::NPC_ValueDependentIsNull)) {
10437 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10438 CK: CK_NullToPointer);
10439 InitField = it;
10440 break;
10441 }
10442 }
10443
10444 CastKind Kind;
10445 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10446 AssignConvertType::Compatible) {
10447 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10448 InitField = it;
10449 break;
10450 }
10451 }
10452
10453 if (!InitField)
10454 return AssignConvertType::Incompatible;
10455
10456 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10457 return AssignConvertType::Compatible;
10458}
10459
10460AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10461 ExprResult &CallerRHS,
10462 bool Diagnose,
10463 bool DiagnoseCFAudited,
10464 bool ConvertRHS) {
10465 // We need to be able to tell the caller whether we diagnosed a problem, if
10466 // they ask us to issue diagnostics.
10467 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10468
10469 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10470 // we can't avoid *all* modifications at the moment, so we need some somewhere
10471 // to put the updated value.
10472 ExprResult LocalRHS = CallerRHS;
10473 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10474
10475 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10476 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10477 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10478 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10479 Diag(Loc: RHS.get()->getExprLoc(),
10480 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10481 << RHS.get()->getSourceRange();
10482 }
10483 }
10484 }
10485
10486 if (getLangOpts().CPlusPlus) {
10487 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10488 // C++ 5.17p3: If the left operand is not of class type, the
10489 // expression is implicitly converted (C++ 4) to the
10490 // cv-unqualified type of the left operand.
10491 QualType RHSType = RHS.get()->getType();
10492 if (Diagnose) {
10493 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10494 Action: AssignmentAction::Assigning);
10495 } else {
10496 ImplicitConversionSequence ICS =
10497 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10498 /*SuppressUserConversions=*/false,
10499 AllowExplicit: AllowedExplicit::None,
10500 /*InOverloadResolution=*/false,
10501 /*CStyle=*/false,
10502 /*AllowObjCWritebackConversion=*/false);
10503 if (ICS.isFailure())
10504 return AssignConvertType::Incompatible;
10505 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10506 ICS, Action: AssignmentAction::Assigning);
10507 }
10508 if (RHS.isInvalid())
10509 return AssignConvertType::Incompatible;
10510 AssignConvertType result = AssignConvertType::Compatible;
10511 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10512 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10513 result = AssignConvertType::IncompatibleObjCWeakRef;
10514
10515 // Check if OBT is being discarded during assignment
10516 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10517 if (RHSType->isOverflowBehaviorType() &&
10518 !LHSType->isOverflowBehaviorType()) {
10519 result = AssignConvertType::CompatibleOBTDiscards;
10520 }
10521
10522 return result;
10523 }
10524
10525 // FIXME: Currently, we fall through and treat C++ classes like C
10526 // structures.
10527 // FIXME: We also fall through for atomics; not sure what should
10528 // happen there, though.
10529 } else if (RHS.get()->getType() == Context.OverloadTy) {
10530 // As a set of extensions to C, we support overloading on functions. These
10531 // functions need to be resolved here.
10532 DeclAccessPair DAP;
10533 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10534 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10535 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10536 else
10537 return AssignConvertType::Incompatible;
10538 }
10539
10540 // For HLSL records, insert derived-to-base conversion if needed.
10541 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10542 QualType RHSType = RHS.get()->getType();
10543 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10544 CXXBasePaths Paths;
10545 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10546 CXXCastPath CastPath;
10547 BuildBasePathArray(Paths, BasePath&: CastPath);
10548 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10549 BasePath: &CastPath);
10550 }
10551 }
10552 }
10553
10554 // This check seems unnatural, however it is necessary to ensure the proper
10555 // conversion of functions/arrays. If the conversion were done for all
10556 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10557 // expressions that suppress this implicit conversion (&, sizeof). This needs
10558 // to happen before we check for null pointer conversions because C does not
10559 // undergo the same implicit conversions as C++ does above (by the calls to
10560 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10561 // lvalue to rvalue cast before checking for null pointer constraints. This
10562 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10563 //
10564 // Suppress this for references: C++ 8.5.3p5.
10565 if (!LHSType->isReferenceType()) {
10566 // FIXME: We potentially allocate here even if ConvertRHS is false.
10567 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10568 if (RHS.isInvalid())
10569 return AssignConvertType::Incompatible;
10570 }
10571
10572 // The constraints are expressed in terms of the atomic, qualified, or
10573 // unqualified type of the LHS.
10574 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10575
10576 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10577 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10578 if ((LHSTypeAfterConversion->isPointerType() ||
10579 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10580 LHSTypeAfterConversion->isBlockPointerType()) &&
10581 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10582 RHS.get()->isNullPointerConstant(Ctx&: Context,
10583 NPC: Expr::NPC_ValueDependentIsNull))) {
10584 AssignConvertType Ret = AssignConvertType::Compatible;
10585 if (Diagnose || ConvertRHS) {
10586 CastKind Kind;
10587 CXXCastPath Path;
10588 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10589 /*IgnoreBaseAccess=*/false, Diagnose);
10590
10591 // If there is a conversion of some kind, check to see what kind of
10592 // pointer conversion happened so we can diagnose a C++ compatibility
10593 // diagnostic if the conversion is invalid. This only matters if the RHS
10594 // is some kind of void pointer. We have a carve-out when the RHS is from
10595 // a macro expansion because the use of a macro may indicate different
10596 // code between C and C++. Consider: char *s = NULL; where NULL is
10597 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10598 // C++, which is valid in C++. Ignore parentheses around the macro when
10599 // checking where the expression originates.
10600 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10601 !RHS.get()->IgnoreParens()->getBeginLoc().isMacroID()) {
10602 QualType CanRHS =
10603 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10604 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10605 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10606 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10607 Loc: RHS.get()->getExprLoc());
10608 // Anything that's not considered perfectly compatible would be
10609 // incompatible in C++.
10610 if (Ret != AssignConvertType::Compatible)
10611 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10612 }
10613 }
10614
10615 if (ConvertRHS)
10616 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10617 }
10618 return Ret;
10619 }
10620 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10621 // unqualified bool, and the right operand is a pointer or its type is
10622 // nullptr_t.
10623 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10624 RHS.get()->getType()->isNullPtrType()) {
10625 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10626 // only handles nullptr -> _Bool due to needing an extra conversion
10627 // step.
10628 // We model this by converting from nullptr -> void * and then let the
10629 // conversion from void * -> _Bool happen naturally.
10630 if (Diagnose || ConvertRHS) {
10631 CastKind Kind;
10632 CXXCastPath Path;
10633 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10634 /*IgnoreBaseAccess=*/false, Diagnose);
10635 if (ConvertRHS)
10636 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10637 BasePath: &Path);
10638 }
10639 }
10640
10641 // OpenCL queue_t type assignment.
10642 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10643 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10644 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10645 return AssignConvertType::Compatible;
10646 }
10647
10648 CastKind Kind;
10649 AssignConvertType result =
10650 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10651
10652 // If assigning a void * created by an allocation function call to some other
10653 // type, check that the allocated size is sufficient for that type.
10654 if (result != AssignConvertType::Incompatible &&
10655 RHS.get()->getType()->isVoidPointerType())
10656 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10657
10658 // C99 6.5.16.1p2: The value of the right operand is converted to the
10659 // type of the assignment expression.
10660 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10661 // so that we can use references in built-in functions even in C.
10662 // The getNonReferenceType() call makes sure that the resulting expression
10663 // does not have reference type.
10664 if (result != AssignConvertType::Incompatible &&
10665 RHS.get()->getType() != LHSType) {
10666 QualType Ty = LHSType.getNonLValueExprType(Context);
10667 Expr *E = RHS.get();
10668
10669 // Check for various Objective-C errors. If we are not reporting
10670 // diagnostics and just checking for errors, e.g., during overload
10671 // resolution, return Incompatible to indicate the failure.
10672 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10673 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10674 CCK: CheckedConversionKind::Implicit, Diagnose,
10675 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10676 if (!Diagnose)
10677 return AssignConvertType::Incompatible;
10678 }
10679 if (getLangOpts().ObjC &&
10680 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10681 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10682 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10683 if (!Diagnose)
10684 return AssignConvertType::Incompatible;
10685 // Replace the expression with a corrected version and continue so we
10686 // can find further errors.
10687 RHS = E;
10688 return AssignConvertType::Compatible;
10689 }
10690
10691 if (ConvertRHS)
10692 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10693 }
10694
10695 return result;
10696}
10697
10698namespace {
10699/// The original operand to an operator, prior to the application of the usual
10700/// arithmetic conversions and converting the arguments of a builtin operator
10701/// candidate.
10702struct OriginalOperand {
10703 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10704 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10705 Op = MTE->getSubExpr();
10706 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10707 Op = BTE->getSubExpr();
10708 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10709 Orig = ICE->getSubExprAsWritten();
10710 Conversion = ICE->getConversionFunction();
10711 }
10712 }
10713
10714 QualType getType() const { return Orig->getType(); }
10715
10716 Expr *Orig;
10717 NamedDecl *Conversion;
10718};
10719}
10720
10721QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10722 ExprResult &RHS) {
10723 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10724
10725 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10726 << OrigLHS.getType() << OrigRHS.getType()
10727 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10728
10729 // If a user-defined conversion was applied to either of the operands prior
10730 // to applying the built-in operator rules, tell the user about it.
10731 if (OrigLHS.Conversion) {
10732 Diag(Loc: OrigLHS.Conversion->getLocation(),
10733 DiagID: diag::note_typecheck_invalid_operands_converted)
10734 << 0 << LHS.get()->getType();
10735 }
10736 if (OrigRHS.Conversion) {
10737 Diag(Loc: OrigRHS.Conversion->getLocation(),
10738 DiagID: diag::note_typecheck_invalid_operands_converted)
10739 << 1 << RHS.get()->getType();
10740 }
10741
10742 return QualType();
10743}
10744
10745QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10746 ExprResult &RHS) {
10747 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10748 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10749
10750 bool LHSNatVec = LHSType->isVectorType();
10751 bool RHSNatVec = RHSType->isVectorType();
10752
10753 if (!(LHSNatVec && RHSNatVec)) {
10754 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10755 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10756 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10757 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10758 << Vector->getSourceRange();
10759 return QualType();
10760 }
10761
10762 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10763 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10764 << RHS.get()->getSourceRange();
10765
10766 return QualType();
10767}
10768
10769/// Try to convert a value of non-vector type to a vector type by converting
10770/// the type to the element type of the vector and then performing a splat.
10771/// If the language is OpenCL, we only use conversions that promote scalar
10772/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10773/// for float->int.
10774///
10775/// OpenCL V2.0 6.2.6.p2:
10776/// An error shall occur if any scalar operand type has greater rank
10777/// than the type of the vector element.
10778///
10779/// \param scalar - if non-null, actually perform the conversions
10780/// \return true if the operation fails (but without diagnosing the failure)
10781static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10782 QualType scalarTy,
10783 QualType vectorEltTy,
10784 QualType vectorTy,
10785 unsigned &DiagID) {
10786 // The conversion to apply to the scalar before splatting it,
10787 // if necessary.
10788 CastKind scalarCast = CK_NoOp;
10789
10790 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10791 scalarCast = CK_IntegralToBoolean;
10792 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10793 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10794 (scalarTy->isIntegerType() &&
10795 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10796 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10797 return true;
10798 }
10799 if (!scalarTy->isIntegralType(Ctx: S.Context))
10800 return true;
10801 scalarCast = CK_IntegralCast;
10802 } else if (vectorEltTy->isRealFloatingType()) {
10803 if (scalarTy->isRealFloatingType()) {
10804 if (S.getLangOpts().OpenCL &&
10805 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10806 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10807 return true;
10808 }
10809 scalarCast = CK_FloatingCast;
10810 }
10811 else if (scalarTy->isIntegralType(Ctx: S.Context))
10812 scalarCast = CK_IntegralToFloating;
10813 else
10814 return true;
10815 } else {
10816 return true;
10817 }
10818
10819 // Adjust scalar if desired.
10820 if (scalar) {
10821 if (scalarCast != CK_NoOp)
10822 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10823 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10824 }
10825 return false;
10826}
10827
10828/// Convert vector E to a vector with the same number of elements but different
10829/// element type.
10830static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10831 const auto *VecTy = E->getType()->getAs<VectorType>();
10832 assert(VecTy && "Expression E must be a vector");
10833 QualType NewVecTy =
10834 VecTy->isExtVectorType()
10835 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10836 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10837 VecKind: VecTy->getVectorKind());
10838
10839 // Look through the implicit cast. Return the subexpression if its type is
10840 // NewVecTy.
10841 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10842 if (ICE->getSubExpr()->getType() == NewVecTy)
10843 return ICE->getSubExpr();
10844
10845 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10846 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10847}
10848
10849/// Test if a (constant) integer Int can be casted to another integer type
10850/// IntTy without losing precision.
10851static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10852 QualType OtherIntTy) {
10853 Expr *E = Int->get();
10854 if (E->containsErrors() || E->isInstantiationDependent())
10855 return false;
10856
10857 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10858
10859 // Reject cases where the value of the Int is unknown as that would
10860 // possibly cause truncation, but accept cases where the scalar can be
10861 // demoted without loss of precision.
10862 Expr::EvalResult EVResult;
10863 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10864 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10865 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10866 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10867
10868 if (CstInt) {
10869 // If the scalar is constant and is of a higher order and has more active
10870 // bits that the vector element type, reject it.
10871 llvm::APSInt Result = EVResult.Val.getInt();
10872 unsigned NumBits = IntSigned
10873 ? (Result.isNegative() ? Result.getSignificantBits()
10874 : Result.getActiveBits())
10875 : Result.getActiveBits();
10876 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10877 return true;
10878
10879 // If the signedness of the scalar type and the vector element type
10880 // differs and the number of bits is greater than that of the vector
10881 // element reject it.
10882 return (IntSigned != OtherIntSigned &&
10883 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10884 }
10885
10886 // Reject cases where the value of the scalar is not constant and it's
10887 // order is greater than that of the vector element type.
10888 return (Order < 0);
10889}
10890
10891/// Test if a (constant) integer Int can be casted to floating point type
10892/// FloatTy without losing precision.
10893static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10894 QualType FloatTy) {
10895 if (Int->get()->containsErrors())
10896 return false;
10897
10898 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10899
10900 // Determine if the integer constant can be expressed as a floating point
10901 // number of the appropriate type.
10902 Expr::EvalResult EVResult;
10903 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10904
10905 uint64_t Bits = 0;
10906 if (CstInt) {
10907 // Reject constants that would be truncated if they were converted to
10908 // the floating point type. Test by simple to/from conversion.
10909 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10910 // could be avoided if there was a convertFromAPInt method
10911 // which could signal back if implicit truncation occurred.
10912 llvm::APSInt Result = EVResult.Val.getInt();
10913 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10914 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10915 RM: llvm::APFloat::rmTowardZero);
10916 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10917 !IntTy->hasSignedIntegerRepresentation());
10918 bool Ignored = false;
10919 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10920 IsExact: &Ignored);
10921 if (Result != ConvertBack)
10922 return true;
10923 } else {
10924 // Reject types that cannot be fully encoded into the mantissa of
10925 // the float.
10926 Bits = S.Context.getTypeSize(T: IntTy);
10927 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10928 S.Context.getFloatTypeSemantics(T: FloatTy));
10929 if (Bits > FloatPrec)
10930 return true;
10931 }
10932
10933 return false;
10934}
10935
10936/// Attempt to convert and splat Scalar into a vector whose types matches
10937/// Vector following GCC conversion rules. The rule is that implicit
10938/// conversion can occur when Scalar can be casted to match Vector's element
10939/// type without causing truncation of Scalar.
10940static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10941 ExprResult *Vector) {
10942 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10943 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10944 QualType VectorEltTy;
10945
10946 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10947 assert(!isa<ExtVectorType>(VT) &&
10948 "ExtVectorTypes should not be handled here!");
10949 VectorEltTy = VT->getElementType();
10950 } else if (VectorTy->isSveVLSBuiltinType()) {
10951 VectorEltTy =
10952 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10953 } else {
10954 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10955 }
10956
10957 // Reject cases where the vector element type or the scalar element type are
10958 // not integral or floating point types.
10959 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10960 return true;
10961
10962 // The conversion to apply to the scalar before splatting it,
10963 // if necessary.
10964 CastKind ScalarCast = CK_NoOp;
10965
10966 // Accept cases where the vector elements are integers and the scalar is
10967 // an integer.
10968 // FIXME: Notionally if the scalar was a floating point value with a precise
10969 // integral representation, we could cast it to an appropriate integer
10970 // type and then perform the rest of the checks here. GCC will perform
10971 // this conversion in some cases as determined by the input language.
10972 // We should accept it on a language independent basis.
10973 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10974 ScalarTy->isIntegralType(Ctx: S.Context) &&
10975 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10976
10977 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10978 return true;
10979
10980 ScalarCast = CK_IntegralCast;
10981 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10982 ScalarTy->isRealFloatingType()) {
10983 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10984 ScalarCast = CK_FloatingToIntegral;
10985 else
10986 return true;
10987 } else if (VectorEltTy->isRealFloatingType()) {
10988 if (ScalarTy->isRealFloatingType()) {
10989
10990 // Reject cases where the scalar type is not a constant and has a higher
10991 // Order than the vector element type.
10992 llvm::APFloat Result(0.0);
10993
10994 // Determine whether this is a constant scalar. In the event that the
10995 // value is dependent (and thus cannot be evaluated by the constant
10996 // evaluator), skip the evaluation. This will then diagnose once the
10997 // expression is instantiated.
10998 bool CstScalar = Scalar->get()->isValueDependent() ||
10999 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
11000 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
11001 if (!CstScalar && Order < 0)
11002 return true;
11003
11004 // If the scalar cannot be safely casted to the vector element type,
11005 // reject it.
11006 if (CstScalar) {
11007 bool Truncated = false;
11008 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
11009 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
11010 if (Truncated)
11011 return true;
11012 }
11013
11014 ScalarCast = CK_FloatingCast;
11015 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
11016 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
11017 return true;
11018
11019 ScalarCast = CK_IntegralToFloating;
11020 } else
11021 return true;
11022 } else if (ScalarTy->isEnumeralType())
11023 return true;
11024
11025 // Adjust scalar if desired.
11026 if (ScalarCast != CK_NoOp)
11027 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
11028 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
11029 return false;
11030}
11031
11032QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11033 SourceLocation Loc, bool IsCompAssign,
11034 bool AllowBothBool,
11035 bool AllowBoolConversions,
11036 bool AllowBoolOperation) {
11037 if (!IsCompAssign) {
11038 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11039 if (LHS.isInvalid())
11040 return QualType();
11041 }
11042 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11043 if (RHS.isInvalid())
11044 return QualType();
11045
11046 // For conversion purposes, we ignore any qualifiers.
11047 // For example, "const float" and "float" are equivalent.
11048 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11049 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11050
11051 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
11052 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
11053 assert(LHSVecType || RHSVecType);
11054
11055 if (getLangOpts().HLSL)
11056 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
11057 IsCompAssign);
11058
11059 // Any operation with MFloat8 type is only possible with C intrinsics
11060 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
11061 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
11062 return InvalidOperands(Loc, LHS, RHS);
11063
11064 // AltiVec-style "vector bool op vector bool" combinations are allowed
11065 // for some operators but not others.
11066 if (!AllowBothBool && LHSVecType &&
11067 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
11068 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11069 return InvalidOperands(Loc, LHS, RHS);
11070
11071 // This operation may not be performed on boolean vectors.
11072 if (!AllowBoolOperation &&
11073 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
11074 return InvalidOperands(Loc, LHS, RHS);
11075
11076 // If the vector types are identical, return.
11077 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11078 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
11079
11080 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11081 if (LHSVecType && RHSVecType &&
11082 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
11083 if (isa<ExtVectorType>(Val: LHSVecType)) {
11084 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
11085 return LHSType;
11086 }
11087
11088 if (!IsCompAssign)
11089 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
11090 return RHSType;
11091 }
11092
11093 // AllowBoolConversions says that bool and non-bool AltiVec vectors
11094 // can be mixed, with the result being the non-bool type. The non-bool
11095 // operand must have integer element type.
11096 if (AllowBoolConversions && LHSVecType && RHSVecType &&
11097 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
11098 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
11099 Context.getTypeSize(T: RHSVecType->getElementType()))) {
11100 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11101 LHSVecType->getElementType()->isIntegerType() &&
11102 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
11103 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
11104 return LHSType;
11105 }
11106 if (!IsCompAssign &&
11107 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
11108 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11109 RHSVecType->getElementType()->isIntegerType()) {
11110 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
11111 return RHSType;
11112 }
11113 }
11114
11115 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11116 // invalid since the ambiguity can affect the ABI.
11117 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11118 unsigned &SVEorRVV) {
11119 const VectorType *VecType = SecondType->getAs<VectorType>();
11120 SVEorRVV = 0;
11121 if (FirstType->isSizelessBuiltinType() && VecType) {
11122 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11123 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
11124 return true;
11125 if (isRVVFixedLengthVectorKind(VK: VecType->getVectorKind())) {
11126 SVEorRVV = 1;
11127 return true;
11128 }
11129 }
11130
11131 return false;
11132 };
11133
11134 unsigned SVEorRVV;
11135 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11136 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11137 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
11138 << SVEorRVV << LHSType << RHSType;
11139 return QualType();
11140 }
11141
11142 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11143 // invalid since the ambiguity can affect the ABI.
11144 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11145 unsigned &SVEorRVV) {
11146 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11147 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11148
11149 SVEorRVV = 0;
11150 if (FirstVecType && SecondVecType) {
11151 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11152 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11153 SecondVecType->getVectorKind() ==
11154 VectorKind::SveFixedLengthPredicate)
11155 return true;
11156 if (isRVVFixedLengthVectorKind(VK: SecondVecType->getVectorKind())) {
11157 SVEorRVV = 1;
11158 return true;
11159 }
11160 }
11161 return false;
11162 }
11163
11164 if (SecondVecType &&
11165 SecondVecType->getVectorKind() == VectorKind::Generic) {
11166 if (FirstType->isSVESizelessBuiltinType())
11167 return true;
11168 if (FirstType->isRVVSizelessBuiltinType()) {
11169 SVEorRVV = 1;
11170 return true;
11171 }
11172 }
11173
11174 return false;
11175 };
11176
11177 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11178 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11179 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
11180 << SVEorRVV << LHSType << RHSType;
11181 return QualType();
11182 }
11183
11184 // If there's a vector type and a scalar, try to convert the scalar to
11185 // the vector element type and splat.
11186 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11187 if (!RHSVecType) {
11188 if (isa<ExtVectorType>(Val: LHSVecType)) {
11189 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
11190 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
11191 DiagID))
11192 return LHSType;
11193 } else {
11194 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11195 return LHSType;
11196 }
11197 }
11198 if (!LHSVecType) {
11199 if (isa<ExtVectorType>(Val: RHSVecType)) {
11200 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
11201 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
11202 vectorTy: RHSType, DiagID))
11203 return RHSType;
11204 } else {
11205 if (LHS.get()->isLValue() ||
11206 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11207 return RHSType;
11208 }
11209 }
11210
11211 // FIXME: The code below also handles conversion between vectors and
11212 // non-scalars, we should break this down into fine grained specific checks
11213 // and emit proper diagnostics.
11214 QualType VecType = LHSVecType ? LHSType : RHSType;
11215 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11216 QualType OtherType = LHSVecType ? RHSType : LHSType;
11217 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11218 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
11219 if (Context.getTargetInfo().getTriple().isPPC() &&
11220 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
11221 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
11222 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11223 // If we're allowing lax vector conversions, only the total (data) size
11224 // needs to be the same. For non compound assignment, if one of the types is
11225 // scalar, the result is always the vector type.
11226 if (!IsCompAssign) {
11227 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
11228 return VecType;
11229 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11230 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11231 // type. Note that this is already done by non-compound assignments in
11232 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11233 // <1 x T> -> T. The result is also a vector type.
11234 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11235 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11236 ExprResult *RHSExpr = &RHS;
11237 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
11238 return VecType;
11239 }
11240 }
11241
11242 // Okay, the expression is invalid.
11243
11244 // If there's a non-vector, non-real operand, diagnose that.
11245 if ((!RHSVecType && !RHSType->isRealType()) ||
11246 (!LHSVecType && !LHSType->isRealType())) {
11247 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11248 << LHSType << RHSType
11249 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11250 return QualType();
11251 }
11252
11253 // OpenCL V1.1 6.2.6.p1:
11254 // If the operands are of more than one vector type, then an error shall
11255 // occur. Implicit conversions between vector types are not permitted, per
11256 // section 6.2.1.
11257 if (getLangOpts().OpenCL &&
11258 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
11259 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
11260 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
11261 << RHSType;
11262 return QualType();
11263 }
11264
11265
11266 // If there is a vector type that is not a ExtVector and a scalar, we reach
11267 // this point if scalar could not be converted to the vector's element type
11268 // without truncation.
11269 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11270 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11271 QualType Scalar = LHSVecType ? RHSType : LHSType;
11272 QualType Vector = LHSVecType ? LHSType : RHSType;
11273 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11274 Diag(Loc,
11275 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11276 << ScalarOrVector << Scalar << Vector;
11277
11278 return QualType();
11279 }
11280
11281 // Otherwise, use the generic diagnostic.
11282 Diag(Loc, DiagID)
11283 << LHSType << RHSType
11284 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11285 return QualType();
11286}
11287
11288QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11289 SourceLocation Loc,
11290 bool IsCompAssign,
11291 ArithConvKind OperationKind) {
11292 if (!IsCompAssign) {
11293 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11294 if (LHS.isInvalid())
11295 return QualType();
11296 }
11297 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11298 if (RHS.isInvalid())
11299 return QualType();
11300
11301 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11302 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11303
11304 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11305 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11306
11307 unsigned DiagID = diag::err_typecheck_invalid_operands;
11308 if ((OperationKind == ArithConvKind::Arithmetic) &&
11309 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11310 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11311 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11312 << RHS.get()->getSourceRange();
11313 return QualType();
11314 }
11315
11316 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11317 return LHSType;
11318
11319 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11320 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11321 return LHSType;
11322 }
11323 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11324 if (LHS.get()->isLValue() ||
11325 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11326 return RHSType;
11327 }
11328
11329 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11330 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11331 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11332 << LHSType << RHSType << LHS.get()->getSourceRange()
11333 << RHS.get()->getSourceRange();
11334 return QualType();
11335 }
11336
11337 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11338 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11339 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11340 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11341 << LHSType << RHSType << LHS.get()->getSourceRange()
11342 << RHS.get()->getSourceRange();
11343 return QualType();
11344 }
11345
11346 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11347 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11348 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11349 bool ScalarOrVector =
11350 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11351
11352 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11353 << ScalarOrVector << Scalar << Vector;
11354
11355 return QualType();
11356 }
11357
11358 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11359 << RHS.get()->getSourceRange();
11360 return QualType();
11361}
11362
11363// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11364// expression. These are mainly cases where the null pointer is used as an
11365// integer instead of a pointer.
11366static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11367 SourceLocation Loc, bool IsCompare) {
11368 // The canonical way to check for a GNU null is with isNullPointerConstant,
11369 // but we use a bit of a hack here for speed; this is a relatively
11370 // hot path, and isNullPointerConstant is slow.
11371 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11372 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11373
11374 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11375
11376 // Avoid analyzing cases where the result will either be invalid (and
11377 // diagnosed as such) or entirely valid and not something to warn about.
11378 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11379 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11380 return;
11381
11382 // Comparison operations would not make sense with a null pointer no matter
11383 // what the other expression is.
11384 if (!IsCompare) {
11385 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11386 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11387 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11388 return;
11389 }
11390
11391 // The rest of the operations only make sense with a null pointer
11392 // if the other expression is a pointer.
11393 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11394 NonNullType->canDecayToPointerType())
11395 return;
11396
11397 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11398 << LHSNull /* LHS is NULL */ << NonNullType
11399 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11400}
11401
11402static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11403 SourceLocation OpLoc) {
11404 // If the divisor is real, then this is real/real or complex/real division.
11405 // Either way there can be no precision loss.
11406 auto *CT = DivisorTy->getAs<ComplexType>();
11407 if (!CT)
11408 return;
11409
11410 QualType ElementType = CT->getElementType().getCanonicalType();
11411 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11412 LangOptions::ComplexRangeKind::CX_Promoted;
11413 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11414 return;
11415
11416 ASTContext &Ctx = S.getASTContext();
11417 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11418 const llvm::fltSemantics &ElementTypeSemantics =
11419 Ctx.getFloatTypeSemantics(T: ElementType);
11420 const llvm::fltSemantics &HigherElementTypeSemantics =
11421 Ctx.getFloatTypeSemantics(T: HigherElementType);
11422
11423 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11424 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11425 (HigherElementType == Ctx.LongDoubleTy &&
11426 !Ctx.getTargetInfo().hasLongDoubleType())) {
11427 // Retain the location of the first use of higher precision type.
11428 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11429 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11430 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11431 if (Type == HigherElementType) {
11432 Num++;
11433 return;
11434 }
11435 }
11436 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11437 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11438 }
11439}
11440
11441static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11442 SourceLocation Loc) {
11443 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11444 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11445 if (!LUE || !RUE)
11446 return;
11447 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11448 RUE->getKind() != UETT_SizeOf)
11449 return;
11450
11451 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11452 QualType LHSTy = LHSArg->getType();
11453 QualType RHSTy;
11454
11455 if (RUE->isArgumentType())
11456 RHSTy = RUE->getArgumentType().getNonReferenceType();
11457 else
11458 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11459
11460 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11461 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11462 return;
11463
11464 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11465 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11466 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11467 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11468 << LHSArgDecl;
11469 }
11470 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11471 QualType ArrayElemTy = ArrayTy->getElementType();
11472 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11473 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11474 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11475 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11476 return;
11477 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11478 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11479 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11480 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11481 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11482 << LHSArgDecl;
11483 }
11484
11485 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11486 }
11487}
11488
11489static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11490 ExprResult &RHS,
11491 SourceLocation Loc, bool IsDiv) {
11492 // Check for division/remainder by zero.
11493 Expr::EvalResult RHSValue;
11494 if (!RHS.get()->isValueDependent() &&
11495 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11496 RHSValue.Val.getInt() == 0)
11497 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11498 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11499 << IsDiv << RHS.get()->getSourceRange());
11500}
11501
11502static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11503 const ExprResult &LHS, const ExprResult &RHS,
11504 BinaryOperatorKind Opc) {
11505 if (!LHS.isUsable() || !RHS.isUsable())
11506 return;
11507 const Expr *LHSExpr = LHS.get();
11508 const Expr *RHSExpr = RHS.get();
11509 const QualType LHSType = LHSExpr->getType();
11510 const QualType RHSType = RHSExpr->getType();
11511 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11512 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11513 if (!LHSIsScoped && !RHSIsScoped)
11514 return;
11515 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11516 return;
11517 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11518 return;
11519 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11520 return;
11521 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11522 SourceLocation BeginLoc = expr->getBeginLoc();
11523 QualType IntType = type->castAs<EnumType>()
11524 ->getDecl()
11525 ->getDefinitionOrSelf()
11526 ->getIntegerType();
11527 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11528 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11529 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11530 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11531 };
11532 if (LHSIsScoped) {
11533 DiagnosticHelper(LHSExpr, LHSType);
11534 }
11535 if (RHSIsScoped) {
11536 DiagnosticHelper(RHSExpr, RHSType);
11537 }
11538}
11539
11540QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11541 SourceLocation Loc,
11542 BinaryOperatorKind Opc) {
11543 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11544 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11545
11546 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11547
11548 QualType LHSTy = LHS.get()->getType();
11549 QualType RHSTy = RHS.get()->getType();
11550 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11551 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11552 /*AllowBothBool*/ getLangOpts().AltiVec,
11553 /*AllowBoolConversions*/ false,
11554 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11555 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11556 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11557 OperationKind: ArithConvKind::Arithmetic);
11558 // In HLSL, multiplying or dividing two matrices is element-wise.
11559 if (getLangOpts().HLSL && LHSTy->isConstantMatrixType() &&
11560 RHSTy->isConstantMatrixType())
11561 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11562 if (!IsDiv &&
11563 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11564 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11565 // For division, only matrix-by-scalar is supported. Other combinations with
11566 // matrix types are invalid.
11567 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11568 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11569
11570 QualType compType = UsualArithmeticConversions(
11571 LHS, RHS, Loc,
11572 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11573 if (LHS.isInvalid() || RHS.isInvalid())
11574 return QualType();
11575
11576 if (compType.isNull() || !compType->isArithmeticType()) {
11577 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11578 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11579 return ResultTy;
11580 }
11581 if (IsDiv) {
11582 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11583 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11584 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11585 }
11586 return compType;
11587}
11588
11589QualType Sema::CheckRemainderOperands(
11590 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11591 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11592
11593 // Note: This check is here to simplify the double exclusions of
11594 // scalar and vector HLSL checks. No getLangOpts().HLSL
11595 // is needed since all languages exlcude doubles.
11596 if (LHS.get()->getType()->isDoubleType() ||
11597 RHS.get()->getType()->isDoubleType() ||
11598 (LHS.get()->getType()->isVectorType() && LHS.get()
11599 ->getType()
11600 ->getAs<VectorType>()
11601 ->getElementType()
11602 ->isDoubleType()) ||
11603 (RHS.get()->getType()->isVectorType() && RHS.get()
11604 ->getType()
11605 ->getAs<VectorType>()
11606 ->getElementType()
11607 ->isDoubleType()))
11608 return InvalidOperands(Loc, LHS, RHS);
11609
11610 if (LHS.get()->getType()->isVectorType() ||
11611 RHS.get()->getType()->isVectorType()) {
11612 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11613 RHS.get()->getType()->hasIntegerRepresentation()) ||
11614 (getLangOpts().HLSL &&
11615 (LHS.get()->getType()->hasFloatingRepresentation() ||
11616 RHS.get()->getType()->hasFloatingRepresentation())))
11617 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11618 /*AllowBothBool*/ getLangOpts().AltiVec,
11619 /*AllowBoolConversions*/ false,
11620 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11621 return InvalidOperands(Loc, LHS, RHS);
11622 }
11623
11624 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11625 RHS.get()->getType()->isSveVLSBuiltinType()) {
11626 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11627 RHS.get()->getType()->hasIntegerRepresentation())
11628 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11629 OperationKind: ArithConvKind::Arithmetic);
11630
11631 return InvalidOperands(Loc, LHS, RHS);
11632 }
11633
11634 QualType compType = UsualArithmeticConversions(
11635 LHS, RHS, Loc,
11636 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11637 if (LHS.isInvalid() || RHS.isInvalid())
11638 return QualType();
11639
11640 if (compType.isNull() ||
11641 (!compType->isIntegerType() &&
11642 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11643 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11644 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11645 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11646 return ResultTy;
11647 }
11648 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11649 return compType;
11650}
11651
11652/// Diagnose invalid arithmetic on two void pointers.
11653static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11654 Expr *LHSExpr, Expr *RHSExpr) {
11655 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11656 ? diag::err_typecheck_pointer_arith_void_type
11657 : diag::ext_gnu_void_ptr)
11658 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11659 << RHSExpr->getSourceRange();
11660}
11661
11662/// Diagnose invalid arithmetic on a void pointer.
11663static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11664 Expr *Pointer) {
11665 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11666 ? diag::err_typecheck_pointer_arith_void_type
11667 : diag::ext_gnu_void_ptr)
11668 << 0 /* one pointer */ << Pointer->getSourceRange();
11669}
11670
11671/// Diagnose invalid arithmetic on a null pointer.
11672///
11673/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11674/// idiom, which we recognize as a GNU extension.
11675///
11676static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11677 Expr *Pointer, bool IsGNUIdiom) {
11678 if (IsGNUIdiom)
11679 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11680 << Pointer->getSourceRange();
11681 else
11682 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11683 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11684}
11685
11686/// Diagnose invalid subraction on a null pointer.
11687///
11688static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11689 Expr *Pointer, bool BothNull) {
11690 // Null - null is valid in C++ [expr.add]p7
11691 if (BothNull && S.getLangOpts().CPlusPlus)
11692 return;
11693
11694 // Is this s a macro from a system header?
11695 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11696 return;
11697
11698 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11699 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11700 << S.getLangOpts().CPlusPlus
11701 << Pointer->getSourceRange());
11702}
11703
11704/// Diagnose invalid arithmetic on two function pointers.
11705static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11706 Expr *LHS, Expr *RHS) {
11707 assert(LHS->getType()->isAnyPointerType());
11708 assert(RHS->getType()->isAnyPointerType());
11709 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11710 ? diag::err_typecheck_pointer_arith_function_type
11711 : diag::ext_gnu_ptr_func_arith)
11712 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11713 // We only show the second type if it differs from the first.
11714 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11715 T2: RHS->getType())
11716 << RHS->getType()->getPointeeType()
11717 << LHS->getSourceRange() << RHS->getSourceRange();
11718}
11719
11720/// Diagnose invalid arithmetic on a function pointer.
11721static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11722 Expr *Pointer) {
11723 assert(Pointer->getType()->isAnyPointerType());
11724 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11725 ? diag::err_typecheck_pointer_arith_function_type
11726 : diag::ext_gnu_ptr_func_arith)
11727 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11728 << 0 /* one pointer, so only one type */
11729 << Pointer->getSourceRange();
11730}
11731
11732/// Emit error if Operand is incomplete pointer type
11733///
11734/// \returns True if pointer has incomplete type
11735static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11736 Expr *Operand) {
11737 QualType ResType = Operand->getType();
11738 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11739 ResType = ResAtomicType->getValueType();
11740
11741 assert(ResType->isAnyPointerType());
11742 QualType PointeeTy = ResType->getPointeeType();
11743 return S.RequireCompleteSizedType(
11744 Loc, T: PointeeTy,
11745 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11746 Args: Operand->getSourceRange());
11747}
11748
11749/// Check the validity of an arithmetic pointer operand.
11750///
11751/// If the operand has pointer type, this code will check for pointer types
11752/// which are invalid in arithmetic operations. These will be diagnosed
11753/// appropriately, including whether or not the use is supported as an
11754/// extension.
11755///
11756/// \returns True when the operand is valid to use (even if as an extension).
11757static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11758 Expr *Operand) {
11759 QualType ResType = Operand->getType();
11760 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11761 ResType = ResAtomicType->getValueType();
11762
11763 if (!ResType->isAnyPointerType()) return true;
11764
11765 QualType PointeeTy = ResType->getPointeeType();
11766 if (PointeeTy->isVoidType()) {
11767 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11768 return !S.getLangOpts().CPlusPlus;
11769 }
11770 if (PointeeTy->isFunctionType()) {
11771 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11772 return !S.getLangOpts().CPlusPlus;
11773 }
11774
11775 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11776
11777 return true;
11778}
11779
11780/// Check the validity of a binary arithmetic operation w.r.t. pointer
11781/// operands.
11782///
11783/// This routine will diagnose any invalid arithmetic on pointer operands much
11784/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11785/// for emitting a single diagnostic even for operations where both LHS and RHS
11786/// are (potentially problematic) pointers.
11787///
11788/// \returns True when the operand is valid to use (even if as an extension).
11789static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11790 Expr *LHSExpr, Expr *RHSExpr) {
11791 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11792 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11793 if (!isLHSPointer && !isRHSPointer) return true;
11794
11795 QualType LHSPointeeTy, RHSPointeeTy;
11796 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11797 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11798
11799 // if both are pointers check if operation is valid wrt address spaces
11800 if (isLHSPointer && isRHSPointer) {
11801 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11802 Ctx: S.getASTContext())) {
11803 S.Diag(Loc,
11804 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11805 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11806 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11807 return false;
11808 }
11809 }
11810
11811 // Check for arithmetic on pointers to incomplete types.
11812 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11813 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11814 if (isLHSVoidPtr || isRHSVoidPtr) {
11815 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11816 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11817 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11818
11819 return !S.getLangOpts().CPlusPlus;
11820 }
11821
11822 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11823 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11824 if (isLHSFuncPtr || isRHSFuncPtr) {
11825 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11826 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11827 Pointer: RHSExpr);
11828 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11829
11830 return !S.getLangOpts().CPlusPlus;
11831 }
11832
11833 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11834 return false;
11835 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11836 return false;
11837
11838 return true;
11839}
11840
11841/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11842/// literal.
11843static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11844 Expr *LHSExpr, Expr *RHSExpr) {
11845 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11846 Expr* IndexExpr = RHSExpr;
11847 if (!StrExpr) {
11848 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11849 IndexExpr = LHSExpr;
11850 }
11851
11852 bool IsStringPlusInt = StrExpr &&
11853 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11854 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11855 return;
11856
11857 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11858 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11859 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11860
11861 // Only print a fixit for "str" + int, not for int + "str".
11862 if (IndexExpr == RHSExpr) {
11863 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11864 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11865 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11866 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11867 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11868 } else
11869 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11870}
11871
11872/// Emit a warning when adding a char literal to a string.
11873static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11874 Expr *LHSExpr, Expr *RHSExpr) {
11875 const Expr *StringRefExpr = LHSExpr;
11876 const CharacterLiteral *CharExpr =
11877 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11878
11879 if (!CharExpr) {
11880 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11881 StringRefExpr = RHSExpr;
11882 }
11883
11884 if (!CharExpr || !StringRefExpr)
11885 return;
11886
11887 const QualType StringType = StringRefExpr->getType();
11888
11889 // Return if not a PointerType.
11890 if (!StringType->isAnyPointerType())
11891 return;
11892
11893 // Return if not a CharacterType.
11894 if (!StringType->getPointeeType()->isAnyCharacterType())
11895 return;
11896
11897 ASTContext &Ctx = Self.getASTContext();
11898 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11899
11900 const QualType CharType = CharExpr->getType();
11901 if (!CharType->isAnyCharacterType() &&
11902 CharType->isIntegerType() &&
11903 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11904 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11905 << DiagRange << Ctx.CharTy;
11906 } else {
11907 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11908 << DiagRange << CharExpr->getType();
11909 }
11910
11911 // Only print a fixit for str + char, not for char + str.
11912 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11913 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11914 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11915 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11916 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11917 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11918 } else {
11919 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11920 }
11921}
11922
11923/// Emit error when two pointers are incompatible.
11924static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11925 Expr *LHSExpr, Expr *RHSExpr) {
11926 assert(LHSExpr->getType()->isAnyPointerType());
11927 assert(RHSExpr->getType()->isAnyPointerType());
11928 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11929 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11930 << RHSExpr->getSourceRange();
11931}
11932
11933// C99 6.5.6
11934QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11935 SourceLocation Loc, BinaryOperatorKind Opc,
11936 QualType* CompLHSTy) {
11937 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11938
11939 if (LHS.get()->getType()->isVectorType() ||
11940 RHS.get()->getType()->isVectorType()) {
11941 QualType compType =
11942 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11943 /*AllowBothBool*/ getLangOpts().AltiVec,
11944 /*AllowBoolConversions*/ getLangOpts().ZVector,
11945 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11946 if (CompLHSTy) *CompLHSTy = compType;
11947 return compType;
11948 }
11949
11950 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11951 RHS.get()->getType()->isSveVLSBuiltinType()) {
11952 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11953 OperationKind: ArithConvKind::Arithmetic);
11954 if (CompLHSTy)
11955 *CompLHSTy = compType;
11956 return compType;
11957 }
11958
11959 if (LHS.get()->getType()->isConstantMatrixType() ||
11960 RHS.get()->getType()->isConstantMatrixType()) {
11961 QualType compType =
11962 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11963 if (CompLHSTy)
11964 *CompLHSTy = compType;
11965 return compType;
11966 }
11967
11968 QualType compType = UsualArithmeticConversions(
11969 LHS, RHS, Loc,
11970 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11971 if (LHS.isInvalid() || RHS.isInvalid())
11972 return QualType();
11973
11974 // Diagnose "string literal" '+' int and string '+' "char literal".
11975 if (Opc == BO_Add) {
11976 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11977 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11978 }
11979
11980 // handle the common case first (both operands are arithmetic).
11981 if (!compType.isNull() && compType->isArithmeticType()) {
11982 if (CompLHSTy) *CompLHSTy = compType;
11983 return compType;
11984 }
11985
11986 // Type-checking. Ultimately the pointer's going to be in PExp;
11987 // note that we bias towards the LHS being the pointer.
11988 Expr *PExp = LHS.get(), *IExp = RHS.get();
11989
11990 bool isObjCPointer;
11991 if (PExp->getType()->isPointerType()) {
11992 isObjCPointer = false;
11993 } else if (PExp->getType()->isObjCObjectPointerType()) {
11994 isObjCPointer = true;
11995 } else {
11996 std::swap(a&: PExp, b&: IExp);
11997 if (PExp->getType()->isPointerType()) {
11998 isObjCPointer = false;
11999 } else if (PExp->getType()->isObjCObjectPointerType()) {
12000 isObjCPointer = true;
12001 } else {
12002 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12003 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12004 return ResultTy;
12005 }
12006 }
12007 assert(PExp->getType()->isAnyPointerType());
12008
12009 if (!IExp->getType()->isIntegerType())
12010 return InvalidOperands(Loc, LHS, RHS);
12011
12012 // Adding to a null pointer results in undefined behavior.
12013 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
12014 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
12015 // In C++ adding zero to a null pointer is defined.
12016 Expr::EvalResult KnownVal;
12017 if (!getLangOpts().CPlusPlus ||
12018 (!IExp->isValueDependent() &&
12019 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
12020 KnownVal.Val.getInt() != 0))) {
12021 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
12022 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
12023 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
12024 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
12025 }
12026 }
12027
12028 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
12029 return QualType();
12030
12031 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
12032 return QualType();
12033
12034 // Arithmetic on label addresses is normally allowed, except when we add
12035 // a ptrauth signature to the addresses.
12036 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
12037 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
12038 << /*addition*/ 1;
12039 return QualType();
12040 }
12041
12042 // Check array bounds for pointer arithemtic
12043 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
12044
12045 if (CompLHSTy) {
12046 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
12047 if (LHSTy.isNull()) {
12048 LHSTy = LHS.get()->getType();
12049 if (Context.isPromotableIntegerType(T: LHSTy))
12050 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
12051 }
12052 *CompLHSTy = LHSTy;
12053 }
12054
12055 return PExp->getType();
12056}
12057
12058/// Determine whether the size of \p T is provably zero: some array dimension
12059/// is provably zero or the base element type has zero size. A variable
12060/// dimension that does not fold to an integer constant is assumed nonzero.
12061static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T) {
12062 while (const ArrayType *AT = Ctx.getAsArrayType(T)) {
12063 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
12064 if (CAT->isZeroSize())
12065 return true;
12066 } else if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
12067 if (const Expr *Bound = VAT->getSizeExpr())
12068 if (std::optional<llvm::APSInt> Size =
12069 Bound->getIntegerConstantExpr(Ctx))
12070 if (*Size == 0)
12071 return true;
12072 }
12073 T = AT->getElementType();
12074 }
12075 return !T->isIncompleteType() && Ctx.getTypeSizeInChars(T).isZero();
12076}
12077
12078// C99 6.5.6
12079QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
12080 SourceLocation Loc,
12081 BinaryOperatorKind Opc,
12082 QualType *CompLHSTy) {
12083 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12084
12085 if (LHS.get()->getType()->isVectorType() ||
12086 RHS.get()->getType()->isVectorType()) {
12087 QualType compType =
12088 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
12089 /*AllowBothBool*/ getLangOpts().AltiVec,
12090 /*AllowBoolConversions*/ getLangOpts().ZVector,
12091 /*AllowBooleanOperation*/ AllowBoolOperation: false);
12092 if (CompLHSTy) *CompLHSTy = compType;
12093 return compType;
12094 }
12095
12096 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12097 RHS.get()->getType()->isSveVLSBuiltinType()) {
12098 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
12099 OperationKind: ArithConvKind::Arithmetic);
12100 if (CompLHSTy)
12101 *CompLHSTy = compType;
12102 return compType;
12103 }
12104
12105 if (LHS.get()->getType()->isConstantMatrixType() ||
12106 RHS.get()->getType()->isConstantMatrixType()) {
12107 QualType compType =
12108 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
12109 if (CompLHSTy)
12110 *CompLHSTy = compType;
12111 return compType;
12112 }
12113
12114 QualType compType = UsualArithmeticConversions(
12115 LHS, RHS, Loc,
12116 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
12117 if (LHS.isInvalid() || RHS.isInvalid())
12118 return QualType();
12119
12120 // Enforce type constraints: C99 6.5.6p3.
12121
12122 // Handle the common case first (both operands are arithmetic).
12123 if (!compType.isNull() && compType->isArithmeticType()) {
12124 if (CompLHSTy) *CompLHSTy = compType;
12125 return compType;
12126 }
12127
12128 // Either ptr - int or ptr - ptr.
12129 if (LHS.get()->getType()->isAnyPointerType()) {
12130 QualType lpointee = LHS.get()->getType()->getPointeeType();
12131
12132 // Diagnose bad cases where we step over interface counts.
12133 if (LHS.get()->getType()->isObjCObjectPointerType() &&
12134 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
12135 return QualType();
12136
12137 // Arithmetic on label addresses is normally allowed, except when we add
12138 // a ptrauth signature to the addresses.
12139 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
12140 getLangOpts().PointerAuthIndirectGotos) {
12141 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
12142 << /*subtraction*/ 0;
12143 return QualType();
12144 }
12145
12146 // The result type of a pointer-int computation is the pointer type.
12147 if (RHS.get()->getType()->isIntegerType()) {
12148 // Subtracting from a null pointer should produce a warning.
12149 // The last argument to the diagnose call says this doesn't match the
12150 // GNU int-to-pointer idiom.
12151 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
12152 NPC: Expr::NPC_ValueDependentIsNotNull)) {
12153 // In C++ adding zero to a null pointer is defined.
12154 Expr::EvalResult KnownVal;
12155 if (!getLangOpts().CPlusPlus ||
12156 (!RHS.get()->isValueDependent() &&
12157 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
12158 KnownVal.Val.getInt() != 0))) {
12159 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
12160 }
12161 }
12162
12163 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
12164 return QualType();
12165
12166 // Check array bounds for pointer arithemtic
12167 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
12168 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12169
12170 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12171 return LHS.get()->getType();
12172 }
12173
12174 // Handle pointer-pointer subtractions.
12175 if (const PointerType *RHSPTy
12176 = RHS.get()->getType()->getAs<PointerType>()) {
12177 QualType rpointee = RHSPTy->getPointeeType();
12178
12179 if (getLangOpts().CPlusPlus) {
12180 // Pointee types must be the same: C++ [expr.add]
12181 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
12182 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12183 }
12184 } else {
12185 // Pointee types must be compatible C99 6.5.6p3
12186 if (!Context.typesAreCompatible(
12187 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
12188 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
12189 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12190 return QualType();
12191 }
12192 }
12193
12194 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
12195 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
12196 return QualType();
12197
12198 // For pointer subtraction, if the address spaces differ but overlap,
12199 // convert both pointers to the composite (superset) address space.
12200 // This is needed because address spaces may use different
12201 // representations, such as a private offset vs a flat address.
12202 LangAS LAddrSpace = lpointee.getAddressSpace();
12203 LangAS RAddrSpace = rpointee.getAddressSpace();
12204 if (LAddrSpace != RAddrSpace) {
12205 Qualifiers LQual = lpointee.getQualifiers();
12206 Qualifiers RQual = rpointee.getQualifiers();
12207 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(other: RQual, Ctx: Context)
12208 ? LAddrSpace
12209 : RAddrSpace;
12210
12211 if (LAddrSpace != ResultAddrSpace) {
12212 QualType NewPteTy = Context.getAddrSpaceQualType(
12213 T: lpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12214 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12215 LHS =
12216 ImpCastExprToType(E: LHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12217 }
12218 if (RAddrSpace != ResultAddrSpace) {
12219 QualType NewPteTy = Context.getAddrSpaceQualType(
12220 T: rpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12221 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12222 RHS =
12223 ImpCastExprToType(E: RHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12224 }
12225 }
12226
12227 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12228 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12229 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12230 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12231
12232 // Subtracting nullptr or from nullptr is suspect
12233 if (LHSIsNullPtr)
12234 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
12235 if (RHSIsNullPtr)
12236 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
12237
12238 // The pointee type may have zero size. As an extension, a structure or
12239 // union may have zero size or an array may have zero length. In this
12240 // case subtraction does not make sense. For a variably modified type,
12241 // warn only when the size is provably zero.
12242 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12243 isProvablyZeroSize(Ctx: Context, T: rpointee))
12244 Diag(Loc, DiagID: diag::warn_sub_ptr_zero_size_types)
12245 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12246 << RHS.get()->getSourceRange();
12247
12248 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12249 return Context.getPointerDiffType();
12250 }
12251 }
12252
12253 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12254 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12255 return ResultTy;
12256}
12257
12258static bool isScopedEnumerationType(QualType T) {
12259 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12260 return ET->getDecl()->isScoped();
12261 return false;
12262}
12263
12264static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12265 SourceLocation Loc, BinaryOperatorKind Opc,
12266 QualType LHSType) {
12267 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12268 // so skip remaining warnings as we don't want to modify values within Sema.
12269 if (S.getLangOpts().OpenCL)
12270 return;
12271
12272 if (Opc == BO_Shr &&
12273 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
12274 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
12275
12276 // Check right/shifter operand
12277 Expr::EvalResult RHSResult;
12278 if (RHS.get()->isValueDependent() ||
12279 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
12280 return;
12281 llvm::APSInt Right = RHSResult.Val.getInt();
12282
12283 if (Right.isNegative()) {
12284 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12285 PD: S.PDiag(DiagID: diag::warn_shift_negative)
12286 << RHS.get()->getSourceRange());
12287 return;
12288 }
12289
12290 QualType LHSExprType = LHS.get()->getType();
12291 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
12292 if (LHSExprType->isBitIntType())
12293 LeftSize = S.Context.getIntWidth(T: LHSExprType);
12294 else if (LHSExprType->isFixedPointType()) {
12295 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
12296 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12297 }
12298 if (Right.uge(RHS: LeftSize)) {
12299 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12300 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
12301 << RHS.get()->getSourceRange());
12302 return;
12303 }
12304
12305 // FIXME: We probably need to handle fixed point types specially here.
12306 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12307 return;
12308
12309 // When left shifting an ICE which is signed, we can check for overflow which
12310 // according to C++ standards prior to C++2a has undefined behavior
12311 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12312 // more than the maximum value representable in the result type, so never
12313 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12314 // expression is still probably a bug.)
12315 Expr::EvalResult LHSResult;
12316 if (LHS.get()->isValueDependent() ||
12317 LHSType->hasUnsignedIntegerRepresentation() ||
12318 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12319 return;
12320 llvm::APSInt Left = LHSResult.Val.getInt();
12321
12322 // Don't warn if signed overflow is defined, then all the rest of the
12323 // diagnostics will not be triggered because the behavior is defined.
12324 // Also don't warn in C++20 mode (and newer), as signed left shifts
12325 // always wrap and never overflow.
12326 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12327 return;
12328
12329 // If LHS does not have a non-negative value then, the
12330 // behavior is undefined before C++2a. Warn about it.
12331 if (Left.isNegative()) {
12332 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
12333 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
12334 << LHS.get()->getSourceRange());
12335 return;
12336 }
12337
12338 llvm::APInt ResultBits =
12339 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12340 if (ResultBits.ule(RHS: LeftSize))
12341 return;
12342 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12343 Result = Result.shl(ShiftAmt: Right);
12344
12345 // Print the bit representation of the signed integer as an unsigned
12346 // hexadecimal number.
12347 SmallString<40> HexResult;
12348 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12349
12350 // If we are only missing a sign bit, this is less likely to result in actual
12351 // bugs -- if the result is cast back to an unsigned type, it will have the
12352 // expected value. Thus we place this behind a different warning that can be
12353 // turned off separately if needed.
12354 if (ResultBits - 1 == LeftSize) {
12355 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12356 << HexResult << LHSType
12357 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12358 return;
12359 }
12360
12361 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12362 << HexResult.str() << Result.getSignificantBits() << LHSType
12363 << Left.getBitWidth() << LHS.get()->getSourceRange()
12364 << RHS.get()->getSourceRange();
12365}
12366
12367/// Return the resulting type when a vector is shifted
12368/// by a scalar or vector shift amount.
12369static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12370 SourceLocation Loc, bool IsCompAssign) {
12371 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12372 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12373 !LHS.get()->getType()->isVectorType()) {
12374 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12375 << RHS.get()->getType() << LHS.get()->getType()
12376 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12377 return QualType();
12378 }
12379
12380 if (!IsCompAssign) {
12381 LHS = S.UsualUnaryConversions(E: LHS.get());
12382 if (LHS.isInvalid()) return QualType();
12383 }
12384
12385 RHS = S.UsualUnaryConversions(E: RHS.get());
12386 if (RHS.isInvalid()) return QualType();
12387
12388 QualType LHSType = LHS.get()->getType();
12389 // Note that LHS might be a scalar because the routine calls not only in
12390 // OpenCL case.
12391 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12392 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12393
12394 // Note that RHS might not be a vector.
12395 QualType RHSType = RHS.get()->getType();
12396 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12397 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12398
12399 // Do not allow shifts for boolean vectors.
12400 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12401 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12402 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12403 << LHS.get()->getType() << RHS.get()->getType()
12404 << LHS.get()->getSourceRange();
12405 return QualType();
12406 }
12407
12408 // The operands need to be integers.
12409 if (!LHSEleType->isIntegerType()) {
12410 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12411 << LHS.get()->getType() << LHS.get()->getSourceRange();
12412 return QualType();
12413 }
12414
12415 if (!RHSEleType->isIntegerType()) {
12416 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12417 << RHS.get()->getType() << RHS.get()->getSourceRange();
12418 return QualType();
12419 }
12420
12421 if (!LHSVecTy) {
12422 assert(RHSVecTy);
12423 if (IsCompAssign)
12424 return RHSType;
12425 if (LHSEleType != RHSEleType) {
12426 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12427 LHSEleType = RHSEleType;
12428 }
12429 QualType VecTy =
12430 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12431 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12432 LHSType = VecTy;
12433 } else if (RHSVecTy) {
12434 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12435 // are applied component-wise. So if RHS is a vector, then ensure
12436 // that the number of elements is the same as LHS...
12437 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12438 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12439 << LHS.get()->getType() << RHS.get()->getType()
12440 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12441 return QualType();
12442 }
12443 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12444 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12445 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12446 if (LHSBT != RHSBT &&
12447 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12448 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12449 << LHS.get()->getType() << RHS.get()->getType()
12450 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12451 }
12452 }
12453 } else {
12454 // ...else expand RHS to match the number of elements in LHS.
12455 QualType VecTy =
12456 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12457 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12458 }
12459
12460 return LHSType;
12461}
12462
12463static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12464 ExprResult &RHS, SourceLocation Loc,
12465 bool IsCompAssign) {
12466 if (!IsCompAssign) {
12467 LHS = S.UsualUnaryConversions(E: LHS.get());
12468 if (LHS.isInvalid())
12469 return QualType();
12470 }
12471
12472 RHS = S.UsualUnaryConversions(E: RHS.get());
12473 if (RHS.isInvalid())
12474 return QualType();
12475
12476 QualType LHSType = LHS.get()->getType();
12477 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12478 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12479 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12480 : LHSType;
12481
12482 // Note that RHS might not be a vector
12483 QualType RHSType = RHS.get()->getType();
12484 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12485 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12486 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12487 : RHSType;
12488
12489 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12490 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12491 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12492 << LHSType << RHSType << LHS.get()->getSourceRange();
12493 return QualType();
12494 }
12495
12496 if (!LHSEleType->isIntegerType()) {
12497 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12498 << LHS.get()->getType() << LHS.get()->getSourceRange();
12499 return QualType();
12500 }
12501
12502 if (!RHSEleType->isIntegerType()) {
12503 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12504 << RHS.get()->getType() << RHS.get()->getSourceRange();
12505 return QualType();
12506 }
12507
12508 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12509 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12510 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12511 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12512 << LHSType << RHSType << LHS.get()->getSourceRange()
12513 << RHS.get()->getSourceRange();
12514 return QualType();
12515 }
12516
12517 if (!LHSType->isSveVLSBuiltinType()) {
12518 assert(RHSType->isSveVLSBuiltinType());
12519 if (IsCompAssign)
12520 return RHSType;
12521 if (LHSEleType != RHSEleType) {
12522 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12523 LHSEleType = RHSEleType;
12524 }
12525 const llvm::ElementCount VecSize =
12526 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12527 QualType VecTy =
12528 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12529 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12530 LHSType = VecTy;
12531 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12532 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12533 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12534 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12535 << LHSType << RHSType << LHS.get()->getSourceRange()
12536 << RHS.get()->getSourceRange();
12537 return QualType();
12538 }
12539 } else {
12540 const llvm::ElementCount VecSize =
12541 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12542 if (LHSEleType != RHSEleType) {
12543 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12544 RHSEleType = LHSEleType;
12545 }
12546 QualType VecTy =
12547 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12548 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12549 }
12550
12551 return LHSType;
12552}
12553
12554// C99 6.5.7
12555QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12556 SourceLocation Loc, BinaryOperatorKind Opc,
12557 bool IsCompAssign) {
12558 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12559
12560 // Vector shifts promote their scalar inputs to vector type.
12561 if (LHS.get()->getType()->isVectorType() ||
12562 RHS.get()->getType()->isVectorType()) {
12563 if (LangOpts.ZVector) {
12564 // The shift operators for the z vector extensions work basically
12565 // like general shifts, except that neither the LHS nor the RHS is
12566 // allowed to be a "vector bool".
12567 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12568 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12569 return InvalidOperands(Loc, LHS, RHS);
12570 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12571 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12572 return InvalidOperands(Loc, LHS, RHS);
12573 }
12574 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12575 }
12576
12577 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12578 RHS.get()->getType()->isSveVLSBuiltinType())
12579 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12580
12581 // Shifts don't perform usual arithmetic conversions, they just do integer
12582 // promotions on each operand. C99 6.5.7p3
12583
12584 // For the LHS, do usual unary conversions, but then reset them away
12585 // if this is a compound assignment.
12586 ExprResult OldLHS = LHS;
12587 LHS = UsualUnaryConversions(E: LHS.get());
12588 if (LHS.isInvalid())
12589 return QualType();
12590 QualType LHSType = LHS.get()->getType();
12591 if (IsCompAssign) LHS = OldLHS;
12592
12593 // The RHS is simpler.
12594 RHS = UsualUnaryConversions(E: RHS.get());
12595 if (RHS.isInvalid())
12596 return QualType();
12597 QualType RHSType = RHS.get()->getType();
12598
12599 // C99 6.5.7p2: Each of the operands shall have integer type.
12600 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12601 if ((!LHSType->isFixedPointOrIntegerType() &&
12602 !LHSType->hasIntegerRepresentation()) ||
12603 !RHSType->hasIntegerRepresentation()) {
12604 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12605 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12606 return ResultTy;
12607 }
12608
12609 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12610
12611 // "The type of the result is that of the promoted left operand."
12612 return LHSType;
12613}
12614
12615/// Diagnose bad pointer comparisons.
12616static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12617 ExprResult &LHS, ExprResult &RHS,
12618 bool IsError) {
12619 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12620 : diag::ext_typecheck_comparison_of_distinct_pointers)
12621 << LHS.get()->getType() << RHS.get()->getType()
12622 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12623}
12624
12625/// Returns false if the pointers are converted to a composite type,
12626/// true otherwise.
12627static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12628 ExprResult &LHS, ExprResult &RHS) {
12629 // C++ [expr.rel]p2:
12630 // [...] Pointer conversions (4.10) and qualification
12631 // conversions (4.4) are performed on pointer operands (or on
12632 // a pointer operand and a null pointer constant) to bring
12633 // them to their composite pointer type. [...]
12634 //
12635 // C++ [expr.eq]p1 uses the same notion for (in)equality
12636 // comparisons of pointers.
12637
12638 QualType LHSType = LHS.get()->getType();
12639 QualType RHSType = RHS.get()->getType();
12640 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12641 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12642
12643 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12644 if (T.isNull()) {
12645 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12646 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12647 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12648 else
12649 S.InvalidOperands(Loc, LHS, RHS);
12650 return true;
12651 }
12652
12653 return false;
12654}
12655
12656static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12657 ExprResult &LHS,
12658 ExprResult &RHS,
12659 bool IsError) {
12660 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12661 : diag::ext_typecheck_comparison_of_fptr_to_void)
12662 << LHS.get()->getType() << RHS.get()->getType()
12663 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12664}
12665
12666static bool isObjCObjectLiteral(ExprResult &E) {
12667 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12668 case Stmt::ObjCArrayLiteralClass:
12669 case Stmt::ObjCDictionaryLiteralClass:
12670 case Stmt::ObjCStringLiteralClass:
12671 case Stmt::ObjCBoxedExprClass:
12672 return true;
12673 default:
12674 // Note that ObjCBoolLiteral is NOT an object literal!
12675 return false;
12676 }
12677}
12678
12679static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12680 const ObjCObjectPointerType *Type =
12681 LHS->getType()->getAs<ObjCObjectPointerType>();
12682
12683 // If this is not actually an Objective-C object, bail out.
12684 if (!Type)
12685 return false;
12686
12687 // Get the LHS object's interface type.
12688 QualType InterfaceType = Type->getPointeeType();
12689
12690 // If the RHS isn't an Objective-C object, bail out.
12691 if (!RHS->getType()->isObjCObjectPointerType())
12692 return false;
12693
12694 // Try to find the -isEqual: method.
12695 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12696 ObjCMethodDecl *Method =
12697 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12698 /*IsInstance=*/true);
12699 if (!Method) {
12700 if (Type->isObjCIdType()) {
12701 // For 'id', just check the global pool.
12702 Method =
12703 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12704 /*receiverId=*/receiverIdOrClass: true);
12705 } else {
12706 // Check protocols.
12707 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12708 /*IsInstance=*/true);
12709 }
12710 }
12711
12712 if (!Method)
12713 return false;
12714
12715 QualType T = Method->parameters()[0]->getType();
12716 if (!T->isObjCObjectPointerType())
12717 return false;
12718
12719 QualType R = Method->getReturnType();
12720 if (!R->isScalarType())
12721 return false;
12722
12723 return true;
12724}
12725
12726static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12727 ExprResult &LHS, ExprResult &RHS,
12728 BinaryOperator::Opcode Opc){
12729 Expr *Literal;
12730 Expr *Other;
12731 if (isObjCObjectLiteral(E&: LHS)) {
12732 Literal = LHS.get();
12733 Other = RHS.get();
12734 } else {
12735 Literal = RHS.get();
12736 Other = LHS.get();
12737 }
12738
12739 // Don't warn on comparisons against nil.
12740 Other = Other->IgnoreParenCasts();
12741 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12742 NPC: Expr::NPC_ValueDependentIsNotNull))
12743 return;
12744
12745 // This should be kept in sync with warn_objc_literal_comparison.
12746 // LK_String should always be after the other literals, since it has its own
12747 // warning flag.
12748 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12749 assert(LiteralKind != SemaObjC::LK_Block);
12750 if (LiteralKind == SemaObjC::LK_None) {
12751 llvm_unreachable("Unknown Objective-C object literal kind");
12752 }
12753
12754 if (LiteralKind == SemaObjC::LK_String)
12755 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12756 << Literal->getSourceRange();
12757 else
12758 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12759 << LiteralKind << Literal->getSourceRange();
12760
12761 if (BinaryOperator::isEqualityOp(Opc) &&
12762 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12763 SourceLocation Start = LHS.get()->getBeginLoc();
12764 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12765 CharSourceRange OpRange =
12766 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12767
12768 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12769 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12770 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12771 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12772 }
12773}
12774
12775/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12776static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12777 ExprResult &RHS, SourceLocation Loc,
12778 BinaryOperatorKind Opc) {
12779 // Check that left hand side is !something.
12780 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12781 if (!UO || UO->getOpcode() != UO_LNot) return;
12782
12783 // Only check if the right hand side is non-bool arithmetic type.
12784 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12785
12786 // Make sure that the something in !something is not bool.
12787 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12788 if (SubExpr->isKnownToHaveBooleanValue()) return;
12789
12790 // Emit warning.
12791 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12792 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12793 << Loc << IsBitwiseOp;
12794
12795 // First note suggest !(x < y)
12796 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12797 SourceLocation FirstClose = RHS.get()->getEndLoc();
12798 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12799 if (FirstClose.isInvalid())
12800 FirstOpen = SourceLocation();
12801 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12802 << IsBitwiseOp
12803 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12804 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12805
12806 // Second note suggests (!x) < y
12807 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12808 SourceLocation SecondClose = LHS.get()->getEndLoc();
12809 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12810 if (SecondClose.isInvalid())
12811 SecondOpen = SourceLocation();
12812 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12813 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12814 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12815}
12816
12817// Returns true if E refers to a non-weak array.
12818static bool checkForArray(const Expr *E) {
12819 const ValueDecl *D = nullptr;
12820 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12821 D = DR->getDecl();
12822 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12823 if (Mem->isImplicitAccess())
12824 D = Mem->getMemberDecl();
12825 }
12826 if (!D)
12827 return false;
12828 return D->getType()->isArrayType() && !D->isWeak();
12829}
12830
12831/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12832/// pointer and size is an unsigned integer. Return whether the result is
12833/// always true/false.
12834static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12835 const Expr *RHS,
12836 BinaryOperatorKind Opc) {
12837 if (!LHS->getType()->isPointerType() ||
12838 S.getLangOpts().PointerOverflowDefined)
12839 return std::nullopt;
12840
12841 // Canonicalize to >= or < predicate.
12842 switch (Opc) {
12843 case BO_GE:
12844 case BO_LT:
12845 break;
12846 case BO_GT:
12847 std::swap(a&: LHS, b&: RHS);
12848 Opc = BO_LT;
12849 break;
12850 case BO_LE:
12851 std::swap(a&: LHS, b&: RHS);
12852 Opc = BO_GE;
12853 break;
12854 default:
12855 return std::nullopt;
12856 }
12857
12858 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12859 if (!BO || BO->getOpcode() != BO_Add)
12860 return std::nullopt;
12861
12862 Expr *Other;
12863 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12864 Other = BO->getRHS();
12865 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12866 Other = BO->getLHS();
12867 else
12868 return std::nullopt;
12869
12870 if (!Other->getType()->isUnsignedIntegerType())
12871 return std::nullopt;
12872
12873 return Opc == BO_GE;
12874}
12875
12876/// Diagnose some forms of syntactically-obvious tautological comparison.
12877static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12878 Expr *LHS, Expr *RHS,
12879 BinaryOperatorKind Opc) {
12880 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12881 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12882
12883 QualType LHSType = LHS->getType();
12884 QualType RHSType = RHS->getType();
12885 if (LHSType->hasFloatingRepresentation() ||
12886 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12887 S.inTemplateInstantiation())
12888 return;
12889
12890 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12891 // Tautological diagnostics.
12892 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12893 return;
12894
12895 // Comparisons between two array types are ill-formed for operator<=>, so
12896 // we shouldn't emit any additional warnings about it.
12897 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12898 return;
12899
12900 // For non-floating point types, check for self-comparisons of the form
12901 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12902 // often indicate logic errors in the program.
12903 //
12904 // NOTE: Don't warn about comparison expressions resulting from macro
12905 // expansion. Also don't warn about comparisons which are only self
12906 // comparisons within a template instantiation. The warnings should catch
12907 // obvious cases in the definition of the template anyways. The idea is to
12908 // warn when the typed comparison operator will always evaluate to the same
12909 // result.
12910
12911 // Used for indexing into %select in warn_comparison_always
12912 enum {
12913 AlwaysConstant,
12914 AlwaysTrue,
12915 AlwaysFalse,
12916 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12917 };
12918
12919 // C++1a [array.comp]:
12920 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12921 // operands of array type.
12922 // C++2a [depr.array.comp]:
12923 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12924 // operands of array type are deprecated.
12925 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12926 RHSStripped->getType()->isArrayType()) {
12927 auto IsDeprArrayComparionIgnored =
12928 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12929 auto DiagID = S.getLangOpts().CPlusPlus26
12930 ? diag::warn_array_comparison_cxx26
12931 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12932 ? diag::warn_array_comparison
12933 : diag::warn_depr_array_comparison;
12934 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12935 << LHSStripped->getType() << RHSStripped->getType();
12936 // Carry on to produce the tautological comparison warning, if this
12937 // expression is potentially-evaluated, we can resolve the array to a
12938 // non-weak declaration, and so on.
12939 }
12940
12941 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12942 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12943 unsigned Result;
12944 switch (Opc) {
12945 case BO_EQ:
12946 case BO_LE:
12947 case BO_GE:
12948 Result = AlwaysTrue;
12949 break;
12950 case BO_NE:
12951 case BO_LT:
12952 case BO_GT:
12953 Result = AlwaysFalse;
12954 break;
12955 case BO_Cmp:
12956 Result = AlwaysEqual;
12957 break;
12958 default:
12959 Result = AlwaysConstant;
12960 break;
12961 }
12962 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12963 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12964 << 0 /*self-comparison*/
12965 << Result);
12966 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12967 // What is it always going to evaluate to?
12968 unsigned Result;
12969 switch (Opc) {
12970 case BO_EQ: // e.g. array1 == array2
12971 Result = AlwaysFalse;
12972 break;
12973 case BO_NE: // e.g. array1 != array2
12974 Result = AlwaysTrue;
12975 break;
12976 default: // e.g. array1 <= array2
12977 // The best we can say is 'a constant'
12978 Result = AlwaysConstant;
12979 break;
12980 }
12981 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12982 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12983 << 1 /*array comparison*/
12984 << Result);
12985 } else if (std::optional<bool> Res =
12986 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12987 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12988 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12989 << 2 /*pointer comparison*/
12990 << (*Res ? AlwaysTrue : AlwaysFalse));
12991 }
12992 }
12993
12994 if (isa<CastExpr>(Val: LHSStripped))
12995 LHSStripped = LHSStripped->IgnoreParenCasts();
12996 if (isa<CastExpr>(Val: RHSStripped))
12997 RHSStripped = RHSStripped->IgnoreParenCasts();
12998
12999 // Warn about comparisons against a string constant (unless the other
13000 // operand is null); the user probably wants string comparison function.
13001 Expr *LiteralString = nullptr;
13002 Expr *LiteralStringStripped = nullptr;
13003 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
13004 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
13005 NPC: Expr::NPC_ValueDependentIsNull)) {
13006 LiteralString = LHS;
13007 LiteralStringStripped = LHSStripped;
13008 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
13009 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
13010 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
13011 NPC: Expr::NPC_ValueDependentIsNull)) {
13012 LiteralString = RHS;
13013 LiteralStringStripped = RHSStripped;
13014 }
13015
13016 if (LiteralString) {
13017 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
13018 PD: S.PDiag(DiagID: diag::warn_stringcompare)
13019 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
13020 << LiteralString->getSourceRange());
13021 }
13022}
13023
13024static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
13025 switch (CK) {
13026 default: {
13027#ifndef NDEBUG
13028 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
13029 << "\n";
13030#endif
13031 llvm_unreachable("unhandled cast kind");
13032 }
13033 case CK_UserDefinedConversion:
13034 return ICK_Identity;
13035 case CK_LValueToRValue:
13036 return ICK_Lvalue_To_Rvalue;
13037 case CK_ArrayToPointerDecay:
13038 return ICK_Array_To_Pointer;
13039 case CK_FunctionToPointerDecay:
13040 return ICK_Function_To_Pointer;
13041 case CK_IntegralCast:
13042 return ICK_Integral_Conversion;
13043 case CK_FloatingCast:
13044 return ICK_Floating_Conversion;
13045 case CK_IntegralToFloating:
13046 case CK_FloatingToIntegral:
13047 return ICK_Floating_Integral;
13048 case CK_IntegralComplexCast:
13049 case CK_FloatingComplexCast:
13050 case CK_FloatingComplexToIntegralComplex:
13051 case CK_IntegralComplexToFloatingComplex:
13052 return ICK_Complex_Conversion;
13053 case CK_FloatingComplexToReal:
13054 case CK_FloatingRealToComplex:
13055 case CK_IntegralComplexToReal:
13056 case CK_IntegralRealToComplex:
13057 return ICK_Complex_Real;
13058 case CK_HLSLArrayRValue:
13059 return ICK_HLSL_Array_RValue;
13060 }
13061}
13062
13063static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
13064 QualType FromType,
13065 SourceLocation Loc) {
13066 // Check for a narrowing implicit conversion.
13067 StandardConversionSequence SCS;
13068 SCS.setAsIdentityConversion();
13069 SCS.setToType(Idx: 0, T: FromType);
13070 SCS.setToType(Idx: 1, T: ToType);
13071 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13072 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
13073
13074 APValue PreNarrowingValue;
13075 QualType PreNarrowingType;
13076 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
13077 ConstantType&: PreNarrowingType,
13078 /*IgnoreFloatToIntegralConversion*/ true)) {
13079 case NK_Dependent_Narrowing:
13080 // Implicit conversion to a narrower type, but the expression is
13081 // value-dependent so we can't tell whether it's actually narrowing.
13082 case NK_Not_Narrowing:
13083 return false;
13084
13085 case NK_Constant_Narrowing:
13086 // Implicit conversion to a narrower type, and the value is not a constant
13087 // expression.
13088 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
13089 << /*Constant*/ 1
13090 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
13091 return true;
13092
13093 case NK_Variable_Narrowing:
13094 // Implicit conversion to a narrower type, and the value is not a constant
13095 // expression.
13096 case NK_Type_Narrowing:
13097 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
13098 << /*Constant*/ 0 << FromType << ToType;
13099 // TODO: It's not a constant expression, but what if the user intended it
13100 // to be? Can we produce notes to help them figure out why it isn't?
13101 return true;
13102 }
13103 llvm_unreachable("unhandled case in switch");
13104}
13105
13106static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
13107 ExprResult &LHS,
13108 ExprResult &RHS,
13109 SourceLocation Loc) {
13110 QualType LHSType = LHS.get()->getType();
13111 QualType RHSType = RHS.get()->getType();
13112 // Dig out the original argument type and expression before implicit casts
13113 // were applied. These are the types/expressions we need to check the
13114 // [expr.spaceship] requirements against.
13115 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
13116 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
13117 QualType LHSStrippedType = LHSStripped.get()->getType();
13118 QualType RHSStrippedType = RHSStripped.get()->getType();
13119
13120 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
13121 // other is not, the program is ill-formed.
13122 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
13123 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
13124 return QualType();
13125 }
13126
13127 // FIXME: Consider combining this with checkEnumArithmeticConversions.
13128 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
13129 RHSStrippedType->isEnumeralType();
13130 if (NumEnumArgs == 1) {
13131 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
13132 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
13133 if (OtherTy->hasFloatingRepresentation()) {
13134 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
13135 return QualType();
13136 }
13137 }
13138 if (NumEnumArgs == 2) {
13139 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
13140 // type E, the operator yields the result of converting the operands
13141 // to the underlying type of E and applying <=> to the converted operands.
13142 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
13143 S.InvalidOperands(Loc, LHS, RHS);
13144 return QualType();
13145 }
13146 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
13147 assert(IntType->isArithmeticType());
13148
13149 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
13150 // promote the boolean type, and all other promotable integer types, to
13151 // avoid this.
13152 if (S.Context.isPromotableIntegerType(T: IntType))
13153 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
13154
13155 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
13156 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
13157 LHSType = RHSType = IntType;
13158 }
13159
13160 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13161 // usual arithmetic conversions are applied to the operands.
13162 QualType Type =
13163 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13164 if (LHS.isInvalid() || RHS.isInvalid())
13165 return QualType();
13166 if (Type.isNull()) {
13167 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13168 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
13169 return ResultTy;
13170 }
13171
13172 std::optional<ComparisonCategoryType> CCT =
13173 getComparisonCategoryForBuiltinCmp(T: Type);
13174 if (!CCT)
13175 return S.InvalidOperands(Loc, LHS, RHS);
13176
13177 bool HasNarrowing = checkThreeWayNarrowingConversion(
13178 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
13179 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
13180 Loc: RHS.get()->getBeginLoc());
13181 if (HasNarrowing)
13182 return QualType();
13183
13184 assert(!Type.isNull() && "composite type for <=> has not been set");
13185
13186 return S.CheckComparisonCategoryType(
13187 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
13188}
13189
13190static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13191 ExprResult &RHS,
13192 SourceLocation Loc,
13193 BinaryOperatorKind Opc) {
13194 if (Opc == BO_Cmp)
13195 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13196
13197 // C99 6.5.8p3 / C99 6.5.9p4
13198 QualType Type =
13199 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13200 if (LHS.isInvalid() || RHS.isInvalid())
13201 return QualType();
13202 if (Type.isNull()) {
13203 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13204 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13205 return ResultTy;
13206 }
13207 assert(Type->isArithmeticType() || Type->isEnumeralType());
13208
13209 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13210 return S.InvalidOperands(Loc, LHS, RHS);
13211
13212 // Check for comparisons of floating point operands using != and ==.
13213 if (Type->hasFloatingRepresentation())
13214 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13215
13216 // The result of comparisons is 'bool' in C++, 'int' in C.
13217 return S.Context.getLogicalOperationType();
13218}
13219
13220void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13221 if (!NullE.get()->getType()->isAnyPointerType())
13222 return;
13223 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
13224 if (!E.get()->getType()->isAnyPointerType() &&
13225 E.get()->isNullPointerConstant(Ctx&: Context,
13226 NPC: Expr::NPC_ValueDependentIsNotNull) ==
13227 Expr::NPCK_ZeroExpression) {
13228 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
13229 if (CL->getValue() == 0)
13230 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13231 << NullValue
13232 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13233 Code: NullValue ? "NULL" : "(void *)0");
13234 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
13235 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13236 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
13237 if (T == Context.CharTy)
13238 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13239 << NullValue
13240 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13241 Code: NullValue ? "NULL" : "(void *)0");
13242 }
13243 }
13244}
13245
13246// C99 6.5.8, C++ [expr.rel]
13247QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13248 SourceLocation Loc,
13249 BinaryOperatorKind Opc) {
13250 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13251 bool IsThreeWay = Opc == BO_Cmp;
13252 bool IsOrdered = IsRelational || IsThreeWay;
13253 auto IsAnyPointerType = [](ExprResult E) {
13254 QualType Ty = E.get()->getType();
13255 return Ty->isPointerType() || Ty->isMemberPointerType();
13256 };
13257
13258 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13259 // type, array-to-pointer, ..., conversions are performed on both operands to
13260 // bring them to their composite type.
13261 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13262 // any type-related checks.
13263 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13264 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13265 if (LHS.isInvalid())
13266 return QualType();
13267 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13268 if (RHS.isInvalid())
13269 return QualType();
13270 } else {
13271 LHS = DefaultLvalueConversion(E: LHS.get());
13272 if (LHS.isInvalid())
13273 return QualType();
13274 RHS = DefaultLvalueConversion(E: RHS.get());
13275 if (RHS.isInvalid())
13276 return QualType();
13277 }
13278
13279 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
13280 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13281 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
13282 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
13283 }
13284
13285 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13286 RHS.get()->getType()->isConstantMatrixType()))
13287 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13288
13289 // Handle vector comparisons separately.
13290 if (LHS.get()->getType()->isVectorType() ||
13291 RHS.get()->getType()->isVectorType())
13292 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13293
13294 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13295 RHS.get()->getType()->isSveVLSBuiltinType())
13296 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13297
13298 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13299 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13300
13301 QualType LHSType = LHS.get()->getType();
13302 QualType RHSType = RHS.get()->getType();
13303 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13304 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13305 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
13306
13307 if ((LHSType->isPointerType() &&
13308 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13309 (RHSType->isPointerType() &&
13310 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13311 return InvalidOperands(Loc, LHS, RHS);
13312
13313 const Expr::NullPointerConstantKind LHSNullKind =
13314 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13315 const Expr::NullPointerConstantKind RHSNullKind =
13316 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13317 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13318 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13319
13320 auto computeResultTy = [&]() {
13321 if (Opc != BO_Cmp)
13322 return QualType(Context.getLogicalOperationType());
13323 assert(getLangOpts().CPlusPlus);
13324 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13325
13326 QualType CompositeTy = LHS.get()->getType();
13327 assert(!CompositeTy->isReferenceType());
13328
13329 std::optional<ComparisonCategoryType> CCT =
13330 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13331 if (!CCT)
13332 return InvalidOperands(Loc, LHS, RHS);
13333
13334 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13335 // P0946R0: Comparisons between a null pointer constant and an object
13336 // pointer result in std::strong_equality, which is ill-formed under
13337 // P1959R0.
13338 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13339 << (LHSIsNull ? LHS.get()->getSourceRange()
13340 : RHS.get()->getSourceRange());
13341 return QualType();
13342 }
13343
13344 return CheckComparisonCategoryType(
13345 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13346 };
13347
13348 if (LHSType->isMetaInfoType() && RHSType->isMetaInfoType()) {
13349 if (!BinaryOperator::isEqualityOp(Opc)) {
13350 return InvalidOperands(Loc, LHS, RHS);
13351 }
13352 return computeResultTy();
13353 }
13354
13355 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13356 bool IsEquality = Opc == BO_EQ;
13357 if (RHSIsNull)
13358 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13359 Range: RHS.get()->getSourceRange());
13360 else
13361 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13362 Range: LHS.get()->getSourceRange());
13363 }
13364
13365 if (IsOrdered && LHSType->isFunctionPointerType() &&
13366 RHSType->isFunctionPointerType()) {
13367 // Valid unless a relational comparison of function pointers
13368 bool IsError = Opc == BO_Cmp;
13369 auto DiagID =
13370 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13371 : getLangOpts().CPlusPlus
13372 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13373 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13374 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13375 << RHS.get()->getSourceRange();
13376 if (IsError)
13377 return QualType();
13378 }
13379
13380 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13381 (RHSType->isIntegerType() && !RHSIsNull)) {
13382 // Skip normal pointer conversion checks in this case; we have better
13383 // diagnostics for this below.
13384 } else if (getLangOpts().CPlusPlus) {
13385 // Equality comparison of a function pointer to a void pointer is invalid,
13386 // but we allow it as an extension.
13387 // FIXME: If we really want to allow this, should it be part of composite
13388 // pointer type computation so it works in conditionals too?
13389 if (!IsOrdered &&
13390 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13391 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13392 // This is a gcc extension compatibility comparison.
13393 // In a SFINAE context, we treat this as a hard error to maintain
13394 // conformance with the C++ standard.
13395 bool IsError = isSFINAEContext();
13396 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13397
13398 if (IsError)
13399 return QualType();
13400
13401 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13402 return computeResultTy();
13403 }
13404
13405 // C++ [expr.eq]p2:
13406 // If at least one operand is a pointer [...] bring them to their
13407 // composite pointer type.
13408 // C++ [expr.spaceship]p6
13409 // If at least one of the operands is of pointer type, [...] bring them
13410 // to their composite pointer type.
13411 // C++ [expr.rel]p2:
13412 // If both operands are pointers, [...] bring them to their composite
13413 // pointer type.
13414 // For <=>, the only valid non-pointer types are arrays and functions, and
13415 // we already decayed those, so this is really the same as the relational
13416 // comparison rule.
13417 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13418 (IsOrdered ? 2 : 1) &&
13419 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13420 RHSType->isObjCObjectPointerType()))) {
13421 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13422 return QualType();
13423 return computeResultTy();
13424 }
13425 } else if (LHSType->isPointerType() &&
13426 RHSType->isPointerType()) { // C99 6.5.8p2
13427 // All of the following pointer-related warnings are GCC extensions, except
13428 // when handling null pointer constants.
13429 QualType LCanPointeeTy =
13430 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13431 QualType RCanPointeeTy =
13432 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13433
13434 // C99 6.5.9p2 and C99 6.5.8p2
13435 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13436 T2: RCanPointeeTy.getUnqualifiedType())) {
13437 if (IsRelational) {
13438 // Pointers both need to point to complete or incomplete types
13439 if ((LCanPointeeTy->isIncompleteType() !=
13440 RCanPointeeTy->isIncompleteType()) &&
13441 !getLangOpts().C11) {
13442 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13443 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13444 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13445 << RCanPointeeTy->isIncompleteType();
13446 }
13447 }
13448 } else if (!IsRelational &&
13449 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13450 // Valid unless comparison between non-null pointer and function pointer
13451 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13452 && !LHSIsNull && !RHSIsNull)
13453 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13454 /*isError*/IsError: false);
13455 } else {
13456 // Invalid
13457 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13458 }
13459 if (LCanPointeeTy != RCanPointeeTy) {
13460 // Treat NULL constant as a special case in OpenCL.
13461 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13462 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13463 Ctx: getASTContext())) {
13464 Diag(Loc,
13465 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13466 << LHSType << RHSType << 0 /* comparison */
13467 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13468 }
13469 }
13470 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13471 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13472 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13473 : CK_BitCast;
13474
13475 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13476 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13477 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13478 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13479 bool ChangingCFIUncheckedCallee =
13480 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13481
13482 if (LHSIsNull && !RHSIsNull)
13483 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13484 else if (!ChangingCFIUncheckedCallee)
13485 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13486 }
13487 return computeResultTy();
13488 }
13489
13490
13491 // C++ [expr.eq]p4:
13492 // Two operands of type std::nullptr_t or one operand of type
13493 // std::nullptr_t and the other a null pointer constant compare
13494 // equal.
13495 // C23 6.5.9p5:
13496 // If both operands have type nullptr_t or one operand has type nullptr_t
13497 // and the other is a null pointer constant, they compare equal if the
13498 // former is a null pointer.
13499 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13500 if (LHSType->isNullPtrType()) {
13501 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13502 return computeResultTy();
13503 }
13504 if (RHSType->isNullPtrType()) {
13505 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13506 return computeResultTy();
13507 }
13508 }
13509
13510 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13511 // C23 6.5.9p6:
13512 // Otherwise, at least one operand is a pointer. If one is a pointer and
13513 // the other is a null pointer constant or has type nullptr_t, they
13514 // compare equal
13515 if (LHSIsNull && RHSType->isPointerType()) {
13516 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13517 return computeResultTy();
13518 }
13519 if (RHSIsNull && LHSType->isPointerType()) {
13520 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13521 return computeResultTy();
13522 }
13523 }
13524
13525 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13526 // These aren't covered by the composite pointer type rules.
13527 if (!IsOrdered && RHSType->isNullPtrType() &&
13528 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13529 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13530 return computeResultTy();
13531 }
13532 if (!IsOrdered && LHSType->isNullPtrType() &&
13533 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13534 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13535 return computeResultTy();
13536 }
13537
13538 if (getLangOpts().CPlusPlus) {
13539 if (IsRelational &&
13540 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13541 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13542 // HACK: Relational comparison of nullptr_t against a pointer type is
13543 // invalid per DR583, but we allow it within std::less<> and friends,
13544 // since otherwise common uses of it break.
13545 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13546 // friends to have std::nullptr_t overload candidates.
13547 DeclContext *DC = CurContext;
13548 if (isa<FunctionDecl>(Val: DC))
13549 DC = DC->getParent();
13550 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13551 if (CTSD->isInStdNamespace() &&
13552 llvm::StringSwitch<bool>(CTSD->getName())
13553 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13554 .Default(Value: false)) {
13555 if (RHSType->isNullPtrType())
13556 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13557 else
13558 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13559 return computeResultTy();
13560 }
13561 }
13562 }
13563
13564 // C++ [expr.eq]p2:
13565 // If at least one operand is a pointer to member, [...] bring them to
13566 // their composite pointer type.
13567 if (!IsOrdered &&
13568 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13569 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13570 return QualType();
13571 else
13572 return computeResultTy();
13573 }
13574 }
13575
13576 // Handle block pointer types.
13577 if (!IsOrdered && LHSType->isBlockPointerType() &&
13578 RHSType->isBlockPointerType()) {
13579 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13580 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13581
13582 if (!LHSIsNull && !RHSIsNull &&
13583 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13584 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13585 << LHSType << RHSType << LHS.get()->getSourceRange()
13586 << RHS.get()->getSourceRange();
13587 }
13588 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13589 return computeResultTy();
13590 }
13591
13592 // Allow block pointers to be compared with null pointer constants.
13593 if (!IsOrdered
13594 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13595 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13596 if (!LHSIsNull && !RHSIsNull) {
13597 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13598 ->getPointeeType()->isVoidType())
13599 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13600 ->getPointeeType()->isVoidType())))
13601 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13602 << LHSType << RHSType << LHS.get()->getSourceRange()
13603 << RHS.get()->getSourceRange();
13604 }
13605 if (LHSIsNull && !RHSIsNull)
13606 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13607 CK: RHSType->isPointerType() ? CK_BitCast
13608 : CK_AnyPointerToBlockPointerCast);
13609 else
13610 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13611 CK: LHSType->isPointerType() ? CK_BitCast
13612 : CK_AnyPointerToBlockPointerCast);
13613 return computeResultTy();
13614 }
13615
13616 if (LHSType->isObjCObjectPointerType() ||
13617 RHSType->isObjCObjectPointerType()) {
13618 const PointerType *LPT = LHSType->getAs<PointerType>();
13619 const PointerType *RPT = RHSType->getAs<PointerType>();
13620 if (LPT || RPT) {
13621 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13622 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13623
13624 if (!LPtrToVoid && !RPtrToVoid &&
13625 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13626 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13627 /*isError*/IsError: false);
13628 }
13629 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13630 // the RHS, but we have test coverage for this behavior.
13631 // FIXME: Consider using convertPointersToCompositeType in C++.
13632 if (LHSIsNull && !RHSIsNull) {
13633 Expr *E = LHS.get();
13634 if (getLangOpts().ObjCAutoRefCount)
13635 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13636 CCK: CheckedConversionKind::Implicit);
13637 LHS = ImpCastExprToType(E, Type: RHSType,
13638 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13639 }
13640 else {
13641 Expr *E = RHS.get();
13642 if (getLangOpts().ObjCAutoRefCount)
13643 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13644 CCK: CheckedConversionKind::Implicit,
13645 /*Diagnose=*/true,
13646 /*DiagnoseCFAudited=*/false, Opc);
13647 RHS = ImpCastExprToType(E, Type: LHSType,
13648 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13649 }
13650 return computeResultTy();
13651 }
13652 if (LHSType->isObjCObjectPointerType() &&
13653 RHSType->isObjCObjectPointerType()) {
13654 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13655 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13656 /*isError*/IsError: false);
13657 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13658 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13659
13660 if (LHSIsNull && !RHSIsNull)
13661 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13662 else
13663 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13664 return computeResultTy();
13665 }
13666
13667 if (!IsOrdered && LHSType->isBlockPointerType() &&
13668 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13669 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13670 CK: CK_BlockPointerToObjCPointerCast);
13671 return computeResultTy();
13672 } else if (!IsOrdered &&
13673 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13674 RHSType->isBlockPointerType()) {
13675 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13676 CK: CK_BlockPointerToObjCPointerCast);
13677 return computeResultTy();
13678 }
13679 }
13680 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13681 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13682 unsigned DiagID = 0;
13683 bool isError = false;
13684 if (LangOpts.DebuggerSupport) {
13685 // Under a debugger, allow the comparison of pointers to integers,
13686 // since users tend to want to compare addresses.
13687 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13688 (RHSIsNull && RHSType->isIntegerType())) {
13689 if (IsOrdered) {
13690 isError = getLangOpts().CPlusPlus;
13691 DiagID =
13692 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13693 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13694 }
13695 } else if (getLangOpts().CPlusPlus) {
13696 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13697 isError = true;
13698 } else if (IsOrdered)
13699 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13700 else
13701 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13702
13703 if (DiagID) {
13704 Diag(Loc, DiagID)
13705 << LHSType << RHSType << LHS.get()->getSourceRange()
13706 << RHS.get()->getSourceRange();
13707 if (isError)
13708 return QualType();
13709 }
13710
13711 if (LHSType->isIntegerType())
13712 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13713 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13714 else
13715 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13716 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13717 return computeResultTy();
13718 }
13719
13720 // Handle block pointers.
13721 if (!IsOrdered && RHSIsNull
13722 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13723 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13724 return computeResultTy();
13725 }
13726 if (!IsOrdered && LHSIsNull
13727 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13728 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13729 return computeResultTy();
13730 }
13731
13732 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13733 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13734 return computeResultTy();
13735 }
13736
13737 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13738 return computeResultTy();
13739 }
13740
13741 if (LHSIsNull && RHSType->isQueueT()) {
13742 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13743 return computeResultTy();
13744 }
13745
13746 if (LHSType->isQueueT() && RHSIsNull) {
13747 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13748 return computeResultTy();
13749 }
13750 }
13751
13752 return InvalidOperands(Loc, LHS, RHS);
13753}
13754
13755QualType Sema::GetSignedVectorType(QualType V) {
13756 const VectorType *VTy = V->castAs<VectorType>();
13757 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13758
13759 if (isa<ExtVectorType>(Val: VTy)) {
13760 if (VTy->isExtVectorBoolType())
13761 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13762 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13763 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13764 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13765 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13766 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13767 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13768 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13769 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13770 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13771 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13772 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13773 return Context.getExtVectorType(VectorType: Context.LongLongTy,
13774 NumElts: VTy->getNumElements());
13775 const auto *BIT = VTy->getElementType()->castAs<BitIntType>();
13776 return Context.getExtVectorType(
13777 VectorType: Context.getBitIntType(/*IsUnsigned=*/Unsigned: false, NumBits: BIT->getNumBits()),
13778 NumElts: VTy->getNumElements());
13779 }
13780
13781 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13782 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13783 VecKind: VectorKind::Generic);
13784 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13785 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13786 VecKind: VectorKind::Generic);
13787 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13788 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13789 VecKind: VectorKind::Generic);
13790 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13791 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13792 VecKind: VectorKind::Generic);
13793 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13794 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13795 VecKind: VectorKind::Generic);
13796 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13797 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13798 VecKind: VectorKind::Generic);
13799 const auto *BIT = VTy->getElementType()->castAs<BitIntType>();
13800 return Context.getVectorType(
13801 VectorType: Context.getBitIntType(/*IsUnsigned=*/Unsigned: false, NumBits: BIT->getNumBits()),
13802 NumElts: VTy->getNumElements(), VecKind: VectorKind::Generic);
13803}
13804
13805QualType Sema::GetSignedSizelessVectorType(QualType V) {
13806 const BuiltinType *VTy = V->castAs<BuiltinType>();
13807 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13808
13809 const QualType ETy = V->getSveEltType(Ctx: Context);
13810 const auto TypeSize = Context.getTypeSize(T: ETy);
13811
13812 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13813 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13814 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13815}
13816
13817QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13818 SourceLocation Loc,
13819 BinaryOperatorKind Opc) {
13820 if (Opc == BO_Cmp) {
13821 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13822 return QualType();
13823 }
13824
13825 // Check to make sure we're operating on vectors of the same type and width,
13826 // Allowing one side to be a scalar of element type.
13827 QualType vType =
13828 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13829 /*AllowBothBool*/ true,
13830 /*AllowBoolConversions*/ getLangOpts().ZVector,
13831 /*AllowBooleanOperation*/ AllowBoolOperation: true);
13832 if (vType.isNull())
13833 return vType;
13834
13835 QualType LHSType = LHS.get()->getType();
13836
13837 // Determine the return type of a vector compare. By default clang will return
13838 // a scalar for all vector compares except vector bool and vector pixel.
13839 // With the gcc compiler we will always return a vector type and with the xl
13840 // compiler we will always return a scalar type. This switch allows choosing
13841 // which behavior is prefered.
13842 if (getLangOpts().AltiVec) {
13843 switch (getLangOpts().getAltivecSrcCompat()) {
13844 case LangOptions::AltivecSrcCompatKind::Mixed:
13845 // If AltiVec, the comparison results in a numeric type, i.e.
13846 // bool for C++, int for C
13847 if (vType->castAs<VectorType>()->getVectorKind() ==
13848 VectorKind::AltiVecVector)
13849 return Context.getLogicalOperationType();
13850 else
13851 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13852 break;
13853 case LangOptions::AltivecSrcCompatKind::GCC:
13854 // For GCC we always return the vector type.
13855 break;
13856 case LangOptions::AltivecSrcCompatKind::XL:
13857 return Context.getLogicalOperationType();
13858 break;
13859 }
13860 }
13861
13862 // For non-floating point types, check for self-comparisons of the form
13863 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13864 // often indicate logic errors in the program.
13865 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13866
13867 // Check for comparisons of floating point operands using != and ==.
13868 if (LHSType->hasFloatingRepresentation()) {
13869 assert(RHS.get()->getType()->hasFloatingRepresentation());
13870 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13871 }
13872
13873 // Return a signed type for the vector.
13874 return GetSignedVectorType(V: vType);
13875}
13876
13877QualType Sema::CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
13878 SourceLocation Loc,
13879 BinaryOperatorKind Opc) {
13880 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13881 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13882
13883 QualType MatrixTy =
13884 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13885 if (MatrixTy.isNull())
13886 return QualType();
13887
13888 if (!LHS.get()->getType()->isMatrixType()) {
13889 LHS = prepareMatrixSplat(MatrixTy, SplattedExpr: LHS.get());
13890 if (LHS.isInvalid())
13891 return QualType();
13892 LHS = ImpCastExprToType(E: LHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13893 }
13894 if (!RHS.get()->getType()->isMatrixType()) {
13895 RHS = prepareMatrixSplat(MatrixTy, SplattedExpr: RHS.get());
13896 if (RHS.isInvalid())
13897 return QualType();
13898 RHS = ImpCastExprToType(E: RHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13899 }
13900
13901 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13902 return Context.getConstantMatrixType(ElementType: Context.BoolTy, NumRows: MT->getNumRows(),
13903 NumColumns: MT->getNumColumns());
13904}
13905
13906QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13907 ExprResult &RHS,
13908 SourceLocation Loc,
13909 BinaryOperatorKind Opc) {
13910 if (Opc == BO_Cmp) {
13911 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13912 return QualType();
13913 }
13914
13915 // Check to make sure we're operating on vectors of the same type and width,
13916 // Allowing one side to be a scalar of element type.
13917 QualType vType = CheckSizelessVectorOperands(
13918 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13919
13920 if (vType.isNull())
13921 return vType;
13922
13923 QualType LHSType = LHS.get()->getType();
13924
13925 // For non-floating point types, check for self-comparisons of the form
13926 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13927 // often indicate logic errors in the program.
13928 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13929
13930 // Check for comparisons of floating point operands using != and ==.
13931 if (LHSType->hasFloatingRepresentation()) {
13932 assert(RHS.get()->getType()->hasFloatingRepresentation());
13933 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13934 }
13935
13936 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13937 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13938
13939 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13940 RHSBuiltinTy->isSVEBool())
13941 return LHSType;
13942
13943 // Return a signed type for the vector.
13944 return GetSignedSizelessVectorType(V: vType);
13945}
13946
13947static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13948 const ExprResult &XorRHS,
13949 const SourceLocation Loc) {
13950 // Do not diagnose macros.
13951 if (Loc.isMacroID())
13952 return;
13953
13954 // Do not diagnose if both LHS and RHS are macros.
13955 if (XorLHS.get()->getExprLoc().isMacroID() &&
13956 XorRHS.get()->getExprLoc().isMacroID())
13957 return;
13958
13959 bool Negative = false;
13960 bool ExplicitPlus = false;
13961 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13962 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13963
13964 if (!LHSInt)
13965 return;
13966 if (!RHSInt) {
13967 // Check negative literals.
13968 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13969 UnaryOperatorKind Opc = UO->getOpcode();
13970 if (Opc != UO_Minus && Opc != UO_Plus)
13971 return;
13972 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13973 if (!RHSInt)
13974 return;
13975 Negative = (Opc == UO_Minus);
13976 ExplicitPlus = !Negative;
13977 } else {
13978 return;
13979 }
13980 }
13981
13982 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13983 llvm::APInt RightSideValue = RHSInt->getValue();
13984 if (LeftSideValue != 2 && LeftSideValue != 10)
13985 return;
13986
13987 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13988 return;
13989
13990 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13991 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13992 llvm::StringRef ExprStr =
13993 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13994
13995 CharSourceRange XorRange =
13996 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13997 llvm::StringRef XorStr =
13998 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13999 // Do not diagnose if xor keyword/macro is used.
14000 if (XorStr == "xor")
14001 return;
14002
14003 std::string LHSStr = std::string(Lexer::getSourceText(
14004 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
14005 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
14006 std::string RHSStr = std::string(Lexer::getSourceText(
14007 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
14008 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
14009
14010 if (Negative) {
14011 RightSideValue = -RightSideValue;
14012 RHSStr = "-" + RHSStr;
14013 } else if (ExplicitPlus) {
14014 RHSStr = "+" + RHSStr;
14015 }
14016
14017 StringRef LHSStrRef = LHSStr;
14018 StringRef RHSStrRef = RHSStr;
14019 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
14020 // literals.
14021 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
14022 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
14023 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
14024 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
14025 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
14026 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
14027 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
14028 return;
14029
14030 bool SuggestXor =
14031 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
14032 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
14033 int64_t RightSideIntValue = RightSideValue.getSExtValue();
14034 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
14035 std::string SuggestedExpr = "1 << " + RHSStr;
14036 bool Overflow = false;
14037 llvm::APInt One = (LeftSideValue - 1);
14038 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
14039 if (Overflow) {
14040 if (RightSideIntValue < 64)
14041 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
14042 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
14043 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
14044 else if (RightSideIntValue == 64)
14045 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
14046 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
14047 else
14048 return;
14049 } else {
14050 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
14051 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
14052 << toString(I: PowValue, Radix: 10, Signed: true)
14053 << FixItHint::CreateReplacement(
14054 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
14055 }
14056
14057 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
14058 << ("0x2 ^ " + RHSStr) << SuggestXor;
14059 } else if (LeftSideValue == 10) {
14060 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
14061 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
14062 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
14063 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
14064 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
14065 << ("0xA ^ " + RHSStr) << SuggestXor;
14066 }
14067}
14068
14069QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14070 SourceLocation Loc,
14071 BinaryOperatorKind Opc) {
14072 // Ensure that either both operands are of the same vector type, or
14073 // one operand is of a vector type and the other is of its element type.
14074 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
14075 /*AllowBothBool*/ true,
14076 /*AllowBoolConversions*/ false,
14077 /*AllowBooleanOperation*/ AllowBoolOperation: false);
14078 if (vType.isNull())
14079 return QualType();
14080 if (getLangOpts().OpenCL &&
14081 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
14082 vType->hasFloatingRepresentation())
14083 return InvalidOperands(Loc, LHS, RHS);
14084 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
14085 // usage of the logical operators && and || with vectors in C. This
14086 // check could be notionally dropped.
14087 if (!getLangOpts().CPlusPlus &&
14088 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
14089 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
14090 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
14091 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
14092 // `select` functions.
14093 if (getLangOpts().HLSL &&
14094 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
14095 (void)InvalidOperands(Loc, LHS, RHS);
14096 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
14097 return QualType();
14098 }
14099
14100 return GetSignedVectorType(V: LHS.get()->getType());
14101}
14102
14103QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14104 SourceLocation Loc,
14105 BinaryOperatorKind Opc) {
14106
14107 if (!getLangOpts().HLSL) {
14108 SemaRef.Diag(Loc, DiagID: diag::err_matrix_logical_operations_supported_for_hlsl);
14109 return QualType();
14110 }
14111
14112 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
14113 (void)InvalidOperands(Loc, LHS, RHS);
14114 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
14115 return QualType();
14116 }
14117 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
14118 << getLangOpts().getHLSLVersion();
14119 return QualType();
14120}
14121
14122QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
14123 SourceLocation Loc,
14124 bool IsCompAssign) {
14125 if (!IsCompAssign) {
14126 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
14127 if (LHS.isInvalid())
14128 return QualType();
14129 }
14130 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
14131 if (RHS.isInvalid())
14132 return QualType();
14133
14134 // For conversion purposes, we ignore any qualifiers.
14135 // For example, "const float" and "float" are equivalent.
14136 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
14137 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
14138
14139 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
14140 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
14141 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14142
14143 if (Context.hasSameType(T1: LHSType, T2: RHSType))
14144 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
14145
14146 // Type conversion may change LHS/RHS. Keep copies to the original results, in
14147 // case we have to return InvalidOperands.
14148 ExprResult OriginalLHS = LHS;
14149 ExprResult OriginalRHS = RHS;
14150 if (LHSMatType && !RHSMatType) {
14151 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
14152 if (!RHS.isInvalid())
14153 return LHSType;
14154
14155 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
14156 }
14157
14158 if (!LHSMatType && RHSMatType) {
14159 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
14160 if (!LHS.isInvalid())
14161 return RHSType;
14162 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
14163 }
14164
14165 return InvalidOperands(Loc, LHS, RHS);
14166}
14167
14168QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
14169 SourceLocation Loc,
14170 bool IsCompAssign) {
14171 if (!IsCompAssign) {
14172 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
14173 if (LHS.isInvalid())
14174 return QualType();
14175 }
14176 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
14177 if (RHS.isInvalid())
14178 return QualType();
14179
14180 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14181 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14182 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14183
14184 if (LHSMatType && RHSMatType) {
14185 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14186 return InvalidOperands(Loc, LHS, RHS);
14187
14188 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
14189 return Context.getCommonSugaredType(
14190 X: LHS.get()->getType().getUnqualifiedType(),
14191 Y: RHS.get()->getType().getUnqualifiedType());
14192
14193 QualType LHSELTy = LHSMatType->getElementType(),
14194 RHSELTy = RHSMatType->getElementType();
14195 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
14196 return InvalidOperands(Loc, LHS, RHS);
14197
14198 return Context.getConstantMatrixType(
14199 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
14200 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
14201 }
14202 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14203}
14204
14205static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
14206 switch (Opc) {
14207 default:
14208 return false;
14209 case BO_And:
14210 case BO_AndAssign:
14211 case BO_Or:
14212 case BO_OrAssign:
14213 case BO_Xor:
14214 case BO_XorAssign:
14215 return true;
14216 }
14217}
14218
14219inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
14220 SourceLocation Loc,
14221 BinaryOperatorKind Opc) {
14222 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
14223
14224 bool IsCompAssign =
14225 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14226
14227 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14228
14229 if (LHS.get()->getType()->isVectorType() ||
14230 RHS.get()->getType()->isVectorType()) {
14231 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14232 RHS.get()->getType()->hasIntegerRepresentation())
14233 return CheckVectorOperands(
14234 LHS, RHS, Loc, IsCompAssign,
14235 /*AllowBothBool*/ true,
14236 /*AllowBoolConversions*/ getLangOpts().ZVector,
14237 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator);
14238 return InvalidOperands(Loc, LHS, RHS);
14239 }
14240
14241 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14242 RHS.get()->getType()->isSveVLSBuiltinType()) {
14243 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14244 RHS.get()->getType()->hasIntegerRepresentation())
14245 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14246 OperationKind: ArithConvKind::BitwiseOp);
14247 return InvalidOperands(Loc, LHS, RHS);
14248 }
14249
14250 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14251 RHS.get()->getType()->isSveVLSBuiltinType()) {
14252 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14253 RHS.get()->getType()->hasIntegerRepresentation())
14254 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14255 OperationKind: ArithConvKind::BitwiseOp);
14256 return InvalidOperands(Loc, LHS, RHS);
14257 }
14258
14259 if (Opc == BO_And)
14260 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
14261
14262 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14263 RHS.get()->getType()->hasFloatingRepresentation())
14264 return InvalidOperands(Loc, LHS, RHS);
14265
14266 ExprResult LHSResult = LHS, RHSResult = RHS;
14267 QualType compType = UsualArithmeticConversions(
14268 LHS&: LHSResult, RHS&: RHSResult, Loc,
14269 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
14270 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14271 return QualType();
14272 LHS = LHSResult.get();
14273 RHS = RHSResult.get();
14274
14275 if (Opc == BO_Xor)
14276 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
14277
14278 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14279 return compType;
14280 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14281 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14282 return ResultTy;
14283}
14284
14285// C99 6.5.[13,14]
14286inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14287 SourceLocation Loc,
14288 BinaryOperatorKind Opc) {
14289 // Check vector operands differently.
14290 if (LHS.get()->getType()->isVectorType() ||
14291 RHS.get()->getType()->isVectorType())
14292 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14293
14294 if (LHS.get()->getType()->isConstantMatrixType() ||
14295 RHS.get()->getType()->isConstantMatrixType())
14296 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14297
14298 bool EnumConstantInBoolContext = false;
14299 for (const ExprResult &HS : {LHS, RHS}) {
14300 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
14301 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
14302 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14303 EnumConstantInBoolContext = true;
14304 }
14305 }
14306
14307 if (EnumConstantInBoolContext)
14308 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
14309
14310 // WebAssembly tables can't be used with logical operators.
14311 QualType LHSTy = LHS.get()->getType();
14312 QualType RHSTy = RHS.get()->getType();
14313 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
14314 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
14315 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14316 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14317 return InvalidOperands(Loc, LHS, RHS);
14318 }
14319
14320 // Diagnose cases where the user write a logical and/or but probably meant a
14321 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14322 // is a constant.
14323 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14324 !LHS.get()->getType()->isBooleanType() &&
14325 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14326 // Don't warn in macros or template instantiations.
14327 !Loc.isMacroID() && !inTemplateInstantiation()) {
14328 // If the RHS can be constant folded, and if it constant folds to something
14329 // that isn't 0 or 1 (which indicate a potential logical operation that
14330 // happened to fold to true/false) then warn.
14331 // Parens on the RHS are ignored.
14332 Expr::EvalResult EVResult;
14333 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
14334 llvm::APSInt Result = EVResult.Val.getInt();
14335 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14336 !RHS.get()->getExprLoc().isMacroID()) ||
14337 (Result != 0 && Result != 1)) {
14338 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
14339 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14340 // Suggest replacing the logical operator with the bitwise version
14341 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
14342 << (Opc == BO_LAnd ? "&" : "|")
14343 << FixItHint::CreateReplacement(
14344 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
14345 Code: Opc == BO_LAnd ? "&" : "|");
14346 if (Opc == BO_LAnd)
14347 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14348 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
14349 << FixItHint::CreateRemoval(
14350 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
14351 RHS.get()->getEndLoc()));
14352 }
14353 }
14354 }
14355
14356 if (!Context.getLangOpts().CPlusPlus) {
14357 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14358 // not operate on the built-in scalar and vector float types.
14359 if (Context.getLangOpts().OpenCL &&
14360 Context.getLangOpts().OpenCLVersion < 120) {
14361 if (LHS.get()->getType()->isFloatingType() ||
14362 RHS.get()->getType()->isFloatingType())
14363 return InvalidOperands(Loc, LHS, RHS);
14364 }
14365
14366 LHS = UsualUnaryConversions(E: LHS.get());
14367 if (LHS.isInvalid())
14368 return QualType();
14369
14370 RHS = UsualUnaryConversions(E: RHS.get());
14371 if (RHS.isInvalid())
14372 return QualType();
14373
14374 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14375 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
14376 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14377 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
14378
14379 if (!LHS.get()->getType()->isScalarType() ||
14380 !RHS.get()->getType()->isScalarType())
14381 return InvalidOperands(Loc, LHS, RHS);
14382
14383 return Context.IntTy;
14384 }
14385
14386 // The following is safe because we only use this method for
14387 // non-overloadable operands.
14388
14389 // C++ [expr.log.and]p1
14390 // C++ [expr.log.or]p1
14391 // The operands are both contextually converted to type bool.
14392 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14393 if (LHSRes.isInvalid()) {
14394 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14395 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14396 return ResultTy;
14397 }
14398 LHS = LHSRes;
14399
14400 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14401 if (RHSRes.isInvalid()) {
14402 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14403 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14404 return ResultTy;
14405 }
14406 RHS = RHSRes;
14407
14408 // C++ [expr.log.and]p2
14409 // C++ [expr.log.or]p2
14410 // The result is a bool.
14411 return Context.BoolTy;
14412}
14413
14414static bool IsReadonlyMessage(Expr *E, Sema &S) {
14415 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14416 if (!ME) return false;
14417 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14418 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14419 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14420 if (!Base) return false;
14421 return Base->getMethodDecl() != nullptr;
14422}
14423
14424/// Is the given expression (which must be 'const') a reference to a
14425/// variable which was originally non-const, but which has become
14426/// 'const' due to being captured within a block?
14427enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14428static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14429 assert(E->isLValue() && E->getType().isConstQualified());
14430 E = E->IgnoreParens();
14431
14432 // Must be a reference to a declaration from an enclosing scope.
14433 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14434 if (!DRE) return NCCK_None;
14435 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14436
14437 ValueDecl *Value = DRE->getDecl();
14438
14439 // The declaration must be a value which is not declared 'const'.
14440 if (Value->getType().isConstQualified())
14441 return NCCK_None;
14442
14443 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14444 if (Binding) {
14445 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14446 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14447 return NCCK_Lambda;
14448 }
14449
14450 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14451 if (!Var)
14452 return NCCK_None;
14453 if (Var->getType()->isReferenceType())
14454 return NCCK_None;
14455
14456 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14457
14458 // Decide whether the first capture was for a block or a lambda.
14459 DeclContext *DC = S.CurContext, *Prev = nullptr;
14460 // Decide whether the first capture was for a block or a lambda.
14461 while (DC) {
14462 // For init-capture, it is possible that the variable belongs to the
14463 // template pattern of the current context.
14464 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14465 if (Var->isInitCapture() &&
14466 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14467 break;
14468 if (DC == Var->getDeclContext())
14469 break;
14470 Prev = DC;
14471 DC = DC->getParent();
14472 }
14473 // Unless we have an init-capture, we've gone one step too far.
14474 if (!Var->isInitCapture())
14475 DC = Prev;
14476 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14477}
14478
14479static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14480 Ty = Ty.getNonReferenceType();
14481 if (IsDereference && Ty->isPointerType())
14482 Ty = Ty->getPointeeType();
14483 return !Ty.isConstQualified();
14484}
14485
14486// Update err_typecheck_assign_const and note_typecheck_assign_const
14487// when this enum is changed.
14488enum {
14489 ConstFunction,
14490 ConstVariable,
14491 ConstMember,
14492 NestedConstMember,
14493 ConstUnknown, // Keep as last element
14494};
14495
14496/// Emit the "read-only variable not assignable" error and print notes to give
14497/// more information about why the variable is not assignable, such as pointing
14498/// to the declaration of a const variable, showing that a method is const, or
14499/// that the function is returning a const reference.
14500static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14501 SourceLocation Loc) {
14502 SourceRange ExprRange = E->getSourceRange();
14503
14504 // Only emit one error on the first const found. All other consts will emit
14505 // a note to the error.
14506 bool DiagnosticEmitted = false;
14507
14508 // Track if the current expression is the result of a dereference, and if the
14509 // next checked expression is the result of a dereference.
14510 bool IsDereference = false;
14511 bool NextIsDereference = false;
14512
14513 // Loop to process MemberExpr chains.
14514 while (true) {
14515 IsDereference = NextIsDereference;
14516
14517 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14518 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14519 NextIsDereference = ME->isArrow();
14520 const ValueDecl *VD = ME->getMemberDecl();
14521 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14522 // Mutable fields can be modified even if the class is const.
14523 if (Field->isMutable()) {
14524 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14525 break;
14526 }
14527
14528 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14529 if (!DiagnosticEmitted) {
14530 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14531 << ExprRange << ConstMember << false /*static*/ << Field
14532 << Field->getType();
14533 DiagnosticEmitted = true;
14534 }
14535 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14536 << ConstMember << false /*static*/ << Field << Field->getType()
14537 << Field->getSourceRange();
14538 }
14539 E = ME->getBase();
14540 continue;
14541 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14542 if (VDecl->getType().isConstQualified()) {
14543 if (!DiagnosticEmitted) {
14544 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14545 << ExprRange << ConstMember << true /*static*/ << VDecl
14546 << VDecl->getType();
14547 DiagnosticEmitted = true;
14548 }
14549 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14550 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14551 << VDecl->getSourceRange();
14552 }
14553 // Static fields do not inherit constness from parents.
14554 break;
14555 }
14556 break; // End MemberExpr
14557 } else if (const ArraySubscriptExpr *ASE =
14558 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14559 E = ASE->getBase()->IgnoreParenImpCasts();
14560 continue;
14561 } else if (const ExtVectorElementExpr *EVE =
14562 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14563 E = EVE->getBase()->IgnoreParenImpCasts();
14564 continue;
14565 }
14566 break;
14567 }
14568
14569 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14570 // Function calls
14571 const FunctionDecl *FD = CE->getDirectCallee();
14572 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14573 if (!DiagnosticEmitted) {
14574 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14575 << ConstFunction << FD;
14576 DiagnosticEmitted = true;
14577 }
14578 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14579 DiagID: diag::note_typecheck_assign_const)
14580 << ConstFunction << FD << FD->getReturnType()
14581 << FD->getReturnTypeSourceRange();
14582 }
14583 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14584 // Point to variable declaration.
14585 if (const ValueDecl *VD = DRE->getDecl()) {
14586 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14587 if (!DiagnosticEmitted) {
14588 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14589 << ExprRange << ConstVariable << VD << VD->getType();
14590 DiagnosticEmitted = true;
14591 }
14592 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14593 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14594 }
14595 }
14596 } else if (isa<CXXThisExpr>(Val: E)) {
14597 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14598 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14599 if (MD->isConst()) {
14600 if (!DiagnosticEmitted) {
14601 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14602 << ExprRange << MD;
14603 DiagnosticEmitted = true;
14604 }
14605 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14606 << MD << MD->getSourceRange();
14607 }
14608 }
14609 }
14610 }
14611
14612 if (DiagnosticEmitted)
14613 return;
14614
14615 // Can't determine a more specific message, so display the generic error.
14616 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14617}
14618
14619enum OriginalExprKind {
14620 OEK_Variable,
14621 OEK_Member,
14622 OEK_LValue
14623};
14624
14625static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14626 const RecordType *Ty,
14627 SourceLocation Loc, SourceRange Range,
14628 OriginalExprKind OEK,
14629 bool &DiagnosticEmitted) {
14630 std::vector<const RecordType *> RecordTypeList;
14631 RecordTypeList.push_back(x: Ty);
14632 unsigned NextToCheckIndex = 0;
14633 // We walk the record hierarchy breadth-first to ensure that we print
14634 // diagnostics in field nesting order.
14635 while (RecordTypeList.size() > NextToCheckIndex) {
14636 bool IsNested = NextToCheckIndex > 0;
14637 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14638 ->getDecl()
14639 ->getDefinitionOrSelf()
14640 ->fields()) {
14641 // First, check every field for constness.
14642 QualType FieldTy = Field->getType();
14643 if (FieldTy.isConstQualified()) {
14644 if (!DiagnosticEmitted) {
14645 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14646 << Range << NestedConstMember << OEK << VD
14647 << IsNested << Field;
14648 DiagnosticEmitted = true;
14649 }
14650 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14651 << NestedConstMember << IsNested << Field
14652 << FieldTy << Field->getSourceRange();
14653 }
14654
14655 // Then we append it to the list to check next in order.
14656 FieldTy = FieldTy.getCanonicalType();
14657 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14658 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14659 RecordTypeList.push_back(x: FieldRecTy);
14660 }
14661 }
14662 ++NextToCheckIndex;
14663 }
14664}
14665
14666/// Emit an error for the case where a record we are trying to assign to has a
14667/// const-qualified field somewhere in its hierarchy.
14668static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14669 SourceLocation Loc) {
14670 QualType Ty = E->getType();
14671 assert(Ty->isRecordType() && "lvalue was not record?");
14672 SourceRange Range = E->getSourceRange();
14673 const auto *RTy = Ty->getAsCanonical<RecordType>();
14674 bool DiagEmitted = false;
14675
14676 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14677 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14678 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14679 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14680 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14681 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14682 else
14683 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14684 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14685 if (!DiagEmitted)
14686 DiagnoseConstAssignment(S, E, Loc);
14687}
14688
14689/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14690/// emit an error and return true. If so, return false.
14691static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14692 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14693
14694 S.CheckShadowingDeclModification(E, Loc);
14695
14696 SourceLocation OrigLoc = Loc;
14697 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14698 Loc: &Loc);
14699 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14700 IsLV = Expr::MLV_InvalidMessageExpression;
14701 if (IsLV == Expr::MLV_Valid)
14702 return false;
14703
14704 unsigned DiagID = 0;
14705 bool NeedType = false;
14706 switch (IsLV) { // C99 6.5.16p2
14707 case Expr::MLV_ConstQualified:
14708 // Use a specialized diagnostic when we're assigning to an object
14709 // from an enclosing function or block.
14710 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14711 if (NCCK == NCCK_Block)
14712 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14713 else
14714 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14715 break;
14716 }
14717
14718 // In ARC, use some specialized diagnostics for occasions where we
14719 // infer 'const'. These are always pseudo-strong variables.
14720 if (S.getLangOpts().ObjCAutoRefCount) {
14721 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14722 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14723 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14724
14725 // Use the normal diagnostic if it's pseudo-__strong but the
14726 // user actually wrote 'const'.
14727 if (var->isARCPseudoStrong() &&
14728 (!var->getTypeSourceInfo() ||
14729 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14730 // There are three pseudo-strong cases:
14731 // - self
14732 ObjCMethodDecl *method = S.getCurMethodDecl();
14733 if (method && var == method->getSelfDecl()) {
14734 DiagID = method->isClassMethod()
14735 ? diag::err_typecheck_arc_assign_self_class_method
14736 : diag::err_typecheck_arc_assign_self;
14737
14738 // - Objective-C externally_retained attribute.
14739 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14740 isa<ParmVarDecl>(Val: var)) {
14741 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14742
14743 // - fast enumeration variables
14744 } else {
14745 DiagID = diag::err_typecheck_arr_assign_enumeration;
14746 }
14747
14748 SourceRange Assign;
14749 if (Loc != OrigLoc)
14750 Assign = SourceRange(OrigLoc, OrigLoc);
14751 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14752 // We need to preserve the AST regardless, so migration tool
14753 // can do its job.
14754 return false;
14755 }
14756 }
14757 }
14758
14759 // If none of the special cases above are triggered, then this is a
14760 // simple const assignment.
14761 if (DiagID == 0) {
14762 DiagnoseConstAssignment(S, E, Loc);
14763 return true;
14764 }
14765
14766 break;
14767 case Expr::MLV_ConstAddrSpace:
14768 DiagnoseConstAssignment(S, E, Loc);
14769 return true;
14770 case Expr::MLV_ConstQualifiedField:
14771 DiagnoseRecursiveConstFields(S, E, Loc);
14772 return true;
14773 case Expr::MLV_ArrayType:
14774 case Expr::MLV_ArrayTemporary:
14775 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14776 NeedType = true;
14777 break;
14778 case Expr::MLV_NotObjectType:
14779 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14780 NeedType = true;
14781 break;
14782 case Expr::MLV_LValueCast:
14783 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14784 break;
14785 case Expr::MLV_Valid:
14786 llvm_unreachable("did not take early return for MLV_Valid");
14787 case Expr::MLV_InvalidExpression:
14788 case Expr::MLV_MemberFunction:
14789 case Expr::MLV_ClassTemporary: {
14790 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E)) {
14791 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14792 if (UnaryOp->getOpcode() == UO_Imag &&
14793 !Op->getType()->isAnyComplexType()) {
14794 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14795 NeedType = true;
14796 break;
14797 }
14798 }
14799
14800 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14801 break;
14802 }
14803 case Expr::MLV_IncompleteType:
14804 case Expr::MLV_IncompleteVoidType:
14805 return S.RequireCompleteType(Loc, T: E->getType(),
14806 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14807 case Expr::MLV_DuplicateVectorComponents:
14808 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14809 break;
14810 case Expr::MLV_DuplicateMatrixComponents:
14811 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14812 break;
14813 case Expr::MLV_NoSetterProperty:
14814 llvm_unreachable("readonly properties should be processed differently");
14815 case Expr::MLV_InvalidMessageExpression:
14816 DiagID = diag::err_readonly_message_assignment;
14817 break;
14818 case Expr::MLV_SubObjCPropertySetting:
14819 DiagID = diag::err_no_subobject_property_setting;
14820 break;
14821 }
14822
14823 SourceRange Assign;
14824 if (Loc != OrigLoc)
14825 Assign = SourceRange(OrigLoc, OrigLoc);
14826 if (NeedType)
14827 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14828 else
14829 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14830 return true;
14831}
14832
14833static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14834 SourceLocation Loc,
14835 Sema &Sema) {
14836 if (Sema.inTemplateInstantiation())
14837 return;
14838 if (Sema.isUnevaluatedContext())
14839 return;
14840 if (Loc.isInvalid() || Loc.isMacroID())
14841 return;
14842 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14843 return;
14844
14845 // C / C++ fields
14846 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14847 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14848 if (ML && MR) {
14849 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14850 return;
14851 const ValueDecl *LHSDecl =
14852 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14853 const ValueDecl *RHSDecl =
14854 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14855 if (LHSDecl != RHSDecl)
14856 return;
14857 if (LHSDecl->getType().isVolatileQualified())
14858 return;
14859 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14860 if (RefTy->getPointeeType().isVolatileQualified())
14861 return;
14862
14863 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14864 }
14865
14866 // Objective-C instance variables
14867 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14868 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14869 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14870 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14871 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14872 if (RL && RR && RL->getDecl() == RR->getDecl())
14873 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14874 }
14875}
14876
14877// C99 6.5.16.1
14878QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14879 SourceLocation Loc,
14880 QualType CompoundType,
14881 BinaryOperatorKind Opc) {
14882 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14883
14884 // Verify that LHS is a modifiable lvalue, and emit error if not.
14885 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14886 return QualType();
14887
14888 QualType LHSType = LHSExpr->getType();
14889 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14890 CompoundType;
14891
14892 if (RHS.isUsable()) {
14893 // Even if this check fails don't return early to allow the best
14894 // possible error recovery and to allow any subsequent diagnostics to
14895 // work.
14896 const ValueDecl *Assignee = nullptr;
14897 bool ShowFullyQualifiedAssigneeName = false;
14898 // In simple cases describe what is being assigned to
14899 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14900 Assignee = DR->getDecl();
14901 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14902 Assignee = ME->getMemberDecl();
14903 ShowFullyQualifiedAssigneeName = true;
14904 }
14905
14906 BoundsSafetyCheckAssignmentToCountAttrPtr(
14907 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14908 ShowFullyQualifiedAssigneeName);
14909 }
14910
14911 // OpenCL v1.2 s6.1.1.1 p2:
14912 // The half data type can only be used to declare a pointer to a buffer that
14913 // contains half values
14914 if (getLangOpts().OpenCL &&
14915 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14916 LHSType->isHalfType()) {
14917 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14918 << LHSType.getUnqualifiedType();
14919 return QualType();
14920 }
14921
14922 // WebAssembly tables can't be used on RHS of an assignment expression.
14923 if (RHSType->isWebAssemblyTableType()) {
14924 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14925 return QualType();
14926 }
14927
14928 AssignConvertType ConvTy;
14929 if (CompoundType.isNull()) {
14930 Expr *RHSCheck = RHS.get();
14931
14932 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14933
14934 QualType LHSTy(LHSType);
14935 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14936 if (RHS.isInvalid())
14937 return QualType();
14938 // Special case of NSObject attributes on c-style pointer types.
14939 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14940 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14941 RHSType->isObjCObjectPointerType()) ||
14942 (Context.isObjCNSObjectType(Ty: RHSType) &&
14943 LHSType->isObjCObjectPointerType())))
14944 ConvTy = AssignConvertType::Compatible;
14945
14946 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14947 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14948
14949 // If the RHS is a unary plus or minus, check to see if they = and + are
14950 // right next to each other. If so, the user may have typo'd "x =+ 4"
14951 // instead of "x += 4".
14952 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14953 RHSCheck = ICE->getSubExpr();
14954 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14955 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14956 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14957 // Only if the two operators are exactly adjacent.
14958 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14959 // And there is a space or other character before the subexpr of the
14960 // unary +/-. We don't want to warn on "x=-1".
14961 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14962 UO->getSubExpr()->getBeginLoc().isFileID()) {
14963 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14964 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14965 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14966 }
14967 }
14968
14969 if (IsAssignConvertCompatible(ConvTy)) {
14970 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14971 // Warn about retain cycles where a block captures the LHS, but
14972 // not if the LHS is a simple variable into which the block is
14973 // being stored...unless that variable can be captured by reference!
14974 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14975 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14976 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14977 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14978 }
14979
14980 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14981 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14982 // It is safe to assign a weak reference into a strong variable.
14983 // Although this code can still have problems:
14984 // id x = self.weakProp;
14985 // id y = self.weakProp;
14986 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14987 // paths through the function. This should be revisited if
14988 // -Wrepeated-use-of-weak is made flow-sensitive.
14989 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14990 // variable, which will be valid for the current autorelease scope.
14991 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14992 Loc: RHS.get()->getBeginLoc()))
14993 getCurFunction()->markSafeWeakUse(E: RHS.get());
14994
14995 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14996 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14997 }
14998 }
14999 } else {
15000 // Compound assignment "x += y"
15001 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
15002 }
15003
15004 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
15005 Action: AssignmentAction::Assigning))
15006 return QualType();
15007
15008 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
15009
15010 AssignedEntity AE{.LHS: LHSExpr};
15011 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
15012
15013 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
15014 if (CompoundType.isNull()) {
15015 // C++2a [expr.ass]p5:
15016 // A simple-assignment whose left operand is of a volatile-qualified
15017 // type is deprecated unless the assignment is either a discarded-value
15018 // expression or an unevaluated operand
15019 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
15020 }
15021 }
15022
15023 // C11 6.5.16p3: The type of an assignment expression is the type of the
15024 // left operand would have after lvalue conversion.
15025 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
15026 // qualified type, the value has the unqualified version of the type of the
15027 // lvalue; additionally, if the lvalue has atomic type, the value has the
15028 // non-atomic version of the type of the lvalue.
15029 // C++ 5.17p1: the type of the assignment expression is that of its left
15030 // operand.
15031 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
15032}
15033
15034// Scenarios to ignore if expression E is:
15035// 1. an explicit cast expression into void
15036// 2. a function call expression that returns void
15037static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
15038 E = E->IgnoreParens();
15039
15040 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
15041 if (CE->getCastKind() == CK_ToVoid) {
15042 return true;
15043 }
15044
15045 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
15046 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
15047 CE->getSubExpr()->getType()->isDependentType()) {
15048 return true;
15049 }
15050 }
15051
15052 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
15053 return CE->getCallReturnType(Ctx: Context)->isVoidType();
15054 return false;
15055}
15056
15057void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
15058 // No warnings in macros
15059 if (Loc.isMacroID())
15060 return;
15061
15062 // Don't warn in template instantiations.
15063 if (inTemplateInstantiation())
15064 return;
15065
15066 // Scope isn't fine-grained enough to explicitly list the specific cases, so
15067 // instead, skip more than needed, then call back into here with the
15068 // CommaVisitor in SemaStmt.cpp.
15069 // The listed locations are the initialization and increment portions
15070 // of a for loop. The additional checks are on the condition of
15071 // if statements, do/while loops, and for loops.
15072 if (getCurScope()->isControlScope())
15073 return;
15074
15075 // If there are multiple comma operators used together, get the RHS of the
15076 // of the comma operator as the LHS.
15077 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
15078 if (BO->getOpcode() != BO_Comma)
15079 break;
15080 LHS = BO->getRHS();
15081 }
15082
15083 // Only allow some expressions on LHS to not warn.
15084 if (IgnoreCommaOperand(E: LHS, Context))
15085 return;
15086
15087 Diag(Loc, DiagID: diag::warn_comma_operator);
15088 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
15089 << LHS->getSourceRange()
15090 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
15091 Code: LangOpts.CPlusPlus ? "static_cast<void>("
15092 : "(void)(")
15093 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
15094 Code: ")");
15095}
15096
15097// C99 6.5.17
15098static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
15099 SourceLocation Loc) {
15100 LHS = S.CheckPlaceholderExpr(E: LHS.get());
15101 RHS = S.CheckPlaceholderExpr(E: RHS.get());
15102 if (LHS.isInvalid() || RHS.isInvalid())
15103 return QualType();
15104
15105 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
15106 // operands, but not unary promotions.
15107 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
15108
15109 // So we treat the LHS as a ignored value, and in C++ we allow the
15110 // containing site to determine what should be done with the RHS.
15111 LHS = S.IgnoredValueConversions(E: LHS.get());
15112 if (LHS.isInvalid())
15113 return QualType();
15114
15115 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
15116
15117 if (!S.getLangOpts().CPlusPlus) {
15118 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
15119 if (RHS.isInvalid())
15120 return QualType();
15121 if (!RHS.get()->getType()->isVoidType())
15122 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
15123 DiagID: diag::err_incomplete_type);
15124 }
15125
15126 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
15127 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
15128
15129 return RHS.get()->getType();
15130}
15131
15132/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
15133/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
15134static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
15135 ExprValueKind &VK,
15136 ExprObjectKind &OK,
15137 SourceLocation OpLoc, bool IsInc,
15138 bool IsPrefix) {
15139 QualType ResType = Op->getType();
15140 // Atomic types can be used for increment / decrement where the non-atomic
15141 // versions can, so ignore the _Atomic() specifier for the purpose of
15142 // checking.
15143 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
15144 ResType = ResAtomicType->getValueType();
15145
15146 assert(!ResType.isNull() && "no type for increment/decrement expression");
15147
15148 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
15149 // Decrement of bool is not allowed.
15150 if (!IsInc) {
15151 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
15152 return QualType();
15153 }
15154 // Increment of bool sets it to true, but is deprecated.
15155 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
15156 : diag::warn_increment_bool)
15157 << Op->getSourceRange();
15158 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
15159 // Error on enum increments and decrements in C++ mode
15160 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
15161 return QualType();
15162 } else if (ResType->isRealType()) {
15163 // OK!
15164 } else if (ResType->isPointerType()) {
15165 // C99 6.5.2.4p2, 6.5.6p2
15166 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
15167 return QualType();
15168 } else if (ResType->isOverflowBehaviorType()) {
15169 // OK!
15170 } else if (ResType->isObjCObjectPointerType()) {
15171 // On modern runtimes, ObjC pointer arithmetic is forbidden.
15172 // Otherwise, we just need a complete type.
15173 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
15174 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
15175 return QualType();
15176 } else if (ResType->isAnyComplexType()) {
15177 // C99 does not support ++/-- on complex types, we allow as an extension.
15178 S.DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::increment_complex)
15179 << IsInc << Op->getSourceRange();
15180 } else if (ResType->isPlaceholderType()) {
15181 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15182 if (PR.isInvalid()) return QualType();
15183 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
15184 IsInc, IsPrefix);
15185 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15186 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15187 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15188 (ResType->castAs<VectorType>()->getVectorKind() !=
15189 VectorKind::AltiVecBool)) {
15190 // The z vector extensions allow ++ and -- for non-bool vectors.
15191 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15192 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15193 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15194 } else {
15195 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
15196 << ResType << int(IsInc) << Op->getSourceRange();
15197 return QualType();
15198 }
15199 // At this point, we know we have a real, complex or pointer type.
15200 // Now make sure the operand is a modifiable lvalue.
15201 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
15202 return QualType();
15203 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15204 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15205 // An operand with volatile-qualified type is deprecated
15206 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
15207 << IsInc << ResType;
15208 }
15209 // In C++, a prefix increment is the same type as the operand. Otherwise
15210 // (in C or with postfix), the increment is the unqualified type of the
15211 // operand.
15212 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15213 VK = VK_LValue;
15214 OK = Op->getObjectKind();
15215 return ResType;
15216 } else {
15217 VK = VK_PRValue;
15218 return ResType.getUnqualifiedType();
15219 }
15220}
15221
15222/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15223/// This routine allows us to typecheck complex/recursive expressions
15224/// where the declaration is needed for type checking. We only need to
15225/// handle cases when the expression references a function designator
15226/// or is an lvalue. Here are some examples:
15227/// - &(x) => x
15228/// - &*****f => f for f a function designator.
15229/// - &s.xx => s
15230/// - &s.zz[1].yy -> s, if zz is an array
15231/// - *(x + 1) -> x, if x is an array
15232/// - &"123"[2] -> 0
15233/// - & __real__ x -> x
15234///
15235/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15236/// members.
15237static ValueDecl *getPrimaryDecl(Expr *E) {
15238 switch (E->getStmtClass()) {
15239 case Stmt::DeclRefExprClass:
15240 return cast<DeclRefExpr>(Val: E)->getDecl();
15241 case Stmt::MemberExprClass:
15242 // If this is an arrow operator, the address is an offset from
15243 // the base's value, so the object the base refers to is
15244 // irrelevant.
15245 if (cast<MemberExpr>(Val: E)->isArrow())
15246 return nullptr;
15247 // Otherwise, the expression refers to a part of the base
15248 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
15249 case Stmt::ArraySubscriptExprClass: {
15250 // FIXME: This code shouldn't be necessary! We should catch the implicit
15251 // promotion of register arrays earlier.
15252 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
15253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
15254 if (ICE->getSubExpr()->getType()->isArrayType())
15255 return getPrimaryDecl(E: ICE->getSubExpr());
15256 }
15257 return nullptr;
15258 }
15259 case Stmt::UnaryOperatorClass: {
15260 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
15261
15262 switch(UO->getOpcode()) {
15263 case UO_Real:
15264 case UO_Imag:
15265 case UO_Extension:
15266 return getPrimaryDecl(E: UO->getSubExpr());
15267 default:
15268 return nullptr;
15269 }
15270 }
15271 case Stmt::ParenExprClass:
15272 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
15273 case Stmt::ImplicitCastExprClass:
15274 // If the result of an implicit cast is an l-value, we care about
15275 // the sub-expression; otherwise, the result here doesn't matter.
15276 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
15277 case Stmt::CXXUuidofExprClass:
15278 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
15279 default:
15280 return nullptr;
15281 }
15282}
15283
15284namespace {
15285enum {
15286 AO_Bit_Field = 0,
15287 AO_Vector_Element = 1,
15288 AO_Property_Expansion = 2,
15289 AO_Register_Variable = 3,
15290 AO_Matrix_Element = 4,
15291 AO_No_Error = 5
15292};
15293}
15294/// Diagnose invalid operand for address of operations.
15295///
15296/// \param Type The type of operand which cannot have its address taken.
15297static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
15298 Expr *E, unsigned Type) {
15299 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
15300}
15301
15302bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
15303 const Expr *Op,
15304 const CXXMethodDecl *MD) {
15305 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
15306
15307 if (Op != DRE)
15308 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
15309 << Op->getSourceRange();
15310
15311 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15312 if (isa<CXXDestructorDecl>(Val: MD))
15313 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
15314 << DRE->getSourceRange();
15315
15316 if (DRE->getQualifier())
15317 return false;
15318
15319 if (MD->getParent()->getName().empty())
15320 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15321 << DRE->getSourceRange();
15322
15323 SmallString<32> Str;
15324 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
15325 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15326 << DRE->getSourceRange()
15327 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
15328}
15329
15330QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15331 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15332 if (PTy->getKind() == BuiltinType::Overload) {
15333 Expr *E = OrigOp.get()->IgnoreParens();
15334 if (!isa<OverloadExpr>(Val: E)) {
15335 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15336 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15337 << OrigOp.get()->getSourceRange();
15338 return QualType();
15339 }
15340
15341 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
15342 if (isa<UnresolvedMemberExpr>(Val: Ovl))
15343 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
15344 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15345 << OrigOp.get()->getSourceRange();
15346 return QualType();
15347 }
15348
15349 return Context.OverloadTy;
15350 }
15351
15352 if (PTy->getKind() == BuiltinType::UnknownAny)
15353 return Context.UnknownAnyTy;
15354
15355 if (PTy->getKind() == BuiltinType::BoundMember) {
15356 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15357 << OrigOp.get()->getSourceRange();
15358 return QualType();
15359 }
15360
15361 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15362 if (OrigOp.isInvalid()) return QualType();
15363 }
15364
15365 if (OrigOp.get()->isTypeDependent())
15366 return Context.DependentTy;
15367
15368 assert(!OrigOp.get()->hasPlaceholderType());
15369
15370 // Make sure to ignore parentheses in subsequent checks
15371 Expr *op = OrigOp.get()->IgnoreParens();
15372
15373 // In OpenCL captures for blocks called as lambda functions
15374 // are located in the private address space. Blocks used in
15375 // enqueue_kernel can be located in a different address space
15376 // depending on a vendor implementation. Thus preventing
15377 // taking an address of the capture to avoid invalid AS casts.
15378 if (LangOpts.OpenCL) {
15379 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15380 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15381 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
15382 return QualType();
15383 }
15384 }
15385
15386 if (getLangOpts().C99) {
15387 // Implement C99-only parts of addressof rules.
15388 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15389 if (uOp->getOpcode() == UO_Deref)
15390 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15391 // (assuming the deref expression is valid).
15392 return uOp->getSubExpr()->getType();
15393 }
15394 // Technically, there should be a check for array subscript
15395 // expressions here, but the result of one is always an lvalue anyway.
15396 }
15397 ValueDecl *dcl = getPrimaryDecl(E: op);
15398
15399 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15400 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15401 Loc: op->getBeginLoc()))
15402 return QualType();
15403
15404 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15405 unsigned AddressOfError = AO_No_Error;
15406
15407 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15408 bool IsError = isSFINAEContext();
15409 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15410 : diag::ext_typecheck_addrof_temporary)
15411 << op->getType() << op->getSourceRange();
15412 if (IsError)
15413 return QualType();
15414 // Materialize the temporary as an lvalue so that we can take its address.
15415 OrigOp = op =
15416 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15417 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15418 return Context.getPointerType(T: op->getType());
15419 } else if (lval == Expr::LV_MemberFunction) {
15420 // If it's an instance method, make a member pointer.
15421 // The expression must have exactly the form &A::foo.
15422
15423 // If the underlying expression isn't a decl ref, give up.
15424 if (!isa<DeclRefExpr>(Val: op)) {
15425 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15426 << OrigOp.get()->getSourceRange();
15427 return QualType();
15428 }
15429 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15430 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15431
15432 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15433 QualType MPTy = Context.getMemberPointerType(
15434 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15435
15436 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15437 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15438 // When pointer authentication is enabled, argument and return types of
15439 // vitual member functions must be complete. This is because vitrual
15440 // member function pointers are implemented using virtual dispatch
15441 // thunks and the thunks cannot be emitted if the argument or return
15442 // types are incomplete.
15443 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15444 SourceLocation DeclRefLoc,
15445 SourceLocation RetArgTypeLoc) {
15446 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15447 Diag(Loc: DeclRefLoc,
15448 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15449 Diag(Loc: RetArgTypeLoc,
15450 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15451 << T;
15452 return true;
15453 }
15454 return false;
15455 };
15456 QualType RetTy = MD->getReturnType();
15457 bool IsIncomplete =
15458 !RetTy->isVoidType() &&
15459 ReturnOrParamTypeIsIncomplete(
15460 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15461 for (auto *PVD : MD->parameters())
15462 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15463 PVD->getBeginLoc());
15464 if (IsIncomplete)
15465 return QualType();
15466 }
15467
15468 // Under the MS ABI, lock down the inheritance model now.
15469 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15470 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15471 return MPTy;
15472 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15473 // C99 6.5.3.2p1
15474 // The operand must be either an l-value or a function designator
15475 if (!op->getType()->isFunctionType()) {
15476 // Use a special diagnostic for loads from property references.
15477 if (isa<PseudoObjectExpr>(Val: op)) {
15478 AddressOfError = AO_Property_Expansion;
15479 } else {
15480 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15481 << op->getType() << op->getSourceRange();
15482 return QualType();
15483 }
15484 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15485 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15486 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15487 }
15488
15489 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15490 // The operand cannot be a bit-field
15491 AddressOfError = AO_Bit_Field;
15492 } else if (op->getObjectKind() == OK_VectorComponent) {
15493 // The operand cannot be an element of a vector
15494 AddressOfError = AO_Vector_Element;
15495 } else if (op->getObjectKind() == OK_MatrixComponent) {
15496 // The operand cannot be an element of a matrix.
15497 AddressOfError = AO_Matrix_Element;
15498 } else if (dcl) { // C99 6.5.3.2p1
15499 // We have an lvalue with a decl. Make sure the decl is not declared
15500 // with the register storage-class specifier.
15501 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15502 // in C++ it is not error to take address of a register
15503 // variable (c++03 7.1.1P3)
15504 if (vd->getStorageClass() == SC_Register &&
15505 !getLangOpts().CPlusPlus) {
15506 AddressOfError = AO_Register_Variable;
15507 }
15508 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15509 AddressOfError = AO_Property_Expansion;
15510 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15511 return Context.OverloadTy;
15512 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15513 // Okay: we can take the address of a field.
15514 // Could be a pointer to member, though, if there is an explicit
15515 // scope qualifier for the class.
15516
15517 // [C++26] [expr.prim.id.general]
15518 // If an id-expression E denotes a non-static non-type member
15519 // of some class C [...] and if E is a qualified-id, E is
15520 // not the un-parenthesized operand of the unary & operator [...]
15521 // the id-expression is transformed into a class member access expression.
15522 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15523 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15524 DeclContext *Ctx = dcl->getDeclContext();
15525 if (Ctx && Ctx->isRecord()) {
15526 if (dcl->getType()->isReferenceType()) {
15527 Diag(Loc: OpLoc,
15528 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15529 << dcl->getDeclName() << dcl->getType();
15530 return QualType();
15531 }
15532
15533 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15534 Ctx = Ctx->getParent();
15535
15536 QualType MPTy = Context.getMemberPointerType(
15537 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15538 // Under the MS ABI, lock down the inheritance model now.
15539 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15540 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15541 return MPTy;
15542 }
15543 }
15544 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15545 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15546 UnnamedGlobalConstantDecl>(Val: dcl))
15547 llvm_unreachable("Unknown/unexpected decl type");
15548 }
15549
15550 if (AddressOfError != AO_No_Error) {
15551 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15552 return QualType();
15553 }
15554
15555 if (lval == Expr::LV_IncompleteVoidType) {
15556 // Taking the address of a void variable is technically illegal, but we
15557 // allow it in cases which are otherwise valid.
15558 // Example: "extern void x; void* y = &x;".
15559 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15560 }
15561
15562 // If the operand has type "type", the result has type "pointer to type".
15563 if (op->getType()->isObjCObjectType())
15564 return Context.getObjCObjectPointerType(OIT: op->getType());
15565
15566 // Cannot take the address of WebAssembly references or tables.
15567 if (Context.getTargetInfo().getTriple().isWasm()) {
15568 QualType OpTy = op->getType();
15569 if (OpTy.isWebAssemblyReferenceType()) {
15570 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15571 << 1 << OrigOp.get()->getSourceRange();
15572 return QualType();
15573 }
15574 if (OpTy->isWebAssemblyTableType()) {
15575 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15576 << 1 << OrigOp.get()->getSourceRange();
15577 return QualType();
15578 }
15579 }
15580
15581 CheckAddressOfPackedMember(rhs: op);
15582
15583 return Context.getPointerType(T: op->getType());
15584}
15585
15586static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15587 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15588 if (!DRE)
15589 return;
15590 const Decl *D = DRE->getDecl();
15591 if (!D)
15592 return;
15593 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15594 if (!Param)
15595 return;
15596 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15597 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15598 return;
15599 if (FunctionScopeInfo *FD = S.getCurFunction())
15600 FD->ModifiedNonNullParams.insert(Ptr: Param);
15601}
15602
15603/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15604static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15605 SourceLocation OpLoc,
15606 bool IsAfterAmp = false) {
15607 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15608 if (ConvResult.isInvalid())
15609 return QualType();
15610 Op = ConvResult.get();
15611 QualType OpTy = Op->getType();
15612 QualType Result;
15613
15614 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15615 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15616 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15617 Range: Op->getSourceRange());
15618 }
15619
15620 if (const PointerType *PT = OpTy->getAs<PointerType>())
15621 {
15622 Result = PT->getPointeeType();
15623 }
15624 else if (const ObjCObjectPointerType *OPT =
15625 OpTy->getAs<ObjCObjectPointerType>())
15626 Result = OPT->getPointeeType();
15627 else {
15628 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15629 if (PR.isInvalid()) return QualType();
15630 if (PR.get() != Op)
15631 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15632 }
15633
15634 if (Result.isNull()) {
15635 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15636 << OpTy << Op->getSourceRange();
15637 return QualType();
15638 }
15639
15640 if (Result->isVoidType()) {
15641 // C++ [expr.unary.op]p1:
15642 // [...] the expression to which [the unary * operator] is applied shall
15643 // be a pointer to an object type, or a pointer to a function type
15644 LangOptions LO = S.getLangOpts();
15645 if (LO.CPlusPlus)
15646 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15647 << OpTy << Op->getSourceRange();
15648 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15649 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15650 << OpTy << Op->getSourceRange();
15651 }
15652
15653 // HLX has no vector pair loads or stores.
15654 if (S.Hexagon().isHLXVectorType(T: Result) &&
15655 S.Context.getTypeSizeInChars(T: Result).getQuantity() == 4096)
15656 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_hlx_vectorpair_pointer)
15657 << OpTy << Op->getSourceRange();
15658
15659 // Dereferences are usually l-values...
15660 VK = VK_LValue;
15661
15662 // ...except that certain expressions are never l-values in C.
15663 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15664 VK = VK_PRValue;
15665
15666 return Result;
15667}
15668
15669BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15670 BinaryOperatorKind Opc;
15671 switch (Kind) {
15672 default: llvm_unreachable("Unknown binop!");
15673 case tok::periodstar: Opc = BO_PtrMemD; break;
15674 case tok::arrowstar: Opc = BO_PtrMemI; break;
15675 case tok::star: Opc = BO_Mul; break;
15676 case tok::slash: Opc = BO_Div; break;
15677 case tok::percent: Opc = BO_Rem; break;
15678 case tok::plus: Opc = BO_Add; break;
15679 case tok::minus: Opc = BO_Sub; break;
15680 case tok::lessless: Opc = BO_Shl; break;
15681 case tok::greatergreater: Opc = BO_Shr; break;
15682 case tok::lessequal: Opc = BO_LE; break;
15683 case tok::less: Opc = BO_LT; break;
15684 case tok::greaterequal: Opc = BO_GE; break;
15685 case tok::greater: Opc = BO_GT; break;
15686 case tok::exclaimequal: Opc = BO_NE; break;
15687 case tok::equalequal: Opc = BO_EQ; break;
15688 case tok::spaceship: Opc = BO_Cmp; break;
15689 case tok::amp: Opc = BO_And; break;
15690 case tok::caret: Opc = BO_Xor; break;
15691 case tok::pipe: Opc = BO_Or; break;
15692 case tok::ampamp: Opc = BO_LAnd; break;
15693 case tok::pipepipe: Opc = BO_LOr; break;
15694 case tok::equal: Opc = BO_Assign; break;
15695 case tok::starequal: Opc = BO_MulAssign; break;
15696 case tok::slashequal: Opc = BO_DivAssign; break;
15697 case tok::percentequal: Opc = BO_RemAssign; break;
15698 case tok::plusequal: Opc = BO_AddAssign; break;
15699 case tok::minusequal: Opc = BO_SubAssign; break;
15700 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15701 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15702 case tok::ampequal: Opc = BO_AndAssign; break;
15703 case tok::caretequal: Opc = BO_XorAssign; break;
15704 case tok::pipeequal: Opc = BO_OrAssign; break;
15705 case tok::comma: Opc = BO_Comma; break;
15706 }
15707 return Opc;
15708}
15709
15710static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15711 tok::TokenKind Kind) {
15712 UnaryOperatorKind Opc;
15713 switch (Kind) {
15714 default: llvm_unreachable("Unknown unary op!");
15715 case tok::plusplus: Opc = UO_PreInc; break;
15716 case tok::minusminus: Opc = UO_PreDec; break;
15717 case tok::amp: Opc = UO_AddrOf; break;
15718 case tok::star: Opc = UO_Deref; break;
15719 case tok::plus: Opc = UO_Plus; break;
15720 case tok::minus: Opc = UO_Minus; break;
15721 case tok::tilde: Opc = UO_Not; break;
15722 case tok::exclaim: Opc = UO_LNot; break;
15723 case tok::kw___real: Opc = UO_Real; break;
15724 case tok::kw___imag: Opc = UO_Imag; break;
15725 case tok::kw___extension__: Opc = UO_Extension; break;
15726 }
15727 return Opc;
15728}
15729
15730const FieldDecl *
15731Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15732 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15733 // common for setters.
15734 // struct A {
15735 // int X;
15736 // -void setX(int X) { X = X; }
15737 // +void setX(int X) { this->X = X; }
15738 // };
15739
15740 // Only consider parameters for self assignment fixes.
15741 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15742 return nullptr;
15743 const auto *Method =
15744 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15745 if (!Method)
15746 return nullptr;
15747
15748 const CXXRecordDecl *Parent = Method->getParent();
15749 // In theory this is fixable if the lambda explicitly captures this, but
15750 // that's added complexity that's rarely going to be used.
15751 if (Parent->isLambda())
15752 return nullptr;
15753
15754 // FIXME: Use an actual Lookup operation instead of just traversing fields
15755 // in order to get base class fields.
15756 auto Field =
15757 llvm::find_if(Range: Parent->fields(),
15758 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15759 return F->getDeclName() == Name;
15760 });
15761 return (Field != Parent->field_end()) ? *Field : nullptr;
15762}
15763
15764/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15765/// This warning suppressed in the event of macro expansions.
15766static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15767 SourceLocation OpLoc, bool IsBuiltin) {
15768 if (S.inTemplateInstantiation())
15769 return;
15770 if (S.isUnevaluatedContext())
15771 return;
15772 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15773 return;
15774 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15775 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15776 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15777 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15778 if (!LHSDeclRef || !RHSDeclRef ||
15779 LHSDeclRef->getLocation().isMacroID() ||
15780 RHSDeclRef->getLocation().isMacroID())
15781 return;
15782 const ValueDecl *LHSDecl =
15783 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15784 const ValueDecl *RHSDecl =
15785 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15786 if (LHSDecl != RHSDecl)
15787 return;
15788 if (LHSDecl->getType().isVolatileQualified())
15789 return;
15790 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15791 if (RefTy->getPointeeType().isVolatileQualified())
15792 return;
15793
15794 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15795 : diag::warn_self_assignment_overloaded)
15796 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15797 << RHSExpr->getSourceRange();
15798 if (const FieldDecl *SelfAssignField =
15799 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15800 Diag << 1 << SelfAssignField
15801 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15802 else
15803 Diag << 0;
15804}
15805
15806/// Check if a bitwise-& is performed on an Objective-C pointer. This
15807/// is usually indicative of introspection within the Objective-C pointer.
15808static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15809 SourceLocation OpLoc) {
15810 if (!S.getLangOpts().ObjC)
15811 return;
15812
15813 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15814 const Expr *LHS = L.get();
15815 const Expr *RHS = R.get();
15816
15817 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15818 ObjCPointerExpr = LHS;
15819 OtherExpr = RHS;
15820 }
15821 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15822 ObjCPointerExpr = RHS;
15823 OtherExpr = LHS;
15824 }
15825
15826 // This warning is deliberately made very specific to reduce false
15827 // positives with logic that uses '&' for hashing. This logic mainly
15828 // looks for code trying to introspect into tagged pointers, which
15829 // code should generally never do.
15830 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15831 unsigned Diag = diag::warn_objc_pointer_masking;
15832 // Determine if we are introspecting the result of performSelectorXXX.
15833 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15834 // Special case messages to -performSelector and friends, which
15835 // can return non-pointer values boxed in a pointer value.
15836 // Some clients may wish to silence warnings in this subcase.
15837 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15838 Selector S = ME->getSelector();
15839 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15840 if (SelArg0.starts_with(Prefix: "performSelector"))
15841 Diag = diag::warn_objc_pointer_masking_performSelector;
15842 }
15843
15844 S.Diag(Loc: OpLoc, DiagID: Diag)
15845 << ObjCPointerExpr->getSourceRange();
15846 }
15847}
15848
15849// This helper function promotes a binary operator's operands (which are of a
15850// half vector type) to a vector of floats and then truncates the result to
15851// a vector of either half or short.
15852static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15853 BinaryOperatorKind Opc, QualType ResultTy,
15854 ExprValueKind VK, ExprObjectKind OK,
15855 bool IsCompAssign, SourceLocation OpLoc,
15856 FPOptionsOverride FPFeatures) {
15857 auto &Context = S.getASTContext();
15858 assert((isVector(ResultTy, Context.HalfTy) ||
15859 isVector(ResultTy, Context.ShortTy)) &&
15860 "Result must be a vector of half or short");
15861 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15862 isVector(RHS.get()->getType(), Context.HalfTy) &&
15863 "both operands expected to be a half vector");
15864
15865 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15866 QualType BinOpResTy = RHS.get()->getType();
15867
15868 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15869 // change BinOpResTy to a vector of ints.
15870 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15871 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15872
15873 if (IsCompAssign)
15874 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15875 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15876 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15877
15878 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15879 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15880 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15881 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15882}
15883
15884/// Returns true if conversion between vectors of halfs and vectors of floats
15885/// is needed.
15886static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15887 QualType ResultTy, Expr *E0,
15888 Expr *E1 = nullptr) {
15889 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15890 return false;
15891
15892 // The conversion truncates the result to a half/short vector, so it shouldn't
15893 // apply when the result is not that type (e.g. HLSL comparisons).
15894 if (ResultTy->isVectorType() && !isVector(QT: ResultTy, ElementType: Ctx.HalfTy) &&
15895 !isVector(QT: ResultTy, ElementType: Ctx.ShortTy))
15896 return false;
15897
15898 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15899 QualType Ty = E->IgnoreImplicit()->getType();
15900
15901 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15902 // to vectors of floats. Although the element type of the vectors is __fp16,
15903 // the vectors shouldn't be treated as storage-only types. See the
15904 // discussion here: https://reviews.llvm.org/rG825235c140e7
15905 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15906 if (VT->getVectorKind() == VectorKind::Neon)
15907 return false;
15908 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15909 }
15910 return false;
15911 };
15912
15913 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15914}
15915
15916ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15917 BinaryOperatorKind Opc, Expr *LHSExpr,
15918 Expr *RHSExpr, bool ForFoldExpression) {
15919 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15920 // The syntax only allows initializer lists on the RHS of assignment,
15921 // so we don't need to worry about accepting invalid code for
15922 // non-assignment operators.
15923 // C++11 5.17p9:
15924 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15925 // of x = {} is x = T().
15926 InitializationKind Kind = InitializationKind::CreateDirectList(
15927 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15928 InitializedEntity Entity =
15929 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15930 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15931 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15932 if (Init.isInvalid())
15933 return Init;
15934 RHSExpr = Init.get();
15935 }
15936
15937 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15938 QualType ResultTy; // Result type of the binary operator.
15939 // The following two variables are used for compound assignment operators
15940 QualType CompLHSTy; // Type of LHS after promotions for computation
15941 QualType CompResultTy; // Type of computation result
15942 ExprValueKind VK = VK_PRValue;
15943 ExprObjectKind OK = OK_Ordinary;
15944 bool ConvertHalfVec = false;
15945
15946 if (!LHS.isUsable() || !RHS.isUsable())
15947 return ExprError();
15948
15949 if (getLangOpts().OpenCL) {
15950 QualType LHSTy = LHSExpr->getType();
15951 QualType RHSTy = RHSExpr->getType();
15952 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15953 // the ATOMIC_VAR_INIT macro.
15954 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15955 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15956 if (BO_Assign == Opc)
15957 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15958 else
15959 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15960 return ExprError();
15961 }
15962
15963 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15964 // only with a builtin functions and therefore should be disallowed here.
15965 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15966 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15967 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15968 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15969 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15970 return ExprError();
15971 }
15972 }
15973
15974 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15975 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15976
15977 switch (Opc) {
15978 case BO_Assign:
15979 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15980 if (getLangOpts().CPlusPlus &&
15981 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15982 VK = LHS.get()->getValueKind();
15983 OK = LHS.get()->getObjectKind();
15984 }
15985 if (!ResultTy.isNull()) {
15986 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15987 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15988
15989 // Avoid copying a block to the heap if the block is assigned to a local
15990 // auto variable that is declared in the same scope as the block. This
15991 // optimization is unsafe if the local variable is declared in an outer
15992 // scope. For example:
15993 //
15994 // BlockTy b;
15995 // {
15996 // b = ^{...};
15997 // }
15998 // // It is unsafe to invoke the block here if it wasn't copied to the
15999 // // heap.
16000 // b();
16001
16002 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
16003 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
16004 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
16005 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
16006 BE->getBlockDecl()->setCanAvoidCopyToHeap();
16007
16008 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
16009 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
16010 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
16011 }
16012 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
16013 break;
16014 case BO_PtrMemD:
16015 case BO_PtrMemI:
16016 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
16017 isIndirect: Opc == BO_PtrMemI);
16018 break;
16019 case BO_Mul:
16020 case BO_Div:
16021 ConvertHalfVec = true;
16022 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
16023 break;
16024 case BO_Rem:
16025 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
16026 break;
16027 case BO_Add:
16028 ConvertHalfVec = true;
16029 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
16030 break;
16031 case BO_Sub:
16032 ConvertHalfVec = true;
16033 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
16034 break;
16035 case BO_Shl:
16036 case BO_Shr:
16037 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
16038 break;
16039 case BO_LE:
16040 case BO_LT:
16041 case BO_GE:
16042 case BO_GT:
16043 ConvertHalfVec = true;
16044 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
16045
16046 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
16047 !ForFoldExpression && BI && BI->isComparisonOp())
16048 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
16049 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
16050
16051 break;
16052 case BO_EQ:
16053 case BO_NE:
16054 ConvertHalfVec = true;
16055 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
16056 break;
16057 case BO_Cmp:
16058 ConvertHalfVec = true;
16059 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
16060 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
16061 break;
16062 case BO_And:
16063 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
16064 [[fallthrough]];
16065 case BO_Xor:
16066 case BO_Or:
16067 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
16068 break;
16069 case BO_LAnd:
16070 case BO_LOr:
16071 ConvertHalfVec = true;
16072 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
16073 break;
16074 case BO_MulAssign:
16075 case BO_DivAssign:
16076 ConvertHalfVec = true;
16077 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
16078 CompLHSTy = CompResultTy;
16079 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16080 ResultTy =
16081 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
16082 break;
16083 case BO_RemAssign:
16084 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
16085 CompLHSTy = CompResultTy;
16086 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16087 ResultTy =
16088 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
16089 break;
16090 case BO_AddAssign:
16091 ConvertHalfVec = true;
16092 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
16093 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16094 ResultTy =
16095 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
16096 break;
16097 case BO_SubAssign:
16098 ConvertHalfVec = true;
16099 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
16100 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16101 ResultTy =
16102 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
16103 break;
16104 case BO_ShlAssign:
16105 case BO_ShrAssign:
16106 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
16107 CompLHSTy = CompResultTy;
16108 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16109 ResultTy =
16110 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
16111 break;
16112 case BO_AndAssign:
16113 case BO_OrAssign: // fallthrough
16114 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
16115 [[fallthrough]];
16116 case BO_XorAssign:
16117 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
16118 CompLHSTy = CompResultTy;
16119 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16120 ResultTy =
16121 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
16122 break;
16123 case BO_Comma:
16124 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
16125 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
16126 VK = RHS.get()->getValueKind();
16127 OK = RHS.get()->getObjectKind();
16128 }
16129 break;
16130 }
16131 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
16132 return ExprError();
16133
16134 // Some of the binary operations require promoting operands of half vector to
16135 // float vectors and truncating the result back to half vector. For now, we do
16136 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
16137 // arm64).
16138 assert(
16139 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
16140 isVector(LHS.get()->getType(), Context.HalfTy)) &&
16141 "both sides are half vectors or neither sides are");
16142 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, ResultTy,
16143 E0: LHS.get(), E1: RHS.get());
16144
16145 // Check for array bounds violations for both sides of the BinaryOperator
16146 CheckArrayAccess(E: LHS.get());
16147 CheckArrayAccess(E: RHS.get());
16148
16149 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
16150 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
16151 Name: &Context.Idents.get(Name: "object_setClass"),
16152 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
16153 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
16154 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
16155 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
16156 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
16157 Code: "object_setClass(")
16158 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
16159 Code: ",")
16160 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
16161 }
16162 else
16163 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
16164 }
16165 else if (const ObjCIvarRefExpr *OIRE =
16166 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
16167 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
16168
16169 // Opc is not a compound assignment if CompResultTy is null.
16170 if (CompResultTy.isNull()) {
16171 if (ConvertHalfVec)
16172 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
16173 OpLoc, FPFeatures: CurFPFeatureOverrides());
16174 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
16175 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16176 }
16177
16178 // Handle compound assignments.
16179 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16180 OK_ObjCProperty) {
16181 VK = VK_LValue;
16182 OK = LHS.get()->getObjectKind();
16183 }
16184
16185 // The LHS is not converted to the result type for fixed-point compound
16186 // assignment as the common type is computed on demand. Reset the CompLHSTy
16187 // to the LHS type we would have gotten after unary conversions.
16188 if (CompResultTy->isFixedPointType())
16189 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
16190
16191 if (ConvertHalfVec)
16192 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
16193 OpLoc, FPFeatures: CurFPFeatureOverrides());
16194
16195 return CompoundAssignOperator::Create(
16196 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
16197 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
16198}
16199
16200/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16201/// operators are mixed in a way that suggests that the programmer forgot that
16202/// comparison operators have higher precedence. The most typical example of
16203/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16204static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
16205 SourceLocation OpLoc, Expr *LHSExpr,
16206 Expr *RHSExpr) {
16207 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
16208 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
16209
16210 // Check that one of the sides is a comparison operator and the other isn't.
16211 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16212 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16213 if (isLeftComp == isRightComp)
16214 return;
16215
16216 // Bitwise operations are sometimes used as eager logical ops.
16217 // Don't diagnose this.
16218 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16219 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16220 if (isLeftBitwise || isRightBitwise)
16221 return;
16222
16223 SourceRange DiagRange = isLeftComp
16224 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16225 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16226 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16227 SourceRange ParensRange =
16228 isLeftComp
16229 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16230 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16231
16232 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
16233 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
16234 SuggestParentheses(Self, Loc: OpLoc,
16235 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
16236 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16237 SuggestParentheses(Self, Loc: OpLoc,
16238 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
16239 << BinaryOperator::getOpcodeStr(Op: Opc),
16240 ParenRange: ParensRange);
16241}
16242
16243/// It accepts a '&&' expr that is inside a '||' one.
16244/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16245/// in parentheses.
16246static void
16247EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
16248 BinaryOperator *Bop) {
16249 assert(Bop->getOpcode() == BO_LAnd);
16250 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
16251 << Bop->getSourceRange() << OpLoc;
16252 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
16253 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
16254 << Bop->getOpcodeStr(),
16255 ParenRange: Bop->getSourceRange());
16256}
16257
16258/// Look for '&&' in the left hand of a '||' expr.
16259static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
16260 Expr *LHSExpr, Expr *RHSExpr) {
16261 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
16262 if (Bop->getOpcode() == BO_LAnd) {
16263 // If it's "string_literal && a || b" don't warn since the precedence
16264 // doesn't matter.
16265 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
16266 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16267 } else if (Bop->getOpcode() == BO_LOr) {
16268 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
16269 // If it's "a || b && string_literal || c" we didn't warn earlier for
16270 // "a || b && string_literal", but warn now.
16271 if (RBop->getOpcode() == BO_LAnd &&
16272 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
16273 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
16274 }
16275 }
16276 }
16277}
16278
16279/// Look for '&&' in the right hand of a '||' expr.
16280static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
16281 Expr *LHSExpr, Expr *RHSExpr) {
16282 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
16283 if (Bop->getOpcode() == BO_LAnd) {
16284 // If it's "a || b && string_literal" don't warn since the precedence
16285 // doesn't matter.
16286 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
16287 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16288 }
16289 }
16290}
16291
16292/// Look for bitwise op in the left or right hand of a bitwise op with
16293/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16294/// the '&' expression in parentheses.
16295static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
16296 SourceLocation OpLoc, Expr *SubExpr) {
16297 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16298 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16299 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
16300 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
16301 << Bop->getSourceRange() << OpLoc;
16302 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16303 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16304 << Bop->getOpcodeStr(),
16305 ParenRange: Bop->getSourceRange());
16306 }
16307 }
16308}
16309
16310static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
16311 Expr *SubExpr, StringRef Shift) {
16312 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16313 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16314 StringRef Op = Bop->getOpcodeStr();
16315 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
16316 << Bop->getSourceRange() << OpLoc << Shift << Op;
16317 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16318 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
16319 ParenRange: Bop->getSourceRange());
16320 }
16321 }
16322}
16323
16324static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16325 Expr *LHSExpr, Expr *RHSExpr) {
16326 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
16327 if (!OCE)
16328 return;
16329
16330 FunctionDecl *FD = OCE->getDirectCallee();
16331 if (!FD || !FD->isOverloadedOperator())
16332 return;
16333
16334 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16335 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16336 return;
16337
16338 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
16339 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16340 << (Kind == OO_LessLess);
16341 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
16342 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16343 << (Kind == OO_LessLess ? "<<" : ">>"),
16344 ParenRange: OCE->getSourceRange());
16345 SuggestParentheses(
16346 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
16347 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
16348}
16349
16350/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16351/// precedence.
16352static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16353 SourceLocation OpLoc, Expr *LHSExpr,
16354 Expr *RHSExpr){
16355 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16356 if (BinaryOperator::isBitwiseOp(Opc))
16357 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16358
16359 // Diagnose "arg1 & arg2 | arg3"
16360 if ((Opc == BO_Or || Opc == BO_Xor) &&
16361 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16362 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
16363 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
16364 }
16365
16366 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16367 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16368 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16369 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16370 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16371 }
16372
16373 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16374 || Opc == BO_Shr) {
16375 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16376 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16377 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16378 }
16379
16380 // Warn on overloaded shift operators and comparisons, such as:
16381 // cout << 5 == 4;
16382 if (BinaryOperator::isComparisonOp(Opc))
16383 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16384}
16385
16386ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16387 tok::TokenKind Kind,
16388 Expr *LHSExpr, Expr *RHSExpr) {
16389 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16390 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16391 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16392
16393 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16394 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16395
16396 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
16397 ? BuiltinCountedByRefKind::Assignment
16398 : BuiltinCountedByRefKind::BinaryExpr;
16399
16400 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
16401 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
16402
16403 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16404}
16405
16406void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16407 UnresolvedSetImpl &Functions) {
16408 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16409 if (OverOp != OO_None && OverOp != OO_Equal)
16410 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16411
16412 // In C++20 onwards, we may have a second operator to look up.
16413 if (getLangOpts().CPlusPlus20) {
16414 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16415 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16416 }
16417}
16418
16419/// Build an overloaded binary operator expression in the given scope.
16420static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16421 BinaryOperatorKind Opc,
16422 Expr *LHS, Expr *RHS) {
16423 switch (Opc) {
16424 case BO_Assign:
16425 // In the non-overloaded case, we warn about self-assignment (x = x) for
16426 // both simple assignment and certain compound assignments where algebra
16427 // tells us the operation yields a constant result. When the operator is
16428 // overloaded, we can't do the latter because we don't want to assume that
16429 // those algebraic identities still apply; for example, a path-building
16430 // library might use operator/= to append paths. But it's still reasonable
16431 // to assume that simple assignment is just moving/copying values around
16432 // and so self-assignment is likely a bug.
16433 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16434 [[fallthrough]];
16435 case BO_DivAssign:
16436 case BO_RemAssign:
16437 case BO_SubAssign:
16438 case BO_AndAssign:
16439 case BO_OrAssign:
16440 case BO_XorAssign:
16441 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16442 break;
16443 default:
16444 break;
16445 }
16446
16447 // Find all of the overloaded operators visible from this point.
16448 UnresolvedSet<16> Functions;
16449 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16450
16451 // Build the (potentially-overloaded, potentially-dependent)
16452 // binary operation.
16453 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16454}
16455
16456ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16457 BinaryOperatorKind Opc, Expr *LHSExpr,
16458 Expr *RHSExpr, bool ForFoldExpression) {
16459 if (!LHSExpr || !RHSExpr)
16460 return ExprError();
16461
16462 // We want to end up calling one of SemaPseudoObject::checkAssignment
16463 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16464 // both expressions are overloadable or either is type-dependent),
16465 // or CreateBuiltinBinOp (in any other case). We also want to get
16466 // any placeholder types out of the way.
16467
16468 // Handle pseudo-objects in the LHS.
16469 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16470 // Assignments with a pseudo-object l-value need special analysis.
16471 if (pty->getKind() == BuiltinType::PseudoObject &&
16472 BinaryOperator::isAssignmentOp(Opc))
16473 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16474
16475 // Don't resolve overloads if the other type is overloadable.
16476 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16477 // We can't actually test that if we still have a placeholder,
16478 // though. Fortunately, none of the exceptions we see in that
16479 // code below are valid when the LHS is an overload set. Note
16480 // that an overload set can be dependently-typed, but it never
16481 // instantiates to having an overloadable type.
16482 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16483 if (resolvedRHS.isInvalid()) return ExprError();
16484 RHSExpr = resolvedRHS.get();
16485
16486 if (RHSExpr->isTypeDependent() ||
16487 RHSExpr->getType()->isOverloadableType())
16488 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16489 }
16490
16491 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16492 // template, diagnose the missing 'template' keyword instead of diagnosing
16493 // an invalid use of a bound member function.
16494 //
16495 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16496 // to C++1z [over.over]/1.4, but we already checked for that case above.
16497 if (Opc == BO_LT && inTemplateInstantiation() &&
16498 (pty->getKind() == BuiltinType::BoundMember ||
16499 pty->getKind() == BuiltinType::Overload)) {
16500 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16501 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16502 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16503 return isa<FunctionTemplateDecl>(Val: ND);
16504 })) {
16505 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16506 : OE->getNameLoc(),
16507 DiagID: diag::err_template_kw_missing)
16508 << OE->getName().getAsIdentifierInfo();
16509 return ExprError();
16510 }
16511 }
16512
16513 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16514 if (LHS.isInvalid()) return ExprError();
16515 LHSExpr = LHS.get();
16516 }
16517
16518 // Handle pseudo-objects in the RHS.
16519 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16520 // An overload in the RHS can potentially be resolved by the type
16521 // being assigned to.
16522 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16523 if (getLangOpts().CPlusPlus &&
16524 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16525 LHSExpr->getType()->isOverloadableType()))
16526 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16527
16528 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16529 ForFoldExpression);
16530 }
16531
16532 // Don't resolve overloads if the other type is overloadable.
16533 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16534 LHSExpr->getType()->isOverloadableType())
16535 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16536
16537 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16538 if (!resolvedRHS.isUsable()) return ExprError();
16539 RHSExpr = resolvedRHS.get();
16540 }
16541
16542 if (getLangOpts().HLSL) {
16543 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16544 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16545 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16546 return ExprError();
16547 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16548 std::optional<ExprResult> ConvRHS =
16549 HLSL().tryPerformConstantBufferConversion(BaseExpr: RHSExpr);
16550 if (ConvRHS && Context.hasSameUnqualifiedType(
16551 T1: LHSExpr->getType(), T2: ConvRHS->get()->getType())) {
16552 assert(!ConvRHS->isInvalid());
16553 RHSExpr = ConvRHS->get();
16554 }
16555 }
16556 }
16557
16558 if (getLangOpts().CPlusPlus) {
16559 bool CanOverloadBinOp =
16560 !getLangOpts().HLSL ||
16561 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16562 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16563 bool TypeDependent =
16564 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16565 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16566 RHSExpr->getType()->isOverloadableType();
16567 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16568 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16569 }
16570
16571 if (getLangOpts().RecoveryAST &&
16572 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16573 assert(!getLangOpts().CPlusPlus);
16574 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16575 "Should only occur in error-recovery path.");
16576 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16577 // C [6.15.16] p3:
16578 // An assignment expression has the value of the left operand after the
16579 // assignment, but is not an lvalue.
16580 return CompoundAssignOperator::Create(
16581 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16582 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16583 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16584 QualType ResultType;
16585 switch (Opc) {
16586 case BO_Assign:
16587 ResultType = LHSExpr->getType().getUnqualifiedType();
16588 break;
16589 case BO_LT:
16590 case BO_GT:
16591 case BO_LE:
16592 case BO_GE:
16593 case BO_EQ:
16594 case BO_NE:
16595 case BO_LAnd:
16596 case BO_LOr:
16597 // These operators have a fixed result type regardless of operands.
16598 ResultType = Context.IntTy;
16599 break;
16600 case BO_Comma:
16601 ResultType = RHSExpr->getType();
16602 break;
16603 default:
16604 ResultType = Context.DependentTy;
16605 break;
16606 }
16607 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16608 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16609 FPFeatures: CurFPFeatureOverrides());
16610 }
16611
16612 // Build a built-in binary operation.
16613 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16614}
16615
16616static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16617 if (T.isNull() || T->isDependentType())
16618 return false;
16619
16620 if (!Ctx.isPromotableIntegerType(T))
16621 return true;
16622
16623 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16624}
16625
16626ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16627 UnaryOperatorKind Opc, Expr *InputExpr,
16628 bool IsAfterAmp) {
16629 ExprResult Input = InputExpr;
16630 ExprValueKind VK = VK_PRValue;
16631 ExprObjectKind OK = OK_Ordinary;
16632 QualType resultType;
16633 bool CanOverflow = false;
16634
16635 bool ConvertHalfVec = false;
16636 if (getLangOpts().OpenCL) {
16637 QualType Ty = InputExpr->getType();
16638 // The only legal unary operation for atomics is '&'.
16639 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16640 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16641 // only with a builtin functions and therefore should be disallowed here.
16642 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16643 || Ty->isBlockPointerType())) {
16644 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16645 << InputExpr->getType()
16646 << Input.get()->getSourceRange());
16647 }
16648 }
16649
16650 if (getLangOpts().HLSL && OpLoc.isValid()) {
16651 if (Opc == UO_AddrOf)
16652 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16653 if (Opc == UO_Deref)
16654 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16655 }
16656
16657 if (InputExpr->isTypeDependent() &&
16658 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16659 resultType = Context.DependentTy;
16660 } else {
16661 switch (Opc) {
16662 case UO_PreInc:
16663 case UO_PreDec:
16664 case UO_PostInc:
16665 case UO_PostDec:
16666 resultType =
16667 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16668 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16669 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16670 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16671 break;
16672 case UO_AddrOf:
16673 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16674 CheckAddressOfNoDeref(E: InputExpr);
16675 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16676 break;
16677 case UO_Deref: {
16678 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16679 if (Input.isInvalid())
16680 return ExprError();
16681 resultType =
16682 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16683 break;
16684 }
16685 case UO_Plus:
16686 case UO_Minus:
16687 CanOverflow = Opc == UO_Minus &&
16688 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16689 Input = UsualUnaryConversions(E: Input.get());
16690 if (Input.isInvalid())
16691 return ExprError();
16692 // Unary plus and minus require promoting an operand of half vector to a
16693 // float vector and truncating the result back to a half vector. For now,
16694 // we do this only when HalfArgsAndReturns is set (that is, when the
16695 // target is arm or arm64).
16696 ConvertHalfVec = needsConversionOfHalfVec(
16697 OpRequiresConversion: true, Ctx&: Context, ResultTy: Input.get()->getType(), E0: Input.get());
16698
16699 // If the operand is a half vector, promote it to a float vector.
16700 if (ConvertHalfVec)
16701 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16702 resultType = Input.get()->getType();
16703 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16704 break;
16705 else if (resultType->isVectorType() &&
16706 // The z vector extensions don't allow + or - with bool vectors.
16707 (!Context.getLangOpts().ZVector ||
16708 resultType->castAs<VectorType>()->getVectorKind() !=
16709 VectorKind::AltiVecBool))
16710 break;
16711 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16712 break;
16713 else if (getLangOpts().HLSL && resultType->isConstantMatrixType())
16714 break;
16715 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16716 Opc == UO_Plus && resultType->isPointerType())
16717 break;
16718
16719 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16720 << resultType << Input.get()->getSourceRange());
16721
16722 case UO_Not: // bitwise complement
16723 Input = UsualUnaryConversions(E: Input.get());
16724 if (Input.isInvalid())
16725 return ExprError();
16726 resultType = Input.get()->getType();
16727 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16728 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16729 // C99 does not support '~' for complex conjugation.
16730 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16731 << resultType << Input.get()->getSourceRange();
16732 else if (resultType->hasIntegerRepresentation())
16733 break;
16734 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16735 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16736 // on vector float types.
16737 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16738 if (!T->isIntegerType())
16739 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16740 << resultType << Input.get()->getSourceRange());
16741 } else {
16742 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16743 << resultType << Input.get()->getSourceRange());
16744 }
16745 break;
16746
16747 case UO_LNot: // logical negation
16748 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16749 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16750 if (Input.isInvalid())
16751 return ExprError();
16752 resultType = Input.get()->getType();
16753
16754 // Though we still have to promote half FP to float...
16755 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16756 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16757 .get();
16758 resultType = Context.FloatTy;
16759 }
16760
16761 // WebAsembly tables can't be used in unary expressions.
16762 if (resultType->isPointerType() &&
16763 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16764 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16765 << resultType << Input.get()->getSourceRange());
16766 }
16767
16768 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType) &&
16769 !resultType->isMetaInfoType()) {
16770 // Before C++26, scalar types are contextually converted to bool,
16771 // std::meta::info is a scalar type but not an arithmetic type.
16772
16773 // C99 6.5.3.3p1: ok, fallthrough;
16774 if (Context.getLangOpts().CPlusPlus) {
16775 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16776 // operand contextually converted to bool.
16777 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16778 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16779 } else if (Context.getLangOpts().OpenCL &&
16780 Context.getLangOpts().OpenCLVersion < 120) {
16781 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16782 // operate on scalar float types.
16783 if (!resultType->isIntegerType() && !resultType->isPointerType())
16784 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16785 << resultType << Input.get()->getSourceRange());
16786 }
16787 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16788 !resultType->hasBooleanRepresentation()) {
16789 // HLSL unary logical 'not' behaves like C++, which states that the
16790 // operand is converted to bool and the result is bool, however HLSL
16791 // extends this property to vectors.
16792 const VectorType *VTy = resultType->castAs<VectorType>();
16793 resultType =
16794 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16795
16796 Input = ImpCastExprToType(
16797 E: Input.get(), Type: resultType,
16798 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16799 .get();
16800 break;
16801 } else if (resultType->isExtVectorType()) {
16802 if (Context.getLangOpts().OpenCL &&
16803 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16804 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16805 // operate on vector float types.
16806 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16807 if (!T->isIntegerType())
16808 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16809 << resultType << Input.get()->getSourceRange());
16810 }
16811 // Vector logical not returns the signed variant of the operand type.
16812 resultType = GetSignedVectorType(V: resultType);
16813 break;
16814 } else if (Context.getLangOpts().CPlusPlus &&
16815 resultType->isVectorType()) {
16816 const VectorType *VTy = resultType->castAs<VectorType>();
16817 if (VTy->getVectorKind() != VectorKind::Generic)
16818 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16819 << resultType << Input.get()->getSourceRange());
16820
16821 // Vector logical not returns the signed variant of the operand type.
16822 resultType = GetSignedVectorType(V: resultType);
16823 break;
16824 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16825 resultType = Context.getLogicalOperationType();
16826 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16827 break;
16828 } else {
16829 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16830 << resultType << Input.get()->getSourceRange());
16831 }
16832
16833 // LNot always has type int. C99 6.5.3.3p5.
16834 // In C++, it's bool. C++ 5.3.1p8
16835 resultType = Context.getLogicalOperationType();
16836 break;
16837 case UO_Real:
16838 case UO_Imag:
16839 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16840 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16841 // ordinary complex l-values to ordinary l-values and all other values to
16842 // r-values.
16843 if (Input.isInvalid())
16844 return ExprError();
16845 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16846 if (Input.get()->isGLValue() &&
16847 Input.get()->getObjectKind() == OK_Ordinary)
16848 VK = Input.get()->getValueKind();
16849 } else if (!getLangOpts().CPlusPlus) {
16850 // In C, a volatile scalar is read by __imag. In C++, it is not.
16851 Input = DefaultLvalueConversion(E: Input.get());
16852 }
16853 break;
16854 case UO_Extension:
16855 resultType = Input.get()->getType();
16856 VK = Input.get()->getValueKind();
16857 OK = Input.get()->getObjectKind();
16858 break;
16859 case UO_Coawait:
16860 // It's unnecessary to represent the pass-through operator co_await in the
16861 // AST; just return the input expression instead.
16862 assert(!Input.get()->getType()->isDependentType() &&
16863 "the co_await expression must be non-dependant before "
16864 "building operator co_await");
16865 return Input;
16866 }
16867 }
16868 if (resultType.isNull() || Input.isInvalid())
16869 return ExprError();
16870
16871 // Check for array bounds violations in the operand of the UnaryOperator,
16872 // except for the '*' and '&' operators that have to be handled specially
16873 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16874 // that are explicitly defined as valid by the standard).
16875 if (Opc != UO_AddrOf && Opc != UO_Deref)
16876 CheckArrayAccess(E: Input.get());
16877
16878 auto *UO =
16879 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16880 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16881
16882 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16883 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16884 !isUnevaluatedContext())
16885 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16886
16887 // Convert the result back to a half vector.
16888 if (ConvertHalfVec)
16889 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16890 return UO;
16891}
16892
16893bool Sema::isQualifiedMemberAccess(Expr *E) {
16894 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16895 if (!DRE->getQualifier())
16896 return false;
16897
16898 ValueDecl *VD = DRE->getDecl();
16899 if (!VD->isCXXClassMember())
16900 return false;
16901
16902 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16903 return true;
16904 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16905 return Method->isImplicitObjectMemberFunction();
16906
16907 return false;
16908 }
16909
16910 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16911 if (!ULE->getQualifier())
16912 return false;
16913
16914 for (NamedDecl *D : ULE->decls()) {
16915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16916 if (Method->isImplicitObjectMemberFunction())
16917 return true;
16918 } else {
16919 // Overload set does not contain methods.
16920 break;
16921 }
16922 }
16923
16924 return false;
16925 }
16926
16927 return false;
16928}
16929
16930ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16931 UnaryOperatorKind Opc, Expr *Input,
16932 bool IsAfterAmp) {
16933 // First things first: handle placeholders so that the
16934 // overloaded-operator check considers the right type.
16935 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16936 // Increment and decrement of pseudo-object references.
16937 if (pty->getKind() == BuiltinType::PseudoObject &&
16938 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16939 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16940
16941 // extension is always a builtin operator.
16942 if (Opc == UO_Extension)
16943 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16944
16945 // & gets special logic for several kinds of placeholder.
16946 // The builtin code knows what to do.
16947 if (Opc == UO_AddrOf &&
16948 (pty->getKind() == BuiltinType::Overload ||
16949 pty->getKind() == BuiltinType::UnknownAny ||
16950 pty->getKind() == BuiltinType::BoundMember))
16951 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16952
16953 // Anything else needs to be handled now.
16954 ExprResult Result = CheckPlaceholderExpr(E: Input);
16955 if (Result.isInvalid()) return ExprError();
16956 Input = Result.get();
16957 }
16958
16959 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16960 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16961 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16962 // Find all of the overloaded operators visible from this point.
16963 UnresolvedSet<16> Functions;
16964 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16965 if (S && OverOp != OO_None)
16966 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16967
16968 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16969 }
16970
16971 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16972}
16973
16974ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16975 Expr *Input, bool IsAfterAmp) {
16976 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16977 IsAfterAmp);
16978}
16979
16980ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16981 LabelDecl *TheDecl) {
16982 TheDecl->markUsed(C&: Context);
16983 // Create the AST node. The address of a label always has type 'void*'.
16984 auto *Res = new (Context) AddrLabelExpr(
16985 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16986
16987 if (getCurFunction())
16988 getCurFunction()->AddrLabels.push_back(Elt: Res);
16989
16990 return Res;
16991}
16992
16993void Sema::ActOnStartStmtExpr() {
16994 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16995 // Make sure we diagnose jumping into a statement expression.
16996 setFunctionHasBranchProtectedScope();
16997}
16998
16999void Sema::ActOnStmtExprError() {
17000 // Note that function is also called by TreeTransform when leaving a
17001 // StmtExpr scope without rebuilding anything.
17002
17003 DiscardCleanupsInEvaluationContext();
17004 PopExpressionEvaluationContext();
17005}
17006
17007ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
17008 SourceLocation RPLoc) {
17009 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
17010}
17011
17012ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
17013 SourceLocation RPLoc, unsigned TemplateDepth) {
17014 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
17015 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
17016
17017 if (hasAnyUnrecoverableErrorsInThisFunction())
17018 DiscardCleanupsInEvaluationContext();
17019 assert(!Cleanup.exprNeedsCleanups() &&
17020 "cleanups within StmtExpr not correctly bound!");
17021 PopExpressionEvaluationContext();
17022
17023 // FIXME: there are a variety of strange constraints to enforce here, for
17024 // example, it is not possible to goto into a stmt expression apparently.
17025 // More semantic analysis is needed.
17026
17027 // If there are sub-stmts in the compound stmt, take the type of the last one
17028 // as the type of the stmtexpr.
17029 QualType Ty = Context.VoidTy;
17030 bool StmtExprMayBindToTemp = false;
17031 if (!Compound->body_empty()) {
17032 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
17033 if (const Expr *Value = LastStmt->getExprStmt()) {
17034 StmtExprMayBindToTemp = true;
17035 Ty = Value->getType();
17036 }
17037 }
17038 }
17039
17040 // FIXME: Check that expression type is complete/non-abstract; statement
17041 // expressions are not lvalues.
17042 Expr *ResStmtExpr =
17043 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
17044 if (StmtExprMayBindToTemp)
17045 return MaybeBindToTemporary(E: ResStmtExpr);
17046 return ResStmtExpr;
17047}
17048
17049ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
17050 if (ER.isInvalid())
17051 return ExprError();
17052
17053 // Do function/array conversion on the last expression, but not
17054 // lvalue-to-rvalue. However, initialize an unqualified type.
17055 ER = DefaultFunctionArrayConversion(E: ER.get());
17056 if (ER.isInvalid())
17057 return ExprError();
17058 Expr *E = ER.get();
17059
17060 if (E->isTypeDependent())
17061 return E;
17062
17063 // In ARC, if the final expression ends in a consume, splice
17064 // the consume out and bind it later. In the alternate case
17065 // (when dealing with a retainable type), the result
17066 // initialization will create a produce. In both cases the
17067 // result will be +1, and we'll need to balance that out with
17068 // a bind.
17069 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
17070 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
17071 return Cast->getSubExpr();
17072
17073 // FIXME: Provide a better location for the initialization.
17074 return PerformCopyInitialization(
17075 Entity: InitializedEntity::InitializeStmtExprResult(
17076 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
17077 EqualLoc: SourceLocation(), Init: E);
17078}
17079
17080ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
17081 TypeSourceInfo *TInfo,
17082 const Designation &Desig,
17083 SourceLocation RParenLoc) {
17084 QualType ArgTy = TInfo->getType();
17085 bool Dependent = ArgTy->isDependentType();
17086 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
17087
17088 // We must have at least one component that refers to the type, and the first
17089 // one is known to be a field designator. Verify that the ArgTy represents
17090 // a struct/union/class.
17091 if (!Dependent && !ArgTy->isRecordType())
17092 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
17093 << ArgTy << TypeRange);
17094
17095 // Type must be complete per C99 7.17p3 because a declaring a variable
17096 // with an incomplete type would be ill-formed.
17097 if (!Dependent
17098 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
17099 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
17100 return ExprError();
17101
17102 bool DidWarnAboutNonPOD = false;
17103 QualType CurrentType = ArgTy;
17104 SmallVector<OffsetOfNode, 4> Comps;
17105 SmallVector<Expr *, 4> Exprs;
17106 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
17107 const Designator &D = Desig.getDesignator(Idx: I);
17108 assert(!D.isArrayRangeDesignator());
17109 if (D.isArrayDesignator()) {
17110 // Offset of an array sub-field. TODO: Should we allow vector elements?
17111 if (!CurrentType->isDependentType()) {
17112 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
17113 if(!AT)
17114 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
17115 << CurrentType);
17116 CurrentType = AT->getElementType();
17117 } else
17118 CurrentType = Context.DependentTy;
17119
17120 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
17121 if (IdxRval.isInvalid())
17122 return ExprError();
17123 Expr *Idx = IdxRval.get();
17124
17125 // The expression must be an integral expression.
17126 // FIXME: An integral constant expression?
17127 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
17128 !Idx->getType()->isIntegerType())
17129 return ExprError(
17130 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
17131 << Idx->getSourceRange());
17132
17133 // Record this array index.
17134 Comps.push_back(
17135 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
17136 Exprs.push_back(Elt: Idx);
17137 continue;
17138 }
17139
17140 assert(D.isFieldDesignator());
17141 const IdentifierInfo *Name = D.getFieldDecl();
17142
17143 // Offset of a field.
17144 if (CurrentType->isDependentType()) {
17145 // We have the offset of a field, but we can't look into the dependent
17146 // type. Just record the identifier of the field.
17147 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
17148 CurrentType = Context.DependentTy;
17149 continue;
17150 }
17151
17152 // We need to have a complete type to look into.
17153 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
17154 DiagID: diag::err_offsetof_incomplete_type))
17155 return ExprError();
17156
17157 // Look for the designated field.
17158 auto *RD = CurrentType->getAsRecordDecl();
17159 if (!RD)
17160 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
17161 << CurrentType);
17162
17163 // C++ [lib.support.types]p5:
17164 // The macro offsetof accepts a restricted set of type arguments in this
17165 // International Standard. type shall be a POD structure or a POD union
17166 // (clause 9).
17167 // C++11 [support.types]p4:
17168 // If type is not a standard-layout class (Clause 9), the results are
17169 // undefined.
17170 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
17171 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
17172 unsigned DiagID =
17173 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
17174 : diag::ext_offsetof_non_pod_type;
17175
17176 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
17177 Diag(Loc: BuiltinLoc, DiagID)
17178 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
17179 << CurrentType;
17180 DidWarnAboutNonPOD = true;
17181 }
17182 }
17183
17184 // Look for the field.
17185 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17186 LookupQualifiedName(R, LookupCtx: RD);
17187 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17188 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17189 if (!MemberDecl) {
17190 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17191 MemberDecl = IndirectMemberDecl->getAnonField();
17192 }
17193
17194 if (!MemberDecl) {
17195 // Lookup could be ambiguous when looking up a placeholder variable
17196 // __builtin_offsetof(S, _).
17197 // In that case we would already have emitted a diagnostic
17198 if (!R.isAmbiguous())
17199 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
17200 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17201 return ExprError();
17202 }
17203
17204 // C99 7.17p3:
17205 // (If the specified member is a bit-field, the behavior is undefined.)
17206 //
17207 // We diagnose this as an error.
17208 if (MemberDecl->isBitField()) {
17209 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
17210 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17211 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
17212 return ExprError();
17213 }
17214
17215 RecordDecl *Parent = MemberDecl->getParent();
17216 if (IndirectMemberDecl)
17217 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
17218
17219 // If the member was found in a base class, introduce OffsetOfNodes for
17220 // the base class indirections.
17221 CXXBasePaths Paths;
17222 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
17223 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
17224 if (Paths.getDetectedVirtual()) {
17225 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
17226 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17227 return ExprError();
17228 }
17229
17230 CXXBasePath &Path = Paths.front();
17231 for (const CXXBasePathElement &B : Path)
17232 Comps.push_back(Elt: OffsetOfNode(B.Base));
17233 }
17234
17235 if (IndirectMemberDecl) {
17236 for (auto *FI : IndirectMemberDecl->chain()) {
17237 assert(isa<FieldDecl>(FI));
17238 Comps.push_back(
17239 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
17240 }
17241 } else
17242 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17243
17244 CurrentType = MemberDecl->getType().getNonReferenceType();
17245 }
17246
17247 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
17248 comps: Comps, exprs: Exprs, RParenLoc);
17249}
17250
17251ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
17252 SourceLocation TypeLoc,
17253 ParsedType ParsedArgTy,
17254 const Designation &Desig,
17255 SourceLocation RParenLoc) {
17256
17257 TypeSourceInfo *ArgTInfo;
17258 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
17259 if (ArgTy.isNull())
17260 return ExprError();
17261
17262 if (!ArgTInfo)
17263 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
17264
17265 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
17266}
17267
17268ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
17269 Expr *CondExpr,
17270 Expr *LHSExpr, Expr *RHSExpr,
17271 SourceLocation RPLoc) {
17272 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17273
17274 ExprValueKind VK = VK_PRValue;
17275 ExprObjectKind OK = OK_Ordinary;
17276 QualType resType;
17277 bool CondIsTrue = false;
17278 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17279 resType = Context.DependentTy;
17280 } else {
17281 // The conditional expression is required to be a constant expression.
17282 llvm::APSInt condEval(32);
17283 ExprResult CondICE = VerifyIntegerConstantExpression(
17284 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
17285 if (CondICE.isInvalid())
17286 return ExprError();
17287 CondExpr = CondICE.get();
17288 CondIsTrue = condEval.getZExtValue();
17289
17290 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17291 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17292
17293 resType = ActiveExpr->getType();
17294 VK = ActiveExpr->getValueKind();
17295 OK = ActiveExpr->getObjectKind();
17296 }
17297
17298 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17299 resType, VK, OK, RPLoc, CondIsTrue);
17300}
17301
17302//===----------------------------------------------------------------------===//
17303// Clang Extensions.
17304//===----------------------------------------------------------------------===//
17305
17306void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17307 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
17308
17309 if (LangOpts.CPlusPlus) {
17310 MangleNumberingContext *MCtx;
17311 Decl *ManglingContextDecl;
17312 std::tie(args&: MCtx, args&: ManglingContextDecl) =
17313 getCurrentMangleNumberContext(DC: Block->getDeclContext());
17314 if (MCtx) {
17315 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
17316 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
17317 }
17318 }
17319
17320 PushBlockScope(BlockScope: CurScope, Block);
17321 CurContext->addDecl(D: Block);
17322 if (CurScope)
17323 PushDeclContext(S: CurScope, DC: Block);
17324 else
17325 CurContext = Block;
17326
17327 getCurBlock()->HasImplicitReturnType = true;
17328
17329 // Enter a new evaluation context to insulate the block from any
17330 // cleanups from the enclosing full-expression.
17331 PushExpressionEvaluationContext(
17332 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
17333}
17334
17335void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
17336 Scope *CurScope) {
17337 assert(ParamInfo.getIdentifier() == nullptr &&
17338 "block-id should have no identifier!");
17339 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17340 BlockScopeInfo *CurBlock = getCurBlock();
17341
17342 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
17343 QualType T = Sig->getType();
17344 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
17345
17346 // GetTypeForDeclarator always produces a function type for a block
17347 // literal signature. Furthermore, it is always a FunctionProtoType
17348 // unless the function was written with a typedef.
17349 assert(T->isFunctionType() &&
17350 "GetTypeForDeclarator made a non-function block signature");
17351
17352 // Look for an explicit signature in that function type.
17353 FunctionProtoTypeLoc ExplicitSignature;
17354
17355 if ((ExplicitSignature = Sig->getTypeLoc()
17356 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17357
17358 // Check whether that explicit signature was synthesized by
17359 // GetTypeForDeclarator. If so, don't save that as part of the
17360 // written signature.
17361 if (ExplicitSignature.getLocalRangeBegin() ==
17362 ExplicitSignature.getLocalRangeEnd()) {
17363 // This would be much cheaper if we stored TypeLocs instead of
17364 // TypeSourceInfos.
17365 TypeLoc Result = ExplicitSignature.getReturnLoc();
17366 unsigned Size = Result.getFullDataSize();
17367 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
17368 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
17369
17370 ExplicitSignature = FunctionProtoTypeLoc();
17371 }
17372 }
17373
17374 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17375 CurBlock->FunctionType = T;
17376
17377 const auto *Fn = T->castAs<FunctionType>();
17378 QualType RetTy = Fn->getReturnType();
17379 bool isVariadic =
17380 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17381
17382 CurBlock->TheDecl->setIsVariadic(isVariadic);
17383
17384 // Context.DependentTy is used as a placeholder for a missing block
17385 // return type. TODO: what should we do with declarators like:
17386 // ^ * { ... }
17387 // If the answer is "apply template argument deduction"....
17388 if (RetTy != Context.DependentTy) {
17389 CurBlock->ReturnType = RetTy;
17390 CurBlock->TheDecl->setBlockMissingReturnType(false);
17391 CurBlock->HasImplicitReturnType = false;
17392 }
17393
17394 // Push block parameters from the declarator if we had them.
17395 SmallVector<ParmVarDecl*, 8> Params;
17396 if (ExplicitSignature) {
17397 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17398 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
17399 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17400 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17401 // Diagnose this as an extension in C17 and earlier.
17402 if (!getLangOpts().C23)
17403 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
17404 }
17405 Params.push_back(Elt: Param);
17406 }
17407
17408 // Fake up parameter variables if we have a typedef, like
17409 // ^ fntype { ... }
17410 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17411 for (const auto &I : Fn->param_types()) {
17412 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17413 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
17414 Params.push_back(Elt: Param);
17415 }
17416 }
17417
17418 // Set the parameters on the block decl.
17419 if (!Params.empty()) {
17420 CurBlock->TheDecl->setParams(Params);
17421 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17422 /*CheckParameterNames=*/false);
17423 }
17424
17425 // Finally we can process decl attributes.
17426 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17427
17428 // Put the parameter variables in scope.
17429 for (auto *AI : CurBlock->TheDecl->parameters()) {
17430 AI->setOwningFunction(CurBlock->TheDecl);
17431
17432 // If this has an identifier, add it to the scope stack.
17433 if (AI->getIdentifier()) {
17434 CheckShadow(S: CurBlock->TheScope, D: AI);
17435
17436 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17437 }
17438
17439 if (AI->isInvalidDecl())
17440 CurBlock->TheDecl->setInvalidDecl();
17441 }
17442}
17443
17444void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17445 // Leave the expression-evaluation context.
17446 DiscardCleanupsInEvaluationContext();
17447 PopExpressionEvaluationContext();
17448
17449 // Pop off CurBlock, handle nested blocks.
17450 PopDeclContext();
17451 PopFunctionScopeInfo();
17452}
17453
17454ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17455 Stmt *Body, Scope *CurScope) {
17456 // If blocks are disabled, emit an error.
17457 if (!LangOpts.Blocks)
17458 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17459
17460 // Leave the expression-evaluation context.
17461 if (hasAnyUnrecoverableErrorsInThisFunction())
17462 DiscardCleanupsInEvaluationContext();
17463 assert(!Cleanup.exprNeedsCleanups() &&
17464 "cleanups within block not correctly bound!");
17465 PopExpressionEvaluationContext();
17466
17467 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17468 BlockDecl *BD = BSI->TheDecl;
17469
17470 maybeAddDeclWithEffects(D: BD);
17471
17472 if (BSI->HasImplicitReturnType)
17473 deduceClosureReturnType(CSI&: *BSI);
17474
17475 QualType RetTy = Context.VoidTy;
17476 if (!BSI->ReturnType.isNull())
17477 RetTy = BSI->ReturnType;
17478
17479 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17480 QualType BlockTy;
17481
17482 // If the user wrote a function type in some form, try to use that.
17483 if (!BSI->FunctionType.isNull()) {
17484 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17485
17486 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17487 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17488
17489 // Turn protoless block types into nullary block types.
17490 if (isa<FunctionNoProtoType>(Val: FTy)) {
17491 FunctionProtoType::ExtProtoInfo EPI;
17492 EPI.ExtInfo = Ext;
17493 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17494
17495 // Otherwise, if we don't need to change anything about the function type,
17496 // preserve its sugar structure.
17497 } else if (FTy->getReturnType() == RetTy &&
17498 (!NoReturn || FTy->getNoReturnAttr())) {
17499 BlockTy = BSI->FunctionType;
17500
17501 // Otherwise, make the minimal modifications to the function type.
17502 } else {
17503 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17504 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17505 EPI.TypeQuals = Qualifiers();
17506 EPI.ExtInfo = Ext;
17507 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17508 }
17509
17510 // If we don't have a function type, just build one from nothing.
17511 } else {
17512 FunctionProtoType::ExtProtoInfo EPI;
17513 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17514 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17515 }
17516
17517 DiagnoseUnusedParameters(Parameters: BD->parameters());
17518 BlockTy = Context.getBlockPointerType(T: BlockTy);
17519
17520 // If needed, diagnose invalid gotos and switches in the block.
17521 if (getCurFunction()->NeedsScopeChecking() &&
17522 !PP.isCodeCompletionEnabled())
17523 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17524
17525 BD->setBody(cast<CompoundStmt>(Val: Body));
17526
17527 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17528 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17529
17530 // Try to apply the named return value optimization. We have to check again
17531 // if we can do this, though, because blocks keep return statements around
17532 // to deduce an implicit return type.
17533 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17534 !BD->isDependentContext())
17535 computeNRVO(Body, Scope: BSI);
17536
17537 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17538 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17539 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17540 UseContext: NonTrivialCUnionContext::FunctionReturn,
17541 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17542
17543 PopDeclContext();
17544
17545 // Set the captured variables on the block.
17546 SmallVector<BlockDecl::Capture, 4> Captures;
17547 for (Capture &Cap : BSI->Captures) {
17548 if (Cap.isInvalid() || Cap.isThisCapture())
17549 continue;
17550 // Cap.getVariable() is always a VarDecl because
17551 // blocks cannot capture structured bindings or other ValueDecl kinds.
17552 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17553 Expr *CopyExpr = nullptr;
17554 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17555 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17556 // The capture logic needs the destructor, so make sure we mark it.
17557 // Usually this is unnecessary because most local variables have
17558 // their destructors marked at declaration time, but parameters are
17559 // an exception because it's technically only the call site that
17560 // actually requires the destructor.
17561 if (isa<ParmVarDecl>(Val: Var))
17562 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17563
17564 // Enter a separate potentially-evaluated context while building block
17565 // initializers to isolate their cleanups from those of the block
17566 // itself.
17567 // FIXME: Is this appropriate even when the block itself occurs in an
17568 // unevaluated operand?
17569 EnterExpressionEvaluationContext EvalContext(
17570 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17571
17572 SourceLocation Loc = Cap.getLocation();
17573
17574 ExprResult Result = BuildDeclarationNameExpr(
17575 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17576
17577 // According to the blocks spec, the capture of a variable from
17578 // the stack requires a const copy constructor. This is not true
17579 // of the copy/move done to move a __block variable to the heap.
17580 if (!Result.isInvalid() &&
17581 !Result.get()->getType().isConstQualified()) {
17582 Result = ImpCastExprToType(E: Result.get(),
17583 Type: Result.get()->getType().withConst(),
17584 CK: CK_NoOp, VK: VK_LValue);
17585 }
17586
17587 if (!Result.isInvalid()) {
17588 Result = PerformCopyInitialization(
17589 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17590 Type: Cap.getCaptureType()),
17591 EqualLoc: Loc, Init: Result.get());
17592 }
17593
17594 // Build a full-expression copy expression if initialization
17595 // succeeded and used a non-trivial constructor. Recover from
17596 // errors by pretending that the copy isn't necessary.
17597 if (!Result.isInvalid() &&
17598 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17599 ->isTrivial()) {
17600 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17601 CopyExpr = Result.get();
17602 }
17603 }
17604 }
17605
17606 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17607 CopyExpr);
17608 Captures.push_back(Elt: NewCap);
17609 }
17610 QualType CXXThisType;
17611 if (BSI->isCXXThisCaptured())
17612 CXXThisType = BSI->getCXXThisCapture().getCaptureType();
17613 BD->setCaptures(Context, Captures, CXXThisType);
17614
17615 // Pop the block scope now but keep it alive to the end of this function.
17616 AnalysisBasedWarnings::Policy WP =
17617 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17618 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17619
17620 BlockExpr *Result = new (Context)
17621 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17622
17623 // If the block isn't obviously global, i.e. it captures anything at
17624 // all, then we need to do a few things in the surrounding context:
17625 if (Result->getBlockDecl()->hasCaptures()) {
17626 // First, this expression has a new cleanup object.
17627 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17628 Cleanup.setExprNeedsCleanups(true);
17629
17630 // It also gets a branch-protected scope if any of the captured
17631 // variables needs destruction.
17632 for (const auto &CI : Result->getBlockDecl()->captures()) {
17633 const VarDecl *var = CI.getVariable();
17634 if (var->getType().isDestructedType() != QualType::DK_none) {
17635 setFunctionHasBranchProtectedScope();
17636 break;
17637 }
17638 }
17639 }
17640
17641 if (getCurFunction())
17642 getCurFunction()->addBlock(BD);
17643
17644 // This can happen if the block's return type is deduced, but
17645 // the return expression is invalid.
17646 if (BD->isInvalidDecl())
17647 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17648 SubExprs: {Result}, T: Result->getType());
17649 return Result;
17650}
17651
17652ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17653 SourceLocation RPLoc) {
17654 TypeSourceInfo *TInfo;
17655 GetTypeFromParser(Ty, TInfo: &TInfo);
17656 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17657}
17658
17659ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17660 Expr *E, TypeSourceInfo *TInfo,
17661 SourceLocation RPLoc) {
17662 Expr *OrigExpr = E;
17663 VAArgExpr::VarArgKind VAKind = VAArgExpr::VA_Std;
17664
17665 // CUDA device global function does not support varargs.
17666 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17667 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17668 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17669 if (T == CUDAFunctionTarget::Global)
17670 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17671 }
17672 }
17673
17674 // NVPTX does not support va_arg expression.
17675 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17676 Context.getTargetInfo().getTriple().isNVPTX())
17677 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17678
17679 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17680 // as Microsoft ABI on an actual Microsoft platform, where
17681 // __builtin_ms_va_list and __builtin_va_list are the same.)
17682 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17683 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17684 QualType MSVaListType = Context.getBuiltinMSVaListType();
17685 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17686 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17687 return ExprError();
17688 VAKind = VAArgExpr::VA_MS;
17689 }
17690 }
17691
17692 // Get the va_list type
17693 QualType VaListType = Context.getBuiltinVaListType();
17694
17695 // It might be a __builtin_zos_va_list!
17696 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17697 // E->getType() can be:
17698 // - va_list: equal to array (char*)[2] (inside function)
17699 // - char **: decayed array (va_list passed as parameter)
17700 // We need to check for both cases.
17701 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17702 assert(ZOSVaListType->isArrayType() &&
17703 "__builtin_zos_va_list must be an array type");
17704 QualType DecayedType = Context.getArrayDecayedType(T: ZOSVaListType);
17705 if (Context.hasSameType(T1: ZOSVaListType, T2: E->getType()) ||
17706 Context.hasSameType(T1: DecayedType, T2: E->getType())) {
17707 VAKind = VAArgExpr::VA_ZOS;
17708 VaListType = ZOSVaListType;
17709 }
17710 }
17711
17712 if (VAKind != VAArgExpr::VA_MS) {
17713 if (VaListType->isArrayType()) {
17714 // Deal with implicit array decay; for example, on x86-64,
17715 // va_list is an array, but it's supposed to decay to
17716 // a pointer for va_arg.
17717 VaListType = Context.getArrayDecayedType(T: VaListType);
17718 // Make sure the input expression also decays appropriately.
17719 ExprResult Result = UsualUnaryConversions(E);
17720 if (Result.isInvalid())
17721 return ExprError();
17722 E = Result.get();
17723 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17724 // If va_list is a record type and we are compiling in C++ mode,
17725 // check the argument using reference binding.
17726 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17727 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17728 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17729 if (Init.isInvalid())
17730 return ExprError();
17731 E = Init.getAs<Expr>();
17732 } else {
17733 // Otherwise, the va_list argument must be an l-value because
17734 // it is modified by va_arg.
17735 if (!E->isTypeDependent() &&
17736 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17737 return ExprError();
17738 }
17739 }
17740
17741 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17742 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17743 return ExprError(
17744 Diag(Loc: E->getBeginLoc(),
17745 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17746 << OrigExpr->getType() << E->getSourceRange());
17747
17748 if (!TInfo->getType()->isDependentType()) {
17749 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17750 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17751 Args: TInfo->getTypeLoc()))
17752 return ExprError();
17753
17754 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17755 T: TInfo->getType(),
17756 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17757 Args: TInfo->getTypeLoc()))
17758 return ExprError();
17759
17760 if (!TInfo->getType().isPODType(Context)) {
17761 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17762 DiagID: TInfo->getType()->isObjCLifetimeType()
17763 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17764 : diag::warn_second_parameter_to_va_arg_not_pod)
17765 << TInfo->getType()
17766 << TInfo->getTypeLoc().getSourceRange();
17767 }
17768
17769 if (TInfo->getType()->isArrayType()) {
17770 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17771 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17772 << TInfo->getType()
17773 << TInfo->getTypeLoc().getSourceRange());
17774 }
17775
17776 // Check for va_arg where arguments of the given type will be promoted
17777 // (i.e. this va_arg is guaranteed to have undefined behavior).
17778 QualType PromoteType;
17779 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17780 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17781 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17782 // and C23 7.16.1.1p2 says, in part:
17783 // If type is not compatible with the type of the actual next argument
17784 // (as promoted according to the default argument promotions), the
17785 // behavior is undefined, except for the following cases:
17786 // - both types are pointers to qualified or unqualified versions of
17787 // compatible types;
17788 // - one type is compatible with a signed integer type, the other
17789 // type is compatible with the corresponding unsigned integer type,
17790 // and the value is representable in both types;
17791 // - one type is pointer to qualified or unqualified void and the
17792 // other is a pointer to a qualified or unqualified character type;
17793 // - or, the type of the next argument is nullptr_t and type is a
17794 // pointer type that has the same representation and alignment
17795 // requirements as a pointer to a character type.
17796 // Given that type compatibility is the primary requirement (ignoring
17797 // qualifications), you would think we could call typesAreCompatible()
17798 // directly to test this. However, in C++, that checks for *same type*,
17799 // which causes false positives when passing an enumeration type to
17800 // va_arg. Instead, get the underlying type of the enumeration and pass
17801 // that.
17802 QualType UnderlyingType = TInfo->getType();
17803 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17804 UnderlyingType = ED->getIntegerType();
17805 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17806 /*CompareUnqualified*/ true))
17807 PromoteType = QualType();
17808
17809 // If the types are still not compatible, we need to test whether the
17810 // promoted type and the underlying type are the same except for
17811 // signedness. Ask the AST for the correctly corresponding type and see
17812 // if that's compatible.
17813 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17814 PromoteType->isUnsignedIntegerType() !=
17815 UnderlyingType->isUnsignedIntegerType()) {
17816 UnderlyingType =
17817 UnderlyingType->isUnsignedIntegerType()
17818 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17819 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17820 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17821 /*CompareUnqualified*/ true))
17822 PromoteType = QualType();
17823 }
17824 }
17825 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17826 PromoteType = Context.DoubleTy;
17827 if (!PromoteType.isNull())
17828 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17829 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17830 << TInfo->getType()
17831 << PromoteType
17832 << TInfo->getTypeLoc().getSourceRange());
17833 }
17834
17835 QualType T = TInfo->getType().getNonLValueExprType(Context);
17836 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17837}
17838
17839ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17840 // The type of __null will be int or long, depending on the size of
17841 // pointers on the target.
17842 QualType Ty;
17843 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17844 if (pw == Context.getTargetInfo().getIntWidth())
17845 Ty = Context.IntTy;
17846 else if (pw == Context.getTargetInfo().getLongWidth())
17847 Ty = Context.LongTy;
17848 else if (pw == Context.getTargetInfo().getLongLongWidth())
17849 Ty = Context.LongLongTy;
17850 else {
17851 llvm_unreachable("I don't know size of pointer!");
17852 }
17853
17854 return new (Context) GNUNullExpr(Ty, TokenLoc);
17855}
17856
17857static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17858 CXXRecordDecl *ImplDecl = nullptr;
17859
17860 // Fetch the std::source_location::__impl decl.
17861 if (NamespaceDecl *Std = S.getStdNamespace()) {
17862 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17863 Loc, Sema::LookupOrdinaryName);
17864 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17865 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17866 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17867 Loc, Sema::LookupOrdinaryName);
17868 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17869 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17870 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17871 }
17872 }
17873 }
17874 }
17875
17876 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17877 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17878 return nullptr;
17879 }
17880
17881 // Verify that __impl is a trivial struct type, with no base classes, and with
17882 // only the four expected fields.
17883 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17884 ImplDecl->getNumBases() != 0) {
17885 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17886 return nullptr;
17887 }
17888
17889 unsigned Count = 0;
17890 for (FieldDecl *F : ImplDecl->fields()) {
17891 StringRef Name = F->getName();
17892
17893 if (Name == "_M_file_name") {
17894 if (F->getType() !=
17895 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17896 break;
17897 Count++;
17898 } else if (Name == "_M_function_name") {
17899 if (F->getType() !=
17900 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17901 break;
17902 Count++;
17903 } else if (Name == "_M_line") {
17904 if (!F->getType()->isIntegerType())
17905 break;
17906 Count++;
17907 } else if (Name == "_M_column") {
17908 if (!F->getType()->isIntegerType())
17909 break;
17910 Count++;
17911 } else {
17912 Count = 100; // invalid
17913 break;
17914 }
17915 }
17916 if (Count != 4) {
17917 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17918 return nullptr;
17919 }
17920
17921 return ImplDecl;
17922}
17923
17924ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17925 SourceLocation BuiltinLoc,
17926 SourceLocation RPLoc) {
17927 QualType ResultTy;
17928 switch (Kind) {
17929 case SourceLocIdentKind::File:
17930 case SourceLocIdentKind::FileName:
17931 case SourceLocIdentKind::Function:
17932 case SourceLocIdentKind::FuncSig: {
17933 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17934 ResultTy =
17935 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17936 break;
17937 }
17938 case SourceLocIdentKind::Line:
17939 case SourceLocIdentKind::Column:
17940 ResultTy = Context.UnsignedIntTy;
17941 break;
17942 case SourceLocIdentKind::SourceLocStruct:
17943 if (!StdSourceLocationImplDecl) {
17944 StdSourceLocationImplDecl =
17945 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17946 if (!StdSourceLocationImplDecl)
17947 return ExprError();
17948 }
17949 ResultTy = Context.getPointerType(
17950 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17951 break;
17952 }
17953
17954 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17955}
17956
17957ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17958 SourceLocation BuiltinLoc,
17959 SourceLocation RPLoc,
17960 DeclContext *ParentContext) {
17961 return new (Context)
17962 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17963}
17964
17965ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17966 StringLiteral *BinaryData, StringRef FileName) {
17967 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17968 Data->BinaryData = BinaryData;
17969 Data->FileName = FileName;
17970 return new (Context)
17971 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17972 Data->getDataElementCount());
17973}
17974
17975static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17976 const Expr *SrcExpr) {
17977 if (!DstType->isFunctionPointerType() ||
17978 !SrcExpr->getType()->isFunctionType())
17979 return false;
17980
17981 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17982 if (!DRE)
17983 return false;
17984
17985 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17986 if (!FD)
17987 return false;
17988
17989 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17990 /*Complain=*/true,
17991 Loc: SrcExpr->getBeginLoc());
17992}
17993
17994bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17995 SourceLocation Loc,
17996 QualType DstType, QualType SrcType,
17997 Expr *SrcExpr, AssignmentAction Action,
17998 bool *Complained) {
17999 if (Complained)
18000 *Complained = false;
18001
18002 // Decode the result (notice that AST's are still created for extensions).
18003 bool CheckInferredResultType = false;
18004 bool isInvalid = false;
18005 unsigned DiagKind = 0;
18006 ConversionFixItGenerator ConvHints;
18007 bool MayHaveConvFixit = false;
18008 bool MayHaveFunctionDiff = false;
18009 const ObjCInterfaceDecl *IFace = nullptr;
18010 const ObjCProtocolDecl *PDecl = nullptr;
18011
18012 switch (ConvTy) {
18013 case AssignConvertType::Compatible:
18014 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
18015 return false;
18016 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
18017 // Still a valid conversion, but we may want to diagnose for C++
18018 // compatibility reasons.
18019 DiagKind = diag::warn_compatible_implicit_pointer_conv;
18020 break;
18021 case AssignConvertType::PointerToInt:
18022 if (getLangOpts().CPlusPlus) {
18023 DiagKind = diag::err_typecheck_convert_pointer_int;
18024 isInvalid = true;
18025 } else {
18026 DiagKind = diag::ext_typecheck_convert_pointer_int;
18027 }
18028 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18029 MayHaveConvFixit = true;
18030 break;
18031 case AssignConvertType::IntToPointer:
18032 if (getLangOpts().CPlusPlus) {
18033 DiagKind = diag::err_typecheck_convert_int_pointer;
18034 isInvalid = true;
18035 } else {
18036 DiagKind = diag::ext_typecheck_convert_int_pointer;
18037 }
18038 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18039 MayHaveConvFixit = true;
18040 break;
18041 case AssignConvertType::IncompatibleFunctionPointerStrict:
18042 DiagKind =
18043 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
18044 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18045 MayHaveConvFixit = true;
18046 break;
18047 case AssignConvertType::IncompatibleFunctionPointer:
18048 if (getLangOpts().CPlusPlus) {
18049 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
18050 isInvalid = true;
18051 } else {
18052 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
18053 }
18054 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18055 MayHaveConvFixit = true;
18056 break;
18057 case AssignConvertType::IncompatiblePointer:
18058 if (Action == AssignmentAction::Passing_CFAudited) {
18059 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
18060 } else if (getLangOpts().CPlusPlus) {
18061 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
18062 isInvalid = true;
18063 } else {
18064 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
18065 }
18066 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
18067 SrcType->isObjCObjectPointerType();
18068 if (CheckInferredResultType) {
18069 SrcType = SrcType.getUnqualifiedType();
18070 DstType = DstType.getUnqualifiedType();
18071 } else {
18072 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18073 }
18074 MayHaveConvFixit = true;
18075 break;
18076 case AssignConvertType::IncompatiblePointerSign:
18077 if (getLangOpts().CPlusPlus) {
18078 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
18079 isInvalid = true;
18080 } else {
18081 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
18082 }
18083 break;
18084 case AssignConvertType::FunctionVoidPointer:
18085 if (getLangOpts().CPlusPlus) {
18086 DiagKind = diag::err_typecheck_convert_pointer_void_func;
18087 isInvalid = true;
18088 } else {
18089 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
18090 }
18091 break;
18092 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
18093 // Perform decay if necessary.
18094 if (SrcType->canDecayToPointerType())
18095 SrcType = Context.getDecayedType(T: SrcType);
18096
18097 isInvalid = true;
18098
18099 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
18100 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
18101 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
18102 DiagKind = diag::err_typecheck_incompatible_address_space;
18103 break;
18104 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
18105 DiagKind = diag::err_typecheck_incompatible_ownership;
18106 break;
18107 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
18108 DiagKind = diag::err_typecheck_incompatible_ptrauth;
18109 break;
18110 }
18111
18112 llvm_unreachable("unknown error case for discarding qualifiers!");
18113 // fallthrough
18114 }
18115 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
18116 if (SrcType->isArrayType())
18117 SrcType = Context.getArrayDecayedType(T: SrcType);
18118
18119 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
18120 break;
18121 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
18122 // If the qualifiers lost were because we were applying the
18123 // (deprecated) C++ conversion from a string literal to a char*
18124 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
18125 // Ideally, this check would be performed in
18126 // checkPointerTypesForAssignment. However, that would require a
18127 // bit of refactoring (so that the second argument is an
18128 // expression, rather than a type), which should be done as part
18129 // of a larger effort to fix checkPointerTypesForAssignment for
18130 // C++ semantics.
18131 if (getLangOpts().CPlusPlus &&
18132 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
18133 return false;
18134 if (getLangOpts().CPlusPlus) {
18135 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
18136 isInvalid = true;
18137 } else {
18138 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
18139 }
18140
18141 break;
18142 case AssignConvertType::IncompatibleNestedPointerQualifiers:
18143 if (getLangOpts().CPlusPlus) {
18144 isInvalid = true;
18145 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
18146 } else {
18147 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
18148 }
18149 break;
18150 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
18151 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
18152 isInvalid = true;
18153 break;
18154 case AssignConvertType::IntToBlockPointer:
18155 DiagKind = diag::err_int_to_block_pointer;
18156 isInvalid = true;
18157 break;
18158 case AssignConvertType::IncompatibleBlockPointer:
18159 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
18160 isInvalid = true;
18161 break;
18162 case AssignConvertType::IncompatibleObjCQualifiedId: {
18163 if (SrcType->isObjCQualifiedIdType()) {
18164 const ObjCObjectPointerType *srcOPT =
18165 SrcType->castAs<ObjCObjectPointerType>();
18166 for (auto *srcProto : srcOPT->quals()) {
18167 PDecl = srcProto;
18168 break;
18169 }
18170 if (const ObjCInterfaceType *IFaceT =
18171 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
18172 IFace = IFaceT->getDecl();
18173 }
18174 else if (DstType->isObjCQualifiedIdType()) {
18175 const ObjCObjectPointerType *dstOPT =
18176 DstType->castAs<ObjCObjectPointerType>();
18177 for (auto *dstProto : dstOPT->quals()) {
18178 PDecl = dstProto;
18179 break;
18180 }
18181 if (const ObjCInterfaceType *IFaceT =
18182 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
18183 IFace = IFaceT->getDecl();
18184 }
18185 if (getLangOpts().CPlusPlus) {
18186 DiagKind = diag::err_incompatible_qualified_id;
18187 isInvalid = true;
18188 } else {
18189 DiagKind = diag::warn_incompatible_qualified_id;
18190 }
18191 break;
18192 }
18193 case AssignConvertType::IncompatibleVectors:
18194 if (getLangOpts().CPlusPlus) {
18195 DiagKind = diag::err_incompatible_vectors;
18196 isInvalid = true;
18197 } else {
18198 DiagKind = diag::warn_incompatible_vectors;
18199 }
18200 break;
18201 case AssignConvertType::IncompatibleObjCWeakRef:
18202 DiagKind = diag::err_arc_weak_unavailable_assign;
18203 isInvalid = true;
18204 break;
18205 case AssignConvertType::CompatibleOBTDiscards:
18206 return false;
18207 case AssignConvertType::IncompatibleOBTKinds: {
18208 assert(!SrcType->isFunctionType() &&
18209 "Unexpected function type found in IncompatibleOBTKinds assignment");
18210 if (SrcType->canDecayToPointerType())
18211 SrcType = Context.getDecayedType(T: SrcType);
18212
18213 auto getOBTKindName = [](QualType Ty) -> StringRef {
18214 if (Ty->isPointerType())
18215 Ty = Ty->getPointeeType();
18216 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18217 return OBT->getBehaviorKind() ==
18218 OverflowBehaviorType::OverflowBehaviorKind::Trap
18219 ? "__ob_trap"
18220 : "__ob_wrap";
18221 }
18222 llvm_unreachable("OBT kind unhandled");
18223 };
18224
18225 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
18226 << DstType << SrcType << getOBTKindName(DstType)
18227 << getOBTKindName(SrcType);
18228 isInvalid = true;
18229 return true;
18230 }
18231 case AssignConvertType::Incompatible:
18232 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
18233 if (Complained)
18234 *Complained = true;
18235 return true;
18236 }
18237
18238 DiagKind = diag::err_typecheck_convert_incompatible;
18239 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18240 MayHaveConvFixit = true;
18241 isInvalid = true;
18242 MayHaveFunctionDiff = true;
18243 break;
18244 }
18245
18246 QualType FirstType, SecondType;
18247 switch (Action) {
18248 case AssignmentAction::Assigning:
18249 case AssignmentAction::Initializing:
18250 // The destination type comes first.
18251 FirstType = DstType;
18252 SecondType = SrcType;
18253 break;
18254
18255 case AssignmentAction::Returning:
18256 case AssignmentAction::Passing:
18257 case AssignmentAction::Passing_CFAudited:
18258 case AssignmentAction::Converting:
18259 case AssignmentAction::Sending:
18260 case AssignmentAction::Casting:
18261 // The source type comes first.
18262 FirstType = SrcType;
18263 SecondType = DstType;
18264 break;
18265 }
18266
18267 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
18268 AssignmentAction ActionForDiag = Action;
18269 if (Action == AssignmentAction::Passing_CFAudited)
18270 ActionForDiag = AssignmentAction::Passing;
18271
18272 FDiag << FirstType << SecondType << ActionForDiag
18273 << SrcExpr->getSourceRange();
18274
18275 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18276 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18277 auto isPlainChar = [](const clang::Type *Type) {
18278 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
18279 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
18280 };
18281 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18282 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18283 }
18284
18285 // If we can fix the conversion, suggest the FixIts.
18286 if (!ConvHints.isNull()) {
18287 for (FixItHint &H : ConvHints.Hints)
18288 FDiag << H;
18289 }
18290
18291 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18292
18293 if (MayHaveFunctionDiff)
18294 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
18295
18296 Diag(Loc, PD: FDiag);
18297 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18298 DiagKind == diag::err_incompatible_qualified_id) &&
18299 PDecl && IFace && !IFace->hasDefinition())
18300 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
18301 << IFace << PDecl;
18302
18303 if (SecondType == Context.OverloadTy)
18304 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
18305 DestType: FirstType, /*TakingAddress=*/true);
18306
18307 if (CheckInferredResultType)
18308 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
18309
18310 if (Action == AssignmentAction::Returning &&
18311 ConvTy == AssignConvertType::IncompatiblePointer)
18312 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
18313
18314 if (Complained)
18315 *Complained = true;
18316 return isInvalid;
18317}
18318
18319ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18320 llvm::APSInt *Result,
18321 AllowFoldKind CanFold) {
18322 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18323 public:
18324 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18325 QualType T) override {
18326 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
18327 << T << S.LangOpts.CPlusPlus;
18328 }
18329 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18330 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18331 }
18332 } Diagnoser;
18333
18334 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18335}
18336
18337ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18338 llvm::APSInt *Result,
18339 unsigned DiagID,
18340 AllowFoldKind CanFold) {
18341 class IDDiagnoser : public VerifyICEDiagnoser {
18342 unsigned DiagID;
18343
18344 public:
18345 IDDiagnoser(unsigned DiagID)
18346 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18347
18348 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18349 return S.Diag(Loc, DiagID);
18350 }
18351 } Diagnoser(DiagID);
18352
18353 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18354}
18355
18356Sema::SemaDiagnosticBuilder
18357Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
18358 QualType T) {
18359 return diagnoseNotICE(S, Loc);
18360}
18361
18362Sema::SemaDiagnosticBuilder
18363Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
18364 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18365}
18366
18367ExprResult
18368Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
18369 VerifyICEDiagnoser &Diagnoser,
18370 AllowFoldKind CanFold) {
18371 SourceLocation DiagLoc = E->getBeginLoc();
18372
18373 if (getLangOpts().CPlusPlus11) {
18374 // C++11 [expr.const]p5:
18375 // If an expression of literal class type is used in a context where an
18376 // integral constant expression is required, then that class type shall
18377 // have a single non-explicit conversion function to an integral or
18378 // unscoped enumeration type
18379 ExprResult Converted;
18380 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18381 VerifyICEDiagnoser &BaseDiagnoser;
18382 public:
18383 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18384 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18385 BaseDiagnoser.Suppress, true),
18386 BaseDiagnoser(BaseDiagnoser) {}
18387
18388 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18389 QualType T) override {
18390 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18391 }
18392
18393 SemaDiagnosticBuilder diagnoseIncomplete(
18394 Sema &S, SourceLocation Loc, QualType T) override {
18395 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
18396 }
18397
18398 SemaDiagnosticBuilder diagnoseExplicitConv(
18399 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18400 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
18401 }
18402
18403 SemaDiagnosticBuilder noteExplicitConv(
18404 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18405 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18406 << ConvTy->isEnumeralType() << ConvTy;
18407 }
18408
18409 SemaDiagnosticBuilder diagnoseAmbiguous(
18410 Sema &S, SourceLocation Loc, QualType T) override {
18411 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
18412 }
18413
18414 SemaDiagnosticBuilder noteAmbiguous(
18415 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18416 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18417 << ConvTy->isEnumeralType() << ConvTy;
18418 }
18419
18420 SemaDiagnosticBuilder diagnoseConversion(
18421 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18422 llvm_unreachable("conversion functions are permitted");
18423 }
18424 } ConvertDiagnoser(Diagnoser);
18425
18426 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18427 Converter&: ConvertDiagnoser);
18428 if (Converted.isInvalid())
18429 return Converted;
18430 E = Converted.get();
18431 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18432 // don't try to evaluate it later. We also don't want to return the
18433 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18434 // this function will attempt to use 'Value'.
18435 if (isa<RecoveryExpr>(Val: E))
18436 return ExprError();
18437 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18438 return ExprError();
18439 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18440 // An ICE must be of integral or unscoped enumeration type.
18441 if (!Diagnoser.Suppress)
18442 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18443 << E->getSourceRange();
18444 return ExprError();
18445 }
18446
18447 ExprResult RValueExpr = DefaultLvalueConversion(E);
18448 if (RValueExpr.isInvalid())
18449 return ExprError();
18450
18451 E = RValueExpr.get();
18452
18453 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18454 // in the non-ICE case.
18455 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18456
18457 if (!Result)
18458 return E;
18459
18460 SmallVector<PartialDiagnosticAt, 8> Notes;
18461 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18462 if (!isa<ConstantExpr>(Val: E))
18463 E = ConstantExpr::Create(Context, E, Result: APValue(*Result));
18464
18465 if (Notes.empty())
18466 return E;
18467
18468 // If our only note is the usual "invalid subexpression" note, just point
18469 // the caret at its location rather than producing an essentially
18470 // redundant note.
18471 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18472 diag::note_invalid_subexpr_in_const_expr) {
18473 DiagLoc = Notes[0].first;
18474 Notes.clear();
18475 }
18476
18477 if (getLangOpts().CPlusPlus) {
18478 if (!Diagnoser.Suppress) {
18479 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18480 for (const PartialDiagnosticAt &Note : Notes)
18481 Diag(Loc: Note.first, PD: Note.second);
18482 }
18483 return ExprError();
18484 }
18485
18486 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18487 for (const PartialDiagnosticAt &Note : Notes)
18488 Diag(Loc: Note.first, PD: Note.second);
18489
18490 return E;
18491 }
18492
18493 Expr::EvalResult EvalResult;
18494 SmallVector<PartialDiagnosticAt, 8> Notes;
18495 SmallVector<PartialDiagnosticAt> MSWarning;
18496 EvalResult.Diag = &Notes;
18497 EvalResult.ExtendedDiag = &MSWarning;
18498
18499 // Try to evaluate the expression, and produce diagnostics explaining why it's
18500 // not a constant expression as a side-effect.
18501 EvalProxy SProxy(*this);
18502 bool Folded =
18503 (getLangOpts().CPlusPlus
18504 ? E->EvaluateAsMandatedConstantRValue(Result&: EvalResult, Ctx: Context, SProxy)
18505 : E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context,
18506 /*isConstantContext=*/InConstantContext: true)) &&
18507 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18508 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18509
18510 if (Folded && !isa<ConstantExpr>(Val: E))
18511 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18512
18513 // For -fms-compatibility mode we relax some requirements
18514 // for constant folding in non-SFINAE contexts
18515 if (!MSWarning.empty()) {
18516 if (isSFINAEContext()) {
18517 Folded = false;
18518 } else {
18519 for (auto &Info : MSWarning)
18520 Diag(Loc: Info.first, PD: Info.second);
18521 }
18522 }
18523
18524 // In C++11, we can rely on diagnostics being produced for any expression
18525 // which is not a constant expression. If no diagnostics were produced, then
18526 // this is a constant expression.
18527 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18528 if (Result)
18529 *Result = EvalResult.Val.getInt();
18530 return E;
18531 }
18532
18533 // If our only note is the usual "invalid subexpression" note, just point
18534 // the caret at its location rather than producing an essentially
18535 // redundant note.
18536 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18537 diag::note_invalid_subexpr_in_const_expr) {
18538 DiagLoc = Notes[0].first;
18539 Notes.clear();
18540 }
18541
18542 if (!Folded || CanFold == AllowFoldKind::No) {
18543 if (!Diagnoser.Suppress) {
18544 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18545 for (const PartialDiagnosticAt &Note : Notes)
18546 Diag(Loc: Note.first, PD: Note.second);
18547 }
18548
18549 return ExprError();
18550 }
18551
18552 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18553 for (const PartialDiagnosticAt &Note : Notes)
18554 Diag(Loc: Note.first, PD: Note.second);
18555
18556 if (Result)
18557 *Result = EvalResult.Val.getInt();
18558 return E;
18559}
18560
18561namespace {
18562 // Handle the case where we conclude a expression which we speculatively
18563 // considered to be unevaluated is actually evaluated.
18564 class TransformToPE : public TreeTransform<TransformToPE> {
18565 typedef TreeTransform<TransformToPE> BaseTransform;
18566
18567 public:
18568 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18569
18570 // Make sure we redo semantic analysis
18571 bool AlwaysRebuild() { return true; }
18572 bool ReplacingOriginal() { return true; }
18573
18574 // We need to special-case DeclRefExprs referring to FieldDecls which
18575 // are not part of a member pointer formation; normal TreeTransforming
18576 // doesn't catch this case because of the way we represent them in the AST.
18577 // FIXME: This is a bit ugly; is it really the best way to handle this
18578 // case?
18579 //
18580 // Error on DeclRefExprs referring to FieldDecls.
18581 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18582 if (isa<FieldDecl>(Val: E->getDecl()) &&
18583 !SemaRef.isUnevaluatedContext())
18584 return SemaRef.Diag(Loc: E->getLocation(),
18585 DiagID: diag::err_invalid_non_static_member_use)
18586 << E->getDecl() << E->getSourceRange();
18587
18588 return BaseTransform::TransformDeclRefExpr(E);
18589 }
18590
18591 // Exception: filter out member pointer formation
18592 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18593 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18594 return E;
18595
18596 return BaseTransform::TransformUnaryOperator(E);
18597 }
18598
18599 // The body of a lambda-expression is in a separate expression evaluation
18600 // context so never needs to be transformed.
18601 // FIXME: Ideally we wouldn't transform the closure type either, and would
18602 // just recreate the capture expressions and lambda expression.
18603 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18604 return SkipLambdaBody(E, S: Body);
18605 }
18606 };
18607}
18608
18609ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18610 assert(isUnevaluatedContext() &&
18611 "Should only transform unevaluated expressions");
18612 ExprEvalContexts.back().Context =
18613 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18614 if (isUnevaluatedContext())
18615 return E;
18616 return TransformToPE(*this).TransformExpr(E);
18617}
18618
18619TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18620 assert(isUnevaluatedContext() &&
18621 "Should only transform unevaluated expressions");
18622 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18623 if (isUnevaluatedContext())
18624 return TInfo;
18625 return TransformToPE(*this).TransformType(TSI: TInfo);
18626}
18627
18628void
18629Sema::PushExpressionEvaluationContext(
18630 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18631 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18632 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18633 Args&: LambdaContextDecl, Args&: ExprContext);
18634
18635 // Discarded statements and immediate contexts nested in other
18636 // discarded statements or immediate context are themselves
18637 // a discarded statement or an immediate context, respectively.
18638 ExprEvalContexts.back().InDiscardedStatement =
18639 parentEvaluationContext().isDiscardedStatementContext();
18640
18641 // C++23 [expr.const]/p15
18642 // An expression or conversion is in an immediate function context if [...]
18643 // it is a subexpression of a manifestly constant-evaluated expression or
18644 // conversion.
18645 const auto &Prev = parentEvaluationContext();
18646 ExprEvalContexts.back().InImmediateFunctionContext =
18647 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18648
18649 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18650 Prev.InImmediateEscalatingFunctionContext;
18651
18652 Cleanup.reset();
18653 if (!MaybeODRUseExprs.empty())
18654 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18655}
18656
18657void
18658Sema::PushExpressionEvaluationContext(
18659 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18660 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18661 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18662 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18663}
18664
18665void Sema::PushExpressionEvaluationContextForFunction(
18666 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18667 // [expr.const]/p14.1
18668 // An expression or conversion is in an immediate function context if it is
18669 // potentially evaluated and either: its innermost enclosing non-block scope
18670 // is a function parameter scope of an immediate function.
18671 PushExpressionEvaluationContext(
18672 NewContext: FD && FD->isConsteval()
18673 ? ExpressionEvaluationContext::ImmediateFunctionContext
18674 : NewContext);
18675 const Sema::ExpressionEvaluationContextRecord &Parent =
18676 parentEvaluationContext();
18677 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18678
18679 Current.InDiscardedStatement = false;
18680
18681 if (FD) {
18682
18683 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18684 // context is nested in an immediate function context, so smaller contexts
18685 // that appear inside immediate functions (like variable initializers) are
18686 // considered to be inside an immediate function context even though by
18687 // themselves they are not immediate function contexts. But when a new
18688 // function is entered, we need to reset this tracking, since the entered
18689 // function might be not an immediate function.
18690
18691 Current.InImmediateEscalatingFunctionContext =
18692 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18693
18694 if (isLambdaMethod(DC: FD) && !isLambdaCallOperator(DC: FD))
18695 Current.InImmediateFunctionContext = FD->isConsteval() ||
18696 Parent.isConstantEvaluated() ||
18697 Parent.isImmediateFunctionContext();
18698 else
18699 Current.InImmediateFunctionContext = FD->isConsteval();
18700 }
18701}
18702
18703ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18704 TypeSourceInfo *TSI) {
18705 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18706}
18707
18708ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18709 TypeSourceInfo *TSI) {
18710 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TSI);
18711}
18712
18713namespace {
18714
18715const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18716 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18717 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18718 if (E->getOpcode() == UO_Deref)
18719 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18720 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18721 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18722 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18723 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18724 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18725 QualType Inner;
18726 QualType Ty = E->getType();
18727 if (const auto *Ptr = Ty->getAs<PointerType>())
18728 Inner = Ptr->getPointeeType();
18729 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18730 Inner = Arr->getElementType();
18731 else
18732 return nullptr;
18733
18734 if (Inner->hasAttr(AK: attr::NoDeref))
18735 return E;
18736 }
18737 return nullptr;
18738}
18739
18740} // namespace
18741
18742void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18743 for (const Expr *E : Rec.PossibleDerefs) {
18744 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18745 if (DeclRef) {
18746 const ValueDecl *Decl = DeclRef->getDecl();
18747 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18748 << Decl->getName() << E->getSourceRange();
18749 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18750 } else {
18751 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18752 << E->getSourceRange();
18753 }
18754 }
18755 Rec.PossibleDerefs.clear();
18756}
18757
18758void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18759 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18760 return;
18761
18762 // Note: ignoring parens here is not justified by the standard rules, but
18763 // ignoring parentheses seems like a more reasonable approach, and this only
18764 // drives a deprecation warning so doesn't affect conformance.
18765 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18766 if (BO->getOpcode() == BO_Assign) {
18767 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18768 llvm::erase(C&: LHSs, V: BO->getLHS());
18769 }
18770 }
18771}
18772
18773void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18774 assert(getLangOpts().CPlusPlus20 &&
18775 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18776 "Cannot mark an immediate escalating expression outside of an "
18777 "immediate escalating context");
18778 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18779 Call && Call->getCallee()) {
18780 if (auto *DeclRef =
18781 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18782 DeclRef->setIsImmediateEscalating(true);
18783 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18784 Ctr->setIsImmediateEscalating(true);
18785 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18786 DeclRef->setIsImmediateEscalating(true);
18787 } else {
18788 assert(false && "expected an immediately escalating expression");
18789 }
18790 if (FunctionScopeInfo *FI = getCurFunction())
18791 FI->FoundImmediateEscalatingExpression = true;
18792}
18793
18794ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18795 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18796 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18797 isCheckingDefaultArgumentOrInitializer() ||
18798 RebuildingImmediateInvocation || isImmediateFunctionContext())
18799 return E;
18800
18801 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18802 /// It's OK if this fails; we'll also remove this in
18803 /// HandleImmediateInvocations, but catching it here allows us to avoid
18804 /// walking the AST looking for it in simple cases.
18805 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18806 if (auto *DeclRef =
18807 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18808 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18809
18810 // C++23 [expr.const]/p16
18811 // An expression or conversion is immediate-escalating if it is not initially
18812 // in an immediate function context and it is [...] an immediate invocation
18813 // that is not a constant expression and is not a subexpression of an
18814 // immediate invocation.
18815 APValue Cached;
18816 auto CheckConstantExpressionAndKeepResult = [&]() {
18817 Expr::EvalResult Eval;
18818 EvalProxy SProxy(*this);
18819 bool Res = E.get()->EvaluateAsMandatedConstantExpr(
18820 Result&: Eval, Ctx: getASTContext(), SProxy, Kind: ConstantExprKind::ImmediateInvocation);
18821 if (Res && !Eval.DiagEmitted) {
18822 Cached = std::move(Eval.Val);
18823 return true;
18824 }
18825 return false;
18826 };
18827
18828 if (!E.get()->isValueDependent() &&
18829 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18830 !CheckConstantExpressionAndKeepResult()) {
18831 MarkExpressionAsImmediateEscalating(E: E.get());
18832 return E;
18833 }
18834
18835 if (Cleanup.exprNeedsCleanups()) {
18836 // Since an immediate invocation is a full expression itself - it requires
18837 // an additional ExprWithCleanups node, but it can participate to a bigger
18838 // full expression which actually requires cleanups to be run after so
18839 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18840 // may discard cleanups for outer expression too early.
18841
18842 // Note that ExprWithCleanups created here must always have empty cleanup
18843 // objects:
18844 // - compound literals do not create cleanup objects in C++ and immediate
18845 // invocations are C++-only.
18846 // - blocks are not allowed inside constant expressions and compiler will
18847 // issue an error if they appear there.
18848 //
18849 // Hence, in correct code any cleanup objects created inside current
18850 // evaluation context must be outside the immediate invocation.
18851 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18852 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18853 }
18854
18855 ConstantExpr *Res = ConstantExpr::Create(
18856 Context: getASTContext(), E: E.get(),
18857 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18858 Context: getASTContext()),
18859 /*IsImmediateInvocation*/ true);
18860 if (Cached.hasValue())
18861 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18862 /// Value-dependent constant expressions should not be immediately
18863 /// evaluated until they are instantiated.
18864 if (!Res->isValueDependent())
18865 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18866 return Res;
18867}
18868
18869static void EvaluateAndDiagnoseImmediateInvocation(
18870 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18871 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18872 Expr::EvalResult Eval;
18873 Eval.Diag = &Notes;
18874 ConstantExpr *CE = Candidate.getPointer();
18875 EvalProxy SProxy(SemaRef);
18876 bool Result =
18877 CE->EvaluateAsMandatedConstantExpr(Result&: Eval, Ctx: SemaRef.getASTContext(), SProxy,
18878 Kind: ConstantExprKind::ImmediateInvocation);
18879 if (!Result || !Notes.empty()) {
18880 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18881 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18882 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18883 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18884 FunctionDecl *FD = nullptr;
18885 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18886 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18887 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18888 FD = Call->getConstructor();
18889 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18890 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18891
18892 assert(FD && FD->isImmediateFunction() &&
18893 "could not find an immediate function in this expression");
18894 if (FD->isInvalidDecl())
18895 return;
18896 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18897 << FD << FD->isConsteval();
18898 if (auto Context =
18899 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18900 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18901 << Context->Decl;
18902 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18903 }
18904 if (!FD->isConsteval())
18905 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18906 for (auto &Note : Notes)
18907 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18908 return;
18909 }
18910 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18911}
18912
18913static void RemoveNestedImmediateInvocation(
18914 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18915 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18916 struct ComplexRemove : TreeTransform<ComplexRemove> {
18917 using Base = TreeTransform<ComplexRemove>;
18918 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18919 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18920 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18921 CurrentII;
18922 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18923 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18924 SmallVector<Sema::ImmediateInvocationCandidate,
18925 4>::reverse_iterator Current)
18926 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18927 void RemoveImmediateInvocation(ConstantExpr* E) {
18928 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18929 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18930 return Elem.getPointer() == E;
18931 });
18932 // It is possible that some subexpression of the current immediate
18933 // invocation was handled from another expression evaluation context. Do
18934 // not handle the current immediate invocation if some of its
18935 // subexpressions failed before.
18936 if (It == IISet.rend()) {
18937 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18938 CurrentII->setInt(1);
18939 } else {
18940 It->setInt(1); // Mark as deleted
18941 }
18942 }
18943 ExprResult TransformConstantExpr(ConstantExpr *E) {
18944 if (!E->isImmediateInvocation())
18945 return Base::TransformConstantExpr(E);
18946 RemoveImmediateInvocation(E);
18947 return Base::TransformExpr(E: E->getSubExpr());
18948 }
18949 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18950 /// we need to remove its DeclRefExpr from the DRSet.
18951 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18952 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18953 return Base::TransformCXXOperatorCallExpr(E);
18954 }
18955 /// Base::TransformUserDefinedLiteral doesn't preserve the
18956 /// UserDefinedLiteral node.
18957 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18958 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18959 /// here.
18960 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18961 if (!Init)
18962 return Init;
18963
18964 // We cannot use IgnoreImpCasts because we need to preserve
18965 // full expressions.
18966 while (true) {
18967 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18968 Init = ICE->getSubExpr();
18969 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18970 Init = ICE->getSubExpr();
18971 else
18972 break;
18973 }
18974 /// ConstantExprs are the first layer of implicit node to be removed so if
18975 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18976 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18977 CE && CE->isImmediateInvocation())
18978 RemoveImmediateInvocation(E: CE);
18979 return Base::TransformInitializer(Init, NotCopyInit);
18980 }
18981 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18982 DRSet.erase(Ptr: E);
18983 return E;
18984 }
18985 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18986 // Do not rebuild lambdas to avoid creating a new type.
18987 // Lambdas have already been processed inside their eval contexts.
18988 return E;
18989 }
18990
18991 // We do not have enough information to transform opaque expressions and
18992 // assume they do not contain immediate subexpressions.
18993 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18994
18995 bool AlwaysRebuild() { return false; }
18996 bool ReplacingOriginal() { return true; }
18997 bool AllowSkippingCXXConstructExpr() {
18998 bool Res = AllowSkippingFirstCXXConstructExpr;
18999 AllowSkippingFirstCXXConstructExpr = true;
19000 return Res;
19001 }
19002 bool AllowSkippingFirstCXXConstructExpr = true;
19003 } Transformer(SemaRef, Rec.ReferenceToConsteval,
19004 Rec.ImmediateInvocationCandidates, It);
19005
19006 /// CXXConstructExpr with a single argument are getting skipped by
19007 /// TreeTransform in some situtation because they could be implicit. This
19008 /// can only occur for the top-level CXXConstructExpr because it is used
19009 /// nowhere in the expression being transformed therefore will not be rebuilt.
19010 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
19011 /// skipping the first CXXConstructExpr.
19012 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
19013 Transformer.AllowSkippingFirstCXXConstructExpr = false;
19014
19015 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
19016 // The result may not be usable in case of previous compilation errors.
19017 // In this case evaluation of the expression may result in crash so just
19018 // don't do anything further with the result.
19019 if (Res.isUsable()) {
19020 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
19021 It->getPointer()->setSubExpr(Res.get());
19022 }
19023}
19024
19025static void
19026HandleImmediateInvocations(Sema &SemaRef,
19027 Sema::ExpressionEvaluationContextRecord &Rec) {
19028 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
19029 Rec.ReferenceToConsteval.size() == 0) ||
19030 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
19031 return;
19032
19033 // An expression or conversion is 'manifestly constant-evaluated' if it is:
19034 // [...]
19035 // - the initializer of a variable that is usable in constant expressions or
19036 // has constant initialization.
19037 if (SemaRef.getLangOpts().CPlusPlus23 &&
19038 Rec.ExprContext ==
19039 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
19040 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
19041 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
19042 VD->hasConstantInitialization())) {
19043 // An expression or conversion is in an 'immediate function context' if it
19044 // is potentially evaluated and either:
19045 // [...]
19046 // - it is a subexpression of a manifestly constant-evaluated expression
19047 // or conversion.
19048 return;
19049 }
19050 }
19051
19052 /// When we have more than 1 ImmediateInvocationCandidates or previously
19053 /// failed immediate invocations, we need to check for nested
19054 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
19055 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
19056 /// invocation.
19057 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
19058 !SemaRef.FailedImmediateInvocations.empty()) {
19059
19060 /// Prevent sema calls during the tree transform from adding pointers that
19061 /// are already in the sets.
19062 llvm::SaveAndRestore DisableIITracking(
19063 SemaRef.RebuildingImmediateInvocation, true);
19064
19065 /// Prevent diagnostic during tree transfrom as they are duplicates
19066 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
19067
19068 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
19069 It != Rec.ImmediateInvocationCandidates.rend(); It++)
19070 if (!It->getInt())
19071 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
19072 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
19073 Rec.ReferenceToConsteval.size()) {
19074 struct SimpleRemove : DynamicRecursiveASTVisitor {
19075 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
19076 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
19077 bool VisitDeclRefExpr(DeclRefExpr *E) override {
19078 DRSet.erase(Ptr: E);
19079 return DRSet.size();
19080 }
19081 } Visitor(Rec.ReferenceToConsteval);
19082 Visitor.TraverseStmt(
19083 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
19084 }
19085 for (auto CE : Rec.ImmediateInvocationCandidates)
19086 if (!CE.getInt())
19087 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
19088 for (auto *DR : Rec.ReferenceToConsteval) {
19089 // If the expression is immediate escalating, it is not an error;
19090 // The outer context itself becomes immediate and further errors,
19091 // if any, will be handled by DiagnoseImmediateEscalatingReason.
19092 if (DR->isImmediateEscalating())
19093 continue;
19094 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
19095 const NamedDecl *ND = FD;
19096 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
19097 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
19098 ND = MD->getParent();
19099
19100 // C++23 [expr.const]/p16
19101 // An expression or conversion is immediate-escalating if it is not
19102 // initially in an immediate function context and it is [...] a
19103 // potentially-evaluated id-expression that denotes an immediate function
19104 // that is not a subexpression of an immediate invocation.
19105 bool ImmediateEscalating = false;
19106 bool IsPotentiallyEvaluated =
19107 Rec.Context ==
19108 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
19109 Rec.Context ==
19110 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
19111 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
19112 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
19113
19114 if (!Rec.InImmediateEscalatingFunctionContext ||
19115 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
19116 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
19117 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
19118 if (!FD->getBuiltinID())
19119 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
19120 if (auto Context =
19121 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
19122 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
19123 << Context->Decl;
19124 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
19125 }
19126 if (FD->isImmediateEscalating() && !FD->isConsteval())
19127 SemaRef.DiagnoseImmediateEscalatingReason(FD);
19128
19129 } else {
19130 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
19131 }
19132 }
19133}
19134
19135void Sema::PopExpressionEvaluationContext() {
19136 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
19137 if (!Rec.Lambdas.empty()) {
19138 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
19139 if (!getLangOpts().CPlusPlus20 &&
19140 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
19141 Rec.isUnevaluated() ||
19142 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
19143 unsigned D;
19144 if (Rec.isUnevaluated()) {
19145 // C++11 [expr.prim.lambda]p2:
19146 // A lambda-expression shall not appear in an unevaluated operand
19147 // (Clause 5).
19148 D = diag::err_lambda_unevaluated_operand;
19149 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
19150 // C++1y [expr.const]p2:
19151 // A conditional-expression e is a core constant expression unless the
19152 // evaluation of e, following the rules of the abstract machine, would
19153 // evaluate [...] a lambda-expression.
19154 D = diag::err_lambda_in_constant_expression;
19155 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
19156 // C++17 [expr.prim.lamda]p2:
19157 // A lambda-expression shall not appear [...] in a template-argument.
19158 D = diag::err_lambda_in_invalid_context;
19159 } else
19160 llvm_unreachable("Couldn't infer lambda error message.");
19161
19162 for (const auto *L : Rec.Lambdas)
19163 Diag(Loc: L->getBeginLoc(), DiagID: D);
19164 }
19165 }
19166
19167 // Append the collected materialized temporaries into previous context before
19168 // exit if the previous also is a lifetime extending context.
19169 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
19170 parentEvaluationContext().InLifetimeExtendingContext &&
19171 !Rec.ForRangeLifetimeExtendTemps.empty()) {
19172 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
19173 RHS: Rec.ForRangeLifetimeExtendTemps);
19174 }
19175
19176 WarnOnPendingNoDerefs(Rec);
19177 HandleImmediateInvocations(SemaRef&: *this, Rec);
19178
19179 // Warn on any volatile-qualified simple-assignments that are not discarded-
19180 // value expressions nor unevaluated operands (those cases get removed from
19181 // this list by CheckUnusedVolatileAssignment).
19182 for (auto *BO : Rec.VolatileAssignmentLHSs)
19183 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
19184 << BO->getType();
19185
19186 // When are coming out of an unevaluated context, clear out any
19187 // temporaries that we may have created as part of the evaluation of
19188 // the expression in that context: they aren't relevant because they
19189 // will never be constructed.
19190 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
19191 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
19192 CE: ExprCleanupObjects.end());
19193 Cleanup = Rec.ParentCleanup;
19194 CleanupVarDeclMarking();
19195 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
19196 // Otherwise, merge the contexts together.
19197 } else {
19198 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
19199 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
19200 }
19201
19202 DiagnoseMisalignedMembers();
19203
19204 // Pop the current expression evaluation context off the stack.
19205 ExprEvalContexts.pop_back();
19206}
19207
19208void Sema::DiscardCleanupsInEvaluationContext() {
19209 ExprCleanupObjects.erase(
19210 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19211 CE: ExprCleanupObjects.end());
19212 Cleanup.reset();
19213 MaybeODRUseExprs.clear();
19214}
19215
19216ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
19217 ExprResult Result = CheckPlaceholderExpr(E);
19218 if (Result.isInvalid())
19219 return ExprError();
19220 E = Result.get();
19221 if (!E->getType()->isVariablyModifiedType())
19222 return E;
19223 return TransformToPotentiallyEvaluated(E);
19224}
19225
19226/// Are we in a context that is potentially constant evaluated per C++20
19227/// [expr.const]p12?
19228static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
19229 /// C++2a [expr.const]p12:
19230 // An expression or conversion is potentially constant evaluated if it is
19231 switch (SemaRef.ExprEvalContexts.back().Context) {
19232 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
19233 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
19234
19235 // -- a manifestly constant-evaluated expression,
19236 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
19237 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19238 case Sema::ExpressionEvaluationContext::DiscardedStatement:
19239 // -- a potentially-evaluated expression,
19240 case Sema::ExpressionEvaluationContext::UnevaluatedList:
19241 // -- an immediate subexpression of a braced-init-list,
19242
19243 // -- [FIXME] an expression of the form & cast-expression that occurs
19244 // within a templated entity
19245 // -- a subexpression of one of the above that is not a subexpression of
19246 // a nested unevaluated operand.
19247 return true;
19248
19249 case Sema::ExpressionEvaluationContext::Unevaluated:
19250 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
19251 // Expressions in this context are never evaluated.
19252 return false;
19253 }
19254 llvm_unreachable("Invalid context");
19255}
19256
19257/// Return true if this function has a calling convention that requires mangling
19258/// in the size of the parameter pack.
19259static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
19260 // These manglings are only applicable for targets whcih use Microsoft
19261 // mangling scheme for C.
19262 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
19263 return false;
19264
19265 // If this is C++ and this isn't an extern "C" function, parameters do not
19266 // need to be complete. In this case, C++ mangling will apply, which doesn't
19267 // use the size of the parameters.
19268 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19269 return false;
19270
19271 // Stdcall, fastcall, and vectorcall need this special treatment.
19272 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19273 switch (CC) {
19274 case CC_X86StdCall:
19275 case CC_X86FastCall:
19276 case CC_X86VectorCall:
19277 return true;
19278 default:
19279 break;
19280 }
19281 return false;
19282}
19283
19284/// Require that all of the parameter types of function be complete. Normally,
19285/// parameter types are only required to be complete when a function is called
19286/// or defined, but to mangle functions with certain calling conventions, the
19287/// mangler needs to know the size of the parameter list. In this situation,
19288/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19289/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19290/// result in a linker error. Clang doesn't implement this behavior, and instead
19291/// attempts to error at compile time.
19292static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
19293 SourceLocation Loc) {
19294 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19295 FunctionDecl *FD;
19296 ParmVarDecl *Param;
19297
19298 public:
19299 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19300 : FD(FD), Param(Param) {}
19301
19302 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19303 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19304 StringRef CCName;
19305 switch (CC) {
19306 case CC_X86StdCall:
19307 CCName = "stdcall";
19308 break;
19309 case CC_X86FastCall:
19310 CCName = "fastcall";
19311 break;
19312 case CC_X86VectorCall:
19313 CCName = "vectorcall";
19314 break;
19315 default:
19316 llvm_unreachable("CC does not need mangling");
19317 }
19318
19319 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
19320 << Param->getDeclName() << FD->getDeclName() << CCName;
19321 }
19322 };
19323
19324 for (ParmVarDecl *Param : FD->parameters()) {
19325 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19326 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
19327 }
19328}
19329
19330namespace {
19331enum class OdrUseContext {
19332 /// Declarations in this context are not odr-used.
19333 None,
19334 /// Declarations in this context are formally odr-used, but this is a
19335 /// dependent context.
19336 Dependent,
19337 /// Declarations in this context are odr-used but not actually used (yet).
19338 FormallyOdrUsed,
19339 /// Declarations in this context are used.
19340 Used
19341};
19342}
19343
19344/// Are we within a context in which references to resolved functions or to
19345/// variables result in odr-use?
19346static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19347 const Sema::ExpressionEvaluationContextRecord &Context =
19348 SemaRef.currentEvaluationContext();
19349
19350 if (Context.isUnevaluated())
19351 return OdrUseContext::None;
19352
19353 if (SemaRef.CurContext->isDependentContext())
19354 return OdrUseContext::Dependent;
19355
19356 if (Context.isDiscardedStatementContext())
19357 return OdrUseContext::FormallyOdrUsed;
19358
19359 else if (Context.Context ==
19360 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
19361 return OdrUseContext::FormallyOdrUsed;
19362
19363 return OdrUseContext::Used;
19364}
19365
19366static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
19367 if (!Func->isConstexpr())
19368 return false;
19369
19370 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19371 return true;
19372
19373 // Lambda conversion operators are never user provided.
19374 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
19375 return isLambdaConversionOperator(C: Conv);
19376
19377 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
19378 return CCD && CCD->getInheritedConstructor();
19379}
19380
19381void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
19382 bool MightBeOdrUse) {
19383 assert(Func && "No function?");
19384
19385 Func->setReferenced();
19386
19387 // Recursive functions aren't really used until they're used from some other
19388 // context.
19389 bool IsRecursiveCall = CurContext == Func;
19390
19391 // C++11 [basic.def.odr]p3:
19392 // A function whose name appears as a potentially-evaluated expression is
19393 // odr-used if it is the unique lookup result or the selected member of a
19394 // set of overloaded functions [...].
19395 //
19396 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19397 // can just check that here.
19398 OdrUseContext OdrUse =
19399 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
19400 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19401 OdrUse = OdrUseContext::FormallyOdrUsed;
19402
19403 // Trivial default constructors and destructors are never actually used.
19404 // FIXME: What about other special members?
19405 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19406 OdrUse == OdrUseContext::Used) {
19407 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
19408 if (Constructor->isDefaultConstructor())
19409 OdrUse = OdrUseContext::FormallyOdrUsed;
19410 if (isa<CXXDestructorDecl>(Val: Func))
19411 OdrUse = OdrUseContext::FormallyOdrUsed;
19412 }
19413
19414 // C++20 [expr.const]p12:
19415 // A function [...] is needed for constant evaluation if it is [...] a
19416 // constexpr function that is named by an expression that is potentially
19417 // constant evaluated
19418 bool NeededForConstantEvaluation =
19419 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
19420 isImplicitlyDefinableConstexprFunction(Func);
19421
19422 // Determine whether we require a function definition to exist, per
19423 // C++11 [temp.inst]p3:
19424 // Unless a function template specialization has been explicitly
19425 // instantiated or explicitly specialized, the function template
19426 // specialization is implicitly instantiated when the specialization is
19427 // referenced in a context that requires a function definition to exist.
19428 // C++20 [temp.inst]p7:
19429 // The existence of a definition of a [...] function is considered to
19430 // affect the semantics of the program if the [...] function is needed for
19431 // constant evaluation by an expression
19432 // C++20 [basic.def.odr]p10:
19433 // Every program shall contain exactly one definition of every non-inline
19434 // function or variable that is odr-used in that program outside of a
19435 // discarded statement
19436 // C++20 [special]p1:
19437 // The implementation will implicitly define [defaulted special members]
19438 // if they are odr-used or needed for constant evaluation.
19439 //
19440 // Note that we skip the implicit instantiation of templates that are only
19441 // used in unused default arguments or by recursive calls to themselves.
19442 // This is formally non-conforming, but seems reasonable in practice.
19443 bool NeedDefinition =
19444 !IsRecursiveCall &&
19445 (OdrUse == OdrUseContext::Used ||
19446 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19447
19448 // C++14 [temp.expl.spec]p6:
19449 // If a template [...] is explicitly specialized then that specialization
19450 // shall be declared before the first use of that specialization that would
19451 // cause an implicit instantiation to take place, in every translation unit
19452 // in which such a use occurs
19453 if (NeedDefinition &&
19454 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19455 Func->getMemberSpecializationInfo()))
19456 checkSpecializationReachability(Loc, Spec: Func);
19457
19458 if (getLangOpts().CUDA)
19459 CUDA().CheckCall(Loc, Callee: Func);
19460
19461 // If we need a definition, try to create one.
19462 if (NeedDefinition && !Func->getBody()) {
19463 runWithSufficientStackSpace(Loc, Fn: [&] {
19464 if (CXXConstructorDecl *Constructor =
19465 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19466 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19467 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19468 if (Constructor->isDefaultConstructor()) {
19469 if (Constructor->isTrivial() &&
19470 !Constructor->hasAttr<DLLExportAttr>())
19471 return;
19472 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19473 } else if (Constructor->isCopyConstructor()) {
19474 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19475 } else if (Constructor->isMoveConstructor()) {
19476 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19477 }
19478 } else if (Constructor->getInheritedConstructor()) {
19479 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19480 }
19481 } else if (CXXDestructorDecl *Destructor =
19482 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19483 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19484 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19485 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19486 return;
19487 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19488 }
19489 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19490 MarkVTableUsed(Loc, Class: Destructor->getParent());
19491 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19492 if (MethodDecl->isOverloadedOperator() &&
19493 MethodDecl->getOverloadedOperator() == OO_Equal) {
19494 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19495 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19496 if (MethodDecl->isCopyAssignmentOperator())
19497 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19498 else if (MethodDecl->isMoveAssignmentOperator())
19499 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19500 }
19501 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19502 MethodDecl->getParent()->isLambda()) {
19503 CXXConversionDecl *Conversion =
19504 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19505 if (Conversion->isLambdaToBlockPointerConversion())
19506 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19507 else
19508 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19509 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19510 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19511 }
19512
19513 if (Func->isDefaulted() && !Func->isDeleted()) {
19514 FunctionDecl::DefaultedFunctionKind DFK =
19515 Func->getDefaultedFunctionKind();
19516 if (DFK.isComparison())
19517 DefineDefaultedComparison(Loc, FD: Func, DCK: DFK.asComparison());
19518 else if (DFK.isPostfixOperator())
19519 DefineDefaultedPostfixOperator(Loc, FD: Func, Kind: DFK.asPostfixOperator());
19520 }
19521
19522 // Implicit instantiation of function templates and member functions of
19523 // class templates.
19524 if (Func->isImplicitlyInstantiable()) {
19525 TemplateSpecializationKind TSK =
19526 Func->getTemplateSpecializationKindForInstantiation();
19527 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19528 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19529 if (FirstInstantiation) {
19530 PointOfInstantiation = Loc;
19531 if (auto *MSI = Func->getMemberSpecializationInfo())
19532 MSI->setPointOfInstantiation(Loc);
19533 // FIXME: Notify listener.
19534 else
19535 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19536 } else if (TSK != TSK_ImplicitInstantiation) {
19537 // Use the point of use as the point of instantiation, instead of the
19538 // point of explicit instantiation (which we track as the actual point
19539 // of instantiation). This gives better backtraces in diagnostics.
19540 PointOfInstantiation = Loc;
19541 }
19542
19543 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19544 Func->isConstexpr()) {
19545 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19546 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19547 CodeSynthesisContexts.size())
19548 PendingLocalImplicitInstantiations.push_back(
19549 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19550 else if (Func->isConstexpr())
19551 // Do not defer instantiations of constexpr functions, to avoid the
19552 // expression evaluator needing to call back into Sema if it sees a
19553 // call to such a function.
19554 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19555 else {
19556 Func->setInstantiationIsPending(true);
19557 PendingInstantiations.push_back(
19558 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19559 if (llvm::isTimeTraceVerbose()) {
19560 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19561 std::string Name;
19562 llvm::raw_string_ostream OS(Name);
19563 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19564 /*Qualified=*/true);
19565 return Name;
19566 });
19567 }
19568 // Notify the consumer that a function was implicitly instantiated.
19569 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19570 }
19571 }
19572 } else {
19573 // Walk redefinitions, as some of them may be instantiable.
19574 for (auto *i : Func->redecls()) {
19575 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19576 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19577 }
19578 }
19579 });
19580 }
19581
19582 // If a constructor was defined in the context of a default parameter
19583 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19584 // context), its initializers may not be referenced yet.
19585 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19586 EnterExpressionEvaluationContext EvalContext(
19587 *this,
19588 Constructor->isImmediateFunction()
19589 ? ExpressionEvaluationContext::ImmediateFunctionContext
19590 : ExpressionEvaluationContext::PotentiallyEvaluated,
19591 Constructor);
19592 for (CXXCtorInitializer *Init : Constructor->inits()) {
19593 if (Init->isInClassMemberInitializer())
19594 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19595 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19596 });
19597 }
19598 }
19599
19600 // C++14 [except.spec]p17:
19601 // An exception-specification is considered to be needed when:
19602 // - the function is odr-used or, if it appears in an unevaluated operand,
19603 // would be odr-used if the expression were potentially-evaluated;
19604 //
19605 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19606 // function is a pure virtual function we're calling, and in that case the
19607 // function was selected by overload resolution and we need to resolve its
19608 // exception specification for a different reason.
19609 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19610 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19611 ResolveExceptionSpec(Loc, FPT);
19612
19613 // A callee could be called by a host function then by a device function.
19614 // If we only try recording once, we will miss recording the use on device
19615 // side. Therefore keep trying until it is recorded.
19616 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19617 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19618 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19619
19620 // If this is the first "real" use, act on that.
19621 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19622 // Keep track of used but undefined functions.
19623 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19624 if (mightHaveNonExternalLinkage(FD: Func))
19625 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19626 else if (Func->getMostRecentDecl()->isInlined() &&
19627 !LangOpts.GNUInline &&
19628 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19629 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19630 else if (isExternalWithNoLinkageType(VD: Func))
19631 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19632 }
19633
19634 // Some x86 Windows calling conventions mangle the size of the parameter
19635 // pack into the name. Computing the size of the parameters requires the
19636 // parameter types to be complete. Check that now.
19637 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19638 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19639
19640 // In the MS C++ ABI, the compiler emits destructor variants where they are
19641 // used. If the destructor is used here but defined elsewhere, mark the
19642 // virtual base destructors referenced. If those virtual base destructors
19643 // are inline, this will ensure they are defined when emitting the complete
19644 // destructor variant. This checking may be redundant if the destructor is
19645 // provided later in this TU.
19646 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19647 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19648 CXXRecordDecl *Parent = Dtor->getParent();
19649 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19650 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19651 }
19652 }
19653
19654 Func->markUsed(C&: Context);
19655 }
19656}
19657
19658/// Directly mark a variable odr-used. Given a choice, prefer to use
19659/// MarkVariableReferenced since it does additional checks and then
19660/// calls MarkVarDeclODRUsed.
19661/// If the variable must be captured:
19662/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19663/// - else capture it in the DeclContext that maps to the
19664/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19665static void
19666MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19667 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19668 // Keep track of used but undefined variables.
19669 // FIXME: We shouldn't suppress this warning for static data members.
19670 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19671 assert(Var && "expected a capturable variable");
19672
19673 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19674 (!Var->isExternallyVisible() || Var->isInline() ||
19675 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19676 !(Var->isStaticDataMember() && Var->hasInit())) {
19677 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19678 if (old.isInvalid())
19679 old = Loc;
19680 }
19681 QualType CaptureType, DeclRefType;
19682 if (SemaRef.LangOpts.OpenMP)
19683 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19684 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19685 /*EllipsisLoc*/ SourceLocation(),
19686 /*BuildAndDiagnose*/ true, CaptureType,
19687 DeclRefType, FunctionScopeIndexToStopAt);
19688
19689 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19690 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19691 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19692 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19693 if (VarTarget == SemaCUDA::CVT_Host &&
19694 (UserTarget == CUDAFunctionTarget::Device ||
19695 UserTarget == CUDAFunctionTarget::HostDevice ||
19696 UserTarget == CUDAFunctionTarget::Global)) {
19697 // Diagnose ODR-use of host global variables in device functions.
19698 // Reference of device global variables in host functions is allowed
19699 // through shadow variables therefore it is not diagnosed.
19700 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19701 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19702 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19703 SemaRef.targetDiag(Loc: Var->getLocation(),
19704 DiagID: Var->getType().isConstQualified()
19705 ? diag::note_cuda_const_var_unpromoted
19706 : diag::note_cuda_host_var);
19707 }
19708 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19709 // Also capture __device__ const variables, which are classified
19710 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19711 // an explicit CUDADeviceAttr to distinguish them from plain
19712 // const variables (no __device__), which also get CVT_Both but
19713 // only have an implicit CUDADeviceAttr.
19714 (VarTarget == SemaCUDA::CVT_Both &&
19715 Var->hasAttr<CUDADeviceAttr>() &&
19716 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19717 !Var->hasAttr<CUDASharedAttr>() &&
19718 (UserTarget == CUDAFunctionTarget::Host ||
19719 UserTarget == CUDAFunctionTarget::HostDevice)) {
19720 // Record a CUDA/HIP device side variable if it is ODR-used
19721 // by host code. This is done conservatively, when the variable is
19722 // referenced in any of the following contexts:
19723 // - a non-function context
19724 // - a host function
19725 // - a host device function
19726 // This makes the ODR-use of the device side variable by host code to
19727 // be visible in the device compilation for the compiler to be able to
19728 // emit template variables instantiated by host code only and to
19729 // externalize the static device side variable ODR-used by host code.
19730 if (!Var->hasExternalStorage())
19731 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19732 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19733 (!FD || (!FD->getDescribedFunctionTemplate() &&
19734 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19735 GVA_StrongExternal)))
19736 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19737 }
19738 }
19739
19740 V->markUsed(C&: SemaRef.Context);
19741}
19742
19743void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19744 SourceLocation Loc,
19745 unsigned CapturingScopeIndex) {
19746 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19747}
19748
19749static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19750 SourceLocation loc,
19751 ValueDecl *var) {
19752 DeclContext *VarDC =
19753 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19754
19755 // If the parameter still belongs to the translation unit, then
19756 // we're actually just using one parameter in the declaration of
19757 // the next.
19758 if (isa<ParmVarDecl>(Val: var) &&
19759 isa<TranslationUnitDecl>(Val: VarDC))
19760 return;
19761
19762 // For C code, don't diagnose about capture if we're not actually in code
19763 // right now; it's impossible to write a non-constant expression outside of
19764 // function context, so we'll get other (more useful) diagnostics later.
19765 //
19766 // For C++, things get a bit more nasty... it would be nice to suppress this
19767 // diagnostic for certain cases like using a local variable in an array bound
19768 // for a member of a local class, but the correct predicate is not obvious.
19769 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19770 return;
19771
19772 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19773 unsigned ContextKind = 3; // unknown
19774 if (isa<CXXMethodDecl>(Val: VarDC) &&
19775 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19776 ContextKind = 2;
19777 } else if (isa<FunctionDecl>(Val: VarDC)) {
19778 ContextKind = 0;
19779 } else if (isa<BlockDecl>(Val: VarDC)) {
19780 ContextKind = 1;
19781 }
19782
19783 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19784 << var << ValueKind << ContextKind << VarDC;
19785 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19786 << var;
19787
19788 // FIXME: Add additional diagnostic info about class etc. which prevents
19789 // capture.
19790}
19791
19792static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19793 ValueDecl *Var,
19794 bool &SubCapturesAreNested,
19795 QualType &CaptureType,
19796 QualType &DeclRefType) {
19797 // Check whether we've already captured it.
19798 if (CSI->CaptureMap.count(Val: Var)) {
19799 // If we found a capture, any subcaptures are nested.
19800 SubCapturesAreNested = true;
19801
19802 // Retrieve the capture type for this variable.
19803 CaptureType = CSI->getCapture(Var).getCaptureType();
19804
19805 // Compute the type of an expression that refers to this variable.
19806 DeclRefType = CaptureType.getNonReferenceType();
19807
19808 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19809 // are mutable in the sense that user can change their value - they are
19810 // private instances of the captured declarations.
19811 const Capture &Cap = CSI->getCapture(Var);
19812 // C++ [expr.prim.lambda]p10:
19813 // The type of such a data member is [...] an lvalue reference to the
19814 // referenced function type if the entity is a reference to a function.
19815 // [...]
19816 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19817 !(isa<LambdaScopeInfo>(Val: CSI) &&
19818 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19819 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19820 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19821 DeclRefType.addConst();
19822 return true;
19823 }
19824 return false;
19825}
19826
19827// Only block literals, captured statements, and lambda expressions can
19828// capture; other scopes don't work.
19829static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19830 ValueDecl *Var,
19831 SourceLocation Loc,
19832 const bool Diagnose,
19833 Sema &S) {
19834 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19835 return getLambdaAwareParentOfDeclContext(DC);
19836
19837 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19838 if (Underlying) {
19839 if (Underlying->hasLocalStorage() && Diagnose)
19840 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19841 }
19842 return nullptr;
19843}
19844
19845// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19846// certain types of variables (unnamed, variably modified types etc.)
19847// so check for eligibility.
19848static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19849 SourceLocation Loc, const bool Diagnose,
19850 Sema &S) {
19851
19852 assert((isa<VarDecl, BindingDecl>(Var)) &&
19853 "Only variables and structured bindings can be captured");
19854
19855 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19856 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19857
19858 // Reject bindings referenced from a lambda or block that wraps an OpenMP
19859 // region.
19860 if ((IsLambda || IsBlock) && S.getLangOpts().OpenMP &&
19861 isa<DecompositionDecl>(Val: Var)) {
19862 if (Diagnose)
19863 S.Diag(Loc, DiagID: diag::err_omp_unsupported_on_binding) << 3;
19864 return false;
19865 }
19866
19867 // Lambdas are not allowed to capture unnamed variables
19868 // (e.g. anonymous unions).
19869 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19870 // assuming that's the intent.
19871 if (IsLambda && !Var->getDeclName()) {
19872 if (Diagnose) {
19873 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19874 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19875 }
19876 return false;
19877 }
19878
19879 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19880 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19881 if (Diagnose) {
19882 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19883 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19884 }
19885 return false;
19886 }
19887 // Prohibit structs with flexible array members too.
19888 // We cannot capture what is in the tail end of the struct.
19889 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19890 VTD && VTD->hasFlexibleArrayMember()) {
19891 if (Diagnose) {
19892 if (IsBlock)
19893 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19894 else
19895 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19896 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19897 }
19898 return false;
19899 }
19900 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19901 // Lambdas and captured statements are not allowed to capture __block
19902 // variables; they don't support the expected semantics.
19903 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19904 if (Diagnose) {
19905 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19906 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19907 }
19908 return false;
19909 }
19910 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19911 if (S.getLangOpts().OpenCL && IsBlock &&
19912 Var->getType()->isBlockPointerType()) {
19913 if (Diagnose)
19914 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19915 return false;
19916 }
19917
19918 if (auto *BD = dyn_cast<BindingDecl>(Val: Var)) {
19919 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19920 if (RSI->CapRegionKind == CR_OpenMP) {
19921 if (BD->getHoldingVar()) {
19922 if (Diagnose) {
19923 S.Diag(Loc, DiagID: diag::err_capture_tuple_binding_openmp) << Var;
19924 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19925 }
19926 return false;
19927 }
19928 if (Diagnose && S.getLangOpts().CPlusPlus) {
19929 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19930 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19931 }
19932 return true;
19933 }
19934 }
19935 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19936 if (Diagnose)
19937 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19938 return false;
19939 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19940 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19941 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19942 }
19943 }
19944
19945 return true;
19946}
19947
19948// Returns true if the capture by block was successful.
19949static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19950 SourceLocation Loc, const bool BuildAndDiagnose,
19951 QualType &CaptureType, QualType &DeclRefType,
19952 const bool Nested, Sema &S, bool Invalid) {
19953 bool ByRef = false;
19954
19955 // Blocks are not allowed to capture arrays, excepting OpenCL.
19956 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19957 // (decayed to pointers).
19958 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19959 if (BuildAndDiagnose) {
19960 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19961 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19962 Invalid = true;
19963 } else {
19964 return false;
19965 }
19966 }
19967
19968 // Forbid the block-capture of autoreleasing variables.
19969 if (!Invalid &&
19970 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19971 if (BuildAndDiagnose) {
19972 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19973 << /*block*/ 0;
19974 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19975 Invalid = true;
19976 } else {
19977 return false;
19978 }
19979 }
19980
19981 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19982 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19983 QualType PointeeTy = PT->getPointeeType();
19984
19985 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19986 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19987 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19988 if (BuildAndDiagnose) {
19989 SourceLocation VarLoc = Var->getLocation();
19990 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19991 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19992 }
19993 }
19994 }
19995
19996 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19997 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19998 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19999 // Block capture by reference does not change the capture or
20000 // declaration reference types.
20001 ByRef = true;
20002 } else {
20003 // Block capture by copy introduces 'const'.
20004 CaptureType = CaptureType.getNonReferenceType().withConst();
20005 DeclRefType = CaptureType;
20006 }
20007
20008 // Actually capture the variable.
20009 if (BuildAndDiagnose)
20010 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
20011 CaptureType, Invalid);
20012
20013 return !Invalid;
20014}
20015
20016/// Capture the given variable in the captured region.
20017static bool captureInCapturedRegion(
20018 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
20019 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
20020 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
20021 Sema &S, bool Invalid) {
20022 // By default, capture variables by reference.
20023 bool ByRef = true;
20024 bool IsBindingDecl = isa<BindingDecl>(Val: Var);
20025 ValueDecl *DSAVar = Var;
20026 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
20027 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
20028 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
20029 // Using an LValue reference type is consistent with Lambdas (see below).
20030 if (VarDecl *VD = S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
20031 Var = VD; // Capture the DecompositionDecl.
20032 bool HasConst = DeclRefType.isConstQualified();
20033 // Note: DeclRefType should remain the BindingDecl's type (e.g., int),
20034 // not the DecompositionDecl's type (e.g., Point). The variable being
20035 // captured is the DecompositionDecl, but expressions still reference
20036 // the individual binding's type.
20037 DeclRefType = DeclRefType.getUnqualifiedType();
20038 // Don't lose diagnostics about assignments to const.
20039 if (HasConst)
20040 DeclRefType.addConst();
20041 }
20042 // Do not capture firstprivates in tasks. For bindings the DSA is on the
20043 // binding, not on the DecompositionDecl; the task firstprivate path still
20044 // needs the DecompositionDecl capture, so skip only private.
20045 OpenMPClauseKind PrivateKind = S.OpenMP().isOpenMPPrivateDecl(
20046 D: IsBindingDecl ? DSAVar : Var, Level: RSI->OpenMPLevel,
20047 CapLevel: RSI->OpenMPCaptureLevel);
20048 if (IsBindingDecl ? PrivateKind == OMPC_private
20049 : PrivateKind != OMPC_unknown)
20050 return true;
20051 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: DSAVar, Level: RSI->OpenMPLevel,
20052 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
20053 // Bindings share the DecompositionDecl storage; a second capture with
20054 // a different capture kind is not representable.
20055 if (BuildAndDiagnose && IsBindingDecl) {
20056 unsigned Idx = RSI->CaptureMap.lookup(Val: Var);
20057 if (Idx != 0 && RSI->Captures[Idx - 1].isReferenceCapture() != ByRef) {
20058 S.Diag(Loc,
20059 DiagID: diag::err_omp_decomposition_bindings_different_capture_kinds)
20060 << DSAVar;
20061 return false;
20062 }
20063 }
20064 }
20065
20066 if (ByRef)
20067 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
20068 else
20069 CaptureType = DeclRefType;
20070
20071 // Actually capture the variable.
20072 if (BuildAndDiagnose)
20073 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
20074 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
20075
20076 if (BuildAndDiagnose && IsBindingDecl)
20077 // Key the binding to its own capture entry so repeated uses hit the
20078 // already-captured path.
20079 RSI->CaptureMap[DSAVar] = RSI->Captures.size();
20080
20081 return !Invalid;
20082}
20083
20084/// Capture the given variable in the lambda.
20085static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
20086 SourceLocation Loc, const bool BuildAndDiagnose,
20087 QualType &CaptureType, QualType &DeclRefType,
20088 const bool RefersToCapturedVariable,
20089 const TryCaptureKind Kind,
20090 SourceLocation EllipsisLoc, const bool IsTopScope,
20091 Sema &S, bool Invalid) {
20092 // Determine whether we are capturing by reference or by value.
20093 bool ByRef = false;
20094 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
20095 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
20096 } else {
20097 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
20098 }
20099
20100 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
20101 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
20102 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
20103 Invalid = true;
20104 }
20105
20106 // Compute the type of the field that will capture this variable.
20107 if (ByRef) {
20108 // C++11 [expr.prim.lambda]p15:
20109 // An entity is captured by reference if it is implicitly or
20110 // explicitly captured but not captured by copy. It is
20111 // unspecified whether additional unnamed non-static data
20112 // members are declared in the closure type for entities
20113 // captured by reference.
20114 //
20115 // FIXME: It is not clear whether we want to build an lvalue reference
20116 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
20117 // to do the former, while EDG does the latter. Core issue 1249 will
20118 // clarify, but for now we follow GCC because it's a more permissive and
20119 // easily defensible position.
20120 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
20121 } else {
20122 // C++11 [expr.prim.lambda]p14:
20123 // For each entity captured by copy, an unnamed non-static
20124 // data member is declared in the closure type. The
20125 // declaration order of these members is unspecified. The type
20126 // of such a data member is the type of the corresponding
20127 // captured entity if the entity is not a reference to an
20128 // object, or the referenced type otherwise. [Note: If the
20129 // captured entity is a reference to a function, the
20130 // corresponding data member is also a reference to a
20131 // function. - end note ]
20132 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
20133 if (!RefType->getPointeeType()->isFunctionType())
20134 CaptureType = RefType->getPointeeType();
20135 }
20136
20137 // Forbid the lambda copy-capture of autoreleasing variables.
20138 if (!Invalid &&
20139 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
20140 if (BuildAndDiagnose) {
20141 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
20142 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
20143 << Var->getDeclName();
20144 Invalid = true;
20145 } else {
20146 return false;
20147 }
20148 }
20149
20150 // Make sure that by-copy captures are of a complete and non-abstract type.
20151 if (!Invalid && BuildAndDiagnose) {
20152 if (!CaptureType->isDependentType() &&
20153 S.RequireCompleteSizedType(
20154 Loc, T: CaptureType,
20155 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
20156 Args: Var->getDeclName()))
20157 Invalid = true;
20158 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
20159 DiagID: diag::err_capture_of_abstract_type))
20160 Invalid = true;
20161 }
20162 }
20163
20164 // Compute the type of a reference to this captured variable.
20165 if (ByRef)
20166 DeclRefType = CaptureType.getNonReferenceType();
20167 else {
20168 // C++ [expr.prim.lambda]p5:
20169 // The closure type for a lambda-expression has a public inline
20170 // function call operator [...]. This function call operator is
20171 // declared const (9.3.1) if and only if the lambda-expression's
20172 // parameter-declaration-clause is not followed by mutable.
20173 DeclRefType = CaptureType.getNonReferenceType();
20174 bool Const = LSI->lambdaCaptureShouldBeConst();
20175 // C++ [expr.prim.lambda]p10:
20176 // The type of such a data member is [...] an lvalue reference to the
20177 // referenced function type if the entity is a reference to a function.
20178 // [...]
20179 if (Const && !CaptureType->isReferenceType() &&
20180 !DeclRefType->isFunctionType())
20181 DeclRefType.addConst();
20182 }
20183
20184 // Add the capture.
20185 if (BuildAndDiagnose)
20186 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
20187 Loc, EllipsisLoc, CaptureType, Invalid);
20188
20189 return !Invalid;
20190}
20191
20192static bool canCaptureVariableByCopy(ValueDecl *Var,
20193 const ASTContext &Context) {
20194 // Offer a Copy fix even if the type is dependent.
20195 if (Var->getType()->isDependentType())
20196 return true;
20197 QualType T = Var->getType().getNonReferenceType();
20198 if (T.isTriviallyCopyableType(Context))
20199 return true;
20200 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
20201
20202 if (!(RD = RD->getDefinition()))
20203 return false;
20204 if (RD->hasSimpleCopyConstructor())
20205 return true;
20206 if (RD->hasUserDeclaredCopyConstructor())
20207 for (CXXConstructorDecl *Ctor : RD->ctors())
20208 if (Ctor->isCopyConstructor())
20209 return !Ctor->isDeleted();
20210 }
20211 return false;
20212}
20213
20214/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
20215/// default capture. Fixes may be omitted if they aren't allowed by the
20216/// standard, for example we can't emit a default copy capture fix-it if we
20217/// already explicitly copy capture capture another variable.
20218static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
20219 ValueDecl *Var) {
20220 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
20221 // Don't offer Capture by copy of default capture by copy fixes if Var is
20222 // known not to be copy constructible.
20223 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
20224
20225 SmallString<32> FixBuffer;
20226 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
20227 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
20228 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
20229 if (ShouldOfferCopyFix) {
20230 // Offer fixes to insert an explicit capture for the variable.
20231 // [] -> [VarName]
20232 // [OtherCapture] -> [OtherCapture, VarName]
20233 FixBuffer.assign(Refs: {Separator, Var->getName()});
20234 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
20235 << Var << /*value*/ 0
20236 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
20237 }
20238 // As above but capture by reference.
20239 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
20240 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
20241 << Var << /*reference*/ 1
20242 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
20243 }
20244
20245 // Only try to offer default capture if there are no captures excluding this
20246 // and init captures.
20247 // [this]: OK.
20248 // [X = Y]: OK.
20249 // [&A, &B]: Don't offer.
20250 // [A, B]: Don't offer.
20251 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
20252 return !C.isThisCapture() && !C.isInitCapture();
20253 }))
20254 return;
20255
20256 // The default capture specifiers, '=' or '&', must appear first in the
20257 // capture body.
20258 SourceLocation DefaultInsertLoc =
20259 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
20260
20261 if (ShouldOfferCopyFix) {
20262 bool CanDefaultCopyCapture = true;
20263 // [=, *this] OK since c++17
20264 // [=, this] OK since c++20
20265 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20266 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20267 ? LSI->getCXXThisCapture().isCopyCapture()
20268 : false;
20269 // We can't use default capture by copy if any captures already specified
20270 // capture by copy.
20271 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20272 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20273 })) {
20274 FixBuffer.assign(Refs: {"=", Separator});
20275 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20276 << /*value*/ 0
20277 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20278 }
20279 }
20280
20281 // We can't use default capture by reference if any captures already specified
20282 // capture by reference.
20283 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20284 return !C.isInitCapture() && C.isReferenceCapture() &&
20285 !C.isThisCapture();
20286 })) {
20287 FixBuffer.assign(Refs: {"&", Separator});
20288 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20289 << /*reference*/ 1
20290 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20291 }
20292}
20293
20294bool Sema::tryCaptureVariable(
20295 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20296 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20297 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20298 // An init-capture is notionally from the context surrounding its
20299 // declaration, but its parent DC is the lambda class.
20300 DeclContext *VarDC =
20301 Var->getDeclContext()->getEnclosingNonExpansionStatementContext();
20302 DeclContext *DC = CurContext;
20303
20304 // Skip past RequiresExprBodys because they don't constitute function scopes.
20305 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20306 DC = DC->getParent();
20307
20308 // tryCaptureVariable is called every time a DeclRef is formed,
20309 // it can therefore have non-negigible impact on performances.
20310 // For local variables and when there is no capturing scope,
20311 // we can bailout early.
20312 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20313 return true;
20314
20315 // Exception: Function parameters are not tied to the function's DeclContext
20316 // until we enter the function definition. Capturing them anyway would result
20317 // in an out-of-bounds error while traversing DC and its parents.
20318 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
20319 return true;
20320
20321 const auto *VD = dyn_cast<VarDecl>(Val: Var);
20322 if (VD) {
20323 if (VD->isInitCapture())
20324 VarDC = VarDC->getParent();
20325 } else {
20326 VD = Var->getPotentiallyDecomposedVarDecl();
20327 }
20328 assert(VD && "Cannot capture a null variable");
20329
20330 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20331 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20332 // We need to sync up the Declaration Context with the
20333 // FunctionScopeIndexToStopAt
20334 if (FunctionScopeIndexToStopAt) {
20335 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20336 unsigned FSIndex = FunctionScopes.size() - 1;
20337 // When we're parsing the lambda parameter list, the current DeclContext is
20338 // NOT the lambda but its parent. So move away the current LSI before
20339 // aligning DC and FunctionScopeIndexToStopAt.
20340 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
20341 FSIndex && LSI && !LSI->AfterParameterList)
20342 --FSIndex;
20343 assert(MaxFunctionScopesIndex <= FSIndex &&
20344 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20345 "FunctionScopes.");
20346 while (FSIndex != MaxFunctionScopesIndex) {
20347 DC = getLambdaAwareParentOfDeclContext(DC);
20348 --FSIndex;
20349 }
20350 }
20351
20352 // Capture global variables if it is required to use private copy of this
20353 // variable.
20354 bool IsGlobal = !VD->hasLocalStorage();
20355 if (IsGlobal && !(LangOpts.OpenMP &&
20356 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
20357 StopAt: MaxFunctionScopesIndex)))
20358 return true;
20359
20360 if (isa<VarDecl>(Val: Var))
20361 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
20362
20363 // Walk up the stack to determine whether we can capture the variable,
20364 // performing the "simple" checks that don't depend on type. We stop when
20365 // we've either hit the declared scope of the variable or find an existing
20366 // capture of that variable. We start from the innermost capturing-entity
20367 // (the DC) and ensure that all intervening capturing-entities
20368 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20369 // declcontext can either capture the variable or have already captured
20370 // the variable.
20371 CaptureType = Var->getType();
20372 DeclRefType = CaptureType.getNonReferenceType();
20373 bool Nested = false;
20374 bool Explicit = (Kind != TryCaptureKind::Implicit);
20375 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20376 do {
20377
20378 LambdaScopeInfo *LSI = nullptr;
20379 if (!FunctionScopes.empty())
20380 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20381 Val: FunctionScopes[FunctionScopesIndex]);
20382
20383 bool IsInScopeDeclarationContext =
20384 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20385
20386 if (LSI && !LSI->AfterParameterList) {
20387 // This allows capturing parameters from a default value which does not
20388 // seems correct
20389 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
20390 return true;
20391 }
20392 // If the variable is declared in the current context, there is no need to
20393 // capture it.
20394 if (IsInScopeDeclarationContext &&
20395 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20396 return true;
20397
20398 // Only block literals, captured statements, and lambda expressions can
20399 // capture; other scopes don't work.
20400 DeclContext *ParentDC =
20401 !IsInScopeDeclarationContext
20402 ? DC->getParent()
20403 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
20404 Diagnose: BuildAndDiagnose, S&: *this);
20405 // We need to check for the parent *first* because, if we *have*
20406 // private-captured a global variable, we need to recursively capture it in
20407 // intermediate blocks, lambdas, etc.
20408 if (!ParentDC) {
20409 if (IsGlobal) {
20410 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20411 break;
20412 }
20413 return true;
20414 }
20415
20416 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20417 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
20418
20419 // Check whether we've already captured it.
20420 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
20421 DeclRefType)) {
20422 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
20423 break;
20424 }
20425
20426 // When evaluating some attributes (like enable_if) we might refer to a
20427 // function parameter appertaining to the same declaration as that
20428 // attribute.
20429 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
20430 Parm && Parm->getDeclContext() == DC)
20431 return true;
20432
20433 // If we are instantiating a generic lambda call operator body,
20434 // we do not want to capture new variables. What was captured
20435 // during either a lambdas transformation or initial parsing
20436 // should be used.
20437 if (isGenericLambdaCallOperatorSpecialization(DC)) {
20438 if (BuildAndDiagnose) {
20439 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20440 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
20441 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20442 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20443 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20444 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20445 } else
20446 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
20447 }
20448 return true;
20449 }
20450
20451 // Try to capture variable-length arrays types.
20452 if (Var->getType()->isVariablyModifiedType()) {
20453 // We're going to walk down into the type and look for VLA
20454 // expressions.
20455 QualType QTy = Var->getType();
20456 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20457 QTy = PVD->getOriginalType();
20458 captureVariablyModifiedType(Context, T: QTy, CSI);
20459 }
20460
20461 if (getLangOpts().OpenMP) {
20462 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20463 // OpenMP private variables should not be captured in outer scope, so
20464 // just break here. Similarly, global variables that are captured in a
20465 // target region should not be captured outside the scope of the region.
20466 if (RSI->CapRegionKind == CR_OpenMP) {
20467 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20468 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
20469 // If the variable is private (i.e. not captured) and has variably
20470 // modified type, we still need to capture the type for correct
20471 // codegen in all regions, associated with the construct. Currently,
20472 // it is captured in the innermost captured region only.
20473 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20474 Var->getType()->isVariablyModifiedType()) {
20475 QualType QTy = Var->getType();
20476 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20477 QTy = PVD->getOriginalType();
20478 for (int I = 1,
20479 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
20480 I < E; ++I) {
20481 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20482 Val: FunctionScopes[FunctionScopesIndex - I]);
20483 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20484 "Wrong number of captured regions associated with the "
20485 "OpenMP construct.");
20486 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
20487 }
20488 }
20489 bool IsTargetCap =
20490 IsOpenMPPrivateDecl != OMPC_private &&
20491 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
20492 CaptureLevel: RSI->OpenMPCaptureLevel);
20493 // Do not capture global if it is not privatized in outer regions.
20494 bool IsGlobalCap =
20495 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20496 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
20497
20498 // When we detect target captures we are looking from inside the
20499 // target region, therefore we need to propagate the capture from the
20500 // enclosing region. Therefore, the capture is not initially nested.
20501 if (IsTargetCap)
20502 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20503 Level: RSI->OpenMPLevel);
20504
20505 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20506 (IsGlobal && !IsGlobalCap)) {
20507 Nested = !IsTargetCap;
20508 bool HasConst = DeclRefType.isConstQualified();
20509 DeclRefType = DeclRefType.getUnqualifiedType();
20510 // Don't lose diagnostics about assignments to const.
20511 if (HasConst)
20512 DeclRefType.addConst();
20513 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20514 break;
20515 }
20516 }
20517 }
20518 }
20519 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20520 // No capture-default, and this is not an explicit capture
20521 // so cannot capture this variable.
20522 if (BuildAndDiagnose) {
20523 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20524 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20525 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20526 if (LSI->Lambda) {
20527 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20528 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20529 }
20530 // FIXME: If we error out because an outer lambda can not implicitly
20531 // capture a variable that an inner lambda explicitly captures, we
20532 // should have the inner lambda do the explicit capture - because
20533 // it makes for cleaner diagnostics later. This would purely be done
20534 // so that the diagnostic does not misleadingly claim that a variable
20535 // can not be captured by a lambda implicitly even though it is captured
20536 // explicitly. Suggestion:
20537 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20538 // at the function head
20539 // - cache the StartingDeclContext - this must be a lambda
20540 // - captureInLambda in the innermost lambda the variable.
20541 }
20542 return true;
20543 }
20544 Explicit = false;
20545 FunctionScopesIndex--;
20546 if (IsInScopeDeclarationContext)
20547 DC = ParentDC;
20548 } while (!VarDC->Equals(DC));
20549
20550 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20551 // computing the type of the capture at each step, checking type-specific
20552 // requirements, and adding captures if requested.
20553 // If the variable had already been captured previously, we start capturing
20554 // at the lambda nested within that one.
20555 bool Invalid = false;
20556 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20557 ++I) {
20558 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20559
20560 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20561 // certain types of variables (unnamed, variably modified types etc.)
20562 // so check for eligibility.
20563 if (!Invalid)
20564 Invalid =
20565 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20566
20567 // After encountering an error, if we're actually supposed to capture, keep
20568 // capturing in nested contexts to suppress any follow-on diagnostics.
20569 if (Invalid && !BuildAndDiagnose)
20570 return true;
20571
20572 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20573 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20574 DeclRefType, Nested, S&: *this, Invalid);
20575 Nested = true;
20576 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20577 Invalid = !captureInCapturedRegion(
20578 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20579 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20580 Nested = true;
20581 } else {
20582 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20583 Invalid =
20584 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20585 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20586 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20587 Nested = true;
20588 }
20589
20590 if (Invalid && !BuildAndDiagnose)
20591 return true;
20592 }
20593 return Invalid;
20594}
20595
20596bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20597 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20598 QualType CaptureType;
20599 QualType DeclRefType;
20600 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20601 /*BuildAndDiagnose=*/true, CaptureType,
20602 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20603}
20604
20605bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20606 QualType CaptureType;
20607 QualType DeclRefType;
20608 return !tryCaptureVariable(
20609 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20610 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20611}
20612
20613QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20614 assert(Var && "Null value cannot be captured");
20615
20616 QualType CaptureType;
20617 QualType DeclRefType;
20618
20619 // Determine whether we can capture this variable.
20620 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20621 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20622 FunctionScopeIndexToStopAt: nullptr))
20623 return QualType();
20624
20625 return DeclRefType;
20626}
20627
20628namespace {
20629// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20630// The produced TemplateArgumentListInfo* points to data stored within this
20631// object, so should only be used in contexts where the pointer will not be
20632// used after the CopiedTemplateArgs object is destroyed.
20633class CopiedTemplateArgs {
20634 bool HasArgs;
20635 TemplateArgumentListInfo TemplateArgStorage;
20636public:
20637 template<typename RefExpr>
20638 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20639 if (HasArgs)
20640 E->copyTemplateArgumentsInto(TemplateArgStorage);
20641 }
20642 operator TemplateArgumentListInfo*()
20643#ifdef __has_cpp_attribute
20644#if __has_cpp_attribute(clang::lifetimebound)
20645 [[clang::lifetimebound]]
20646#endif
20647#endif
20648 {
20649 return HasArgs ? &TemplateArgStorage : nullptr;
20650 }
20651};
20652}
20653
20654/// Walk the set of potential results of an expression and mark them all as
20655/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20656///
20657/// \return A new expression if we found any potential results, ExprEmpty() if
20658/// not, and ExprError() if we diagnosed an error.
20659static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20660 NonOdrUseReason NOUR) {
20661 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20662 // an object that satisfies the requirements for appearing in a
20663 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20664 // is immediately applied." This function handles the lvalue-to-rvalue
20665 // conversion part.
20666 //
20667 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20668 // transform it into the relevant kind of non-odr-use node and rebuild the
20669 // tree of nodes leading to it.
20670 //
20671 // This is a mini-TreeTransform that only transforms a restricted subset of
20672 // nodes (and only certain operands of them).
20673
20674 // Rebuild a subexpression.
20675 auto Rebuild = [&](Expr *Sub) {
20676 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20677 };
20678
20679 // Check whether a potential result satisfies the requirements of NOUR.
20680 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20681 // Any entity other than a VarDecl is always odr-used whenever it's named
20682 // in a potentially-evaluated expression.
20683 auto *VD = dyn_cast<VarDecl>(Val: D);
20684 if (!VD)
20685 return true;
20686
20687 // C++2a [basic.def.odr]p4:
20688 // A variable x whose name appears as a potentially-evalauted expression
20689 // e is odr-used by e unless
20690 // -- x is a reference that is usable in constant expressions, or
20691 // -- x is a variable of non-reference type that is usable in constant
20692 // expressions and has no mutable subobjects, and e is an element of
20693 // the set of potential results of an expression of
20694 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20695 // conversion is applied, or
20696 // -- x is a variable of non-reference type, and e is an element of the
20697 // set of potential results of a discarded-value expression to which
20698 // the lvalue-to-rvalue conversion is not applied
20699 //
20700 // We check the first bullet and the "potentially-evaluated" condition in
20701 // BuildDeclRefExpr. We check the type requirements in the second bullet
20702 // in CheckLValueToRValueConversionOperand below.
20703 switch (NOUR) {
20704 case NOUR_None:
20705 case NOUR_Unevaluated:
20706 llvm_unreachable("unexpected non-odr-use-reason");
20707
20708 case NOUR_Constant:
20709 // Constant references were handled when they were built.
20710 if (VD->getType()->isReferenceType())
20711 return true;
20712 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20713 if (RD->hasDefinition() && RD->hasMutableFields())
20714 return true;
20715 if (!VD->isUsableInConstantExpressions(C: S.Context))
20716 return true;
20717 break;
20718
20719 case NOUR_Discarded:
20720 if (VD->getType()->isReferenceType())
20721 return true;
20722 break;
20723 }
20724 return false;
20725 };
20726
20727 // Check whether this expression may be odr-used in CUDA/HIP.
20728 auto MaybeCUDAODRUsed = [&]() -> bool {
20729 if (!S.LangOpts.CUDA)
20730 return false;
20731 LambdaScopeInfo *LSI = S.getCurLambda();
20732 if (!LSI)
20733 return false;
20734 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20735 if (!DRE)
20736 return false;
20737 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20738 if (!VD)
20739 return false;
20740 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20741 };
20742
20743 // Mark that this expression does not constitute an odr-use.
20744 auto MarkNotOdrUsed = [&] {
20745 if (!MaybeCUDAODRUsed()) {
20746 S.MaybeODRUseExprs.remove(X: E);
20747 if (LambdaScopeInfo *LSI = S.getCurLambda())
20748 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20749 }
20750 };
20751
20752 // C++2a [basic.def.odr]p2:
20753 // The set of potential results of an expression e is defined as follows:
20754 switch (E->getStmtClass()) {
20755 // -- If e is an id-expression, ...
20756 case Expr::DeclRefExprClass: {
20757 auto *DRE = cast<DeclRefExpr>(Val: E);
20758 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20759 break;
20760
20761 // Rebuild as a non-odr-use DeclRefExpr.
20762 MarkNotOdrUsed();
20763 return DeclRefExpr::Create(
20764 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20765 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20766 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20767 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20768 }
20769
20770 case Expr::FunctionParmPackExprClass: {
20771 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20772 // If any of the declarations in the pack is odr-used, then the expression
20773 // as a whole constitutes an odr-use.
20774 for (ValueDecl *D : *FPPE)
20775 if (IsPotentialResultOdrUsed(D))
20776 return ExprEmpty();
20777
20778 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20779 // nothing cares about whether we marked this as an odr-use, but it might
20780 // be useful for non-compiler tools.
20781 MarkNotOdrUsed();
20782 break;
20783 }
20784
20785 // -- If e is a subscripting operation with an array operand...
20786 case Expr::ArraySubscriptExprClass: {
20787 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20788 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20789 if (!OldBase->getType()->isArrayType())
20790 break;
20791 ExprResult Base = Rebuild(OldBase);
20792 if (!Base.isUsable())
20793 return Base;
20794 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20795 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20796 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20797 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20798 rbLoc: ASE->getRBracketLoc());
20799 }
20800
20801 case Expr::MemberExprClass: {
20802 auto *ME = cast<MemberExpr>(Val: E);
20803 // -- If e is a class member access expression [...] naming a non-static
20804 // data member...
20805 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20806 ExprResult Base = Rebuild(ME->getBase());
20807 if (!Base.isUsable())
20808 return Base;
20809 return MemberExpr::Create(
20810 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20811 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20812 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20813 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20814 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20815 }
20816
20817 if (ME->getMemberDecl()->isCXXInstanceMember())
20818 break;
20819
20820 // -- If e is a class member access expression naming a static data member,
20821 // ...
20822 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20823 break;
20824
20825 // Rebuild as a non-odr-use MemberExpr.
20826 MarkNotOdrUsed();
20827 return MemberExpr::Create(
20828 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20829 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20830 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20831 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20832 }
20833
20834 case Expr::BinaryOperatorClass: {
20835 auto *BO = cast<BinaryOperator>(Val: E);
20836 Expr *LHS = BO->getLHS();
20837 Expr *RHS = BO->getRHS();
20838 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20839 if (BO->getOpcode() == BO_PtrMemD) {
20840 ExprResult Sub = Rebuild(LHS);
20841 if (!Sub.isUsable())
20842 return Sub;
20843 BO->setLHS(Sub.get());
20844 // -- If e is a comma expression, ...
20845 } else if (BO->getOpcode() == BO_Comma) {
20846 ExprResult Sub = Rebuild(RHS);
20847 if (!Sub.isUsable())
20848 return Sub;
20849 BO->setRHS(Sub.get());
20850 } else {
20851 break;
20852 }
20853 return ExprResult(BO);
20854 }
20855
20856 // -- If e has the form (e1)...
20857 case Expr::ParenExprClass: {
20858 auto *PE = cast<ParenExpr>(Val: E);
20859 ExprResult Sub = Rebuild(PE->getSubExpr());
20860 if (!Sub.isUsable())
20861 return Sub;
20862 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20863 }
20864
20865 // -- If e is a glvalue conditional expression, ...
20866 // We don't apply this to a binary conditional operator. FIXME: Should we?
20867 case Expr::ConditionalOperatorClass: {
20868 auto *CO = cast<ConditionalOperator>(Val: E);
20869 ExprResult LHS = Rebuild(CO->getLHS());
20870 if (LHS.isInvalid())
20871 return ExprError();
20872 ExprResult RHS = Rebuild(CO->getRHS());
20873 if (RHS.isInvalid())
20874 return ExprError();
20875 if (!LHS.isUsable() && !RHS.isUsable())
20876 return ExprEmpty();
20877 if (!LHS.isUsable())
20878 LHS = CO->getLHS();
20879 if (!RHS.isUsable())
20880 RHS = CO->getRHS();
20881 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20882 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20883 }
20884
20885 // [Clang extension]
20886 // -- If e has the form __extension__ e1...
20887 case Expr::UnaryOperatorClass: {
20888 auto *UO = cast<UnaryOperator>(Val: E);
20889 if (UO->getOpcode() != UO_Extension)
20890 break;
20891 ExprResult Sub = Rebuild(UO->getSubExpr());
20892 if (!Sub.isUsable())
20893 return Sub;
20894 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20895 Input: Sub.get());
20896 }
20897
20898 // [Clang extension]
20899 // -- If e has the form _Generic(...), the set of potential results is the
20900 // union of the sets of potential results of the associated expressions.
20901 case Expr::GenericSelectionExprClass: {
20902 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20903
20904 SmallVector<Expr *, 4> AssocExprs;
20905 bool AnyChanged = false;
20906 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20907 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20908 if (AssocExpr.isInvalid())
20909 return ExprError();
20910 if (AssocExpr.isUsable()) {
20911 AssocExprs.push_back(Elt: AssocExpr.get());
20912 AnyChanged = true;
20913 } else {
20914 AssocExprs.push_back(Elt: OrigAssocExpr);
20915 }
20916 }
20917
20918 void *ExOrTy = nullptr;
20919 bool IsExpr = GSE->isExprPredicate();
20920 if (IsExpr)
20921 ExOrTy = GSE->getControllingExpr();
20922 else
20923 ExOrTy = GSE->getControllingType();
20924 return AnyChanged ? S.CreateGenericSelectionExpr(
20925 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20926 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20927 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20928 : ExprEmpty();
20929 }
20930
20931 // [Clang extension]
20932 // -- If e has the form __builtin_choose_expr(...), the set of potential
20933 // results is the union of the sets of potential results of the
20934 // second and third subexpressions.
20935 case Expr::ChooseExprClass: {
20936 auto *CE = cast<ChooseExpr>(Val: E);
20937
20938 ExprResult LHS = Rebuild(CE->getLHS());
20939 if (LHS.isInvalid())
20940 return ExprError();
20941
20942 ExprResult RHS = Rebuild(CE->getLHS());
20943 if (RHS.isInvalid())
20944 return ExprError();
20945
20946 if (!LHS.get() && !RHS.get())
20947 return ExprEmpty();
20948 if (!LHS.isUsable())
20949 LHS = CE->getLHS();
20950 if (!RHS.isUsable())
20951 RHS = CE->getRHS();
20952
20953 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20954 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20955 }
20956
20957 // Step through non-syntactic nodes.
20958 case Expr::ConstantExprClass: {
20959 auto *CE = cast<ConstantExpr>(Val: E);
20960 ExprResult Sub = Rebuild(CE->getSubExpr());
20961 if (!Sub.isUsable())
20962 return Sub;
20963 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20964 }
20965
20966 // We could mostly rely on the recursive rebuilding to rebuild implicit
20967 // casts, but not at the top level, so rebuild them here.
20968 case Expr::ImplicitCastExprClass: {
20969 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20970 // Only step through the narrow set of cast kinds we expect to encounter.
20971 // Anything else suggests we've left the region in which potential results
20972 // can be found.
20973 switch (ICE->getCastKind()) {
20974 case CK_NoOp:
20975 case CK_DerivedToBase:
20976 case CK_UncheckedDerivedToBase: {
20977 ExprResult Sub = Rebuild(ICE->getSubExpr());
20978 if (!Sub.isUsable())
20979 return Sub;
20980 CXXCastPath Path(ICE->path());
20981 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20982 VK: ICE->getValueKind(), BasePath: &Path);
20983 }
20984
20985 default:
20986 break;
20987 }
20988 break;
20989 }
20990
20991 default:
20992 break;
20993 }
20994
20995 // Can't traverse through this node. Nothing to do.
20996 return ExprEmpty();
20997}
20998
20999ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
21000 // Check whether the operand is or contains an object of non-trivial C union
21001 // type.
21002 if (E->getType().isVolatileQualified() &&
21003 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
21004 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
21005 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
21006 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
21007 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
21008
21009 // C++2a [basic.def.odr]p4:
21010 // [...] an expression of non-volatile-qualified non-class type to which
21011 // the lvalue-to-rvalue conversion is applied [...]
21012 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
21013 return E;
21014
21015 ExprResult Result =
21016 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
21017 if (Result.isInvalid())
21018 return ExprError();
21019 return Result.get() ? Result : E;
21020}
21021
21022ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
21023 if (!Res.isUsable())
21024 return Res;
21025
21026 // If a constant-expression is a reference to a variable where we delay
21027 // deciding whether it is an odr-use, just assume we will apply the
21028 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
21029 // (a non-type template argument), we have special handling anyway.
21030 return CheckLValueToRValueConversionOperand(E: Res.get());
21031}
21032
21033void Sema::CleanupVarDeclMarking() {
21034 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
21035 // call.
21036 MaybeODRUseExprSet LocalMaybeODRUseExprs;
21037 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
21038
21039 for (Expr *E : LocalMaybeODRUseExprs) {
21040 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
21041 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
21042 Loc: DRE->getLocation(), SemaRef&: *this);
21043 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
21044 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
21045 SemaRef&: *this);
21046 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
21047 for (ValueDecl *VD : *FP)
21048 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
21049 } else {
21050 llvm_unreachable("Unexpected expression");
21051 }
21052 }
21053
21054 assert(MaybeODRUseExprs.empty() &&
21055 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
21056}
21057
21058static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
21059 ValueDecl *Var, Expr *E) {
21060 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
21061 if (!VD)
21062 return;
21063
21064 const bool RefersToEnclosingScope =
21065 (SemaRef.CurContext != VD->getDeclContext() &&
21066 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
21067 if (RefersToEnclosingScope) {
21068 LambdaScopeInfo *const LSI =
21069 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
21070 if (LSI && (!LSI->CallOperator ||
21071 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
21072 // If a variable could potentially be odr-used, defer marking it so
21073 // until we finish analyzing the full expression for any
21074 // lvalue-to-rvalue
21075 // or discarded value conversions that would obviate odr-use.
21076 // Add it to the list of potential captures that will be analyzed
21077 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
21078 // unless the variable is a reference that was initialized by a constant
21079 // expression (this will never need to be captured or odr-used).
21080 //
21081 // FIXME: We can simplify this a lot after implementing P0588R1.
21082 assert(E && "Capture variable should be used in an expression.");
21083 if (!Var->getType()->isReferenceType() ||
21084 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
21085 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
21086 }
21087 }
21088}
21089
21090static void DoMarkVarDeclReferenced(
21091 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
21092 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21093 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
21094 isa<FunctionParmPackExpr>(E)) &&
21095 "Invalid Expr argument to DoMarkVarDeclReferenced");
21096 Var->setReferenced();
21097
21098 if (Var->isInvalidDecl())
21099 return;
21100
21101 auto *MSI = Var->getMemberSpecializationInfo();
21102 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
21103 : Var->getTemplateSpecializationKind();
21104
21105 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21106 bool UsableInConstantExpr =
21107 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
21108
21109 // Only track variables with internal linkage or local scope.
21110 // Use canonical decl so in-class declarations and out-of-class definitions
21111 // of static data members in anonymous namespaces are tracked as a single
21112 // entry.
21113 const VarDecl *CanonVar = Var->getCanonicalDecl();
21114 if ((CanonVar->isLocalVarDeclOrParm() ||
21115 CanonVar->isInternalLinkageFileVar()) &&
21116 !CanonVar->hasExternalStorage()) {
21117 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
21118 }
21119
21120 // C++20 [expr.const]p12:
21121 // A variable [...] is needed for constant evaluation if it is [...] a
21122 // variable whose name appears as a potentially constant evaluated
21123 // expression that is either a contexpr variable or is of non-volatile
21124 // const-qualified integral type or of reference type
21125 bool NeededForConstantEvaluation =
21126 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
21127
21128 bool NeedDefinition =
21129 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
21130 (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());
21131
21132 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
21133 "Can't instantiate a partial template specialization.");
21134
21135 // If this might be a member specialization of a static data member, check
21136 // the specialization is visible. We already did the checks for variable
21137 // template specializations when we created them.
21138 if (NeedDefinition && TSK != TSK_Undeclared &&
21139 !isa<VarTemplateSpecializationDecl>(Val: Var))
21140 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
21141
21142 // Perform implicit instantiation of static data members, static data member
21143 // templates of class templates, and variable template specializations. Delay
21144 // instantiations of variable templates, except for those that could be used
21145 // in a constant expression.
21146 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
21147 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
21148 // instantiation declaration if a variable is usable in a constant
21149 // expression (among other cases).
21150 bool TryInstantiating =
21151 TSK == TSK_ImplicitInstantiation ||
21152 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
21153
21154 if (TryInstantiating) {
21155 SourceLocation PointOfInstantiation =
21156 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
21157 bool FirstInstantiation = PointOfInstantiation.isInvalid();
21158 if (FirstInstantiation) {
21159 PointOfInstantiation = Loc;
21160 if (MSI)
21161 MSI->setPointOfInstantiation(PointOfInstantiation);
21162 // FIXME: Notify listener.
21163 else
21164 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
21165 }
21166
21167 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
21168 // Do not defer instantiations of variables that could be used in a
21169 // constant expression.
21170 // The type deduction also needs a complete initializer.
21171 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
21172 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
21173 });
21174
21175 // The size of an incomplete array type can be updated by
21176 // instantiating the initializer. The DeclRefExpr's type should be
21177 // updated accordingly too, or users of it would be confused!
21178 if (E)
21179 SemaRef.getCompletedType(E);
21180
21181 // Re-set the member to trigger a recomputation of the dependence bits
21182 // for the expression.
21183 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
21184 DRE->setDecl(DRE->getDecl());
21185 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
21186 ME->setMemberDecl(ME->getMemberDecl());
21187 } else if (FirstInstantiation) {
21188 SemaRef.PendingInstantiations
21189 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
21190 } else {
21191 bool Inserted = false;
21192 for (auto &I : SemaRef.SavedPendingInstantiations) {
21193 auto Iter = llvm::find_if(
21194 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
21195 return P.first == Var;
21196 });
21197 if (Iter != I.end()) {
21198 SemaRef.PendingInstantiations.push_back(x: *Iter);
21199 I.erase(position: Iter);
21200 Inserted = true;
21201 break;
21202 }
21203 }
21204
21205 // FIXME: For a specialization of a variable template, we don't
21206 // distinguish between "declaration and type implicitly instantiated"
21207 // and "implicit instantiation of definition requested", so we have
21208 // no direct way to avoid enqueueing the pending instantiation
21209 // multiple times.
21210 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
21211 SemaRef.PendingInstantiations
21212 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
21213 }
21214 }
21215 }
21216
21217 // C++2a [basic.def.odr]p4:
21218 // A variable x whose name appears as a potentially-evaluated expression e
21219 // is odr-used by e unless
21220 // -- x is a reference that is usable in constant expressions
21221 // -- x is a variable of non-reference type that is usable in constant
21222 // expressions and has no mutable subobjects [FIXME], and e is an
21223 // element of the set of potential results of an expression of
21224 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
21225 // conversion is applied
21226 // -- x is a variable of non-reference type, and e is an element of the set
21227 // of potential results of a discarded-value expression to which the
21228 // lvalue-to-rvalue conversion is not applied [FIXME]
21229 //
21230 // We check the first part of the second bullet here, and
21231 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
21232 // FIXME: To get the third bullet right, we need to delay this even for
21233 // variables that are not usable in constant expressions.
21234
21235 // If we already know this isn't an odr-use, there's nothing more to do.
21236 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
21237 if (DRE->isNonOdrUse())
21238 return;
21239 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
21240 if (ME->isNonOdrUse())
21241 return;
21242
21243 switch (OdrUse) {
21244 case OdrUseContext::None:
21245 // In some cases, a variable may not have been marked unevaluated, if it
21246 // appears in a defaukt initializer.
21247 assert((!E || isa<FunctionParmPackExpr>(E) ||
21248 SemaRef.isUnevaluatedContext()) &&
21249 "missing non-odr-use marking for unevaluated decl ref");
21250 break;
21251
21252 case OdrUseContext::FormallyOdrUsed:
21253 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21254 // behavior.
21255 break;
21256
21257 case OdrUseContext::Used:
21258 // If we might later find that this expression isn't actually an odr-use,
21259 // delay the marking.
21260 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
21261 SemaRef.MaybeODRUseExprs.insert(X: E);
21262 else
21263 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
21264 break;
21265
21266 case OdrUseContext::Dependent:
21267 // If this is a dependent context, we don't need to mark variables as
21268 // odr-used, but we may still need to track them for lambda capture.
21269 // FIXME: Do we also need to do this inside dependent typeid expressions
21270 // (which are modeled as unevaluated at this point)?
21271 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21272 break;
21273 }
21274}
21275
21276static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
21277 BindingDecl *BD, Expr *E) {
21278 BD->setReferenced();
21279
21280 if (BD->isInvalidDecl())
21281 return;
21282
21283 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21284 if (OdrUse == OdrUseContext::Used) {
21285 QualType CaptureType, DeclRefType;
21286 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
21287 /*EllipsisLoc*/ SourceLocation(),
21288 /*BuildAndDiagnose*/ true, CaptureType,
21289 DeclRefType,
21290 /*FunctionScopeIndexToStopAt*/ nullptr);
21291 } else if (OdrUse == OdrUseContext::Dependent) {
21292 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
21293 }
21294}
21295
21296void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
21297 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
21298}
21299
21300// C++ [temp.dep.expr]p3:
21301// An id-expression is type-dependent if it contains:
21302// - an identifier associated by name lookup with an entity captured by copy
21303// in a lambda-expression that has an explicit object parameter whose type
21304// is dependent ([dcl.fct]),
21305static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
21306 Sema &SemaRef, ValueDecl *D, Expr *E) {
21307 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
21308 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21309 return;
21310
21311 // If any enclosing lambda with a dependent explicit object parameter either
21312 // explicitly captures the variable by value, or has a capture default of '='
21313 // and does not capture the variable by reference, then the type of the DRE
21314 // is dependent on the type of that lambda's explicit object parameter.
21315 auto IsDependent = [&]() {
21316 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
21317 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
21318 if (!LSI)
21319 continue;
21320
21321 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
21322 LSI->AfterParameterList)
21323 return false;
21324
21325 const auto *MD = LSI->CallOperator;
21326 if (MD->getType().isNull())
21327 continue;
21328
21329 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21330 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21331 !Ty->getParamType(i: 0)->isDependentType())
21332 continue;
21333
21334 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
21335 if (C->isCopyCapture())
21336 return true;
21337 continue;
21338 }
21339
21340 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21341 return true;
21342 }
21343 return false;
21344 }();
21345
21346 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21347 Set: IsDependent, Context: SemaRef.getASTContext());
21348}
21349
21350static void
21351MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
21352 bool MightBeOdrUse,
21353 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21354 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
21355 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
21356
21357 if (SemaRef.getLangOpts().OpenACC)
21358 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21359
21360 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
21361 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
21362 if (SemaRef.getLangOpts().CPlusPlus)
21363 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21364 D: Var, E);
21365 return;
21366 }
21367
21368 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
21369 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
21370 if (SemaRef.getLangOpts().CPlusPlus)
21371 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21372 D: Decl, E);
21373 return;
21374 }
21375 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21376
21377 // If this is a call to a method via a cast, also mark the method in the
21378 // derived class used in case codegen can devirtualize the call.
21379 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
21380 if (!ME)
21381 return;
21382 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
21383 if (!MD)
21384 return;
21385 // Only attempt to devirtualize if this is truly a virtual call.
21386 bool IsVirtualCall = MD->isVirtual() &&
21387 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
21388 if (!IsVirtualCall)
21389 return;
21390
21391 // If it's possible to devirtualize the call, mark the called function
21392 // referenced.
21393 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
21394 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
21395 if (DM)
21396 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
21397}
21398
21399void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
21400 // [basic.def.odr] (CWG 1614)
21401 // A function is named by an expression or conversion [...]
21402 // unless it is a pure virtual function and either the expression is not an
21403 // id-expression naming the function with an explicitly qualified name or
21404 // the expression forms a pointer to member
21405 bool OdrUse = true;
21406 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
21407 if (Method->isVirtual() &&
21408 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
21409 OdrUse = false;
21410
21411 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
21412 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
21413 !isImmediateFunctionContext() &&
21414 !isCheckingDefaultArgumentOrInitializer() &&
21415 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21416 !FD->isDependentContext())
21417 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
21418 }
21419 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
21420 RefsMinusAssignments);
21421}
21422
21423void Sema::MarkMemberReferenced(MemberExpr *E) {
21424 // C++11 [basic.def.odr]p2:
21425 // A non-overloaded function whose name appears as a potentially-evaluated
21426 // expression or a member of a set of candidate functions, if selected by
21427 // overload resolution when referred to from a potentially-evaluated
21428 // expression, is odr-used, unless it is a pure virtual function and its
21429 // name is not explicitly qualified.
21430 bool MightBeOdrUse = true;
21431 if (E->performsVirtualDispatch(LO: getLangOpts())) {
21432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
21433 if (Method->isPureVirtual())
21434 MightBeOdrUse = false;
21435 }
21436 SourceLocation Loc =
21437 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21438 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
21439 RefsMinusAssignments);
21440}
21441
21442void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
21443 for (ValueDecl *VD : *E)
21444 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
21445 RefsMinusAssignments);
21446}
21447
21448/// Perform marking for a reference to an arbitrary declaration. It
21449/// marks the declaration referenced, and performs odr-use checking for
21450/// functions and variables. This method should not be used when building a
21451/// normal expression which refers to a variable.
21452void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
21453 bool MightBeOdrUse) {
21454 if (MightBeOdrUse) {
21455 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
21456 MarkVariableReferenced(Loc, Var: VD);
21457 return;
21458 }
21459 }
21460 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
21461 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
21462 return;
21463 }
21464 D->setReferenced();
21465}
21466
21467namespace {
21468 // Mark all of the declarations used by a type as referenced.
21469 // FIXME: Not fully implemented yet! We need to have a better understanding
21470 // of when we're entering a context we should not recurse into.
21471 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21472 // TreeTransforms rebuilding the type in a new context. Rather than
21473 // duplicating the TreeTransform logic, we should consider reusing it here.
21474 // Currently that causes problems when rebuilding LambdaExprs.
21475class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21476 Sema &S;
21477 SourceLocation Loc;
21478
21479public:
21480 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21481
21482 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21483};
21484}
21485
21486bool MarkReferencedDecls::TraverseTemplateArgument(
21487 const TemplateArgument &Arg) {
21488 {
21489 // A non-type template argument is a constant-evaluated context.
21490 EnterExpressionEvaluationContext Evaluated(
21491 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
21492 if (Arg.getKind() == TemplateArgument::Declaration) {
21493 if (Decl *D = Arg.getAsDecl())
21494 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
21495 } else if (Arg.getKind() == TemplateArgument::Expression) {
21496 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
21497 }
21498 }
21499
21500 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
21501}
21502
21503void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
21504 MarkReferencedDecls Marker(*this, Loc);
21505 Marker.TraverseType(T);
21506}
21507
21508namespace {
21509/// Helper class that marks all of the declarations referenced by
21510/// potentially-evaluated subexpressions as "referenced".
21511class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21512public:
21513 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21514 bool SkipLocalVariables;
21515 ArrayRef<const Expr *> StopAt;
21516
21517 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21518 ArrayRef<const Expr *> StopAt)
21519 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21520
21521 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21522 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21523 }
21524
21525 void Visit(Expr *E) {
21526 if (llvm::is_contained(Range&: StopAt, Element: E))
21527 return;
21528 Inherited::Visit(S: E);
21529 }
21530
21531 void VisitConstantExpr(ConstantExpr *E) {
21532 // Don't mark declarations within a ConstantExpression, as this expression
21533 // will be evaluated and folded to a value.
21534 }
21535
21536 void VisitDeclRefExpr(DeclRefExpr *E) {
21537 // If we were asked not to visit local variables, don't.
21538 if (SkipLocalVariables) {
21539 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21540 if (VD->hasLocalStorage())
21541 return;
21542 }
21543
21544 // FIXME: This can trigger the instantiation of the initializer of a
21545 // variable, which can cause the expression to become value-dependent
21546 // or error-dependent. Do we need to propagate the new dependence bits?
21547 S.MarkDeclRefReferenced(E);
21548 }
21549
21550 void VisitMemberExpr(MemberExpr *E) {
21551 S.MarkMemberReferenced(E);
21552 Visit(E: E->getBase());
21553 }
21554};
21555} // namespace
21556
21557void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21558 bool SkipLocalVariables,
21559 ArrayRef<const Expr*> StopAt) {
21560 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21561}
21562
21563/// Emit a diagnostic when statements are reachable.
21564bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21565 const PartialDiagnostic &PD) {
21566 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21567 // The initializer of a constexpr variable or of the first declaration of a
21568 // static data member is not syntactically a constant evaluated constant,
21569 // but nonetheless is always required to be a constant expression, so we
21570 // can skip diagnosing.
21571 if (Decl &&
21572 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21573 Decl->isFirstDecl() && !Decl->isInline())))
21574 return false;
21575
21576 if (Stmts.empty()) {
21577 Diag(Loc, PD);
21578 return true;
21579 }
21580
21581 if (getCurFunction()) {
21582 // This queue flushes after the function is analyzed, by which time an
21583 // ignore-all-warnings region live here is gone, so sample it now. A note
21584 // is not error-class either, so this also drops the notes that accompany a
21585 // skipped warning. They arrive on their own call, out of reach of the
21586 // engine's rule that drops a note whose warning was ignored.
21587 if (Diags.getIgnoreAllWarnings() &&
21588 Diags.getDiagnosticIDs()->isWarningOrExtension(DiagID: PD.getDiagID()))
21589 return false;
21590 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21591 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21592 return true;
21593 }
21594
21595 // For non-constexpr file-scope variables with reachability context (non-empty
21596 // Stmts), build a CFG for the initializer and check whether the context in
21597 // question is reachable.
21598 if (Decl && Decl->isFileVarDecl()) {
21599 AnalysisWarnings.registerVarDeclWarning(
21600 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21601 return true;
21602 }
21603
21604 Diag(Loc, PD);
21605 return true;
21606}
21607
21608/// Emit a diagnostic that describes an effect on the run-time behavior
21609/// of the program being compiled.
21610///
21611/// This routine emits the given diagnostic when the code currently being
21612/// type-checked is "potentially evaluated", meaning that there is a
21613/// possibility that the code will actually be executable. Code in sizeof()
21614/// expressions, code used only during overload resolution, etc., are not
21615/// potentially evaluated. This routine will suppress such diagnostics or,
21616/// in the absolutely nutty case of potentially potentially evaluated
21617/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21618/// later.
21619///
21620/// This routine should be used for all diagnostics that describe the run-time
21621/// behavior of a program, such as passing a non-POD value through an ellipsis.
21622/// Failure to do so will likely result in spurious diagnostics or failures
21623/// during overload resolution or within sizeof/alignof/typeof/typeid.
21624bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21625 const PartialDiagnostic &PD) {
21626
21627 if (ExprEvalContexts.back().isDiscardedStatementContext())
21628 return false;
21629
21630 switch (ExprEvalContexts.back().Context) {
21631 case ExpressionEvaluationContext::Unevaluated:
21632 case ExpressionEvaluationContext::UnevaluatedList:
21633 case ExpressionEvaluationContext::UnevaluatedAbstract:
21634 case ExpressionEvaluationContext::DiscardedStatement:
21635 // The argument will never be evaluated, so don't complain.
21636 break;
21637
21638 case ExpressionEvaluationContext::ConstantEvaluated:
21639 case ExpressionEvaluationContext::ImmediateFunctionContext:
21640 // Relevant diagnostics should be produced by constant evaluation.
21641 break;
21642
21643 case ExpressionEvaluationContext::PotentiallyEvaluated:
21644 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21645 return DiagIfReachable(Loc, Stmts, PD);
21646 }
21647
21648 return false;
21649}
21650
21651bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21652 const PartialDiagnostic &PD) {
21653 return DiagRuntimeBehavior(
21654 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21655 PD);
21656}
21657
21658bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21659 CallExpr *CE, FunctionDecl *FD) {
21660 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21661 return false;
21662
21663 // If we're inside a decltype's expression, don't check for a valid return
21664 // type or construct temporaries until we know whether this is the last call.
21665 if (ExprEvalContexts.back().ExprContext ==
21666 ExpressionEvaluationContextRecord::EK_Decltype) {
21667 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21668 return false;
21669 }
21670
21671 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21672 FunctionDecl *FD;
21673 CallExpr *CE;
21674
21675 public:
21676 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21677 : FD(FD), CE(CE) { }
21678
21679 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21680 if (!FD) {
21681 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21682 << T << CE->getSourceRange();
21683 return;
21684 }
21685
21686 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21687 << CE->getSourceRange() << FD << T;
21688 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21689 << FD->getDeclName();
21690 }
21691 } Diagnoser(FD, CE);
21692
21693 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21694 return true;
21695
21696 return false;
21697}
21698
21699// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21700// will prevent this condition from triggering, which is what we want.
21701void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21702 SourceLocation Loc;
21703
21704 unsigned diagnostic = diag::warn_condition_is_assignment;
21705 bool IsOrAssign = false;
21706
21707 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21708 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21709 return;
21710
21711 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21712
21713 // Greylist some idioms by putting them into a warning subcategory.
21714 if (ObjCMessageExpr *ME
21715 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21716 Selector Sel = ME->getSelector();
21717
21718 // self = [<foo> init...]
21719 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21720 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21721
21722 // <foo> = [<bar> nextObject]
21723 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21724 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21725 }
21726
21727 Loc = Op->getOperatorLoc();
21728 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21729 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21730 return;
21731
21732 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21733 Loc = Op->getOperatorLoc();
21734 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21735 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21736 else {
21737 // Not an assignment.
21738 return;
21739 }
21740
21741 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21742
21743 SourceLocation Open = E->getBeginLoc();
21744 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21745 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21746 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21747 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21748
21749 if (IsOrAssign)
21750 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21751 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21752 else
21753 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21754 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21755}
21756
21757void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21758 // Don't warn if the parens came from a macro.
21759 SourceLocation parenLoc = ParenE->getBeginLoc();
21760 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21761 return;
21762 // Don't warn for dependent expressions.
21763 if (ParenE->isTypeDependent())
21764 return;
21765
21766 Expr *E = ParenE->IgnoreParens();
21767 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21768 return;
21769
21770 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21771 if (opE->getOpcode() == BO_EQ &&
21772 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21773 == Expr::MLV_Valid) {
21774 SourceLocation Loc = opE->getOperatorLoc();
21775
21776 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21777 SourceRange ParenERange = ParenE->getSourceRange();
21778 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21779 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21780 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21781 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21782 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21783 }
21784}
21785
21786ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21787 bool IsConstexpr) {
21788 DiagnoseAssignmentAsCondition(E);
21789 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21790 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21791
21792 ExprResult result = CheckPlaceholderExpr(E);
21793 if (result.isInvalid()) return ExprError();
21794 E = result.get();
21795
21796 if (!E->isTypeDependent()) {
21797 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21798 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21799
21800 if (getLangOpts().CPlusPlus)
21801 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21802
21803 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21804 if (ERes.isInvalid())
21805 return ExprError();
21806 E = ERes.get();
21807
21808 QualType T = E->getType();
21809 if (!T->isScalarType()) { // C99 6.8.4.1p1
21810 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21811 << T << E->getSourceRange();
21812 return ExprError();
21813 }
21814 CheckBoolLikeConversion(E, CC: Loc);
21815 }
21816
21817 return E;
21818}
21819
21820Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21821 Expr *SubExpr, ConditionKind CK,
21822 bool MissingOK) {
21823 // MissingOK indicates whether having no condition expression is valid
21824 // (for loop) or invalid (e.g. while loop).
21825 if (!SubExpr)
21826 return MissingOK ? ConditionResult() : ConditionError();
21827
21828 ExprResult Cond;
21829 switch (CK) {
21830 case ConditionKind::Boolean:
21831 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21832 break;
21833
21834 case ConditionKind::ConstexprIf:
21835 // Note: this might produce a FullExpr
21836 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21837 break;
21838
21839 case ConditionKind::Switch:
21840 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21841 break;
21842 }
21843 if (Cond.isInvalid()) {
21844 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21845 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21846 if (!Cond.get())
21847 return ConditionError();
21848 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21849 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21850
21851 if (!Cond.isUsable())
21852 return ConditionError();
21853
21854 return ConditionResult(*this, nullptr, Cond,
21855 CK == ConditionKind::ConstexprIf);
21856}
21857
21858namespace {
21859 /// A visitor for rebuilding a call to an __unknown_any expression
21860 /// to have an appropriate type.
21861 struct RebuildUnknownAnyFunction
21862 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21863
21864 Sema &S;
21865
21866 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21867
21868 ExprResult VisitStmt(Stmt *S) {
21869 llvm_unreachable("unexpected statement!");
21870 }
21871
21872 ExprResult VisitExpr(Expr *E) {
21873 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21874 << E->getSourceRange();
21875 return ExprError();
21876 }
21877
21878 /// Rebuild an expression which simply semantically wraps another
21879 /// expression which it shares the type and value kind of.
21880 template <class T> ExprResult rebuildSugarExpr(T *E) {
21881 ExprResult SubResult = Visit(S: E->getSubExpr());
21882 if (SubResult.isInvalid()) return ExprError();
21883
21884 Expr *SubExpr = SubResult.get();
21885 E->setSubExpr(SubExpr);
21886 E->setType(SubExpr->getType());
21887 E->setValueKind(SubExpr->getValueKind());
21888 assert(E->getObjectKind() == OK_Ordinary);
21889 return E;
21890 }
21891
21892 ExprResult VisitParenExpr(ParenExpr *E) {
21893 return rebuildSugarExpr(E);
21894 }
21895
21896 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21897 return rebuildSugarExpr(E);
21898 }
21899
21900 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21901 ExprResult SubResult = Visit(S: E->getSubExpr());
21902 if (SubResult.isInvalid()) return ExprError();
21903
21904 Expr *SubExpr = SubResult.get();
21905 E->setSubExpr(SubExpr);
21906 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21907 assert(E->isPRValue());
21908 assert(E->getObjectKind() == OK_Ordinary);
21909 return E;
21910 }
21911
21912 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21913 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21914
21915 E->setType(VD->getType());
21916
21917 assert(E->isPRValue());
21918 if (S.getLangOpts().CPlusPlus &&
21919 !(isa<CXXMethodDecl>(Val: VD) &&
21920 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21921 E->setValueKind(VK_LValue);
21922
21923 return E;
21924 }
21925
21926 ExprResult VisitMemberExpr(MemberExpr *E) {
21927 return resolveDecl(E, VD: E->getMemberDecl());
21928 }
21929
21930 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21931 return resolveDecl(E, VD: E->getDecl());
21932 }
21933 };
21934}
21935
21936/// Given a function expression of unknown-any type, try to rebuild it
21937/// to have a function type.
21938static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21939 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21940 if (Result.isInvalid()) return ExprError();
21941 return S.DefaultFunctionArrayConversion(E: Result.get());
21942}
21943
21944namespace {
21945 /// A visitor for rebuilding an expression of type __unknown_anytype
21946 /// into one which resolves the type directly on the referring
21947 /// expression. Strict preservation of the original source
21948 /// structure is not a goal.
21949 struct RebuildUnknownAnyExpr
21950 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21951
21952 Sema &S;
21953
21954 /// The current destination type.
21955 QualType DestType;
21956
21957 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21958 : S(S), DestType(CastType) {}
21959
21960 ExprResult VisitStmt(Stmt *S) {
21961 llvm_unreachable("unexpected statement!");
21962 }
21963
21964 ExprResult VisitExpr(Expr *E) {
21965 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21966 << E->getSourceRange();
21967 return ExprError();
21968 }
21969
21970 ExprResult VisitCallExpr(CallExpr *E);
21971 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21972
21973 /// Rebuild an expression which simply semantically wraps another
21974 /// expression which it shares the type and value kind of.
21975 template <class T> ExprResult rebuildSugarExpr(T *E) {
21976 ExprResult SubResult = Visit(S: E->getSubExpr());
21977 if (SubResult.isInvalid()) return ExprError();
21978 Expr *SubExpr = SubResult.get();
21979 E->setSubExpr(SubExpr);
21980 E->setType(SubExpr->getType());
21981 E->setValueKind(SubExpr->getValueKind());
21982 assert(E->getObjectKind() == OK_Ordinary);
21983 return E;
21984 }
21985
21986 ExprResult VisitParenExpr(ParenExpr *E) {
21987 return rebuildSugarExpr(E);
21988 }
21989
21990 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21991 return rebuildSugarExpr(E);
21992 }
21993
21994 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21995 const PointerType *Ptr = DestType->getAs<PointerType>();
21996 if (!Ptr) {
21997 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21998 << E->getSourceRange();
21999 return ExprError();
22000 }
22001
22002 if (isa<CallExpr>(Val: E->getSubExpr())) {
22003 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
22004 << E->getSourceRange();
22005 return ExprError();
22006 }
22007
22008 assert(E->isPRValue());
22009 assert(E->getObjectKind() == OK_Ordinary);
22010 E->setType(DestType);
22011
22012 // Build the sub-expression as if it were an object of the pointee type.
22013 DestType = Ptr->getPointeeType();
22014 ExprResult SubResult = Visit(S: E->getSubExpr());
22015 if (SubResult.isInvalid()) return ExprError();
22016 E->setSubExpr(SubResult.get());
22017 return E;
22018 }
22019
22020 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
22021
22022 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
22023
22024 ExprResult VisitMemberExpr(MemberExpr *E) {
22025 return resolveDecl(E, VD: E->getMemberDecl());
22026 }
22027
22028 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
22029 return resolveDecl(E, VD: E->getDecl());
22030 }
22031 };
22032}
22033
22034/// Rebuilds a call expression which yielded __unknown_anytype.
22035ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
22036 Expr *CalleeExpr = E->getCallee();
22037
22038 enum FnKind {
22039 FK_MemberFunction,
22040 FK_FunctionPointer,
22041 FK_BlockPointer
22042 };
22043
22044 FnKind Kind;
22045 QualType CalleeType = CalleeExpr->getType();
22046 if (CalleeType == S.Context.BoundMemberTy) {
22047 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
22048 Kind = FK_MemberFunction;
22049 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
22050 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
22051 CalleeType = Ptr->getPointeeType();
22052 Kind = FK_FunctionPointer;
22053 } else {
22054 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
22055 Kind = FK_BlockPointer;
22056 }
22057 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
22058
22059 // Verify that this is a legal result type of a function.
22060 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
22061 DestType->isFunctionType()) {
22062 unsigned diagID = diag::err_func_returning_array_function;
22063 if (Kind == FK_BlockPointer)
22064 diagID = diag::err_block_returning_array_function;
22065
22066 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
22067 << DestType->isFunctionType() << DestType;
22068 return ExprError();
22069 }
22070
22071 // Otherwise, go ahead and set DestType as the call's result.
22072 E->setType(DestType.getNonLValueExprType(Context: S.Context));
22073 E->setValueKind(Expr::getValueKindForType(T: DestType));
22074 assert(E->getObjectKind() == OK_Ordinary);
22075
22076 // Rebuild the function type, replacing the result type with DestType.
22077 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
22078 if (Proto) {
22079 // __unknown_anytype(...) is a special case used by the debugger when
22080 // it has no idea what a function's signature is.
22081 //
22082 // We want to build this call essentially under the K&R
22083 // unprototyped rules, but making a FunctionNoProtoType in C++
22084 // would foul up all sorts of assumptions. However, we cannot
22085 // simply pass all arguments as variadic arguments, nor can we
22086 // portably just call the function under a non-variadic type; see
22087 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
22088 // However, it turns out that in practice it is generally safe to
22089 // call a function declared as "A foo(B,C,D);" under the prototype
22090 // "A foo(B,C,D,...);". The only known exception is with the
22091 // Windows ABI, where any variadic function is implicitly cdecl
22092 // regardless of its normal CC. Therefore we change the parameter
22093 // types to match the types of the arguments.
22094 //
22095 // This is a hack, but it is far superior to moving the
22096 // corresponding target-specific code from IR-gen to Sema/AST.
22097
22098 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
22099 SmallVector<QualType, 8> ArgTypes;
22100 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
22101 ArgTypes.reserve(N: E->getNumArgs());
22102 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
22103 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
22104 }
22105 ParamTypes = ArgTypes;
22106 }
22107 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
22108 EPI: Proto->getExtProtoInfo());
22109 } else {
22110 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
22111 Info: FnType->getExtInfo());
22112 }
22113
22114 // Rebuild the appropriate pointer-to-function type.
22115 switch (Kind) {
22116 case FK_MemberFunction:
22117 // Nothing to do.
22118 break;
22119
22120 case FK_FunctionPointer:
22121 DestType = S.Context.getPointerType(T: DestType);
22122 break;
22123
22124 case FK_BlockPointer:
22125 DestType = S.Context.getBlockPointerType(T: DestType);
22126 break;
22127 }
22128
22129 // Finally, we can recurse.
22130 ExprResult CalleeResult = Visit(S: CalleeExpr);
22131 if (!CalleeResult.isUsable()) return ExprError();
22132 E->setCallee(CalleeResult.get());
22133
22134 // Bind a temporary if necessary.
22135 return S.MaybeBindToTemporary(E);
22136}
22137
22138ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
22139 // Verify that this is a legal result type of a call.
22140 if (DestType->isArrayType() || DestType->isFunctionType()) {
22141 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
22142 << DestType->isFunctionType() << DestType;
22143 return ExprError();
22144 }
22145
22146 // Rewrite the method result type if available.
22147 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
22148 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
22149 Method->setReturnType(DestType);
22150 }
22151
22152 // Change the type of the message.
22153 E->setType(DestType.getNonReferenceType());
22154 E->setValueKind(Expr::getValueKindForType(T: DestType));
22155
22156 return S.MaybeBindToTemporary(E);
22157}
22158
22159ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
22160 // The only case we should ever see here is a function-to-pointer decay.
22161 if (E->getCastKind() == CK_FunctionToPointerDecay) {
22162 assert(E->isPRValue());
22163 assert(E->getObjectKind() == OK_Ordinary);
22164
22165 E->setType(DestType);
22166
22167 // Rebuild the sub-expression as the pointee (function) type.
22168 DestType = DestType->castAs<PointerType>()->getPointeeType();
22169
22170 ExprResult Result = Visit(S: E->getSubExpr());
22171 if (!Result.isUsable()) return ExprError();
22172
22173 E->setSubExpr(Result.get());
22174 return E;
22175 } else if (E->getCastKind() == CK_LValueToRValue) {
22176 assert(E->isPRValue());
22177 assert(E->getObjectKind() == OK_Ordinary);
22178
22179 assert(isa<BlockPointerType>(E->getType()));
22180
22181 E->setType(DestType);
22182
22183 // The sub-expression has to be a lvalue reference, so rebuild it as such.
22184 DestType = S.Context.getLValueReferenceType(T: DestType);
22185
22186 ExprResult Result = Visit(S: E->getSubExpr());
22187 if (!Result.isUsable()) return ExprError();
22188
22189 E->setSubExpr(Result.get());
22190 return E;
22191 } else {
22192 llvm_unreachable("Unhandled cast type!");
22193 }
22194}
22195
22196ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
22197 ExprValueKind ValueKind = VK_LValue;
22198 QualType Type = DestType;
22199
22200 // We know how to make this work for certain kinds of decls:
22201
22202 // - functions
22203 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
22204 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
22205 DestType = Ptr->getPointeeType();
22206 ExprResult Result = resolveDecl(E, VD);
22207 if (Result.isInvalid()) return ExprError();
22208 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
22209 VK: VK_PRValue);
22210 }
22211
22212 if (!Type->isFunctionType()) {
22213 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
22214 << VD << E->getSourceRange();
22215 return ExprError();
22216 }
22217 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
22218 // We must match the FunctionDecl's type to the hack introduced in
22219 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
22220 // type. See the lengthy commentary in that routine.
22221 QualType FDT = FD->getType();
22222 const FunctionType *FnType = FDT->castAs<FunctionType>();
22223 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
22224 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
22225 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
22226 SourceLocation Loc = FD->getLocation();
22227 FunctionDecl *NewFD = FunctionDecl::Create(
22228 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
22229 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
22230 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
22231 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
22232 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
22233
22234 if (FD->getQualifier())
22235 NewFD->setQualifierInfo(FD->getQualifierLoc());
22236
22237 SmallVector<ParmVarDecl*, 16> Params;
22238 for (const auto &AI : FT->param_types()) {
22239 ParmVarDecl *Param =
22240 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
22241 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
22242 Params.push_back(Elt: Param);
22243 }
22244 NewFD->setParams(Params);
22245 DRE->setDecl(NewFD);
22246 VD = DRE->getDecl();
22247 }
22248 }
22249
22250 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
22251 if (MD->isInstance()) {
22252 ValueKind = VK_PRValue;
22253 Type = S.Context.BoundMemberTy;
22254 }
22255
22256 // Function references aren't l-values in C.
22257 if (!S.getLangOpts().CPlusPlus)
22258 ValueKind = VK_PRValue;
22259
22260 // - variables
22261 } else if (isa<VarDecl>(Val: VD)) {
22262 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22263 Type = RefTy->getPointeeType();
22264 } else if (Type->isFunctionType()) {
22265 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
22266 << VD << E->getSourceRange();
22267 return ExprError();
22268 }
22269
22270 // - nothing else
22271 } else {
22272 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
22273 << VD << E->getSourceRange();
22274 return ExprError();
22275 }
22276
22277 // Modifying the declaration like this is friendly to IR-gen but
22278 // also really dangerous.
22279 VD->setType(DestType);
22280 E->setType(Type);
22281 E->setValueKind(ValueKind);
22282 return E;
22283}
22284
22285ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
22286 Expr *CastExpr, CastKind &CastKind,
22287 ExprValueKind &VK, CXXCastPath &Path) {
22288 // The type we're casting to must be either void or complete.
22289 if (!CastType->isVoidType() &&
22290 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
22291 DiagID: diag::err_typecheck_cast_to_incomplete))
22292 return ExprError();
22293
22294 // Rewrite the casted expression from scratch.
22295 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
22296 if (!result.isUsable()) return ExprError();
22297
22298 CastExpr = result.get();
22299 VK = CastExpr->getValueKind();
22300 CastKind = CK_NoOp;
22301
22302 return CastExpr;
22303}
22304
22305ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
22306 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
22307}
22308
22309ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
22310 Expr *arg, QualType &paramType) {
22311 // If the syntactic form of the argument is not an explicit cast of
22312 // any sort, just do default argument promotion.
22313 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
22314 if (!castArg) {
22315 ExprResult result = DefaultArgumentPromotion(E: arg);
22316 if (result.isInvalid()) return ExprError();
22317 paramType = result.get()->getType();
22318 return result;
22319 }
22320
22321 // Otherwise, use the type that was written in the explicit cast.
22322 assert(!arg->hasPlaceholderType());
22323 paramType = castArg->getTypeAsWritten();
22324
22325 // Copy-initialize a parameter of that type.
22326 InitializedEntity entity =
22327 InitializedEntity::InitializeParameter(Context, Type: paramType,
22328 /*consumed*/ Consumed: false);
22329 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
22330}
22331
22332static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
22333 Expr *orig = E;
22334 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22335 while (true) {
22336 E = E->IgnoreParenImpCasts();
22337 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
22338 E = call->getCallee();
22339 diagID = diag::err_uncasted_call_of_unknown_any;
22340 } else {
22341 break;
22342 }
22343 }
22344
22345 SourceLocation loc;
22346 NamedDecl *d;
22347 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
22348 loc = ref->getLocation();
22349 d = ref->getDecl();
22350 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
22351 loc = mem->getMemberLoc();
22352 d = mem->getMemberDecl();
22353 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
22354 diagID = diag::err_uncasted_call_of_unknown_any;
22355 loc = msg->getSelectorStartLoc();
22356 d = msg->getMethodDecl();
22357 if (!d) {
22358 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
22359 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22360 << orig->getSourceRange();
22361 return ExprError();
22362 }
22363 } else {
22364 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
22365 << E->getSourceRange();
22366 return ExprError();
22367 }
22368
22369 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
22370
22371 // Never recoverable.
22372 return ExprError();
22373}
22374
22375ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
22376 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22377 if (!placeholderType) return E;
22378
22379 switch (placeholderType->getKind()) {
22380 case BuiltinType::UnresolvedTemplate: {
22381 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
22382 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22383 // There's only one FoundDecl for UnresolvedTemplate type. See
22384 // BuildTemplateIdExpr.
22385 NamedDecl *Temp = *ULE->decls_begin();
22386 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
22387
22388 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22389 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22390 // as it models only the unqualified-id case, where this case can clearly be
22391 // qualified. Thus we can't just qualify an assumed template.
22392 TemplateName TN;
22393 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
22394 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
22395 Template: TemplateName(TD));
22396 else
22397 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
22398
22399 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
22400 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22401 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
22402 << IsTypeAliasTemplateDecl;
22403
22404 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22405 bool HasAnyDependentTA = false;
22406 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22407 HasAnyDependentTA |= Arg.getArgument().isDependent();
22408 TAL.addArgument(Loc: Arg);
22409 }
22410
22411 QualType TST;
22412 {
22413 SFINAETrap Trap(*this);
22414 TST = CheckTemplateIdType(
22415 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
22416 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22417 }
22418 if (TST.isNull())
22419 TST = Context.getTemplateSpecializationType(
22420 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
22421 /*CanonicalArgs=*/{},
22422 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22423 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
22424 T: TST);
22425 }
22426
22427 // Overloaded expressions.
22428 case BuiltinType::Overload: {
22429 // Try to resolve a single function template specialization.
22430 // This is obligatory.
22431 ExprResult Result = E;
22432 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
22433 return Result;
22434
22435 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22436 // leaves Result unchanged on failure.
22437 Result = E;
22438 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
22439 return Result;
22440
22441 // If that failed, try to recover with a call.
22442 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
22443 /*complain*/ ForceComplain: true);
22444 return Result;
22445 }
22446
22447 // Bound member functions.
22448 case BuiltinType::BoundMember: {
22449 ExprResult result = E;
22450 const Expr *BME = E->IgnoreParens();
22451 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
22452 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22453 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
22454 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22455 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
22456 if (ME->getMemberNameInfo().getName().getNameKind() ==
22457 DeclarationName::CXXDestructorName)
22458 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22459 }
22460 tryToRecoverWithCall(E&: result, PD,
22461 /*complain*/ ForceComplain: true);
22462 return result;
22463 }
22464
22465 // ARC unbridged casts.
22466 case BuiltinType::ARCUnbridgedCast: {
22467 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
22468 ObjC().diagnoseARCUnbridgedCast(e: realCast);
22469 return realCast;
22470 }
22471
22472 // Expressions of unknown type.
22473 case BuiltinType::UnknownAny:
22474 return diagnoseUnknownAnyExpr(S&: *this, E);
22475
22476 // Pseudo-objects.
22477 case BuiltinType::PseudoObject:
22478 return PseudoObject().checkRValue(E);
22479
22480 case BuiltinType::BuiltinFn: {
22481 // Accept __noop without parens by implicitly converting it to a call expr.
22482 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
22483 if (DRE) {
22484 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
22485 unsigned BuiltinID = FD->getBuiltinID();
22486 if (BuiltinID == Builtin::BI__noop) {
22487 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
22488 CK: CK_BuiltinFnToFnPtr)
22489 .get();
22490 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
22491 VK: VK_PRValue, RParenLoc: SourceLocation(),
22492 FPFeatures: FPOptionsOverride());
22493 }
22494
22495 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
22496 // Any use of these other than a direct call is ill-formed as of C++20,
22497 // because they are not addressable functions. In earlier language
22498 // modes, warn and force an instantiation of the real body.
22499 Diag(Loc: E->getBeginLoc(),
22500 DiagID: getLangOpts().CPlusPlus20
22501 ? diag::err_use_of_unaddressable_function
22502 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22503 if (FD->isImplicitlyInstantiable()) {
22504 // Require a definition here because a normal attempt at
22505 // instantiation for a builtin will be ignored, and we won't try
22506 // again later. We assume that the definition of the template
22507 // precedes this use.
22508 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
22509 /*Recursive=*/false,
22510 /*DefinitionRequired=*/true,
22511 /*AtEndOfTU=*/false);
22512 }
22513 // Produce a properly-typed reference to the function.
22514 CXXScopeSpec SS;
22515 SS.Adopt(Other: DRE->getQualifierLoc());
22516 TemplateArgumentListInfo TemplateArgs;
22517 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22518 return BuildDeclRefExpr(
22519 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22520 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22521 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22522 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22523 }
22524 }
22525
22526 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22527 return ExprError();
22528 }
22529
22530 case BuiltinType::IncompleteMatrixIdx: {
22531 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22532 // At this point, we know there was no second [] to complete the operator.
22533 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22534 if (getLangOpts().HLSL) {
22535 return CreateBuiltinMatrixSingleSubscriptExpr(
22536 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22537 }
22538 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22539 return ExprError();
22540 }
22541
22542 // Expressions of unknown type.
22543 case BuiltinType::ArraySection:
22544 // If we've already diagnosed something on the array section type, we
22545 // shouldn't need to do any further diagnostic here.
22546 if (!E->containsErrors())
22547 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22548 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22549 return ExprError();
22550
22551 // Expressions of unknown type.
22552 case BuiltinType::OMPArrayShaping:
22553 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22554
22555 case BuiltinType::OMPIterator:
22556 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22557
22558 // Everything else should be impossible.
22559#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22560 case BuiltinType::Id:
22561#include "clang/Basic/OpenCLImageTypes.def"
22562#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22563 case BuiltinType::Id:
22564#include "clang/Basic/OpenCLExtensionTypes.def"
22565#define SVE_TYPE(Name, Id, SingletonId) \
22566 case BuiltinType::Id:
22567#include "clang/Basic/AArch64ACLETypes.def"
22568#define PPC_VECTOR_TYPE(Name, Id, Size) \
22569 case BuiltinType::Id:
22570#include "clang/Basic/PPCTypes.def"
22571#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22572#include "clang/Basic/RISCVVTypes.def"
22573#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22574#include "clang/Basic/WebAssemblyReferenceTypes.def"
22575#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22576#include "clang/Basic/AMDGPUTypes.def"
22577#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22578#include "clang/Basic/HLSLIntangibleTypes.def"
22579#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22580#include "clang/Basic/HLSLPackedTypes.def"
22581#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22582#include "clang/Basic/SPIRVTypes.def"
22583#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22584#define PLACEHOLDER_TYPE(Id, SingletonId)
22585#include "clang/AST/BuiltinTypes.def"
22586 break;
22587 }
22588
22589 llvm_unreachable("invalid placeholder type!");
22590}
22591
22592bool Sema::CheckCaseExpression(Expr *E) {
22593 if (E->isTypeDependent())
22594 return true;
22595 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22596 return E->getType()->isIntegralOrEnumerationType();
22597 return false;
22598}
22599
22600ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22601 ArrayRef<Expr *> SubExprs, QualType T) {
22602 if (!Context.getLangOpts().RecoveryAST)
22603 return ExprError();
22604
22605 if (isSFINAEContext())
22606 return ExprError();
22607
22608 if (T.isNull() || T->isUndeducedType() ||
22609 !Context.getLangOpts().RecoveryASTType)
22610 // We don't know the concrete type, fallback to dependent type.
22611 T = Context.DependentTy;
22612
22613 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22614}
22615