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/SemaCUDA.h"
59#include "clang/Sema/SemaFixItUtils.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/SemaOpenCL.h"
63#include "clang/Sema/SemaOpenMP.h"
64#include "clang/Sema/SemaPseudoObject.h"
65#include "clang/Sema/Template.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/IR/DerivedTypes.h"
69#include "llvm/Support/ConvertUTF.h"
70#include "llvm/Support/SaveAndRestore.h"
71#include "llvm/Support/TimeProfiler.h"
72#include "llvm/Support/TypeSize.h"
73#include <limits>
74#include <optional>
75
76using namespace clang;
77using namespace sema;
78
79bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
80 // See if this is an auto-typed variable whose initializer we are parsing.
81 if (ParsingInitForAutoVars.count(Ptr: D))
82 return false;
83
84 // See if this is a deleted function.
85 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
86 if (FD->isDeleted())
87 return false;
88
89 // If the function has a deduced return type, and we can't deduce it,
90 // then we can't use it either.
91 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
92 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
93 return false;
94
95 // See if this is an aligned allocation/deallocation function that is
96 // unavailable.
97 if (TreatUnavailableAsInvalid &&
98 isUnavailableAlignedAllocationFunction(FD: *FD))
99 return false;
100 }
101
102 // See if this function is unavailable.
103 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
104 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
105 return false;
106
107 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
108 return false;
109
110 return true;
111}
112
113static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
114 // Warn if this is used but marked unused.
115 if (const auto *A = D->getAttr<UnusedAttr>()) {
116 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
117 // should diagnose them.
118 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
119 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
120 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
121 if (DC && !DC->hasAttr<UnusedAttr>())
122 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
123 }
124 }
125}
126
127void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
128 assert(Decl && Decl->isDeleted());
129
130 if (Decl->isDefaulted()) {
131 // If the method was explicitly defaulted, point at that declaration.
132 if (!Decl->isImplicit())
133 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
134
135 // Try to diagnose why this special member function was implicitly
136 // deleted. This might fail, if that reason no longer applies.
137 DiagnoseDeletedDefaultedFunction(FD: Decl);
138 return;
139 }
140
141 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
142 if (Ctor && Ctor->isInheritingConstructor())
143 return NoteDeletedInheritingConstructor(CD: Ctor);
144
145 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
146 << Decl << 1;
147}
148
149/// Determine whether a FunctionDecl was ever declared with an
150/// explicit storage class.
151static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
152 for (auto *I : D->redecls()) {
153 if (I->getStorageClass() != SC_None)
154 return true;
155 }
156 return false;
157}
158
159/// Check whether we're in an extern inline function and referring to a
160/// variable or function with internal linkage (C11 6.7.4p3).
161///
162/// This is only a warning because we used to silently accept this code, but
163/// in many cases it will not behave correctly. This is not enabled in C++ mode
164/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
165/// and so while there may still be user mistakes, most of the time we can't
166/// prove that there are errors.
167static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
168 const NamedDecl *D,
169 SourceLocation Loc) {
170 // This is disabled under C++; there are too many ways for this to fire in
171 // contexts where the warning is a false positive, or where it is technically
172 // correct but benign.
173 //
174 // WG14 N3622 which removed the constraint entirely in C2y. It is left
175 // enabled in earlier language modes because this is a constraint in those
176 // language modes. But in C2y mode, we still want to issue the "incompatible
177 // with previous standards" diagnostic, too.
178 if (S.getLangOpts().CPlusPlus)
179 return;
180
181 // Check if this is an inlined function or method.
182 FunctionDecl *Current = S.getCurFunctionDecl();
183 if (!Current)
184 return;
185 if (!Current->isInlined())
186 return;
187 if (!Current->isExternallyVisible())
188 return;
189
190 // Check if the decl has internal linkage.
191 if (D->getFormalLinkage() != Linkage::Internal)
192 return;
193
194 // Downgrade from ExtWarn to Extension if
195 // (1) the supposedly external inline function is in the main file,
196 // and probably won't be included anywhere else.
197 // (2) the thing we're referencing is a pure function.
198 // (3) the thing we're referencing is another inline function.
199 // This last can give us false negatives, but it's better than warning on
200 // wrappers for simple C library functions.
201 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
202 unsigned DiagID;
203 if (S.getLangOpts().C2y)
204 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
205 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
206 S.getSourceManager().isInMainFile(Loc))
207 DiagID = diag::ext_internal_in_extern_inline_quiet;
208 else
209 DiagID = diag::ext_internal_in_extern_inline;
210
211 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
212 S.MaybeSuggestAddingStaticToDecl(D: Current);
213 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
214 << D;
215}
216
217void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
218 const FunctionDecl *First = Cur->getFirstDecl();
219
220 // Suggest "static" on the function, if possible.
221 if (!hasAnyExplicitStorageClass(D: First)) {
222 SourceLocation DeclBegin = First->getSourceRange().getBegin();
223 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
224 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
225 }
226}
227
228bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
229 const ObjCInterfaceDecl *UnknownObjCClass,
230 bool ObjCPropertyAccess,
231 bool AvoidPartialAvailabilityChecks,
232 ObjCInterfaceDecl *ClassReceiver,
233 bool SkipTrailingRequiresClause) {
234 SourceLocation Loc = Locs.front();
235 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
236 // If there were any diagnostics suppressed by template argument deduction,
237 // emit them now.
238 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
239 if (Pos != SuppressedDiagnostics.end()) {
240 for (const auto &[DiagLoc, PD] : Pos->second) {
241 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
242 PD.Emit(DB: Builder);
243 }
244 // Clear out the list of suppressed diagnostics, so that we don't emit
245 // them again for this specialization. However, we don't obsolete this
246 // entry from the table, because we want to avoid ever emitting these
247 // diagnostics again.
248 Pos->second.clear();
249 }
250
251 // C++ [basic.start.main]p3:
252 // The function 'main' shall not be used within a program.
253 if (cast<FunctionDecl>(Val: D)->isMain())
254 Diag(Loc, DiagID: diag::ext_main_used);
255
256 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
257 }
258
259 // See if this is an auto-typed variable whose initializer we are parsing.
260 if (ParsingInitForAutoVars.count(Ptr: D)) {
261 if (isa<BindingDecl>(Val: D)) {
262 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
263 << D->getDeclName();
264 } else {
265 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << diag::ParsingInitFor::Var << D->getDeclName()
267 << cast<VarDecl>(Val: D)->getType();
268 }
269 return true;
270 }
271
272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
273 // See if this is a deleted function.
274 if (FD->isDeleted()) {
275 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
276 if (Ctor && Ctor->isInheritingConstructor())
277 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
278 << Ctor->getParent()
279 << Ctor->getInheritedConstructor().getConstructor()->getParent();
280 else {
281 StringLiteral *Msg = FD->getDeletedMessage();
282 Diag(Loc, DiagID: diag::err_deleted_function_use)
283 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
284 }
285 NoteDeletedFunction(Decl: FD);
286 return true;
287 }
288
289 // [expr.prim.id]p4
290 // A program that refers explicitly or implicitly to a function with a
291 // trailing requires-clause whose constraint-expression is not satisfied,
292 // other than to declare it, is ill-formed. [...]
293 //
294 // See if this is a function with constraints that need to be satisfied.
295 // Check this before deducing the return type, as it might instantiate the
296 // definition.
297 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
298 ConstraintSatisfaction Satisfaction;
299 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
300 /*ForOverloadResolution*/ true))
301 // A diagnostic will have already been generated (non-constant
302 // constraint expression, for example)
303 return true;
304 if (!Satisfaction.IsSatisfied) {
305 Diag(Loc,
306 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
307 << D;
308 DiagnoseUnsatisfiedConstraint(Satisfaction);
309 return true;
310 }
311 }
312
313 // If the function has a deduced return type, and we can't deduce it,
314 // then we can't use it either.
315 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
316 DeduceReturnType(FD, Loc))
317 return true;
318
319 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
320 return true;
321
322 }
323
324 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
325 Concept && CheckConceptUseInDefinition(Concept, Loc))
326 return true;
327
328 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
329 // Lambdas are only default-constructible or assignable in C++2a onwards.
330 if (MD->getParent()->isLambda() &&
331 ((isa<CXXConstructorDecl>(Val: MD) &&
332 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
333 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
334 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
335 << !isa<CXXConstructorDecl>(Val: MD);
336 }
337 }
338
339 auto getReferencedObjCProp = [](const NamedDecl *D) ->
340 const ObjCPropertyDecl * {
341 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
342 return MD->findPropertyDecl();
343 return nullptr;
344 };
345 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
346 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
347 return true;
348 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
349 return true;
350 }
351
352 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
353 // Only the variables omp_in and omp_out are allowed in the combiner.
354 // Only the variables omp_priv and omp_orig are allowed in the
355 // initializer-clause.
356 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
357 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
358 isa<VarDecl>(Val: D)) {
359 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
360 << getCurFunction()->HasOMPDeclareReductionCombiner;
361 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
366 // List-items in map clauses on this construct may only refer to the declared
367 // variable var and entities that could be referenced by a procedure defined
368 // at the same location.
369 // [OpenMP 5.2] Also allow iterator declared variables.
370 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
371 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
372 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
373 << OpenMP().getOpenMPDeclareMapperVarName();
374 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
375 return true;
376 }
377
378 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
379 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
380 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
381 return true;
382 }
383
384 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
385 AvoidPartialAvailabilityChecks, ClassReceiver);
386
387 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
388
389 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
390
391 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
392 if (getLangOpts().getFPEvalMethod() !=
393 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
394 PP.getLastFPEvalPragmaLocation().isValid() &&
395 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
396 Diag(Loc: D->getLocation(),
397 DiagID: diag::err_type_available_only_in_default_eval_method)
398 << D->getName();
399 }
400
401 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
402 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
403
404 if (LangOpts.SYCLIsDevice ||
405 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
406 if (!Context.getTargetInfo().isTLSSupported())
407 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
408 if (VD->getTLSKind() != VarDecl::TLS_None)
409 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
410 }
411
412 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
413 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
414
415 return false;
416}
417
418void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
419 ArrayRef<Expr *> Args) {
420 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
421 if (!Attr)
422 return;
423
424 // The number of formal parameters of the declaration.
425 unsigned NumFormalParams;
426
427 // The kind of declaration. This is also an index into a %select in
428 // the diagnostic.
429 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
430
431 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
432 NumFormalParams = MD->param_size();
433 CalleeKind = CK_Method;
434 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
435 NumFormalParams = FD->param_size();
436 CalleeKind = CK_Function;
437 if (FD->hasCXXExplicitFunctionObjectParameter())
438 NumFormalParams++;
439 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
440 QualType Ty = VD->getType();
441 const FunctionType *Fn = nullptr;
442 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
443 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
444 if (!Fn)
445 return;
446 CalleeKind = CK_Function;
447 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
448 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
449 CalleeKind = CK_Block;
450 } else {
451 return;
452 }
453
454 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
455 NumFormalParams = proto->getNumParams();
456 else
457 NumFormalParams = 0;
458 } else {
459 return;
460 }
461
462 // "NullPos" is the number of formal parameters at the end which
463 // effectively count as part of the variadic arguments. This is
464 // useful if you would prefer to not have *any* formal parameters,
465 // but the language forces you to have at least one.
466 unsigned NullPos = Attr->getNullPos();
467 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
468 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
469
470 // The number of arguments which should follow the sentinel.
471 unsigned NumArgsAfterSentinel = Attr->getSentinel();
472
473 // If there aren't enough arguments for all the formal parameters,
474 // the sentinel, and the args after the sentinel, complain.
475 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
476 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
477 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
478 return;
479 }
480
481 // Otherwise, find the sentinel expression.
482 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
483 if (!SentinelExpr)
484 return;
485 if (SentinelExpr->isValueDependent())
486 return;
487 if (Context.isSentinelNullExpr(E: SentinelExpr))
488 return;
489
490 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
491 // or 'NULL' if those are actually defined in the context. Only use
492 // 'nil' for ObjC methods, where it's much more likely that the
493 // variadic arguments form a list of object pointers.
494 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
495 std::string NullValue;
496 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
497 NullValue = "nil";
498 else if (getLangOpts().CPlusPlus11)
499 NullValue = "nullptr";
500 else if (PP.isMacroDefined(Id: "NULL"))
501 NullValue = "NULL";
502 else
503 NullValue = "(void*) 0";
504
505 if (MissingNilLoc.isInvalid())
506 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
507 else
508 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
509 << int(CalleeKind)
510 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
511 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
512 << int(CalleeKind) << Attr->getRange();
513}
514
515SourceRange Sema::getExprRange(Expr *E) const {
516 return E ? E->getSourceRange() : SourceRange();
517}
518
519//===----------------------------------------------------------------------===//
520// Standard Promotions and Conversions
521//===----------------------------------------------------------------------===//
522
523/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
524ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
525 // Handle any placeholder expressions which made it here.
526 if (E->hasPlaceholderType()) {
527 ExprResult result = CheckPlaceholderExpr(E);
528 if (result.isInvalid()) return ExprError();
529 E = result.get();
530 }
531
532 QualType Ty = E->getType();
533 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
534
535 if (Ty->isFunctionType()) {
536 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
537 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
538 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
539 return ExprError();
540
541 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
542 CK: CK_FunctionToPointerDecay).get();
543 } else if (Ty->isArrayType()) {
544 // In C90 mode, arrays only promote to pointers if the array expression is
545 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
546 // type 'array of type' is converted to an expression that has type 'pointer
547 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
548 // that has type 'array of type' ...". The relevant change is "an lvalue"
549 // (C90) to "an expression" (C99).
550 //
551 // C++ 4.2p1:
552 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
553 // T" can be converted to an rvalue of type "pointer to T".
554 //
555 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
556 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
557 CK: CK_ArrayToPointerDecay);
558 if (Res.isInvalid())
559 return ExprError();
560 E = Res.get();
561 }
562 }
563 return E;
564}
565
566static void CheckForNullPointerDereference(Sema &S, Expr *E) {
567 // Check to see if we are dereferencing a null pointer. If so,
568 // and if not volatile-qualified, this is undefined behavior that the
569 // optimizer will delete, so warn about it. People sometimes try to use this
570 // to get a deterministic trap and are surprised by clang's behavior. This
571 // only handles the pattern "*null", which is a very syntactic check.
572 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
573 if (UO && UO->getOpcode() == UO_Deref &&
574 UO->getSubExpr()->getType()->isPointerType()) {
575 const LangAS AS =
576 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
577 if ((!isTargetAddressSpace(AS) ||
578 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
579 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
580 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
581 !UO->getType().isVolatileQualified()) {
582 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
583 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
584 << UO->getSubExpr()->getSourceRange());
585 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
586 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
587 }
588 }
589}
590
591static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
592 SourceLocation AssignLoc,
593 const Expr* RHS) {
594 const ObjCIvarDecl *IV = OIRE->getDecl();
595 if (!IV)
596 return;
597
598 DeclarationName MemberName = IV->getDeclName();
599 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
600 if (!Member || !Member->isStr(Str: "isa"))
601 return;
602
603 const Expr *Base = OIRE->getBase();
604 QualType BaseType = Base->getType();
605 if (OIRE->isArrow())
606 BaseType = BaseType->getPointeeType();
607 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
608 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
609 ObjCInterfaceDecl *ClassDeclared = nullptr;
610 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
611 if (!ClassDeclared->getSuperClass()
612 && (*ClassDeclared->ivar_begin()) == IV) {
613 if (RHS) {
614 NamedDecl *ObjectSetClass =
615 S.LookupSingleName(S: S.TUScope,
616 Name: &S.Context.Idents.get(Name: "object_setClass"),
617 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
618 if (ObjectSetClass) {
619 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
620 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
621 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
622 Code: "object_setClass(")
623 << FixItHint::CreateReplacement(
624 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
625 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
626 }
627 else
628 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
629 } else {
630 NamedDecl *ObjectGetClass =
631 S.LookupSingleName(S: S.TUScope,
632 Name: &S.Context.Idents.get(Name: "object_getClass"),
633 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
634 if (ObjectGetClass)
635 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
636 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
637 Code: "object_getClass(")
638 << FixItHint::CreateReplacement(
639 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
640 else
641 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
642 }
643 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
644 }
645 }
646}
647
648ExprResult Sema::DefaultLvalueConversion(Expr *E) {
649 // Handle any placeholder expressions which made it here.
650 if (E->hasPlaceholderType()) {
651 ExprResult result = CheckPlaceholderExpr(E);
652 if (result.isInvalid()) return ExprError();
653 E = result.get();
654 }
655
656 // C++ [conv.lval]p1:
657 // A glvalue of a non-function, non-array type T can be
658 // converted to a prvalue.
659 if (!E->isGLValue()) return E;
660
661 QualType T = E->getType();
662 assert(!T.isNull() && "r-value conversion on typeless expression?");
663
664 // lvalue-to-rvalue conversion cannot be applied to types that decay to
665 // pointers (i.e. function or array types).
666 if (T->canDecayToPointerType())
667 return E;
668
669 // We don't want to throw lvalue-to-rvalue casts on top of
670 // expressions of certain types in C++.
671 // In HLSL LvaluetoRvalue conversion is allowed on records.
672 if (getLangOpts().CPlusPlus) {
673 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
674 (T->isDependentType() && !T->isAnyPointerType() &&
675 !T->isMemberPointerType()))
676 return E;
677 }
678
679 // The C standard is actually really unclear on this point, and
680 // DR106 tells us what the result should be but not why. It's
681 // generally best to say that void types just doesn't undergo
682 // lvalue-to-rvalue at all. Note that expressions of unqualified
683 // 'void' type are never l-values, but qualified void can be.
684 if (T->isVoidType())
685 return E;
686
687 // OpenCL usually rejects direct accesses to values of 'half' type.
688 if (getLangOpts().OpenCL &&
689 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
690 T->isHalfType()) {
691 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
692 << 0 << T;
693 return ExprError();
694 }
695
696 CheckForNullPointerDereference(S&: *this, E);
697 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
698 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
699 Name: &Context.Idents.get(Name: "object_getClass"),
700 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
701 if (ObjectGetClass)
702 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
703 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
704 << FixItHint::CreateReplacement(
705 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
706 else
707 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
708 }
709 else if (const ObjCIvarRefExpr *OIRE =
710 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
711 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
712
713 // C++ [conv.lval]p1:
714 // [...] If T is a non-class type, the type of the prvalue is the
715 // cv-unqualified version of T. Otherwise, the type of the
716 // rvalue is T.
717 //
718 // C99 6.3.2.1p2:
719 // If the lvalue has qualified type, the value has the unqualified
720 // version of the type of the lvalue; otherwise, the value has the
721 // type of the lvalue.
722 if (T.hasQualifiers())
723 T = T.getUnqualifiedType();
724
725 // Under the MS ABI, lock down the inheritance model now.
726 if (T->isMemberPointerType() &&
727 Context.getTargetInfo().getCXXABI().isMicrosoft())
728 (void)isCompleteType(Loc: E->getExprLoc(), T);
729
730 ExprResult Res = CheckLValueToRValueConversionOperand(E);
731 if (Res.isInvalid())
732 return Res;
733 E = Res.get();
734
735 // Loading a __weak object implicitly retains the value, so we need a cleanup to
736 // balance that.
737 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
738 Cleanup.setExprNeedsCleanups(true);
739
740 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
741 Cleanup.setExprNeedsCleanups(true);
742
743 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
744 return ExprError();
745
746 // C++ [conv.lval]p3:
747 // If T is cv std::nullptr_t, the result is a null pointer constant.
748 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
749 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
750 FPO: CurFPFeatureOverrides());
751
752 // C11 6.3.2.1p2:
753 // ... if the lvalue has atomic type, the value has the non-atomic version
754 // of the type of the lvalue ...
755 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
756 T = Atomic->getValueType().getUnqualifiedType();
757 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
758 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
759 }
760
761 return Res;
762}
763
764ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
765 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
766 if (Res.isInvalid())
767 return ExprError();
768 Res = DefaultLvalueConversion(E: Res.get());
769 if (Res.isInvalid())
770 return ExprError();
771 return Res;
772}
773
774ExprResult Sema::CallExprUnaryConversions(Expr *E) {
775 QualType Ty = E->getType();
776 ExprResult Res = E;
777 // Only do implicit cast for a function type, but not for a pointer
778 // to function type.
779 if (Ty->isFunctionType()) {
780 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
781 CK: CK_FunctionToPointerDecay);
782 if (Res.isInvalid())
783 return ExprError();
784 }
785 Res = DefaultLvalueConversion(E: Res.get());
786 if (Res.isInvalid())
787 return ExprError();
788 return Res.get();
789}
790
791/// UsualUnaryFPConversions - Promotes floating-point types according to the
792/// current language semantics.
793ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
794 QualType Ty = E->getType();
795 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
796
797 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
798 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
799 (getLangOpts().getFPEvalMethod() !=
800 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
801 PP.getLastFPEvalPragmaLocation().isValid())) {
802 switch (EvalMethod) {
803 default:
804 llvm_unreachable("Unrecognized float evaluation method");
805 break;
806 case LangOptions::FEM_UnsetOnCommandLine:
807 llvm_unreachable("Float evaluation method should be set by now");
808 break;
809 case LangOptions::FEM_Double:
810 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
811 // Widen the expression to double.
812 return Ty->isComplexType()
813 ? ImpCastExprToType(E,
814 Type: Context.getComplexType(T: Context.DoubleTy),
815 CK: CK_FloatingComplexCast)
816 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
817 break;
818 case LangOptions::FEM_Extended:
819 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
820 // Widen the expression to long double.
821 return Ty->isComplexType()
822 ? ImpCastExprToType(
823 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
824 CK: CK_FloatingComplexCast)
825 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
826 CK: CK_FloatingCast);
827 break;
828 }
829 }
830
831 // Half FP have to be promoted to float unless it is natively supported
832 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
833 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
834
835 return E;
836}
837
838/// UsualUnaryConversions - Performs various conversions that are common to most
839/// operators (C99 6.3). The conversions of array and function types are
840/// sometimes suppressed. For example, the array->pointer conversion doesn't
841/// apply if the array is an argument to the sizeof or address (&) operators.
842/// In these instances, this routine should *not* be called.
843ExprResult Sema::UsualUnaryConversions(Expr *E) {
844 // First, convert to an r-value.
845 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
846 if (Res.isInvalid())
847 return ExprError();
848
849 // Promote floating-point types.
850 Res = UsualUnaryFPConversions(E: Res.get());
851 if (Res.isInvalid())
852 return ExprError();
853 E = Res.get();
854
855 QualType Ty = E->getType();
856 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
857
858 // Try to perform integral promotions if the object has a theoretically
859 // promotable type.
860 if (Ty->isIntegralOrUnscopedEnumerationType()) {
861 // C99 6.3.1.1p2:
862 //
863 // The following may be used in an expression wherever an int or
864 // unsigned int may be used:
865 // - an object or expression with an integer type whose integer
866 // conversion rank is less than or equal to the rank of int
867 // and unsigned int.
868 // - A bit-field of type _Bool, int, signed int, or unsigned int.
869 //
870 // If an int can represent all values of the original type, the
871 // value is converted to an int; otherwise, it is converted to an
872 // unsigned int. These are called the integer promotions. All
873 // other types are unchanged by the integer promotions.
874
875 QualType PTy = Context.isPromotableBitField(E);
876 if (!PTy.isNull()) {
877 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
878 return E;
879 }
880 if (Context.isPromotableIntegerType(T: Ty)) {
881 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
882 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
883 return E;
884 }
885 }
886 return E;
887}
888
889/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
890/// do not have a prototype. Arguments that have type float or __fp16
891/// are promoted to double. All other argument types are converted by
892/// UsualUnaryConversions().
893ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
894 QualType Ty = E->getType();
895 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
896
897 ExprResult Res = UsualUnaryConversions(E);
898 if (Res.isInvalid())
899 return ExprError();
900 E = Res.get();
901
902 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
903 // promote to double.
904 // Note that default argument promotion applies only to float (and
905 // half/fp16); it does not apply to _Float16.
906 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
907 if (BTy && (BTy->getKind() == BuiltinType::Half ||
908 BTy->getKind() == BuiltinType::Float)) {
909 if (getLangOpts().OpenCL &&
910 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
911 if (BTy->getKind() == BuiltinType::Half) {
912 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
913 }
914 } else {
915 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
916 }
917 }
918 if (BTy &&
919 getLangOpts().getExtendIntArgs() ==
920 LangOptions::ExtendArgsKind::ExtendTo64 &&
921 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
922 Context.getTypeSizeInChars(T: BTy) <
923 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
924 E = (Ty->isUnsignedIntegerType())
925 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
926 .get()
927 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
928 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
929 "Unexpected typesize for LongLongTy");
930 }
931
932 // C++ performs lvalue-to-rvalue conversion as a default argument
933 // promotion, even on class types, but note:
934 // C++11 [conv.lval]p2:
935 // When an lvalue-to-rvalue conversion occurs in an unevaluated
936 // operand or a subexpression thereof the value contained in the
937 // referenced object is not accessed. Otherwise, if the glvalue
938 // has a class type, the conversion copy-initializes a temporary
939 // of type T from the glvalue and the result of the conversion
940 // is a prvalue for the temporary.
941 // FIXME: add some way to gate this entire thing for correctness in
942 // potentially potentially evaluated contexts.
943 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
944 ExprResult Temp = PerformCopyInitialization(
945 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
946 EqualLoc: E->getExprLoc(), Init: E);
947 if (Temp.isInvalid())
948 return ExprError();
949 E = Temp.get();
950 }
951
952 // C++ [expr.call]p7, per CWG722:
953 // An argument that has (possibly cv-qualified) type std::nullptr_t is
954 // converted to void* ([conv.ptr]).
955 // (This does not apply to C23 nullptr)
956 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
957 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
958
959 return E;
960}
961
962VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
963 if (Ty->isIncompleteType()) {
964 // C++11 [expr.call]p7:
965 // After these conversions, if the argument does not have arithmetic,
966 // enumeration, pointer, pointer to member, or class type, the program
967 // is ill-formed.
968 //
969 // Since we've already performed null pointer conversion, array-to-pointer
970 // decay and function-to-pointer decay, the only such type in C++ is cv
971 // void. This also handles initializer lists as variadic arguments.
972 if (Ty->isVoidType())
973 return VarArgKind::Invalid;
974
975 if (Ty->isObjCObjectType())
976 return VarArgKind::Invalid;
977 return VarArgKind::Valid;
978 }
979
980 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
981 return VarArgKind::Invalid;
982
983 if (Context.getTargetInfo().getTriple().isWasm() &&
984 Ty.isWebAssemblyReferenceType()) {
985 return VarArgKind::Invalid;
986 }
987
988 if (Ty.isCXX98PODType(Context))
989 return VarArgKind::Valid;
990
991 // C++11 [expr.call]p7:
992 // Passing a potentially-evaluated argument of class type (Clause 9)
993 // having a non-trivial copy constructor, a non-trivial move constructor,
994 // or a non-trivial destructor, with no corresponding parameter,
995 // is conditionally-supported with implementation-defined semantics.
996 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
997 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
998 if (!Record->hasNonTrivialCopyConstructor() &&
999 !Record->hasNonTrivialMoveConstructor() &&
1000 !Record->hasNonTrivialDestructor())
1001 return VarArgKind::ValidInCXX11;
1002
1003 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1004 return VarArgKind::Valid;
1005
1006 if (Ty->isObjCObjectType())
1007 return VarArgKind::Invalid;
1008
1009 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1010 return VarArgKind::Valid;
1011
1012 if (getLangOpts().MSVCCompat)
1013 return VarArgKind::MSVCUndefined;
1014
1015 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1016 return VarArgKind::Valid;
1017
1018 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1019 // permitted to reject them. We should consider doing so.
1020 return VarArgKind::Undefined;
1021}
1022
1023void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1024 // Don't allow one to pass an Objective-C interface to a vararg.
1025 const QualType &Ty = E->getType();
1026 VarArgKind VAK = isValidVarArgType(Ty);
1027
1028 // Complain about passing non-POD types through varargs.
1029 switch (VAK) {
1030 case VarArgKind::ValidInCXX11:
1031 DiagRuntimeBehavior(
1032 Loc: E->getBeginLoc(), Statement: nullptr,
1033 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1034 [[fallthrough]];
1035 case VarArgKind::Valid:
1036 if (Ty->isRecordType()) {
1037 // This is unlikely to be what the user intended. If the class has a
1038 // 'c_str' member function, the user probably meant to call that.
1039 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1040 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1041 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1042 }
1043 break;
1044
1045 case VarArgKind::Undefined:
1046 case VarArgKind::MSVCUndefined:
1047 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1048 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1049 << getLangOpts().CPlusPlus11 << Ty << CT);
1050 break;
1051
1052 case VarArgKind::Invalid:
1053 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1054 Diag(Loc: E->getBeginLoc(),
1055 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1056 << Ty << CT;
1057 else if (Ty->isObjCObjectType())
1058 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1059 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1060 << Ty << CT);
1061 else
1062 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1063 << isa<InitListExpr>(Val: E) << Ty << CT;
1064 break;
1065 }
1066}
1067
1068ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1069 FunctionDecl *FDecl) {
1070 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1071 // Strip the unbridged-cast placeholder expression off, if applicable.
1072 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1073 (CT == VariadicCallType::Method ||
1074 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1075 E = ObjC().stripARCUnbridgedCast(e: E);
1076
1077 // Otherwise, do normal placeholder checking.
1078 } else {
1079 ExprResult ExprRes = CheckPlaceholderExpr(E);
1080 if (ExprRes.isInvalid())
1081 return ExprError();
1082 E = ExprRes.get();
1083 }
1084 }
1085
1086 ExprResult ExprRes = DefaultArgumentPromotion(E);
1087 if (ExprRes.isInvalid())
1088 return ExprError();
1089
1090 // Copy blocks to the heap.
1091 if (ExprRes.get()->getType()->isBlockPointerType())
1092 maybeExtendBlockObject(E&: ExprRes);
1093
1094 E = ExprRes.get();
1095
1096 // Diagnostics regarding non-POD argument types are
1097 // emitted along with format string checking in Sema::CheckFunctionCall().
1098 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1099 // Turn this into a trap.
1100 CXXScopeSpec SS;
1101 SourceLocation TemplateKWLoc;
1102 UnqualifiedId Name;
1103 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1104 IdLoc: E->getBeginLoc());
1105 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1106 /*HasTrailingLParen=*/true,
1107 /*IsAddressOfOperand=*/false);
1108 if (TrapFn.isInvalid())
1109 return ExprError();
1110
1111 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1112 RParenLoc: E->getEndLoc());
1113 if (Call.isInvalid())
1114 return ExprError();
1115
1116 ExprResult Comma =
1117 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1118 if (Comma.isInvalid())
1119 return ExprError();
1120 return Comma.get();
1121 }
1122
1123 if (!getLangOpts().CPlusPlus &&
1124 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1125 DiagID: diag::err_call_incomplete_argument))
1126 return ExprError();
1127
1128 return E;
1129}
1130
1131/// Convert complex integers to complex floats and real integers to
1132/// real floats as required for complex arithmetic. Helper function of
1133/// UsualArithmeticConversions()
1134///
1135/// \return false if the integer expression is an integer type and is
1136/// successfully converted to the (complex) float type.
1137static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1138 ExprResult &ComplexExpr,
1139 QualType IntTy,
1140 QualType ComplexTy,
1141 bool SkipCast) {
1142 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1143 if (SkipCast) return false;
1144 if (IntTy->isIntegerType()) {
1145 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1146 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1147 } else {
1148 assert(IntTy->isComplexIntegerType());
1149 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1150 CK: CK_IntegralComplexToFloatingComplex);
1151 }
1152 return false;
1153}
1154
1155// This handles complex/complex, complex/float, or float/complex.
1156// When both operands are complex, the shorter operand is converted to the
1157// type of the longer, and that is the type of the result. This corresponds
1158// to what is done when combining two real floating-point operands.
1159// The fun begins when size promotion occur across type domains.
1160// From H&S 6.3.4: When one operand is complex and the other is a real
1161// floating-point type, the less precise type is converted, within it's
1162// real or complex domain, to the precision of the other type. For example,
1163// when combining a "long double" with a "double _Complex", the
1164// "double _Complex" is promoted to "long double _Complex".
1165static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1166 QualType ShorterType,
1167 QualType LongerType,
1168 bool PromotePrecision) {
1169 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1170 QualType Result =
1171 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1172
1173 if (PromotePrecision) {
1174 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1175 Shorter =
1176 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1177 } else {
1178 if (LongerIsComplex)
1179 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1180 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1181 }
1182 }
1183 return Result;
1184}
1185
1186/// Handle arithmetic conversion with complex types. Helper function of
1187/// UsualArithmeticConversions()
1188static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1189 ExprResult &RHS, QualType LHSType,
1190 QualType RHSType, bool IsCompAssign) {
1191 // Handle (complex) integer types.
1192 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1193 /*SkipCast=*/false))
1194 return LHSType;
1195 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1196 /*SkipCast=*/IsCompAssign))
1197 return RHSType;
1198
1199 // Compute the rank of the two types, regardless of whether they are complex.
1200 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1201 if (Order < 0)
1202 // Promote the precision of the LHS if not an assignment.
1203 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1204 /*PromotePrecision=*/!IsCompAssign);
1205 // Promote the precision of the RHS unless it is already the same as the LHS.
1206 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1207 /*PromotePrecision=*/Order > 0);
1208}
1209
1210/// Handle arithmetic conversion from integer to float. Helper function
1211/// of UsualArithmeticConversions()
1212static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1213 ExprResult &IntExpr,
1214 QualType FloatTy, QualType IntTy,
1215 bool ConvertFloat, bool ConvertInt) {
1216 if (IntTy->isIntegerType()) {
1217 if (ConvertInt)
1218 // Convert intExpr to the lhs floating point type.
1219 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1220 CK: CK_IntegralToFloating);
1221 return FloatTy;
1222 }
1223
1224 // Convert both sides to the appropriate complex float.
1225 assert(IntTy->isComplexIntegerType());
1226 QualType result = S.Context.getComplexType(T: FloatTy);
1227
1228 // _Complex int -> _Complex float
1229 if (ConvertInt)
1230 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1231 CK: CK_IntegralComplexToFloatingComplex);
1232
1233 // float -> _Complex float
1234 if (ConvertFloat)
1235 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1236 CK: CK_FloatingRealToComplex);
1237
1238 return result;
1239}
1240
1241/// Handle arithmethic conversion with floating point types. Helper
1242/// function of UsualArithmeticConversions()
1243static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1244 ExprResult &RHS, QualType LHSType,
1245 QualType RHSType, bool IsCompAssign) {
1246 bool LHSFloat = LHSType->isRealFloatingType();
1247 bool RHSFloat = RHSType->isRealFloatingType();
1248
1249 // N1169 4.1.4: If one of the operands has a floating type and the other
1250 // operand has a fixed-point type, the fixed-point operand
1251 // is converted to the floating type [...]
1252 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1253 if (LHSFloat)
1254 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1255 else if (!IsCompAssign)
1256 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1257 return LHSFloat ? LHSType : RHSType;
1258 }
1259
1260 // If we have two real floating types, convert the smaller operand
1261 // to the bigger result.
1262 if (LHSFloat && RHSFloat) {
1263 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1264 if (order > 0) {
1265 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1266 return LHSType;
1267 }
1268
1269 assert(order < 0 && "illegal float comparison");
1270 if (!IsCompAssign)
1271 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1272 return RHSType;
1273 }
1274
1275 if (LHSFloat) {
1276 // Half FP has to be promoted to float unless it is natively supported
1277 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1278 LHSType = S.Context.FloatTy;
1279
1280 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1281 /*ConvertFloat=*/!IsCompAssign,
1282 /*ConvertInt=*/ true);
1283 }
1284 assert(RHSFloat);
1285 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1286 /*ConvertFloat=*/ true,
1287 /*ConvertInt=*/!IsCompAssign);
1288}
1289
1290/// Diagnose attempts to convert between __float128, __ibm128 and
1291/// long double if there is no support for such conversion.
1292/// Helper function of UsualArithmeticConversions().
1293static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1294 QualType RHSType) {
1295 // No issue if either is not a floating point type.
1296 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1297 return false;
1298
1299 // No issue if both have the same 128-bit float semantics.
1300 auto *LHSComplex = LHSType->getAs<ComplexType>();
1301 auto *RHSComplex = RHSType->getAs<ComplexType>();
1302
1303 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1304 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1305
1306 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1307 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1308
1309 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1310 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1311 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1312 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1313 return false;
1314
1315 return true;
1316}
1317
1318typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1319
1320namespace {
1321/// These helper callbacks are placed in an anonymous namespace to
1322/// permit their use as function template parameters.
1323ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1324 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1325}
1326
1327ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1328 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1329 CK: CK_IntegralComplexCast);
1330}
1331}
1332
1333/// Handle integer arithmetic conversions. Helper function of
1334/// UsualArithmeticConversions()
1335template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1336static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1337 ExprResult &RHS, QualType LHSType,
1338 QualType RHSType, bool IsCompAssign) {
1339 // The rules for this case are in C99 6.3.1.8
1340 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1341 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1342 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1343 if (LHSSigned == RHSSigned) {
1344 // Same signedness; use the higher-ranked type
1345 if (order >= 0) {
1346 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1347 return LHSType;
1348 } else if (!IsCompAssign)
1349 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1350 return RHSType;
1351 } else if (order != (LHSSigned ? 1 : -1)) {
1352 // The unsigned type has greater than or equal rank to the
1353 // signed type, so use the unsigned type
1354 if (RHSSigned) {
1355 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1356 return LHSType;
1357 } else if (!IsCompAssign)
1358 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1359 return RHSType;
1360 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1361 // The two types are different widths; if we are here, that
1362 // means the signed type is larger than the unsigned type, so
1363 // use the signed type.
1364 if (LHSSigned) {
1365 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1366 return LHSType;
1367 } else if (!IsCompAssign)
1368 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1369 return RHSType;
1370 } else {
1371 // The signed type is higher-ranked than the unsigned type,
1372 // but isn't actually any bigger (like unsigned int and long
1373 // on most 32-bit systems). Use the unsigned type corresponding
1374 // to the signed type.
1375 QualType result =
1376 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1377 RHS = (*doRHSCast)(S, RHS.get(), result);
1378 if (!IsCompAssign)
1379 LHS = (*doLHSCast)(S, LHS.get(), result);
1380 return result;
1381 }
1382}
1383
1384/// Handle conversions with GCC complex int extension. Helper function
1385/// of UsualArithmeticConversions()
1386static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1387 ExprResult &RHS, QualType LHSType,
1388 QualType RHSType,
1389 bool IsCompAssign) {
1390 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1391 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1392
1393 if (LHSComplexInt && RHSComplexInt) {
1394 QualType LHSEltType = LHSComplexInt->getElementType();
1395 QualType RHSEltType = RHSComplexInt->getElementType();
1396 QualType ScalarType =
1397 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1398 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1399
1400 return S.Context.getComplexType(T: ScalarType);
1401 }
1402
1403 if (LHSComplexInt) {
1404 QualType LHSEltType = LHSComplexInt->getElementType();
1405 QualType ScalarType =
1406 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1407 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1408 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1409 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1410 CK: CK_IntegralRealToComplex);
1411
1412 return ComplexType;
1413 }
1414
1415 assert(RHSComplexInt);
1416
1417 QualType RHSEltType = RHSComplexInt->getElementType();
1418 QualType ScalarType =
1419 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1420 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1421 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1422
1423 if (!IsCompAssign)
1424 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1425 CK: CK_IntegralRealToComplex);
1426 return ComplexType;
1427}
1428
1429static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1430 ExprResult &RHS,
1431 QualType LHSType,
1432 QualType RHSType,
1433 bool IsCompAssign) {
1434
1435 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1436 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1437
1438 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1439 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1440
1441 bool LHSHasTrap =
1442 LhsOBT && LhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1444 bool RHSHasTrap =
1445 RhsOBT && RhsOBT->getBehaviorKind() ==
1446 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1447 bool LHSHasWrap =
1448 LhsOBT && LhsOBT->getBehaviorKind() ==
1449 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1450 bool RHSHasWrap =
1451 RhsOBT && RhsOBT->getBehaviorKind() ==
1452 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1453
1454 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1455 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1456
1457 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1458 if (LHSHasTrap || RHSHasTrap)
1459 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1460 else if (LHSHasWrap || RHSHasWrap)
1461 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1462
1463 QualType LHSConvType = LHSUnderlyingType;
1464 QualType RHSConvType = RHSUnderlyingType;
1465 if (DominantBehavior) {
1466 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1467 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1468 Wrapped: LHSUnderlyingType);
1469 else
1470 LHSConvType = LHSType;
1471
1472 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1473 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1474 Wrapped: RHSUnderlyingType);
1475 else
1476 RHSConvType = RHSType;
1477 }
1478
1479 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1480 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1481}
1482
1483/// Return the rank of a given fixed point or integer type. The value itself
1484/// doesn't matter, but the values must be increasing with proper increasing
1485/// rank as described in N1169 4.1.1.
1486static unsigned GetFixedPointRank(QualType Ty) {
1487 const auto *BTy = Ty->getAs<BuiltinType>();
1488 assert(BTy && "Expected a builtin type.");
1489
1490 switch (BTy->getKind()) {
1491 case BuiltinType::ShortFract:
1492 case BuiltinType::UShortFract:
1493 case BuiltinType::SatShortFract:
1494 case BuiltinType::SatUShortFract:
1495 return 1;
1496 case BuiltinType::Fract:
1497 case BuiltinType::UFract:
1498 case BuiltinType::SatFract:
1499 case BuiltinType::SatUFract:
1500 return 2;
1501 case BuiltinType::LongFract:
1502 case BuiltinType::ULongFract:
1503 case BuiltinType::SatLongFract:
1504 case BuiltinType::SatULongFract:
1505 return 3;
1506 case BuiltinType::ShortAccum:
1507 case BuiltinType::UShortAccum:
1508 case BuiltinType::SatShortAccum:
1509 case BuiltinType::SatUShortAccum:
1510 return 4;
1511 case BuiltinType::Accum:
1512 case BuiltinType::UAccum:
1513 case BuiltinType::SatAccum:
1514 case BuiltinType::SatUAccum:
1515 return 5;
1516 case BuiltinType::LongAccum:
1517 case BuiltinType::ULongAccum:
1518 case BuiltinType::SatLongAccum:
1519 case BuiltinType::SatULongAccum:
1520 return 6;
1521 default:
1522 if (BTy->isInteger())
1523 return 0;
1524 llvm_unreachable("Unexpected fixed point or integer type");
1525 }
1526}
1527
1528/// handleFixedPointConversion - Fixed point operations between fixed
1529/// point types and integers or other fixed point types do not fall under
1530/// usual arithmetic conversion since these conversions could result in loss
1531/// of precsision (N1169 4.1.4). These operations should be calculated with
1532/// the full precision of their result type (N1169 4.1.6.2.1).
1533static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1534 QualType RHSTy) {
1535 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1536 "Expected at least one of the operands to be a fixed point type");
1537 assert((LHSTy->isFixedPointOrIntegerType() ||
1538 RHSTy->isFixedPointOrIntegerType()) &&
1539 "Special fixed point arithmetic operation conversions are only "
1540 "applied to ints or other fixed point types");
1541
1542 // If one operand has signed fixed-point type and the other operand has
1543 // unsigned fixed-point type, then the unsigned fixed-point operand is
1544 // converted to its corresponding signed fixed-point type and the resulting
1545 // type is the type of the converted operand.
1546 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1547 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1548 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1549 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1550
1551 // The result type is the type with the highest rank, whereby a fixed-point
1552 // conversion rank is always greater than an integer conversion rank; if the
1553 // type of either of the operands is a saturating fixedpoint type, the result
1554 // type shall be the saturating fixed-point type corresponding to the type
1555 // with the highest rank; the resulting value is converted (taking into
1556 // account rounding and overflow) to the precision of the resulting type.
1557 // Same ranks between signed and unsigned types are resolved earlier, so both
1558 // types are either signed or both unsigned at this point.
1559 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1560 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1561
1562 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1563
1564 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1565 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1566
1567 return ResultTy;
1568}
1569
1570/// Check that the usual arithmetic conversions can be performed on this pair of
1571/// expressions that might be of enumeration type.
1572void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1573 SourceLocation Loc,
1574 ArithConvKind ACK) {
1575 // C++2a [expr.arith.conv]p1:
1576 // If one operand is of enumeration type and the other operand is of a
1577 // different enumeration type or a floating-point type, this behavior is
1578 // deprecated ([depr.arith.conv.enum]).
1579 //
1580 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1581 // Eventually we will presumably reject these cases (in C++23 onwards?).
1582 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1583 R = RHS->getEnumCoercedType(Ctx: Context);
1584 bool LEnum = L->isUnscopedEnumerationType(),
1585 REnum = R->isUnscopedEnumerationType();
1586 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1587 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1588 (REnum && L->isFloatingType())) {
1589 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1590 : getLangOpts().CPlusPlus20
1591 ? diag::warn_arith_conv_enum_float_cxx20
1592 : diag::warn_arith_conv_enum_float)
1593 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1594 << L << R;
1595 } else if (!IsCompAssign && LEnum && REnum &&
1596 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1597 unsigned DiagID;
1598 // In C++ 26, usual arithmetic conversions between 2 different enum types
1599 // are ill-formed.
1600 if (getLangOpts().CPlusPlus26)
1601 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1602 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1603 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1604 // If either enumeration type is unnamed, it's less likely that the
1605 // user cares about this, but this situation is still deprecated in
1606 // C++2a. Use a different warning group.
1607 DiagID = getLangOpts().CPlusPlus20
1608 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1609 : diag::warn_arith_conv_mixed_anon_enum_types;
1610 } else if (ACK == ArithConvKind::Conditional) {
1611 // Conditional expressions are separated out because they have
1612 // historically had a different warning flag.
1613 DiagID = getLangOpts().CPlusPlus20
1614 ? diag::warn_conditional_mixed_enum_types_cxx20
1615 : diag::warn_conditional_mixed_enum_types;
1616 } else if (ACK == ArithConvKind::Comparison) {
1617 // Comparison expressions are separated out because they have
1618 // historically had a different warning flag.
1619 DiagID = getLangOpts().CPlusPlus20
1620 ? diag::warn_comparison_mixed_enum_types_cxx20
1621 : diag::warn_comparison_mixed_enum_types;
1622 } else {
1623 DiagID = getLangOpts().CPlusPlus20
1624 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1625 : diag::warn_arith_conv_mixed_enum_types;
1626 }
1627 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1628 << (int)ACK << L << R;
1629 }
1630}
1631
1632static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1633 Expr *RHS, SourceLocation Loc,
1634 ArithConvKind ACK) {
1635 QualType LHSType = LHS->getType().getUnqualifiedType();
1636 QualType RHSType = RHS->getType().getUnqualifiedType();
1637
1638 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1639 !RHSType->isUnicodeCharacterType())
1640 return;
1641
1642 if (ACK == ArithConvKind::Comparison) {
1643 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1644 return;
1645
1646 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1647 if (T->isChar8Type())
1648 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1649 if (T->isChar16Type())
1650 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1651 assert(T->isChar32Type());
1652 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1653 };
1654
1655 Expr::EvalResult LHSRes, RHSRes;
1656 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1657 AllowSideEffects: Expr::SE_AllowSideEffects,
1658 InConstantContext: SemaRef.isConstantEvaluatedContext());
1659 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1660 AllowSideEffects: Expr::SE_AllowSideEffects,
1661 InConstantContext: SemaRef.isConstantEvaluatedContext());
1662
1663 // Don't warn if the one known value is a representable
1664 // in the type of both expressions.
1665 if (LHSSuccess != RHSuccess) {
1666 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1667 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1668 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1669 return;
1670 }
1671
1672 if (!LHSSuccess || !RHSuccess) {
1673 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1674 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1675 << RHSType;
1676 return;
1677 }
1678
1679 llvm::APSInt LHSValue(32);
1680 LHSValue = LHSRes.Val.getInt();
1681 llvm::APSInt RHSValue(32);
1682 RHSValue = RHSRes.Val.getInt();
1683
1684 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1685 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1686 if (LHSSafe && RHSSafe)
1687 return;
1688
1689 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1690 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1691 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1692 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1693 return;
1694 }
1695
1696 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1697 return;
1698
1699 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1700 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1701 << RHSType;
1702}
1703
1704/// UsualArithmeticConversions - Performs various conversions that are common to
1705/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1706/// routine returns the first non-arithmetic type found. The client is
1707/// responsible for emitting appropriate error diagnostics.
1708QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1709 SourceLocation Loc,
1710 ArithConvKind ACK) {
1711
1712 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1713
1714 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1715
1716 if (ACK != ArithConvKind::CompAssign) {
1717 LHS = UsualUnaryConversions(E: LHS.get());
1718 if (LHS.isInvalid())
1719 return QualType();
1720 }
1721
1722 RHS = UsualUnaryConversions(E: RHS.get());
1723 if (RHS.isInvalid())
1724 return QualType();
1725
1726 // For conversion purposes, we ignore any qualifiers.
1727 // For example, "const float" and "float" are equivalent.
1728 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1729 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1730
1731 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1732 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1733 LHSType = AtomicLHS->getValueType();
1734
1735 // If both types are identical, no conversion is needed.
1736 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1737 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1738
1739 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1740 // The caller can deal with this (e.g. pointer + int).
1741 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1742 return QualType();
1743
1744 // Apply unary and bitfield promotions to the LHS's type.
1745 QualType LHSUnpromotedType = LHSType;
1746 if (Context.isPromotableIntegerType(T: LHSType))
1747 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1748 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1749 if (!LHSBitfieldPromoteTy.isNull())
1750 LHSType = LHSBitfieldPromoteTy;
1751 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1752 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1753
1754 // If both types are identical, no conversion is needed.
1755 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1756 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1757
1758 // At this point, we have two different arithmetic types.
1759
1760 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1761 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1762 return QualType();
1763
1764 // Diagnose attempts to convert between __ibm128, __float128 and long double
1765 // where such conversions currently can't be handled.
1766 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1767 return QualType();
1768
1769 // Handle complex types first (C99 6.3.1.8p1).
1770 if (LHSType->isComplexType() || RHSType->isComplexType())
1771 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1772 IsCompAssign: ACK == ArithConvKind::CompAssign);
1773
1774 // Now handle "real" floating types (i.e. float, double, long double).
1775 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1776 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1777 IsCompAssign: ACK == ArithConvKind::CompAssign);
1778
1779 // Handle GCC complex int extension.
1780 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1781 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1782 IsCompAssign: ACK == ArithConvKind::CompAssign);
1783
1784 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1785 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1786
1787 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1788 return handleOverflowBehaviorTypeConversion(
1789 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1790
1791 // Finally, we have two differing integer types.
1792 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1793 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1794}
1795
1796//===----------------------------------------------------------------------===//
1797// Semantic Analysis for various Expression Types
1798//===----------------------------------------------------------------------===//
1799
1800
1801ExprResult Sema::ActOnGenericSelectionExpr(
1802 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1803 bool PredicateIsExpr, void *ControllingExprOrType,
1804 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1805 unsigned NumAssocs = ArgTypes.size();
1806 assert(NumAssocs == ArgExprs.size());
1807
1808 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1809 for (unsigned i = 0; i < NumAssocs; ++i) {
1810 if (ArgTypes[i])
1811 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1812 else
1813 Types[i] = nullptr;
1814 }
1815
1816 // If we have a controlling type, we need to convert it from a parsed type
1817 // into a semantic type and then pass that along.
1818 if (!PredicateIsExpr) {
1819 TypeSourceInfo *ControllingType;
1820 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1821 TInfo: &ControllingType);
1822 assert(ControllingType && "couldn't get the type out of the parser");
1823 ControllingExprOrType = ControllingType;
1824 }
1825
1826 ExprResult ER = CreateGenericSelectionExpr(
1827 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1828 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1829 delete [] Types;
1830 return ER;
1831}
1832
1833// Helper function to determine type compatibility for C _Generic expressions.
1834// Multiple compatible types within the same _Generic expression is ambiguous
1835// and not valid.
1836static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1837 QualType U) {
1838 // Try to handle special types like OverflowBehaviorTypes
1839 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1840 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1841
1842 if (TOBT || UOBT) {
1843 if (TOBT && UOBT) {
1844 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1845 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1846 T2: UOBT->getUnderlyingType());
1847 return false;
1848 }
1849 return false;
1850 }
1851
1852 // We're dealing with types that don't require special handling.
1853 return Ctx.typesAreCompatible(T1: T, T2: U);
1854}
1855
1856ExprResult Sema::CreateGenericSelectionExpr(
1857 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1858 bool PredicateIsExpr, void *ControllingExprOrType,
1859 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1860 unsigned NumAssocs = Types.size();
1861 assert(NumAssocs == Exprs.size());
1862 assert(ControllingExprOrType &&
1863 "Must have either a controlling expression or a controlling type");
1864
1865 Expr *ControllingExpr = nullptr;
1866 TypeSourceInfo *ControllingType = nullptr;
1867 if (PredicateIsExpr) {
1868 // Decay and strip qualifiers for the controlling expression type, and
1869 // handle placeholder type replacement. See committee discussion from WG14
1870 // DR423.
1871 EnterExpressionEvaluationContext Unevaluated(
1872 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1873 ExprResult R = DefaultFunctionArrayLvalueConversion(
1874 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1875 if (R.isInvalid())
1876 return ExprError();
1877 ControllingExpr = R.get();
1878 } else {
1879 // The extension form uses the type directly rather than converting it.
1880 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1881 if (!ControllingType)
1882 return ExprError();
1883 }
1884
1885 bool TypeErrorFound = false,
1886 IsResultDependent = ControllingExpr
1887 ? ControllingExpr->isTypeDependent()
1888 : ControllingType->getType()->isDependentType(),
1889 ContainsUnexpandedParameterPack =
1890 ControllingExpr
1891 ? ControllingExpr->containsUnexpandedParameterPack()
1892 : ControllingType->getType()->containsUnexpandedParameterPack();
1893
1894 // The controlling expression is an unevaluated operand, so side effects are
1895 // likely unintended.
1896 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1897 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1898 Diag(Loc: ControllingExpr->getExprLoc(),
1899 DiagID: diag::warn_side_effects_unevaluated_context);
1900
1901 for (unsigned i = 0; i < NumAssocs; ++i) {
1902 if (Exprs[i]->containsUnexpandedParameterPack())
1903 ContainsUnexpandedParameterPack = true;
1904
1905 if (Types[i]) {
1906 if (Types[i]->getType()->containsUnexpandedParameterPack())
1907 ContainsUnexpandedParameterPack = true;
1908
1909 if (Types[i]->getType()->isDependentType()) {
1910 IsResultDependent = true;
1911 } else {
1912 // We relax the restriction on use of incomplete types and non-object
1913 // types with the type-based extension of _Generic. Allowing incomplete
1914 // objects means those can be used as "tags" for a type-safe way to map
1915 // to a value. Similarly, matching on function types rather than
1916 // function pointer types can be useful. However, the restriction on VM
1917 // types makes sense to retain as there are open questions about how
1918 // the selection can be made at compile time.
1919 //
1920 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1921 // complete object type other than a variably modified type."
1922 // C2y removed the requirement that an expression form must
1923 // use a complete type, though it's still as-if the type has undergone
1924 // lvalue conversion. We support this as an extension in C23 and
1925 // earlier because GCC does so.
1926 unsigned D = 0;
1927 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1928 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1929 : diag::compat_pre_c2y_assoc_type_incomplete;
1930 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1931 D = diag::err_assoc_type_nonobject;
1932 else if (Types[i]->getType()->isVariablyModifiedType())
1933 D = diag::err_assoc_type_variably_modified;
1934 else if (ControllingExpr) {
1935 // Because the controlling expression undergoes lvalue conversion,
1936 // array conversion, and function conversion, an association which is
1937 // of array type, function type, or is qualified can never be
1938 // reached. We will warn about this so users are less surprised by
1939 // the unreachable association. However, we don't have to handle
1940 // function types; that's not an object type, so it's handled above.
1941 //
1942 // The logic is somewhat different for C++ because C++ has different
1943 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1944 // If T is a non-class type, the type of the prvalue is the cv-
1945 // unqualified version of T. Otherwise, the type of the prvalue is T.
1946 // The result of these rules is that all qualified types in an
1947 // association in C are unreachable, and in C++, only qualified non-
1948 // class types are unreachable.
1949 //
1950 // NB: this does not apply when the first operand is a type rather
1951 // than an expression, because the type form does not undergo
1952 // conversion.
1953 unsigned Reason = 0;
1954 QualType QT = Types[i]->getType();
1955 if (QT->isArrayType())
1956 Reason = 1;
1957 else if (QT.hasQualifiers() &&
1958 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1959 Reason = 2;
1960
1961 if (Reason)
1962 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1963 DiagID: diag::warn_unreachable_association)
1964 << QT << (Reason - 1);
1965 }
1966
1967 if (D != 0) {
1968 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1969 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1970 if (getDiagnostics().getDiagnosticLevel(
1971 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1972 DiagnosticsEngine::Error)
1973 TypeErrorFound = true;
1974 }
1975
1976 // C11 6.5.1.1p2 "No two generic associations in the same generic
1977 // selection shall specify compatible types."
1978 for (unsigned j = i+1; j < NumAssocs; ++j)
1979 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1980 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1981 U: Types[j]->getType())) {
1982 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1983 DiagID: diag::err_assoc_compatible_types)
1984 << Types[j]->getTypeLoc().getSourceRange()
1985 << Types[j]->getType()
1986 << Types[i]->getType();
1987 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1988 DiagID: diag::note_compat_assoc)
1989 << Types[i]->getTypeLoc().getSourceRange()
1990 << Types[i]->getType();
1991 TypeErrorFound = true;
1992 }
1993 }
1994 }
1995 }
1996 if (TypeErrorFound)
1997 return ExprError();
1998
1999 // If we determined that the generic selection is result-dependent, don't
2000 // try to compute the result expression.
2001 if (IsResultDependent) {
2002 if (ControllingExpr)
2003 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
2004 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2005 ContainsUnexpandedParameterPack);
2006 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
2007 AssocExprs: Exprs, DefaultLoc, RParenLoc,
2008 ContainsUnexpandedParameterPack);
2009 }
2010
2011 SmallVector<unsigned, 1> CompatIndices;
2012 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2013 // Look at the canonical type of the controlling expression in case it was a
2014 // deduced type like __auto_type. However, when issuing diagnostics, use the
2015 // type the user wrote in source rather than the canonical one.
2016 for (unsigned i = 0; i < NumAssocs; ++i) {
2017 if (!Types[i])
2018 DefaultIndex = i;
2019 else {
2020 bool Compatible;
2021 QualType ControllingQT =
2022 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2023 : ControllingType->getType().getCanonicalType();
2024 QualType AssocQT = Types[i]->getType();
2025
2026 Compatible =
2027 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2028
2029 if (Compatible)
2030 CompatIndices.push_back(Elt: i);
2031 }
2032 }
2033
2034 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2035 TypeSourceInfo *ControllingType) {
2036 // We strip parens here because the controlling expression is typically
2037 // parenthesized in macro definitions.
2038 if (ControllingExpr)
2039 ControllingExpr = ControllingExpr->IgnoreParens();
2040
2041 SourceRange SR = ControllingExpr
2042 ? ControllingExpr->getSourceRange()
2043 : ControllingType->getTypeLoc().getSourceRange();
2044 QualType QT = ControllingExpr ? ControllingExpr->getType()
2045 : ControllingType->getType();
2046
2047 return std::make_pair(x&: SR, y&: QT);
2048 };
2049
2050 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2051 // type compatible with at most one of the types named in its generic
2052 // association list."
2053 if (CompatIndices.size() > 1) {
2054 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2055 SourceRange SR = P.first;
2056 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2057 << SR << P.second << (unsigned)CompatIndices.size();
2058 for (unsigned I : CompatIndices) {
2059 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2060 DiagID: diag::note_compat_assoc)
2061 << Types[I]->getTypeLoc().getSourceRange()
2062 << Types[I]->getType();
2063 }
2064 return ExprError();
2065 }
2066
2067 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2068 // its controlling expression shall have type compatible with exactly one of
2069 // the types named in its generic association list."
2070 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2071 CompatIndices.size() == 0) {
2072 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2073 SourceRange SR = P.first;
2074 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2075 return ExprError();
2076 }
2077
2078 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2079 // type name that is compatible with the type of the controlling expression,
2080 // then the result expression of the generic selection is the expression
2081 // in that generic association. Otherwise, the result expression of the
2082 // generic selection is the expression in the default generic association."
2083 unsigned ResultIndex =
2084 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2085
2086 if (ControllingExpr) {
2087 return GenericSelectionExpr::Create(
2088 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2089 ContainsUnexpandedParameterPack, ResultIndex);
2090 }
2091 return GenericSelectionExpr::Create(
2092 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2093 ContainsUnexpandedParameterPack, ResultIndex);
2094}
2095
2096static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2097 switch (Kind) {
2098 default:
2099 llvm_unreachable("unexpected TokenKind");
2100 case tok::kw___func__:
2101 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2102 case tok::kw___FUNCTION__:
2103 return PredefinedIdentKind::Function;
2104 case tok::kw___FUNCDNAME__:
2105 return PredefinedIdentKind::FuncDName; // [MS]
2106 case tok::kw___FUNCSIG__:
2107 return PredefinedIdentKind::FuncSig; // [MS]
2108 case tok::kw_L__FUNCTION__:
2109 return PredefinedIdentKind::LFunction; // [MS]
2110 case tok::kw_L__FUNCSIG__:
2111 return PredefinedIdentKind::LFuncSig; // [MS]
2112 case tok::kw___PRETTY_FUNCTION__:
2113 return PredefinedIdentKind::PrettyFunction; // [GNU]
2114 }
2115}
2116
2117/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2118/// to determine the value of a PredefinedExpr. This can be either a
2119/// block, lambda, captured statement, function, otherwise a nullptr.
2120static Decl *getPredefinedExprDecl(Sema &S, DeclContext *DC) {
2121 auto LSI = S.FunctionScopes.rbegin();
2122
2123 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2124 if (isLambdaCallOperator(DC)) {
2125 auto E = S.FunctionScopes.rend();
2126 while (LSI != E && !isa<LambdaScopeInfo>(Val: *LSI))
2127 ++LSI;
2128 assert(LSI != E && "Should be in a lambda scope info");
2129 if (dyn_cast<LambdaScopeInfo>(Val: *LSI)->BeforeCompoundStatement)
2130 DC = DC->getParent();
2131 ++LSI;
2132 }
2133 };
2134
2135 tryAdjustLambdaContext(DC);
2136 while (DC &&
2137 !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) {
2138 DC = DC->getParent();
2139 tryAdjustLambdaContext(DC);
2140 }
2141
2142 return cast_or_null<Decl>(Val: DC);
2143}
2144
2145/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2146/// location of the token and the offset of the ud-suffix within it.
2147static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2148 unsigned Offset) {
2149 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2150 LangOpts: S.getLangOpts());
2151}
2152
2153/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2154/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2155static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2156 IdentifierInfo *UDSuffix,
2157 SourceLocation UDSuffixLoc,
2158 ArrayRef<Expr*> Args,
2159 SourceLocation LitEndLoc) {
2160 assert(Args.size() <= 2 && "too many arguments for literal operator");
2161
2162 QualType ArgTy[2];
2163 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2164 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2165 if (ArgTy[ArgIdx]->isArrayType())
2166 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2167 }
2168
2169 DeclarationName OpName =
2170 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2171 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2172 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2173
2174 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2175 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2176 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2177 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2178 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2179 return ExprError();
2180
2181 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2182}
2183
2184ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2185 // StringToks needs backing storage as it doesn't hold array elements itself
2186 std::vector<Token> ExpandedToks;
2187 if (getLangOpts().MicrosoftExt)
2188 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2189
2190 StringLiteralParser Literal(StringToks, PP,
2191 StringLiteralEvalMethod::Unevaluated);
2192 if (Literal.hadError)
2193 return ExprError();
2194
2195 SmallVector<SourceLocation, 4> StringTokLocs;
2196 for (const Token &Tok : StringToks)
2197 StringTokLocs.push_back(Elt: Tok.getLocation());
2198
2199 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2200 Kind: StringLiteralKind::Unevaluated,
2201 Pascal: false, Ty: {}, Locs: StringTokLocs);
2202
2203 if (!Literal.getUDSuffix().empty()) {
2204 SourceLocation UDSuffixLoc =
2205 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2206 Offset: Literal.getUDSuffixOffset());
2207 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2208 }
2209
2210 return Lit;
2211}
2212
2213std::vector<Token>
2214Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2215 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2216 // local macros that expand to string literals that may be concatenated.
2217 // These macros are expanded here (in Sema), because StringLiteralParser
2218 // (in Lex) doesn't know the enclosing function (because it hasn't been
2219 // parsed yet).
2220 assert(getLangOpts().MicrosoftExt);
2221
2222 // Note: Although function local macros are defined only inside functions,
2223 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2224 // expansion of macros into empty string literals without additional checks.
2225 Decl *CurrentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
2226 if (!CurrentDecl)
2227 CurrentDecl = Context.getTranslationUnitDecl();
2228
2229 std::vector<Token> ExpandedToks;
2230 ExpandedToks.reserve(n: Toks.size());
2231 for (const Token &Tok : Toks) {
2232 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2233 assert(tok::isStringLiteral(Tok.getKind()));
2234 ExpandedToks.emplace_back(args: Tok);
2235 continue;
2236 }
2237 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2238 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2239 // Stringify predefined expression
2240 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2241 << Tok.getKind();
2242 SmallString<64> Str;
2243 llvm::raw_svector_ostream OS(Str);
2244 Token &Exp = ExpandedToks.emplace_back();
2245 Exp.startToken();
2246 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2247 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2248 OS << 'L';
2249 Exp.setKind(tok::wide_string_literal);
2250 } else {
2251 Exp.setKind(tok::string_literal);
2252 }
2253 OS << '"'
2254 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2255 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2256 << '"';
2257 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2258 }
2259 return ExpandedToks;
2260}
2261
2262ExprResult
2263Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2264 assert(!StringToks.empty() && "Must have at least one string!");
2265
2266 // StringToks needs backing storage as it doesn't hold array elements itself
2267 std::vector<Token> ExpandedToks;
2268 if (getLangOpts().MicrosoftExt)
2269 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2270
2271 StringLiteralParser Literal(
2272 StringToks, PP, StringLiteralEvalMethod::Evaluated, CA_ToLiteralEncoding);
2273 if (Literal.hadError)
2274 return ExprError();
2275
2276 SmallVector<SourceLocation, 4> StringTokLocs;
2277 for (const Token &Tok : StringToks)
2278 StringTokLocs.push_back(Elt: Tok.getLocation());
2279
2280 QualType CharTy = Context.CharTy;
2281 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2282 if (Literal.isWide()) {
2283 CharTy = Context.getWideCharType();
2284 Kind = StringLiteralKind::Wide;
2285 } else if (Literal.isUTF8()) {
2286 if (getLangOpts().Char8)
2287 CharTy = Context.Char8Ty;
2288 else if (getLangOpts().C23)
2289 CharTy = Context.UnsignedCharTy;
2290 Kind = StringLiteralKind::UTF8;
2291 } else if (Literal.isUTF16()) {
2292 CharTy = Context.Char16Ty;
2293 Kind = StringLiteralKind::UTF16;
2294 } else if (Literal.isUTF32()) {
2295 CharTy = Context.Char32Ty;
2296 Kind = StringLiteralKind::UTF32;
2297 } else if (Literal.isPascal()) {
2298 CharTy = Context.UnsignedCharTy;
2299 }
2300
2301 // Warn on u8 string literals before C++20 and C23, whose type
2302 // was an array of char before but becomes an array of char8_t.
2303 // In C++20, it cannot be used where a pointer to char is expected.
2304 // In C23, it might have an unexpected value if char was signed.
2305 if (Kind == StringLiteralKind::UTF8 &&
2306 (getLangOpts().CPlusPlus
2307 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2308 : !getLangOpts().C23)) {
2309 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2310 ? diag::warn_cxx20_compat_utf8_string
2311 : diag::warn_c23_compat_utf8_string);
2312
2313 // Create removals for all 'u8' prefixes in the string literal(s). This
2314 // ensures C++20/C23 compatibility (but may change the program behavior when
2315 // built by non-Clang compilers for which the execution character set is
2316 // not always UTF-8).
2317 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2318 SourceLocation RemovalDiagLoc;
2319 for (const Token &Tok : StringToks) {
2320 if (Tok.getKind() == tok::utf8_string_literal) {
2321 if (RemovalDiagLoc.isInvalid())
2322 RemovalDiagLoc = Tok.getLocation();
2323 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2324 B: Tok.getLocation(),
2325 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2326 SM: getSourceManager(), LangOpts: getLangOpts())));
2327 }
2328 }
2329 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2330 }
2331
2332 QualType StrTy =
2333 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2334
2335 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2336 StringLiteral *Lit = StringLiteral::Create(
2337 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2338 if (Literal.getUDSuffix().empty())
2339 return Lit;
2340
2341 // We're building a user-defined literal.
2342 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2343 SourceLocation UDSuffixLoc =
2344 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2345 Offset: Literal.getUDSuffixOffset());
2346
2347 // Make sure we're allowed user-defined literals here.
2348 if (!UDLScope)
2349 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2350
2351 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2352 // operator "" X (str, len)
2353 QualType SizeType = Context.getSizeType();
2354
2355 DeclarationName OpName =
2356 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2357 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2358 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2359
2360 QualType ArgTy[] = {
2361 Context.getArrayDecayedType(T: StrTy), SizeType
2362 };
2363
2364 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2365 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2366 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2367 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2368 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2369
2370 case LOLR_Cooked: {
2371 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2372 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2373 l: StringTokLocs[0]);
2374 Expr *Args[] = { Lit, LenArg };
2375
2376 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2377 }
2378
2379 case LOLR_Template: {
2380 TemplateArgumentListInfo ExplicitArgs;
2381 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2382 TemplateArgumentLocInfo ArgInfo(Lit);
2383 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2384 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2385 ExplicitTemplateArgs: &ExplicitArgs);
2386 }
2387
2388 case LOLR_StringTemplatePack: {
2389 TemplateArgumentListInfo ExplicitArgs;
2390
2391 unsigned CharBits = Context.getIntWidth(T: CharTy);
2392 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2393 llvm::APSInt Value(CharBits, CharIsUnsigned);
2394
2395 TemplateArgument TypeArg(CharTy);
2396 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2397 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2398
2399 SourceLocation Loc = StringTokLocs.back();
2400 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2401 Value = Lit->getCodeUnit(I);
2402 TemplateArgument Arg(Context, Value, CharTy);
2403 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2404 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2405 }
2406 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2407 }
2408 case LOLR_Raw:
2409 case LOLR_ErrorNoDiagnostic:
2410 llvm_unreachable("unexpected literal operator lookup result");
2411 case LOLR_Error:
2412 return ExprError();
2413 }
2414 llvm_unreachable("unexpected literal operator lookup result");
2415}
2416
2417DeclRefExpr *
2418Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2419 SourceLocation Loc,
2420 const CXXScopeSpec *SS) {
2421 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2422 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2423}
2424
2425DeclRefExpr *
2426Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2427 const DeclarationNameInfo &NameInfo,
2428 const CXXScopeSpec *SS, NamedDecl *FoundD,
2429 SourceLocation TemplateKWLoc,
2430 const TemplateArgumentListInfo *TemplateArgs) {
2431 NestedNameSpecifierLoc NNS =
2432 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2433 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2434 TemplateArgs);
2435}
2436
2437// CUDA/HIP: Check whether a captured reference variable is referencing a
2438// host variable in a device or host device lambda.
2439static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2440 VarDecl *VD) {
2441 if (!S.getLangOpts().CUDA || !VD->hasInit())
2442 return false;
2443 assert(VD->getType()->isReferenceType());
2444
2445 // Check whether the reference variable is referencing a host variable.
2446 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2447 if (!DRE)
2448 return false;
2449 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2450 if (!Referee || !Referee->hasGlobalStorage() ||
2451 Referee->hasAttr<CUDADeviceAttr>())
2452 return false;
2453
2454 // Check whether the current function is a device or host device lambda.
2455 // Check whether the reference variable is a capture by getDeclContext()
2456 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2457 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2458 if (MD && MD->getParent()->isLambda() &&
2459 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2460 VD->getDeclContext() != MD)
2461 return true;
2462
2463 return false;
2464}
2465
2466NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2467 // A declaration named in an unevaluated operand never constitutes an odr-use.
2468 if (isUnevaluatedContext())
2469 return NOUR_Unevaluated;
2470
2471 // C++2a [basic.def.odr]p4:
2472 // A variable x whose name appears as a potentially-evaluated expression e
2473 // is odr-used by e unless [...] x is a reference that is usable in
2474 // constant expressions.
2475 // CUDA/HIP:
2476 // If a reference variable referencing a host variable is captured in a
2477 // device or host device lambda, the value of the referee must be copied
2478 // to the capture and the reference variable must be treated as odr-use
2479 // since the value of the referee is not known at compile time and must
2480 // be loaded from the captured.
2481 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2482 if (VD->getType()->isReferenceType() &&
2483 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2484 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2485 VD->isUsableInConstantExpressions(C: Context))
2486 return NOUR_Constant;
2487 }
2488
2489 // All remaining non-variable cases constitute an odr-use. For variables, we
2490 // need to wait and see how the expression is used.
2491 return NOUR_None;
2492}
2493
2494DeclRefExpr *
2495Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2496 const DeclarationNameInfo &NameInfo,
2497 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2498 SourceLocation TemplateKWLoc,
2499 const TemplateArgumentListInfo *TemplateArgs) {
2500 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2501 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2502
2503 DeclRefExpr *E = DeclRefExpr::Create(
2504 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2505 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2506 MarkDeclRefReferenced(E);
2507
2508 // C++ [except.spec]p17:
2509 // An exception-specification is considered to be needed when:
2510 // - in an expression, the function is the unique lookup result or
2511 // the selected member of a set of overloaded functions.
2512 //
2513 // We delay doing this until after we've built the function reference and
2514 // marked it as used so that:
2515 // a) if the function is defaulted, we get errors from defining it before /
2516 // instead of errors from computing its exception specification, and
2517 // b) if the function is a defaulted comparison, we can use the body we
2518 // build when defining it as input to the exception specification
2519 // computation rather than computing a new body.
2520 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2521 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2522 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2523 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2524 }
2525 }
2526
2527 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2528 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2529 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2530 getCurFunction()->recordUseOfWeak(E);
2531
2532 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2533 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2534 FD = IFD->getAnonField();
2535 if (FD) {
2536 UnusedPrivateFields.remove(X: FD);
2537 // Just in case we're building an illegal pointer-to-member.
2538 if (FD->isBitField())
2539 E->setObjectKind(OK_BitField);
2540 }
2541
2542 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2543 // designates a bit-field.
2544 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2545 if (const auto *BE = BD->getBinding())
2546 E->setObjectKind(BE->getObjectKind());
2547
2548 return E;
2549}
2550
2551void
2552Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2553 TemplateArgumentListInfo &Buffer,
2554 DeclarationNameInfo &NameInfo,
2555 const TemplateArgumentListInfo *&TemplateArgs) {
2556 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2557 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2558 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2559
2560 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2561 Id.TemplateId->NumArgs);
2562 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2563
2564 TemplateName TName = Id.TemplateId->Template.get();
2565 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2566 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2567 TemplateArgs = &Buffer;
2568 } else {
2569 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2570 TemplateArgs = nullptr;
2571 }
2572}
2573
2574bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2575 // During a default argument instantiation the CurContext points
2576 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2577 // function parameter list, hence add an explicit check.
2578 bool isDefaultArgument =
2579 !CodeSynthesisContexts.empty() &&
2580 CodeSynthesisContexts.back().Kind ==
2581 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2582 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2583 bool isInstance = CurMethod && CurMethod->isInstance() &&
2584 R.getNamingClass() == CurMethod->getParent() &&
2585 !isDefaultArgument;
2586
2587 // There are two ways we can find a class-scope declaration during template
2588 // instantiation that we did not find in the template definition: if it is a
2589 // member of a dependent base class, or if it is declared after the point of
2590 // use in the same class. Distinguish these by comparing the class in which
2591 // the member was found to the naming class of the lookup.
2592 unsigned DiagID = diag::err_found_in_dependent_base;
2593 unsigned NoteID = diag::note_member_declared_at;
2594 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2595 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2596 : diag::err_found_later_in_class;
2597 } else if (getLangOpts().MSVCCompat) {
2598 DiagID = diag::ext_found_in_dependent_base;
2599 NoteID = diag::note_dependent_member_use;
2600 }
2601
2602 if (isInstance) {
2603 // Give a code modification hint to insert 'this->'.
2604 Diag(Loc: R.getNameLoc(), DiagID)
2605 << R.getLookupName()
2606 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2607 CheckCXXThisCapture(Loc: R.getNameLoc());
2608 } else {
2609 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2610 // they're not shadowed).
2611 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2612 }
2613
2614 for (const NamedDecl *D : R)
2615 Diag(Loc: D->getLocation(), DiagID: NoteID);
2616
2617 // Return true if we are inside a default argument instantiation
2618 // and the found name refers to an instance member function, otherwise
2619 // the caller will try to create an implicit member call and this is wrong
2620 // for default arguments.
2621 //
2622 // FIXME: Is this special case necessary? We could allow the caller to
2623 // diagnose this.
2624 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2625 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2626 return true;
2627 }
2628
2629 // Tell the callee to try to recover.
2630 return false;
2631}
2632
2633bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2634 CorrectionCandidateCallback &CCC,
2635 TemplateArgumentListInfo *ExplicitTemplateArgs,
2636 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2637 DeclarationName Name = R.getLookupName();
2638 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2639
2640 unsigned diagnostic = diag::err_undeclared_var_use;
2641 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2642 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2643 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2644 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2645 diagnostic = diag::err_undeclared_use;
2646 diagnostic_suggest = diag::err_undeclared_use_suggest;
2647 }
2648
2649 // If the original lookup was an unqualified lookup, fake an
2650 // unqualified lookup. This is useful when (for example) the
2651 // original lookup would not have found something because it was a
2652 // dependent name.
2653 DeclContext *DC =
2654 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2655 while (DC) {
2656 if (isa<CXXRecordDecl>(Val: DC)) {
2657 if (ExplicitTemplateArgs) {
2658 if (LookupTemplateName(
2659 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2660 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2661 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2662 return true;
2663 } else {
2664 LookupQualifiedName(R, LookupCtx: DC);
2665 }
2666
2667 if (!R.empty()) {
2668 // Don't give errors about ambiguities in this lookup.
2669 R.suppressDiagnostics();
2670
2671 // If there's a best viable function among the results, only mention
2672 // that one in the notes.
2673 OverloadCandidateSet Candidates(R.getNameLoc(),
2674 OverloadCandidateSet::CSK_Normal);
2675 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2676 OverloadCandidateSet::iterator Best;
2677 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2678 OR_Success) {
2679 R.clear();
2680 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2681 R.resolveKind();
2682 }
2683
2684 return DiagnoseDependentMemberLookup(R);
2685 }
2686
2687 R.clear();
2688 }
2689
2690 DC = DC->getLookupParent();
2691 }
2692
2693 // We didn't find anything, so try to correct for a typo.
2694 TypoCorrection Corrected;
2695 if (S && (Corrected =
2696 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2697 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2698 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2699 bool DroppedSpecifier =
2700 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2701 R.setLookupName(Corrected.getCorrection());
2702
2703 bool AcceptableWithRecovery = false;
2704 bool AcceptableWithoutRecovery = false;
2705 NamedDecl *ND = Corrected.getFoundDecl();
2706 if (ND) {
2707 if (Corrected.isOverloaded()) {
2708 OverloadCandidateSet OCS(R.getNameLoc(),
2709 OverloadCandidateSet::CSK_Normal);
2710 OverloadCandidateSet::iterator Best;
2711 for (NamedDecl *CD : Corrected) {
2712 if (FunctionTemplateDecl *FTD =
2713 dyn_cast<FunctionTemplateDecl>(Val: CD))
2714 AddTemplateOverloadCandidate(
2715 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2716 Args, CandidateSet&: OCS);
2717 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2718 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2719 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2720 Args, CandidateSet&: OCS);
2721 }
2722 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2723 case OR_Success:
2724 ND = Best->FoundDecl;
2725 Corrected.setCorrectionDecl(ND);
2726 break;
2727 default:
2728 // FIXME: Arbitrarily pick the first declaration for the note.
2729 Corrected.setCorrectionDecl(ND);
2730 break;
2731 }
2732 }
2733 R.addDecl(D: ND);
2734 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2735 CXXRecordDecl *Record =
2736 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2737 if (!Record)
2738 Record = cast<CXXRecordDecl>(
2739 Val: ND->getDeclContext()->getRedeclContext());
2740 R.setNamingClass(Record);
2741 }
2742
2743 auto *UnderlyingND = ND->getUnderlyingDecl();
2744 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2745 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2746 // FIXME: If we ended up with a typo for a type name or
2747 // Objective-C class name, we're in trouble because the parser
2748 // is in the wrong place to recover. Suggest the typo
2749 // correction, but don't make it a fix-it since we're not going
2750 // to recover well anyway.
2751 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2752 getAsTypeTemplateDecl(D: UnderlyingND) ||
2753 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2754 } else {
2755 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2756 // because we aren't able to recover.
2757 AcceptableWithoutRecovery = true;
2758 }
2759
2760 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2761 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2762 ? diag::note_implicit_param_decl
2763 : diag::note_previous_decl;
2764 if (SS.isEmpty())
2765 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2766 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2767 else
2768 diagnoseTypo(Correction: Corrected,
2769 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2770 << Name << computeDeclContext(SS, EnteringContext: false)
2771 << DroppedSpecifier << NameRange,
2772 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2773
2774 if (Corrected.WillReplaceSpecifier()) {
2775 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2776 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2777 SS.MakeTrivial(Context, Qualifier: NNS,
2778 R: NNS ? NameRange.getBegin() : SourceRange());
2779 }
2780
2781 // Tell the callee whether to try to recover.
2782 return !AcceptableWithRecovery;
2783 }
2784 }
2785 R.clear();
2786
2787 // Emit a special diagnostic for failed member lookups.
2788 // FIXME: computing the declaration context might fail here (?)
2789 if (!SS.isEmpty()) {
2790 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2791 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2792 return true;
2793 }
2794
2795 // Give up, we can't recover.
2796 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2797 return true;
2798}
2799
2800/// In Microsoft mode, if we are inside a template class whose parent class has
2801/// dependent base classes, and we can't resolve an unqualified identifier, then
2802/// assume the identifier is a member of a dependent base class. We can only
2803/// recover successfully in static methods, instance methods, and other contexts
2804/// where 'this' is available. This doesn't precisely match MSVC's
2805/// instantiation model, but it's close enough.
2806static Expr *
2807recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2808 DeclarationNameInfo &NameInfo,
2809 SourceLocation TemplateKWLoc,
2810 const TemplateArgumentListInfo *TemplateArgs) {
2811 // Only try to recover from lookup into dependent bases in static methods or
2812 // contexts where 'this' is available.
2813 QualType ThisType = S.getCurrentThisType();
2814 const CXXRecordDecl *RD = nullptr;
2815 if (!ThisType.isNull())
2816 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2817 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2818 RD = MD->getParent();
2819 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2820 return nullptr;
2821
2822 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2823 // is available, suggest inserting 'this->' as a fixit.
2824 SourceLocation Loc = NameInfo.getLoc();
2825 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2826 DB << NameInfo.getName() << RD;
2827
2828 if (!ThisType.isNull()) {
2829 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2830 return CXXDependentScopeMemberExpr::Create(
2831 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2832 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2833 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2834 }
2835
2836 // Synthesize a fake NNS that points to the derived class. This will
2837 // perform name lookup during template instantiation.
2838 CXXScopeSpec SS;
2839 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2840 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2841 return DependentScopeDeclRefExpr::Create(
2842 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2843 TemplateArgs);
2844}
2845
2846ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2847 SourceLocation TemplateKWLoc,
2848 UnqualifiedId &Id, bool HasTrailingLParen,
2849 bool IsAddressOfOperand,
2850 CorrectionCandidateCallback *CCC,
2851 bool IsInlineAsmIdentifier) {
2852 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2853 "cannot be direct & operand and have a trailing lparen");
2854 if (SS.isInvalid())
2855 return ExprError();
2856
2857 TemplateArgumentListInfo TemplateArgsBuffer;
2858
2859 // Decompose the UnqualifiedId into the following data.
2860 DeclarationNameInfo NameInfo;
2861 const TemplateArgumentListInfo *TemplateArgs;
2862 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2863
2864 DeclarationName Name = NameInfo.getName();
2865 IdentifierInfo *II = Name.getAsIdentifierInfo();
2866 SourceLocation NameLoc = NameInfo.getLoc();
2867
2868 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId &&
2869 Id.TemplateId->Template)
2870 if (TemplateName TN = Id.TemplateId->Template.get();
2871 TN.getAsPackIndexingTemplate())
2872 return CheckVarOrConceptTemplateTemplateId(NameInfo, Template: TN, TemplateArgs);
2873
2874 if (II && II->isEditorPlaceholder()) {
2875 // FIXME: When typed placeholders are supported we can create a typed
2876 // placeholder expression node.
2877 return ExprError();
2878 }
2879
2880 // This specially handles arguments of attributes appertains to a type of C
2881 // struct field such that the name lookup within a struct finds the member
2882 // name, which is not the case for other contexts in C.
2883 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2884 // See if this is reference to a field of struct.
2885 LookupResult R(*this, NameInfo, LookupMemberName);
2886 // LookupName handles a name lookup from within anonymous struct.
2887 if (LookupName(R, S)) {
2888 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2889 QualType type = VD->getType().getNonReferenceType();
2890 // This will eventually be translated into MemberExpr upon
2891 // the use of instantiated struct fields.
2892 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2893 }
2894 }
2895 }
2896
2897 // Perform the required lookup.
2898 LookupResult R(*this, NameInfo,
2899 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2900 ? LookupObjCImplicitSelfParam
2901 : LookupOrdinaryName);
2902 if (TemplateKWLoc.isValid() || TemplateArgs) {
2903 // Lookup the template name again to correctly establish the context in
2904 // which it was found. This is really unfortunate as we already did the
2905 // lookup to determine that it was a template name in the first place. If
2906 // this becomes a performance hit, we can work harder to preserve those
2907 // results until we get here but it's likely not worth it.
2908 AssumedTemplateKind AssumedTemplate;
2909 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2910 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2911 ATK: &AssumedTemplate))
2912 return ExprError();
2913
2914 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2915 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2916 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2917 } else {
2918 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2919 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2920 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2921
2922 // If the result might be in a dependent base class, this is a dependent
2923 // id-expression.
2924 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2925 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2926 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2927
2928 // If this reference is in an Objective-C method, then we need to do
2929 // some special Objective-C lookup, too.
2930 if (IvarLookupFollowUp) {
2931 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2932 if (E.isInvalid())
2933 return ExprError();
2934
2935 if (Expr *Ex = E.getAs<Expr>())
2936 return Ex;
2937 }
2938 }
2939
2940 if (R.isAmbiguous())
2941 return ExprError();
2942
2943 // This could be an implicitly declared function reference if the language
2944 // mode allows it as a feature.
2945 if (R.empty() && HasTrailingLParen && II &&
2946 getLangOpts().implicitFunctionsAllowed()) {
2947 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2948 if (D) R.addDecl(D);
2949 }
2950
2951 // Determine whether this name might be a candidate for
2952 // argument-dependent lookup.
2953 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2954
2955 if (R.empty() && !ADL) {
2956 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2957 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2958 TemplateKWLoc, TemplateArgs))
2959 return E;
2960 }
2961
2962 // Don't diagnose an empty lookup for inline assembly.
2963 if (IsInlineAsmIdentifier)
2964 return ExprError();
2965
2966 // If this name wasn't predeclared and if this is not a function
2967 // call, diagnose the problem.
2968 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2969 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2970 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2971 "Typo correction callback misconfigured");
2972 if (CCC) {
2973 // Make sure the callback knows what the typo being diagnosed is.
2974 CCC->setTypoName(II);
2975 if (SS.isValid())
2976 CCC->setTypoNNS(SS.getScopeRep());
2977 }
2978 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2979 // a template name, but we happen to have always already looked up the name
2980 // before we get here if it must be a template name.
2981 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2982 Args: {}, LookupCtx: nullptr))
2983 return ExprError();
2984
2985 assert(!R.empty() &&
2986 "DiagnoseEmptyLookup returned false but added no results");
2987
2988 // If we found an Objective-C instance variable, let
2989 // LookupInObjCMethod build the appropriate expression to
2990 // reference the ivar.
2991 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2992 R.clear();
2993 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2994 // In a hopelessly buggy code, Objective-C instance variable
2995 // lookup fails and no expression will be built to reference it.
2996 if (!E.isInvalid() && !E.get())
2997 return ExprError();
2998 return E;
2999 }
3000 }
3001
3002 // This is guaranteed from this point on.
3003 assert(!R.empty() || ADL);
3004
3005 // Check whether this might be a C++ implicit instance member access.
3006 // C++ [class.mfct.non-static]p3:
3007 // When an id-expression that is not part of a class member access
3008 // syntax and not used to form a pointer to member is used in the
3009 // body of a non-static member function of class X, if name lookup
3010 // resolves the name in the id-expression to a non-static non-type
3011 // member of some class C, the id-expression is transformed into a
3012 // class member access expression using (*this) as the
3013 // postfix-expression to the left of the . operator.
3014 //
3015 // But we don't actually need to do this for '&' operands if R
3016 // resolved to a function or overloaded function set, because the
3017 // expression is ill-formed if it actually works out to be a
3018 // non-static member function:
3019 //
3020 // C++ [expr.ref]p4:
3021 // Otherwise, if E1.E2 refers to a non-static member function. . .
3022 // [t]he expression can be used only as the left-hand operand of a
3023 // member function call.
3024 //
3025 // There are other safeguards against such uses, but it's important
3026 // to get this right here so that we don't end up making a
3027 // spuriously dependent expression if we're inside a dependent
3028 // instance method.
3029 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3030 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3031 S);
3032
3033 if (TemplateArgs || TemplateKWLoc.isValid()) {
3034
3035 // In C++1y, if this is a variable template id, then check it
3036 // in BuildTemplateIdExpr().
3037 // The single lookup result must be a variable template declaration.
3038 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3039 (Id.TemplateId->Kind == TNK_Var_template ||
3040 Id.TemplateId->Kind == TNK_Concept_template)) {
3041 assert(R.getAsSingle<TemplateDecl>() &&
3042 "There should only be one declaration found.");
3043 }
3044
3045 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3046 }
3047
3048 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3049}
3050
3051ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3052 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3053 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3054 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3055 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3056
3057 if (R.isAmbiguous())
3058 return ExprError();
3059
3060 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3061 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3062 NameInfo, /*TemplateArgs=*/nullptr);
3063
3064 if (R.empty()) {
3065 // Don't diagnose problems with invalid record decl, the secondary no_member
3066 // diagnostic during template instantiation is likely bogus, e.g. if a class
3067 // is invalid because it's derived from an invalid base class, then missing
3068 // members were likely supposed to be inherited.
3069 DeclContext *DC = computeDeclContext(SS);
3070 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3071 if (CD->isInvalidDecl() || CD->isBeingDefined())
3072 return ExprError();
3073 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3074 << NameInfo.getName() << DC << SS.getRange();
3075 return ExprError();
3076 }
3077
3078 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3079 QualType ET;
3080 TypeLocBuilder TLB;
3081 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3082 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3083 Qualifier: SS.getScopeRep(), TD: TagD,
3084 /*OwnsTag=*/false);
3085 auto TL = TLB.push<TagTypeLoc>(T: ET);
3086 TL.setElaboratedKeywordLoc(SourceLocation());
3087 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3088 TL.setNameLoc(NameInfo.getLoc());
3089 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3090 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3091 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3092 TLB.push<TypedefTypeLoc>(T: ET).set(
3093 /*ElaboratedKeywordLoc=*/SourceLocation(),
3094 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3095 } else {
3096 // FIXME: What else can appear here?
3097 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3098 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3099 assert(SS.isEmpty());
3100 }
3101
3102 // Diagnose a missing typename if this resolved unambiguously to a type in
3103 // a dependent context. If we can recover with a type, downgrade this to
3104 // a warning in Microsoft compatibility mode.
3105 unsigned DiagID = diag::err_typename_missing;
3106 if (RecoveryTSI && getLangOpts().MSVCCompat)
3107 DiagID = diag::ext_typename_missing;
3108 SourceLocation Loc = SS.getBeginLoc();
3109 auto D = Diag(Loc, DiagID);
3110 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3111
3112 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3113 // context.
3114 if (!RecoveryTSI)
3115 return ExprError();
3116
3117 // Only issue the fixit if we're prepared to recover.
3118 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3119
3120 // Recover by pretending this was an elaborated type.
3121 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3122
3123 return ExprEmpty();
3124 }
3125
3126 // If necessary, build an implicit class member access.
3127 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3128 return BuildPossibleImplicitMemberExpr(SS,
3129 /*TemplateKWLoc=*/SourceLocation(),
3130 R, /*TemplateArgs=*/nullptr,
3131 /*S=*/nullptr);
3132
3133 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3134}
3135
3136ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3137 NestedNameSpecifier Qualifier,
3138 NamedDecl *FoundDecl,
3139 NamedDecl *Member) {
3140 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3141 if (!RD)
3142 return From;
3143
3144 QualType DestRecordType;
3145 QualType DestType;
3146 QualType FromRecordType;
3147 QualType FromType = From->getType();
3148 bool PointerConversions = false;
3149 if (isa<FieldDecl>(Val: Member)) {
3150 DestRecordType = Context.getCanonicalTagType(TD: RD);
3151 auto FromPtrType = FromType->getAs<PointerType>();
3152 DestRecordType = Context.getAddrSpaceQualType(
3153 T: DestRecordType, AddressSpace: FromPtrType
3154 ? FromType->getPointeeType().getAddressSpace()
3155 : FromType.getAddressSpace());
3156
3157 if (FromPtrType) {
3158 DestType = Context.getPointerType(T: DestRecordType);
3159 FromRecordType = FromPtrType->getPointeeType();
3160 PointerConversions = true;
3161 } else {
3162 DestType = DestRecordType;
3163 FromRecordType = FromType;
3164 }
3165 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3166 if (!Method->isImplicitObjectMemberFunction())
3167 return From;
3168
3169 DestType = Method->getThisType().getNonReferenceType();
3170 DestRecordType = Method->getFunctionObjectParameterType();
3171
3172 if (FromType->getAs<PointerType>()) {
3173 FromRecordType = FromType->getPointeeType();
3174 PointerConversions = true;
3175 } else {
3176 FromRecordType = FromType;
3177 DestType = DestRecordType;
3178 }
3179
3180 LangAS FromAS = FromRecordType.getAddressSpace();
3181 LangAS DestAS = DestRecordType.getAddressSpace();
3182 if (FromAS != DestAS) {
3183 QualType FromRecordTypeWithoutAS =
3184 Context.removeAddrSpaceQualType(T: FromRecordType);
3185 QualType FromTypeWithDestAS =
3186 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3187 if (PointerConversions)
3188 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3189 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3190 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3191 .get();
3192 }
3193 } else {
3194 // No conversion necessary.
3195 return From;
3196 }
3197
3198 if (DestType->isDependentType() || FromType->isDependentType())
3199 return From;
3200
3201 // If the unqualified types are the same, no conversion is necessary.
3202 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3203 return From;
3204
3205 SourceRange FromRange = From->getSourceRange();
3206 SourceLocation FromLoc = FromRange.getBegin();
3207
3208 ExprValueKind VK = From->getValueKind();
3209
3210 // C++ [class.member.lookup]p8:
3211 // [...] Ambiguities can often be resolved by qualifying a name with its
3212 // class name.
3213 //
3214 // If the member was a qualified name and the qualified referred to a
3215 // specific base subobject type, we'll cast to that intermediate type
3216 // first and then to the object in which the member is declared. That allows
3217 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3218 //
3219 // class Base { public: int x; };
3220 // class Derived1 : public Base { };
3221 // class Derived2 : public Base { };
3222 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3223 //
3224 // void VeryDerived::f() {
3225 // x = 17; // error: ambiguous base subobjects
3226 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3227 // }
3228 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3229 QualType QType = QualType(Qualifier.getAsType(), 0);
3230 assert(QType->isRecordType() && "lookup done with non-record type");
3231
3232 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3233
3234 // In C++98, the qualifier type doesn't actually have to be a base
3235 // type of the object type, in which case we just ignore it.
3236 // Otherwise build the appropriate casts.
3237 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3238 CXXCastPath BasePath;
3239 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3240 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3241 return ExprError();
3242
3243 if (PointerConversions)
3244 QType = Context.getPointerType(T: QType);
3245 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3246 VK, BasePath: &BasePath).get();
3247
3248 FromType = QType;
3249 FromRecordType = QRecordType;
3250
3251 // If the qualifier type was the same as the destination type,
3252 // we're done.
3253 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3254 return From;
3255 }
3256 }
3257
3258 CXXCastPath BasePath;
3259 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3260 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3261 /*IgnoreAccess=*/true))
3262 return ExprError();
3263
3264 // Propagate qualifiers to base subobjects as per:
3265 // C++ [basic.type.qualifier]p1.2:
3266 // A volatile object is [...] a subobject of a volatile object.
3267 Qualifiers FromTypeQuals = FromType.getQualifiers();
3268 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3269 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3270
3271 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3272 BasePath: &BasePath);
3273}
3274
3275bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3276 const LookupResult &R,
3277 bool HasTrailingLParen) {
3278 // Only when used directly as the postfix-expression of a call.
3279 if (!HasTrailingLParen)
3280 return false;
3281
3282 // Never if a scope specifier was provided.
3283 if (SS.isNotEmpty())
3284 return false;
3285
3286 // Only in C++ or ObjC++.
3287 if (!getLangOpts().CPlusPlus)
3288 return false;
3289
3290 // Turn off ADL when we find certain kinds of declarations during
3291 // normal lookup:
3292 for (const NamedDecl *D : R) {
3293 // C++0x [basic.lookup.argdep]p3:
3294 // -- a declaration of a class member
3295 // Since using decls preserve this property, we check this on the
3296 // original decl.
3297 if (D->isCXXClassMember())
3298 return false;
3299
3300 // C++0x [basic.lookup.argdep]p3:
3301 // -- a block-scope function declaration that is not a
3302 // using-declaration
3303 // NOTE: we also trigger this for function templates (in fact, we
3304 // don't check the decl type at all, since all other decl types
3305 // turn off ADL anyway).
3306 if (isa<UsingShadowDecl>(Val: D))
3307 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3308 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3309 return false;
3310
3311 // C++0x [basic.lookup.argdep]p3:
3312 // -- a declaration that is neither a function or a function
3313 // template
3314 // And also for builtin functions.
3315 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3316 // But also builtin functions.
3317 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3318 return false;
3319 } else if (!isa<FunctionTemplateDecl>(Val: D))
3320 return false;
3321 }
3322
3323 return true;
3324}
3325
3326
3327/// Diagnoses obvious problems with the use of the given declaration
3328/// as an expression. This is only actually called for lookups that
3329/// were not overloaded, and it doesn't promise that the declaration
3330/// will in fact be used.
3331static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3332 bool AcceptInvalid) {
3333 if (D->isInvalidDecl() && !AcceptInvalid)
3334 return true;
3335
3336 if (isa<TypedefNameDecl>(Val: D)) {
3337 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3338 return true;
3339 }
3340
3341 if (isa<ObjCInterfaceDecl>(Val: D)) {
3342 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3343 return true;
3344 }
3345
3346 if (isa<NamespaceDecl>(Val: D)) {
3347 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3348 return true;
3349 }
3350
3351 return false;
3352}
3353
3354// Certain multiversion types should be treated as overloaded even when there is
3355// only one result.
3356static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3357 assert(R.isSingleResult() && "Expected only a single result");
3358 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3359 return FD &&
3360 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3361}
3362
3363ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3364 LookupResult &R, bool NeedsADL,
3365 bool AcceptInvalidDecl) {
3366 // If this is a single, fully-resolved result and we don't need ADL,
3367 // just build an ordinary singleton decl ref.
3368 if (!NeedsADL && R.isSingleResult() &&
3369 !R.getAsSingle<FunctionTemplateDecl>() &&
3370 !ShouldLookupResultBeMultiVersionOverload(R))
3371 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3372 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3373 AcceptInvalidDecl);
3374
3375 // We only need to check the declaration if there's exactly one
3376 // result, because in the overloaded case the results can only be
3377 // functions and function templates.
3378 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3379 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3380 AcceptInvalid: AcceptInvalidDecl))
3381 return ExprError();
3382
3383 // Otherwise, just build an unresolved lookup expression. Suppress
3384 // any lookup-related diagnostics; we'll hash these out later, when
3385 // we've picked a target.
3386 R.suppressDiagnostics();
3387
3388 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3389 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3390 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3391 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3392
3393 return ULE;
3394}
3395
3396ExprResult Sema::BuildDeclarationNameExpr(
3397 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3398 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3399 bool AcceptInvalidDecl) {
3400 assert(D && "Cannot refer to a NULL declaration");
3401 assert(!isa<FunctionTemplateDecl>(D) &&
3402 "Cannot refer unambiguously to a function template");
3403
3404 SourceLocation Loc = NameInfo.getLoc();
3405 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3406 // Recovery from invalid cases (e.g. D is an invalid Decl).
3407 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3408 // diagnostics, as invalid decls use int as a fallback type.
3409 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3410 }
3411
3412 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3413 // Specifically diagnose references to class templates that are missing
3414 // a template argument list.
3415 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3416 return ExprError();
3417 }
3418
3419 // Make sure that we're referring to a value.
3420 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3421 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3422 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3423 return ExprError();
3424 }
3425
3426 // Check whether this declaration can be used. Note that we suppress
3427 // this check when we're going to perform argument-dependent lookup
3428 // on this function name, because this might not be the function
3429 // that overload resolution actually selects.
3430 if (DiagnoseUseOfDecl(D, Locs: Loc))
3431 return ExprError();
3432
3433 auto *VD = cast<ValueDecl>(Val: D);
3434
3435 // Only create DeclRefExpr's for valid Decl's.
3436 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3437 return ExprError();
3438
3439 // Handle members of anonymous structs and unions. If we got here,
3440 // and the reference is to a class member indirect field, then this
3441 // must be the subject of a pointer-to-member expression.
3442 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3443 IndirectField && !IndirectField->isCXXClassMember())
3444 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3445 indirectField: IndirectField);
3446
3447 QualType type = VD->getType();
3448 if (type.isNull())
3449 return ExprError();
3450 ExprValueKind valueKind = VK_PRValue;
3451
3452 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3453 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3454 // is expanded by some outer '...' in the context of the use.
3455 type = type.getNonPackExpansionType();
3456
3457 switch (D->getKind()) {
3458 // Ignore all the non-ValueDecl kinds.
3459#define ABSTRACT_DECL(kind)
3460#define VALUE(type, base)
3461#define DECL(type, base) case Decl::type:
3462#include "clang/AST/DeclNodes.inc"
3463 llvm_unreachable("invalid value decl kind");
3464
3465 // These shouldn't make it here.
3466 case Decl::ObjCAtDefsField:
3467 llvm_unreachable("forming non-member reference to ivar?");
3468
3469 // Enum constants are always r-values and never references.
3470 // Unresolved using declarations are dependent.
3471 case Decl::EnumConstant:
3472 case Decl::UnresolvedUsingValue:
3473 case Decl::OMPDeclareReduction:
3474 case Decl::OMPDeclareMapper:
3475 valueKind = VK_PRValue;
3476 break;
3477
3478 // Fields and indirect fields that got here must be for
3479 // pointer-to-member expressions; we just call them l-values for
3480 // internal consistency, because this subexpression doesn't really
3481 // exist in the high-level semantics.
3482 case Decl::Field:
3483 case Decl::IndirectField:
3484 case Decl::ObjCIvar:
3485 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3486 "building reference to field in C?");
3487
3488 // These can't have reference type in well-formed programs, but
3489 // for internal consistency we do this anyway.
3490 type = type.getNonReferenceType();
3491 valueKind = VK_LValue;
3492 break;
3493
3494 // Non-type template parameters are either l-values or r-values
3495 // depending on the type.
3496 case Decl::NonTypeTemplateParm: {
3497 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3498 type = reftype->getPointeeType();
3499 valueKind = VK_LValue; // even if the parameter is an r-value reference
3500 break;
3501 }
3502
3503 // [expr.prim.id.unqual]p2:
3504 // If the entity is a template parameter object for a template
3505 // parameter of type T, the type of the expression is const T.
3506 // [...] The expression is an lvalue if the entity is a [...] template
3507 // parameter object.
3508 if (type->isRecordType()) {
3509 type = type.getUnqualifiedType().withConst();
3510 valueKind = VK_LValue;
3511 break;
3512 }
3513
3514 // For non-references, we need to strip qualifiers just in case
3515 // the template parameter was declared as 'const int' or whatever.
3516 valueKind = VK_PRValue;
3517 type = type.getUnqualifiedType();
3518 break;
3519 }
3520
3521 case Decl::Var:
3522 case Decl::VarTemplateSpecialization:
3523 case Decl::VarTemplatePartialSpecialization:
3524 case Decl::Decomposition:
3525 case Decl::Binding:
3526 case Decl::OMPCapturedExpr:
3527 // In C, "extern void blah;" is valid and is an r-value.
3528 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3529 type->isVoidType()) {
3530 valueKind = VK_PRValue;
3531 break;
3532 }
3533 [[fallthrough]];
3534
3535 case Decl::ImplicitParam:
3536 case Decl::ParmVar: {
3537 // These are always l-values.
3538 valueKind = VK_LValue;
3539 type = type.getNonReferenceType();
3540
3541 // FIXME: Does the addition of const really only apply in
3542 // potentially-evaluated contexts? Since the variable isn't actually
3543 // captured in an unevaluated context, it seems that the answer is no.
3544 if (!isUnevaluatedContext()) {
3545 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3546 if (!CapturedType.isNull())
3547 type = CapturedType;
3548 }
3549 break;
3550 }
3551
3552 case Decl::Function: {
3553 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3554 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3555 type = Context.BuiltinFnTy;
3556 valueKind = VK_PRValue;
3557 break;
3558 }
3559 }
3560
3561 const FunctionType *fty = type->castAs<FunctionType>();
3562
3563 // If we're referring to a function with an __unknown_anytype
3564 // result type, make the entire expression __unknown_anytype.
3565 if (fty->getReturnType() == Context.UnknownAnyTy) {
3566 type = Context.UnknownAnyTy;
3567 valueKind = VK_PRValue;
3568 break;
3569 }
3570
3571 // Functions are l-values in C++.
3572 if (getLangOpts().CPlusPlus) {
3573 valueKind = VK_LValue;
3574 break;
3575 }
3576
3577 // C99 DR 316 says that, if a function type comes from a
3578 // function definition (without a prototype), that type is only
3579 // used for checking compatibility. Therefore, when referencing
3580 // the function, we pretend that we don't have the full function
3581 // type.
3582 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3583 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3584 Info: fty->getExtInfo());
3585
3586 // Functions are r-values in C.
3587 valueKind = VK_PRValue;
3588 break;
3589 }
3590
3591 case Decl::CXXDeductionGuide:
3592 llvm_unreachable("building reference to deduction guide");
3593
3594 case Decl::MSProperty:
3595 case Decl::MSGuid:
3596 case Decl::TemplateParamObject:
3597 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3598 // capture in OpenMP, or duplicated between host and device?
3599 valueKind = VK_LValue;
3600 break;
3601
3602 case Decl::UnnamedGlobalConstant:
3603 valueKind = VK_LValue;
3604 break;
3605
3606 case Decl::CXXMethod:
3607 // If we're referring to a method with an __unknown_anytype
3608 // result type, make the entire expression __unknown_anytype.
3609 // This should only be possible with a type written directly.
3610 if (const FunctionProtoType *proto =
3611 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3612 if (proto->getReturnType() == Context.UnknownAnyTy) {
3613 type = Context.UnknownAnyTy;
3614 valueKind = VK_PRValue;
3615 break;
3616 }
3617
3618 // C++ methods are l-values if static, r-values if non-static.
3619 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3620 valueKind = VK_LValue;
3621 break;
3622 }
3623 [[fallthrough]];
3624
3625 case Decl::CXXConversion:
3626 case Decl::CXXDestructor:
3627 case Decl::CXXConstructor:
3628 valueKind = VK_PRValue;
3629 break;
3630 }
3631
3632 auto *E =
3633 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3634 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3635 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3636 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3637 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3638 // diagnostics).
3639 if (VD->isInvalidDecl() && E)
3640 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3641 return E;
3642}
3643
3644static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3645 SmallString<32> &Target) {
3646 Target.resize(N: CharByteWidth * (Source.size() + 1));
3647 char *ResultPtr = &Target[0];
3648 const llvm::UTF8 *ErrorPtr;
3649 bool success =
3650 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3651 (void)success;
3652 assert(success);
3653 Target.resize(N: ResultPtr - &Target[0]);
3654}
3655
3656ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3657 PredefinedIdentKind IK) {
3658 Decl *currentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
3659 if (!currentDecl) {
3660 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3661 currentDecl = Context.getTranslationUnitDecl();
3662 }
3663
3664 QualType ResTy;
3665 StringLiteral *SL = nullptr;
3666 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3667 ResTy = Context.DependentTy;
3668 else {
3669 // Pre-defined identifiers are of type char[x], where x is the length of
3670 // the string.
3671 bool ForceElaboratedPrinting =
3672 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3673 auto Str =
3674 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3675 unsigned Length = Str.length();
3676
3677 llvm::APInt LengthI(32, Length + 1);
3678 if (IK == PredefinedIdentKind::LFunction ||
3679 IK == PredefinedIdentKind::LFuncSig) {
3680 ResTy =
3681 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3682 SmallString<32> RawChars;
3683 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3684 Source: Str, Target&: RawChars);
3685 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3686 ASM: ArraySizeModifier::Normal,
3687 /*IndexTypeQuals*/ 0);
3688 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3689 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3690 } else {
3691 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3692 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3693 ASM: ArraySizeModifier::Normal,
3694 /*IndexTypeQuals*/ 0);
3695 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3696 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3697 }
3698 }
3699
3700 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3701 SL);
3702}
3703
3704ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3705 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3706}
3707
3708ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3709 SmallString<16> CharBuffer;
3710 bool Invalid = false;
3711 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3712 if (Invalid)
3713 return ExprError();
3714
3715 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3716 PP, Tok.getKind());
3717 if (Literal.hadError())
3718 return ExprError();
3719
3720 QualType Ty;
3721 if (Literal.isWide())
3722 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3723 else if (Literal.isUTF8() && getLangOpts().C23)
3724 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3725 else if (Literal.isUTF8() && getLangOpts().Char8)
3726 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3727 else if (Literal.isUTF16())
3728 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3729 else if (Literal.isUTF32())
3730 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3731 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3732 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3733 else
3734 Ty = Context.CharTy; // 'x' -> char in C++;
3735 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3736
3737 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3738 if (Literal.isWide())
3739 Kind = CharacterLiteralKind::Wide;
3740 else if (Literal.isUTF16())
3741 Kind = CharacterLiteralKind::UTF16;
3742 else if (Literal.isUTF32())
3743 Kind = CharacterLiteralKind::UTF32;
3744 else if (Literal.isUTF8())
3745 Kind = CharacterLiteralKind::UTF8;
3746
3747 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3748 Tok.getLocation());
3749
3750 if (Literal.getUDSuffix().empty())
3751 return Lit;
3752
3753 // We're building a user-defined literal.
3754 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3755 SourceLocation UDSuffixLoc =
3756 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3757
3758 // Make sure we're allowed user-defined literals here.
3759 if (!UDLScope)
3760 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3761
3762 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3763 // operator "" X (ch)
3764 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3765 Args: Lit, LitEndLoc: Tok.getLocation());
3766}
3767
3768ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3769 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3770 return IntegerLiteral::Create(C: Context,
3771 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3772 type: Context.IntTy, l: Loc);
3773}
3774
3775ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3776 ExprResult Inner;
3777 if (getLangOpts().CPlusPlus) {
3778 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3779 } else {
3780 // C doesn't actually have a way to represent literal values of type
3781 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3782 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3783 Inner =
3784 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3785 }
3786 return Inner;
3787}
3788
3789static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3790 QualType Ty, SourceLocation Loc) {
3791 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3792
3793 using llvm::APFloat;
3794 APFloat Val(Format);
3795
3796 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3797 if (RM == llvm::RoundingMode::Dynamic)
3798 RM = llvm::RoundingMode::NearestTiesToEven;
3799 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3800
3801 // Overflow is always an error, but underflow is only an error if
3802 // we underflowed to zero (APFloat reports denormals as underflow).
3803 if ((result & APFloat::opOverflow) ||
3804 ((result & APFloat::opUnderflow) && Val.isZero())) {
3805 unsigned diagnostic;
3806 SmallString<20> buffer;
3807 if (result & APFloat::opOverflow) {
3808 diagnostic = diag::warn_float_overflow;
3809 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3810 } else {
3811 diagnostic = diag::warn_float_underflow;
3812 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3813 }
3814
3815 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3816 }
3817
3818 bool isExact = (result == APFloat::opOK);
3819 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3820}
3821
3822bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3823 assert(E && "Invalid expression");
3824
3825 if (E->isValueDependent())
3826 return false;
3827
3828 QualType QT = E->getType();
3829 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3830 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3831 return true;
3832 }
3833
3834 llvm::APSInt ValueAPS;
3835 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3836
3837 if (R.isInvalid())
3838 return true;
3839
3840 // GCC allows the value of unroll count to be 0.
3841 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3842 // "The values of 0 and 1 block any unrolling of the loop."
3843 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3844 // '#pragma unroll' cases.
3845 bool ValueIsPositive =
3846 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3847 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3848 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3849 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3850 return true;
3851 }
3852
3853 return false;
3854}
3855
3856ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3857 // Fast path for a single digit (which is quite common). A single digit
3858 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3859 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3860 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3861 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3862 }
3863
3864 SmallString<128> SpellingBuffer;
3865 // NumericLiteralParser wants to overread by one character. Add padding to
3866 // the buffer in case the token is copied to the buffer. If getSpelling()
3867 // returns a StringRef to the memory buffer, it should have a null char at
3868 // the EOF, so it is also safe.
3869 SpellingBuffer.resize(N: Tok.getLength() + 1);
3870
3871 // Get the spelling of the token, which eliminates trigraphs, etc.
3872 bool Invalid = false;
3873 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3874 if (Invalid)
3875 return ExprError();
3876
3877 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3878 PP.getSourceManager(), PP.getLangOpts(),
3879 PP.getTargetInfo(), PP.getDiagnostics());
3880 if (Literal.hadError)
3881 return ExprError();
3882
3883 if (Literal.hasUDSuffix()) {
3884 // We're building a user-defined literal.
3885 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3886 SourceLocation UDSuffixLoc =
3887 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3888
3889 // Make sure we're allowed user-defined literals here.
3890 if (!UDLScope)
3891 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3892
3893 QualType CookedTy;
3894 if (Literal.isFloatingLiteral()) {
3895 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3896 // long double, the literal is treated as a call of the form
3897 // operator "" X (f L)
3898 CookedTy = Context.LongDoubleTy;
3899 } else {
3900 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3901 // unsigned long long, the literal is treated as a call of the form
3902 // operator "" X (n ULL)
3903 CookedTy = Context.UnsignedLongLongTy;
3904 }
3905
3906 DeclarationName OpName =
3907 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3908 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3909 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3910
3911 SourceLocation TokLoc = Tok.getLocation();
3912
3913 // Perform literal operator lookup to determine if we're building a raw
3914 // literal or a cooked one.
3915 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3916 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3917 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3918 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3919 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3920 case LOLR_ErrorNoDiagnostic:
3921 // Lookup failure for imaginary constants isn't fatal, there's still the
3922 // GNU extension producing _Complex types.
3923 break;
3924 case LOLR_Error:
3925 return ExprError();
3926 case LOLR_Cooked: {
3927 Expr *Lit;
3928 if (Literal.isFloatingLiteral()) {
3929 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3930 } else {
3931 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3932 if (Literal.GetIntegerValue(Val&: ResultVal))
3933 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3934 << /* Unsigned */ 1;
3935 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3936 l: Tok.getLocation());
3937 }
3938 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3939 }
3940
3941 case LOLR_Raw: {
3942 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3943 // literal is treated as a call of the form
3944 // operator "" X ("n")
3945 unsigned Length = Literal.getUDSuffixOffset();
3946 QualType StrTy = Context.getConstantArrayType(
3947 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3948 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3949 Expr *Lit =
3950 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3951 Kind: StringLiteralKind::Ordinary,
3952 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3953 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3954 }
3955
3956 case LOLR_Template: {
3957 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3958 // template), L is treated as a call fo the form
3959 // operator "" X <'c1', 'c2', ... 'ck'>()
3960 // where n is the source character sequence c1 c2 ... ck.
3961 TemplateArgumentListInfo ExplicitArgs;
3962 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3963 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3964 llvm::APSInt Value(CharBits, CharIsUnsigned);
3965 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3966 Value = TokSpelling[I];
3967 TemplateArgument Arg(Context, Value, Context.CharTy);
3968 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
3969 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3970 }
3971 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3972 }
3973 case LOLR_StringTemplatePack:
3974 llvm_unreachable("unexpected literal operator lookup result");
3975 }
3976 }
3977
3978 Expr *Res;
3979
3980 if (Literal.isFixedPointLiteral()) {
3981 QualType Ty;
3982
3983 if (Literal.isAccum) {
3984 if (Literal.isHalf) {
3985 Ty = Context.ShortAccumTy;
3986 } else if (Literal.isLong) {
3987 Ty = Context.LongAccumTy;
3988 } else {
3989 Ty = Context.AccumTy;
3990 }
3991 } else if (Literal.isFract) {
3992 if (Literal.isHalf) {
3993 Ty = Context.ShortFractTy;
3994 } else if (Literal.isLong) {
3995 Ty = Context.LongFractTy;
3996 } else {
3997 Ty = Context.FractTy;
3998 }
3999 }
4000
4001 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
4002
4003 bool isSigned = !Literal.isUnsigned;
4004 unsigned scale = Context.getFixedPointScale(Ty);
4005 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4006
4007 llvm::APInt Val(bit_width, 0, isSigned);
4008 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
4009 bool ValIsZero = Val.isZero() && !Overflowed;
4010
4011 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4012 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4013 // Clause 6.4.4 - The value of a constant shall be in the range of
4014 // representable values for its type, with exception for constants of a
4015 // fract type with a value of exactly 1; such a constant shall denote
4016 // the maximal value for the type.
4017 --Val;
4018 else if (Val.ugt(RHS: MaxVal) || Overflowed)
4019 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
4020
4021 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4022 l: Tok.getLocation(), Scale: scale);
4023 } else if (Literal.isFloatingLiteral()) {
4024 QualType Ty;
4025 if (Literal.isHalf){
4026 if (getLangOpts().HLSL ||
4027 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4028 Ty = Context.HalfTy;
4029 else {
4030 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4031 return ExprError();
4032 }
4033 } else if (Literal.isFloat)
4034 Ty = Context.FloatTy;
4035 else if (Literal.isLong)
4036 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4037 else if (Literal.isFloat16)
4038 Ty = Context.Float16Ty;
4039 else if (Literal.isFloat128)
4040 Ty = Context.Float128Ty;
4041 else if (getLangOpts().HLSL)
4042 Ty = Context.FloatTy;
4043 else
4044 Ty = Context.DoubleTy;
4045
4046 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4047
4048 if (Ty == Context.DoubleTy) {
4049 if (getLangOpts().SinglePrecisionConstants) {
4050 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4051 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4052 }
4053 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4054 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4055 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4056 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4057 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4058 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4059 }
4060 }
4061 } else if (!Literal.isIntegerLiteral()) {
4062 return ExprError();
4063 } else {
4064 QualType Ty;
4065
4066 // 'z/uz' literals are a C++23 feature.
4067 if (Literal.isSizeT)
4068 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
4069 ? getLangOpts().CPlusPlus23
4070 ? diag::warn_cxx20_compat_size_t_suffix
4071 : diag::ext_cxx23_size_t_suffix
4072 : diag::err_cxx23_size_t_suffix);
4073
4074 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4075 // but we do not currently support the suffix in C++ mode because it's not
4076 // entirely clear whether WG21 will prefer this suffix to return a library
4077 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4078 // literals are a C++ extension.
4079 if (Literal.isBitInt)
4080 PP.Diag(Loc: Tok.getLocation(),
4081 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4082 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4083 : diag::ext_c23_bitint_suffix);
4084
4085 // Get the value in the widest-possible width. What is "widest" depends on
4086 // whether the literal is a bit-precise integer or not. For a bit-precise
4087 // integer type, try to scan the source to determine how many bits are
4088 // needed to represent the value. This may seem a bit expensive, but trying
4089 // to get the integer value from an overly-wide APInt is *extremely*
4090 // expensive, so the naive approach of assuming
4091 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4092 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4093 if (Literal.isBitInt)
4094 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4095 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4096 if (Literal.MicrosoftInteger) {
4097 if (Literal.MicrosoftInteger == 128 &&
4098 !Context.getTargetInfo().hasInt128Type())
4099 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4100 << Literal.isUnsigned;
4101 BitsNeeded = std::max<unsigned>(a: BitsNeeded, b: Literal.MicrosoftInteger);
4102 }
4103
4104 llvm::APInt ResultVal(BitsNeeded, 0);
4105
4106 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4107 // If this value didn't fit into uintmax_t, error and force to ull.
4108 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4109 << /* Unsigned */ 1;
4110 Ty = Context.UnsignedLongLongTy;
4111 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4112 "long long is not intmax_t?");
4113 } else {
4114 // If this value fits into a ULL, try to figure out what else it fits into
4115 // according to the rules of C99 6.4.4.1p5.
4116
4117 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4118 // be an unsigned int.
4119 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4120
4121 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4122 // suffix for portability of code with C++, but both `l` and `ll` are
4123 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4124 // same.
4125 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4126 Literal.isLong = true;
4127 Literal.isLongLong = false;
4128 }
4129
4130 // Check from smallest to largest, picking the smallest type we can.
4131 unsigned Width = 0;
4132
4133 // Microsoft specific integer suffixes are explicitly sized.
4134 if (Literal.MicrosoftInteger) {
4135 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4136 Width = 8;
4137 Ty = Context.CharTy;
4138 } else {
4139 Width = Literal.MicrosoftInteger;
4140 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4141 /*Signed=*/!Literal.isUnsigned);
4142 }
4143 // To maintain consistency with MSVC, we chose to truncate directly
4144 // without issuing any warnings.
4145 ResultVal = ResultVal.zextOrTrunc(width: Width);
4146 }
4147
4148 // Bit-precise integer literals are automagically-sized based on the
4149 // width required by the literal.
4150 if (Literal.isBitInt) {
4151 // The signed version has one more bit for the sign value. There are no
4152 // zero-width bit-precise integers, even if the literal value is 0.
4153 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4154 (Literal.isUnsigned ? 0u : 1u);
4155
4156 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4157 // and reset the type to the largest supported width.
4158 unsigned int MaxBitIntWidth =
4159 Context.getTargetInfo().getMaxBitIntWidth();
4160 if (Width > MaxBitIntWidth) {
4161 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4162 << Literal.isUnsigned;
4163 Width = MaxBitIntWidth;
4164 }
4165
4166 // Reset the result value to the smaller APInt and select the correct
4167 // type to be used. Note, we zext even for signed values because the
4168 // literal itself is always an unsigned value (a preceeding - is a
4169 // unary operator, not part of the literal).
4170 ResultVal = ResultVal.zextOrTrunc(width: Width);
4171 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4172 }
4173
4174 // Check C++23 size_t literals.
4175 if (Literal.isSizeT) {
4176 assert(!Literal.MicrosoftInteger &&
4177 "size_t literals can't be Microsoft literals");
4178 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4179 T: Context.getTargetInfo().getSizeType());
4180
4181 // Does it fit in size_t?
4182 if (ResultVal.isIntN(N: SizeTSize)) {
4183 // Does it fit in ssize_t?
4184 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4185 Ty = Context.getSignedSizeType();
4186 else if (AllowUnsigned)
4187 Ty = Context.getSizeType();
4188 Width = SizeTSize;
4189 }
4190 }
4191
4192 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4193 !Literal.isSizeT) {
4194 // Are int/unsigned possibilities?
4195 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4196
4197 // Does it fit in a unsigned int?
4198 if (ResultVal.isIntN(N: IntSize)) {
4199 // Does it fit in a signed int?
4200 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4201 Ty = Context.IntTy;
4202 else if (AllowUnsigned)
4203 Ty = Context.UnsignedIntTy;
4204 Width = IntSize;
4205 }
4206 }
4207
4208 // Are long/unsigned long possibilities?
4209 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4210 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4211
4212 // Does it fit in a unsigned long?
4213 if (ResultVal.isIntN(N: LongSize)) {
4214 // Does it fit in a signed long?
4215 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4216 Ty = Context.LongTy;
4217 else if (AllowUnsigned)
4218 Ty = Context.UnsignedLongTy;
4219 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4220 // is compatible.
4221 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4222 const unsigned LongLongSize =
4223 Context.getTargetInfo().getLongLongWidth();
4224 Diag(Loc: Tok.getLocation(),
4225 DiagID: getLangOpts().CPlusPlus
4226 ? Literal.isLong
4227 ? diag::warn_old_implicitly_unsigned_long_cxx
4228 : /*C++98 UB*/ diag::
4229 ext_old_implicitly_unsigned_long_cxx
4230 : diag::warn_old_implicitly_unsigned_long)
4231 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4232 : /*will be ill-formed*/ 1);
4233 Ty = Context.UnsignedLongTy;
4234 }
4235 Width = LongSize;
4236 }
4237 }
4238
4239 // Check long long if needed.
4240 if (Ty.isNull() && !Literal.isSizeT) {
4241 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4242
4243 // Does it fit in a unsigned long long?
4244 if (ResultVal.isIntN(N: LongLongSize)) {
4245 // Does it fit in a signed long long?
4246 // To be compatible with MSVC, hex integer literals ending with the
4247 // LL or i64 suffix are always signed in Microsoft mode.
4248 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4249 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4250 Ty = Context.LongLongTy;
4251 else if (AllowUnsigned)
4252 Ty = Context.UnsignedLongLongTy;
4253 Width = LongLongSize;
4254
4255 // 'long long' is a C99 or C++11 feature, whether the literal
4256 // explicitly specified 'long long' or we needed the extra width.
4257 if (getLangOpts().CPlusPlus)
4258 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4259 ? diag::warn_cxx98_compat_longlong
4260 : diag::ext_cxx11_longlong);
4261 else if (!getLangOpts().C99)
4262 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4263 }
4264 }
4265
4266 // If we still couldn't decide a type, we either have 'size_t' literal
4267 // that is out of range, or a decimal literal that does not fit in a
4268 // signed long long and has no U suffix.
4269 if (Ty.isNull()) {
4270 if (Literal.isSizeT)
4271 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4272 << Literal.isUnsigned;
4273 else
4274 Diag(Loc: Tok.getLocation(),
4275 DiagID: diag::ext_integer_literal_too_large_for_signed);
4276 Ty = Context.UnsignedLongLongTy;
4277 Width = Context.getTargetInfo().getLongLongWidth();
4278 }
4279
4280 if (ResultVal.getBitWidth() != Width)
4281 ResultVal = ResultVal.trunc(width: Width);
4282 }
4283 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4284 }
4285
4286 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4287 if (Literal.isImaginary) {
4288 Res = new (Context) ImaginaryLiteral(Res,
4289 Context.getComplexType(T: Res->getType()));
4290
4291 // In C++, this is a GNU extension. In C, it's a C2y extension.
4292 if (getLangOpts().CPlusPlus)
4293 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_gnu_imaginary_constant);
4294 else
4295 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::imaginary_constant);
4296 }
4297 return Res;
4298}
4299
4300ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4301 assert(E && "ActOnParenExpr() missing expr");
4302 QualType ExprTy = E->getType();
4303 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4304 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4305 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4306 return new (Context) ParenExpr(L, R, E);
4307}
4308
4309static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4310 SourceLocation Loc,
4311 SourceRange ArgRange) {
4312 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4313 // scalar or vector data type argument..."
4314 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4315 // type (C99 6.2.5p18) or void.
4316 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4317 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4318 << T << ArgRange;
4319 return true;
4320 }
4321
4322 assert((T->isVoidType() || !T->isIncompleteType()) &&
4323 "Scalar types should always be complete");
4324 return false;
4325}
4326
4327static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4328 SourceLocation Loc,
4329 SourceRange ArgRange) {
4330 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4331 if (!T->isVectorType() && !T->isSizelessVectorType())
4332 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4333 << ""
4334 << "__builtin_vectorelements" << T << ArgRange;
4335
4336 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4337 if (T->isSVESizelessBuiltinType()) {
4338 llvm::StringMap<bool> CallerFeatureMap;
4339 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4340 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4341 }
4342 }
4343
4344 return false;
4345}
4346
4347static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4348 SourceLocation Loc,
4349 SourceRange ArgRange) {
4350 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4351 return true;
4352
4353 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4354 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4355 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4356 return true;
4357 }
4358
4359 return false;
4360}
4361
4362static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4363 SourceLocation Loc,
4364 SourceRange ArgRange,
4365 UnaryExprOrTypeTrait TraitKind) {
4366 // Invalid types must be hard errors for SFINAE in C++.
4367 if (S.LangOpts.CPlusPlus)
4368 return true;
4369
4370 // C99 6.5.3.4p1:
4371 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4372 TraitKind == UETT_PreferredAlignOf) {
4373
4374 // sizeof(function)/alignof(function) is allowed as an extension.
4375 if (T->isFunctionType()) {
4376 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4377 << getTraitSpelling(T: TraitKind) << ArgRange;
4378 return false;
4379 }
4380
4381 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4382 // this is an error (OpenCL v1.1 s6.3.k)
4383 if (T->isVoidType()) {
4384 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4385 : diag::ext_sizeof_alignof_void_type;
4386 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4387 return false;
4388 }
4389 }
4390 return true;
4391}
4392
4393static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4394 SourceLocation Loc,
4395 SourceRange ArgRange,
4396 UnaryExprOrTypeTrait TraitKind) {
4397 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4398 // runtime doesn't allow it.
4399 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4400 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4401 << T << (TraitKind == UETT_SizeOf)
4402 << ArgRange;
4403 return true;
4404 }
4405
4406 return false;
4407}
4408
4409/// Check whether E is a pointer from a decayed array type (the decayed
4410/// pointer type is equal to T) and emit a warning if it is.
4411static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4412 const Expr *E) {
4413 // Don't warn if the operation changed the type.
4414 if (T != E->getType())
4415 return;
4416
4417 // Now look for array decays.
4418 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4419 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4420 return;
4421
4422 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4423 << ICE->getType()
4424 << ICE->getSubExpr()->getType();
4425}
4426
4427bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4428 UnaryExprOrTypeTrait ExprKind) {
4429 QualType ExprTy = E->getType();
4430 assert(!ExprTy->isReferenceType());
4431
4432 bool IsUnevaluatedOperand =
4433 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4434 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4435 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4436 if (IsUnevaluatedOperand) {
4437 ExprResult Result = CheckUnevaluatedOperand(E);
4438 if (Result.isInvalid())
4439 return true;
4440 E = Result.get();
4441 }
4442
4443 // The operand for sizeof and alignof is in an unevaluated expression context,
4444 // so side effects could result in unintended consequences.
4445 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4446 // used to build SFINAE gadgets.
4447 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4448 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4449 !E->isInstantiationDependent() &&
4450 !E->getType()->isVariableArrayType() &&
4451 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4452 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4453
4454 if (ExprKind == UETT_VecStep)
4455 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4456 ArgRange: E->getSourceRange());
4457
4458 if (ExprKind == UETT_VectorElements)
4459 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4460 ArgRange: E->getSourceRange());
4461
4462 // Explicitly list some types as extensions.
4463 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4464 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4465 return false;
4466
4467 // WebAssembly tables are always illegal operands to unary expressions and
4468 // type traits.
4469 if (Context.getTargetInfo().getTriple().isWasm() &&
4470 E->getType()->isWebAssemblyTableType()) {
4471 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4472 << getTraitSpelling(T: ExprKind);
4473 return true;
4474 }
4475
4476 // 'alignof' applied to an expression only requires the base element type of
4477 // the expression to be complete. 'sizeof' requires the expression's type to
4478 // be complete (and will attempt to complete it if it's an array of unknown
4479 // bound).
4480 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4481 if (RequireCompleteSizedType(
4482 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4483 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4484 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4485 return true;
4486 } else {
4487 if (RequireCompleteSizedExprType(
4488 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4489 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4490 return true;
4491 }
4492
4493 // Completing the expression's type may have changed it.
4494 ExprTy = E->getType();
4495 assert(!ExprTy->isReferenceType());
4496
4497 if (ExprTy->isFunctionType()) {
4498 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4499 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4500 return true;
4501 }
4502
4503 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4504 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4505 return true;
4506
4507 if (ExprKind == UETT_CountOf) {
4508 // The type has to be an array type. We already checked for incomplete
4509 // types above.
4510 QualType ExprType = E->IgnoreParens()->getType();
4511 if (!ExprType->isArrayType()) {
4512 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4513 return true;
4514 }
4515 // FIXME: warn on _Countof on an array parameter. Not warning on it
4516 // currently because there are papers in WG14 about array types which do
4517 // not decay that could impact this behavior, so we want to see if anything
4518 // changes here before coming up with a warning group for _Countof-related
4519 // diagnostics.
4520 }
4521
4522 if (ExprKind == UETT_SizeOf) {
4523 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4524 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4525 QualType OType = PVD->getOriginalType();
4526 QualType Type = PVD->getType();
4527 if (Type->isPointerType() && OType->isArrayType()) {
4528 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4529 << Type << OType;
4530 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4531 }
4532 }
4533 }
4534
4535 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4536 // decays into a pointer and returns an unintended result. This is most
4537 // likely a typo for "sizeof(array) op x".
4538 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4539 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4540 E: BO->getLHS());
4541 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4542 E: BO->getRHS());
4543 }
4544 }
4545
4546 return false;
4547}
4548
4549static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4550 // Cannot know anything else if the expression is dependent.
4551 if (E->isTypeDependent())
4552 return false;
4553
4554 if (E->getObjectKind() == OK_BitField) {
4555 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4556 << 1 << E->getSourceRange();
4557 return true;
4558 }
4559
4560 ValueDecl *D = nullptr;
4561 Expr *Inner = E->IgnoreParens();
4562 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4563 D = DRE->getDecl();
4564 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4565 D = ME->getMemberDecl();
4566 }
4567
4568 // If it's a field, require the containing struct to have a
4569 // complete definition so that we can compute the layout.
4570 //
4571 // This can happen in C++11 onwards, either by naming the member
4572 // in a way that is not transformed into a member access expression
4573 // (in an unevaluated operand, for instance), or by naming the member
4574 // in a trailing-return-type.
4575 //
4576 // For the record, since __alignof__ on expressions is a GCC
4577 // extension, GCC seems to permit this but always gives the
4578 // nonsensical answer 0.
4579 //
4580 // We don't really need the layout here --- we could instead just
4581 // directly check for all the appropriate alignment-lowing
4582 // attributes --- but that would require duplicating a lot of
4583 // logic that just isn't worth duplicating for such a marginal
4584 // use-case.
4585 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4586 // Fast path this check, since we at least know the record has a
4587 // definition if we can find a member of it.
4588 if (!FD->getParent()->isCompleteDefinition()) {
4589 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4590 << E->getSourceRange();
4591 return true;
4592 }
4593
4594 // Otherwise, if it's a field, and the field doesn't have
4595 // reference type, then it must have a complete type (or be a
4596 // flexible array member, which we explicitly want to
4597 // white-list anyway), which makes the following checks trivial.
4598 if (!FD->getType()->isReferenceType())
4599 return false;
4600 }
4601
4602 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4603}
4604
4605bool Sema::CheckVecStepExpr(Expr *E) {
4606 E = E->IgnoreParens();
4607
4608 // Cannot know anything else if the expression is dependent.
4609 if (E->isTypeDependent())
4610 return false;
4611
4612 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4613}
4614
4615static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4616 CapturingScopeInfo *CSI) {
4617 assert(T->isVariablyModifiedType());
4618 assert(CSI != nullptr);
4619
4620 // We're going to walk down into the type and look for VLA expressions.
4621 do {
4622 const Type *Ty = T.getTypePtr();
4623 switch (Ty->getTypeClass()) {
4624#define TYPE(Class, Base)
4625#define ABSTRACT_TYPE(Class, Base)
4626#define NON_CANONICAL_TYPE(Class, Base)
4627#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4628#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4629#include "clang/AST/TypeNodes.inc"
4630 T = QualType();
4631 break;
4632 // These types are never variably-modified.
4633 case Type::Builtin:
4634 case Type::Complex:
4635 case Type::Vector:
4636 case Type::ExtVector:
4637 case Type::ConstantMatrix:
4638 case Type::Record:
4639 case Type::Enum:
4640 case Type::TemplateSpecialization:
4641 case Type::ObjCObject:
4642 case Type::ObjCInterface:
4643 case Type::ObjCObjectPointer:
4644 case Type::ObjCTypeParam:
4645 case Type::Pipe:
4646 case Type::BitInt:
4647 case Type::HLSLInlineSpirv:
4648 llvm_unreachable("type class is never variably-modified!");
4649 case Type::Adjusted:
4650 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4651 break;
4652 case Type::Decayed:
4653 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4654 break;
4655 case Type::ArrayParameter:
4656 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4657 break;
4658 case Type::Pointer:
4659 T = cast<PointerType>(Val: Ty)->getPointeeType();
4660 break;
4661 case Type::BlockPointer:
4662 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4663 break;
4664 case Type::LValueReference:
4665 case Type::RValueReference:
4666 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4667 break;
4668 case Type::MemberPointer:
4669 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4670 break;
4671 case Type::ConstantArray:
4672 case Type::IncompleteArray:
4673 // Losing element qualification here is fine.
4674 T = cast<ArrayType>(Val: Ty)->getElementType();
4675 break;
4676 case Type::VariableArray: {
4677 // Losing element qualification here is fine.
4678 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4679
4680 // Unknown size indication requires no size computation.
4681 // Otherwise, evaluate and record it.
4682 auto Size = VAT->getSizeExpr();
4683 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4684 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4685 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4686
4687 T = VAT->getElementType();
4688 break;
4689 }
4690 case Type::FunctionProto:
4691 case Type::FunctionNoProto:
4692 T = cast<FunctionType>(Val: Ty)->getReturnType();
4693 break;
4694 case Type::Paren:
4695 case Type::TypeOf:
4696 case Type::UnaryTransform:
4697 case Type::Attributed:
4698 case Type::BTFTagAttributed:
4699 case Type::OverflowBehavior:
4700 case Type::HLSLAttributedResource:
4701 case Type::SubstTemplateTypeParm:
4702 case Type::MacroQualified:
4703 case Type::CountAttributed:
4704 case Type::LateParsedAttr:
4705 // Keep walking after single level desugaring.
4706 T = T.getSingleStepDesugaredType(Context);
4707 break;
4708 case Type::Typedef:
4709 T = cast<TypedefType>(Val: Ty)->desugar();
4710 break;
4711 case Type::Decltype:
4712 T = cast<DecltypeType>(Val: Ty)->desugar();
4713 break;
4714 case Type::PackIndexing:
4715 T = cast<PackIndexingType>(Val: Ty)->desugar();
4716 break;
4717 case Type::Using:
4718 T = cast<UsingType>(Val: Ty)->desugar();
4719 break;
4720 case Type::Auto:
4721 case Type::DeducedTemplateSpecialization:
4722 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4723 break;
4724 case Type::TypeOfExpr:
4725 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4726 break;
4727 case Type::Atomic:
4728 T = cast<AtomicType>(Val: Ty)->getValueType();
4729 break;
4730 case Type::PredefinedSugar:
4731 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4732 break;
4733 }
4734 } while (!T.isNull() && T->isVariablyModifiedType());
4735}
4736
4737bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4738 SourceLocation OpLoc,
4739 SourceRange ExprRange,
4740 UnaryExprOrTypeTrait ExprKind,
4741 StringRef KWName) {
4742 if (ExprType->isDependentType())
4743 return false;
4744
4745 // C++ [expr.sizeof]p2:
4746 // When applied to a reference or a reference type, the result
4747 // is the size of the referenced type.
4748 // C++11 [expr.alignof]p3:
4749 // When alignof is applied to a reference type, the result
4750 // shall be the alignment of the referenced type.
4751 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4752 ExprType = Ref->getPointeeType();
4753
4754 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4755 // When alignof or _Alignof is applied to an array type, the result
4756 // is the alignment of the element type.
4757 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4758 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4759 // If the trait is 'alignof' in C before C2y, the ability to apply the
4760 // trait to an incomplete array is an extension.
4761 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4762 ExprType->isIncompleteArrayType())
4763 DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::alignof_incomplete_array);
4764 ExprType = Context.getBaseElementType(QT: ExprType);
4765 }
4766
4767 if (ExprKind == UETT_VecStep)
4768 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4769
4770 if (ExprKind == UETT_VectorElements)
4771 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4772 ArgRange: ExprRange);
4773
4774 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4775 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4776 ArgRange: ExprRange);
4777
4778 // Explicitly list some types as extensions.
4779 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4780 TraitKind: ExprKind))
4781 return false;
4782
4783 if (RequireCompleteSizedType(
4784 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4785 Args: KWName, Args: ExprRange))
4786 return true;
4787
4788 if (ExprType->isFunctionType()) {
4789 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4790 return true;
4791 }
4792
4793 if (ExprKind == UETT_CountOf) {
4794 // The type has to be an array type. We already checked for incomplete
4795 // types above.
4796 if (!ExprType->isArrayType()) {
4797 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4798 return true;
4799 }
4800 }
4801
4802 // WebAssembly tables are always illegal operands to unary expressions and
4803 // type traits.
4804 if (Context.getTargetInfo().getTriple().isWasm() &&
4805 ExprType->isWebAssemblyTableType()) {
4806 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4807 << getTraitSpelling(T: ExprKind);
4808 return true;
4809 }
4810
4811 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4812 TraitKind: ExprKind))
4813 return true;
4814
4815 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4816 if (auto *TT = ExprType->getAs<TypedefType>()) {
4817 for (auto I = FunctionScopes.rbegin(),
4818 E = std::prev(x: FunctionScopes.rend());
4819 I != E; ++I) {
4820 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4821 if (CSI == nullptr)
4822 break;
4823 DeclContext *DC = nullptr;
4824 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4825 DC = LSI->CallOperator;
4826 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4827 DC = CRSI->TheCapturedDecl;
4828 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4829 DC = BSI->TheDecl;
4830 if (DC) {
4831 if (DC->containsDecl(D: TT->getDecl()))
4832 break;
4833 captureVariablyModifiedType(Context, T: ExprType, CSI);
4834 }
4835 }
4836 }
4837 }
4838
4839 return false;
4840}
4841
4842ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4843 SourceLocation OpLoc,
4844 UnaryExprOrTypeTrait ExprKind,
4845 SourceRange R) {
4846 if (!TInfo)
4847 return ExprError();
4848
4849 QualType T = TInfo->getType();
4850
4851 if (!T->isDependentType() &&
4852 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4853 KWName: getTraitSpelling(T: ExprKind)))
4854 return ExprError();
4855
4856 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4857 // properly deal with VLAs in nested calls of sizeof and typeof.
4858 if (currentEvaluationContext().isUnevaluated() &&
4859 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4860 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4861 TInfo->getType()->isVariablyModifiedType())
4862 TInfo = TransformToPotentiallyEvaluated(TInfo);
4863
4864 // It's possible that the transformation above failed.
4865 if (!TInfo)
4866 return ExprError();
4867
4868 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4869 return new (Context) UnaryExprOrTypeTraitExpr(
4870 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4871}
4872
4873ExprResult
4874Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4875 UnaryExprOrTypeTrait ExprKind) {
4876 ExprResult PE = CheckPlaceholderExpr(E);
4877 if (PE.isInvalid())
4878 return ExprError();
4879
4880 E = PE.get();
4881
4882 // Verify that the operand is valid.
4883 bool isInvalid = false;
4884 if (E->isTypeDependent()) {
4885 // Delay type-checking for type-dependent expressions.
4886 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4887 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4888 } else if (ExprKind == UETT_VecStep) {
4889 isInvalid = CheckVecStepExpr(E);
4890 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4891 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4892 isInvalid = true;
4893 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4894 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4895 isInvalid = true;
4896 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4897 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4898 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4899 }
4900
4901 if (isInvalid)
4902 return ExprError();
4903
4904 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4905 E->getType()->isVariableArrayType()) {
4906 PE = TransformToPotentiallyEvaluated(E);
4907 if (PE.isInvalid()) return ExprError();
4908 E = PE.get();
4909 }
4910
4911 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4912 return new (Context) UnaryExprOrTypeTraitExpr(
4913 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4914}
4915
4916ExprResult
4917Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4918 UnaryExprOrTypeTrait ExprKind, bool IsType,
4919 void *TyOrEx, SourceRange ArgRange) {
4920 // If error parsing type, ignore.
4921 if (!TyOrEx) return ExprError();
4922
4923 if (IsType) {
4924 TypeSourceInfo *TInfo;
4925 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4926 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4927 }
4928
4929 Expr *ArgEx = (Expr *)TyOrEx;
4930 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4931 return Result;
4932}
4933
4934bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4935 SourceLocation OpLoc, SourceRange R) {
4936 if (!TInfo)
4937 return true;
4938 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4939 ExprKind: UETT_AlignOf, KWName);
4940}
4941
4942bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4943 SourceLocation OpLoc, SourceRange R) {
4944 TypeSourceInfo *TInfo;
4945 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4946 TInfo: &TInfo);
4947 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4948}
4949
4950static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4951 bool IsReal) {
4952 if (V.get()->isTypeDependent())
4953 return S.Context.DependentTy;
4954
4955 // _Real and _Imag are only l-values for normal l-values.
4956 if (V.get()->getObjectKind() != OK_Ordinary) {
4957 V = S.DefaultLvalueConversion(E: V.get());
4958 if (V.isInvalid())
4959 return QualType();
4960 }
4961
4962 // These operators return the element type of a complex type.
4963 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4964 return CT->getElementType();
4965
4966 // Otherwise they pass through real integer and floating point types here.
4967 if (V.get()->getType()->isArithmeticType())
4968 return V.get()->getType();
4969
4970 // Test for placeholders.
4971 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4972 if (PR.isInvalid()) return QualType();
4973 if (PR.get() != V.get()) {
4974 V = PR;
4975 return CheckRealImagOperand(S, V, Loc, IsReal);
4976 }
4977
4978 // Reject anything else.
4979 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4980 << (IsReal ? "__real" : "__imag");
4981 return QualType();
4982}
4983
4984
4985
4986ExprResult
4987Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4988 tok::TokenKind Kind, Expr *Input) {
4989 UnaryOperatorKind Opc;
4990 switch (Kind) {
4991 default: llvm_unreachable("Unknown unary op!");
4992 case tok::plusplus: Opc = UO_PostInc; break;
4993 case tok::minusminus: Opc = UO_PostDec; break;
4994 }
4995
4996 // Since this might is a postfix expression, get rid of ParenListExprs.
4997 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4998 if (Result.isInvalid()) return ExprError();
4999 Input = Result.get();
5000
5001 return BuildUnaryOp(S, OpLoc, Opc, Input);
5002}
5003
5004/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5005///
5006/// \return true on error
5007static bool checkArithmeticOnObjCPointer(Sema &S,
5008 SourceLocation opLoc,
5009 Expr *op) {
5010 assert(op->getType()->isObjCObjectPointerType());
5011 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5012 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5013 return false;
5014
5015 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
5016 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5017 << op->getSourceRange();
5018 return true;
5019}
5020
5021static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5022 auto *BaseNoParens = Base->IgnoreParens();
5023 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5024 return MSProp->getPropertyDecl()->getType()->isArrayType();
5025 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
5026}
5027
5028// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5029// Typically this is DependentTy, but can sometimes be more precise.
5030//
5031// There are cases when we could determine a non-dependent type:
5032// - LHS and RHS may have non-dependent types despite being type-dependent
5033// (e.g. unbounded array static members of the current instantiation)
5034// - one may be a dependent-sized array with known element type
5035// - one may be a dependent-typed valid index (enum in current instantiation)
5036//
5037// We *always* return a dependent type, in such cases it is DependentTy.
5038// This avoids creating type-dependent expressions with non-dependent types.
5039// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5040static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5041 const ASTContext &Ctx) {
5042 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5043 QualType LTy = LHS->getType(), RTy = RHS->getType();
5044 QualType Result = Ctx.DependentTy;
5045 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5046 if (const PointerType *PT = LTy->getAs<PointerType>())
5047 Result = PT->getPointeeType();
5048 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5049 Result = AT->getElementType();
5050 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5051 if (const PointerType *PT = RTy->getAs<PointerType>())
5052 Result = PT->getPointeeType();
5053 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5054 Result = AT->getElementType();
5055 }
5056 // Ensure we return a dependent type.
5057 return Result->isDependentType() ? Result : Ctx.DependentTy;
5058}
5059
5060ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5061 SourceLocation lbLoc,
5062 MultiExprArg ArgExprs,
5063 SourceLocation rbLoc) {
5064
5065 if (base && !base->getType().isNull() &&
5066 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5067 auto *AS = cast<ArraySectionExpr>(Val: base);
5068 if (AS->isOMPArraySection())
5069 return OpenMP().ActOnOMPArraySectionExpr(
5070 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5071 /*Length*/ nullptr,
5072 /*Stride=*/nullptr, RBLoc: rbLoc);
5073
5074 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5075 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5076 RBLoc: rbLoc);
5077 }
5078
5079 // Since this might be a postfix expression, get rid of ParenListExprs.
5080 if (isa<ParenListExpr>(Val: base)) {
5081 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5082 if (result.isInvalid())
5083 return ExprError();
5084 base = result.get();
5085 }
5086
5087 // Check if base and idx form a MatrixSubscriptExpr.
5088 //
5089 // Helper to check for comma expressions, which are not allowed as indices for
5090 // matrix subscript expressions.
5091 //
5092 // In C++23, we get multiple arguments instead of a comma expression.
5093 auto CheckAndReportCommaError = [&](Expr *E) {
5094 if (ArgExprs.size() > 1 ||
5095 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5096 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5097 << SourceRange(base->getBeginLoc(), rbLoc);
5098 return true;
5099 }
5100 return false;
5101 };
5102 // The matrix subscript operator ([][])is considered a single operator.
5103 // Separating the index expressions by parenthesis is not allowed.
5104 if (base && !base->getType().isNull() &&
5105 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5106 !isa<MatrixSubscriptExpr>(Val: base)) {
5107 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5108 << SourceRange(base->getBeginLoc(), rbLoc);
5109 return ExprError();
5110 }
5111 // If the base is a MatrixSubscriptExpr, try to create a new
5112 // MatrixSubscriptExpr.
5113 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5114 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5115 if (CheckAndReportCommaError(ArgExprs.front()))
5116 return ExprError();
5117
5118 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5119 RowIdx: matSubscriptE->getRowIdx(),
5120 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5121 }
5122 if (base->getType()->isWebAssemblyTableType()) {
5123 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5124 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5125 return ExprError();
5126 }
5127
5128 CheckInvalidBuiltinCountedByRef(E: base,
5129 K: BuiltinCountedByRefKind::ArraySubscript);
5130
5131 // Handle any non-overload placeholder types in the base and index
5132 // expressions. We can't handle overloads here because the other
5133 // operand might be an overloadable type, in which case the overload
5134 // resolution for the operator overload should get the first crack
5135 // at the overload.
5136 bool IsMSPropertySubscript = false;
5137 if (base->getType()->isNonOverloadPlaceholderType()) {
5138 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5139 if (!IsMSPropertySubscript) {
5140 ExprResult result = CheckPlaceholderExpr(E: base);
5141 if (result.isInvalid())
5142 return ExprError();
5143 base = result.get();
5144 }
5145 }
5146
5147 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5148 if (base->getType()->isMatrixType()) {
5149 if (CheckAndReportCommaError(ArgExprs.front()))
5150 return ExprError();
5151
5152 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5153 RBLoc: rbLoc);
5154 }
5155
5156 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5157 Expr *idx = ArgExprs[0];
5158 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5159 (isa<CXXOperatorCallExpr>(Val: idx) &&
5160 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5161 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5162 << SourceRange(base->getBeginLoc(), rbLoc);
5163 }
5164 }
5165
5166 if (ArgExprs.size() == 1 &&
5167 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5168 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5169 if (result.isInvalid())
5170 return ExprError();
5171 ArgExprs[0] = result.get();
5172 } else {
5173 if (CheckArgsForPlaceholders(args: ArgExprs))
5174 return ExprError();
5175 }
5176
5177 // Build an unanalyzed expression if either operand is type-dependent.
5178 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5179 (base->isTypeDependent() ||
5180 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5181 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5182 return new (Context) ArraySubscriptExpr(
5183 base, ArgExprs.front(),
5184 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5185 VK_LValue, OK_Ordinary, rbLoc);
5186 }
5187
5188 // MSDN, property (C++)
5189 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5190 // This attribute can also be used in the declaration of an empty array in a
5191 // class or structure definition. For example:
5192 // __declspec(property(get=GetX, put=PutX)) int x[];
5193 // The above statement indicates that x[] can be used with one or more array
5194 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5195 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5196 if (IsMSPropertySubscript) {
5197 if (ArgExprs.size() > 1) {
5198 Diag(Loc: base->getExprLoc(),
5199 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5200 return ExprError();
5201 }
5202
5203 // Build MS property subscript expression if base is MS property reference
5204 // or MS property subscript.
5205 return new (Context)
5206 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5207 VK_LValue, OK_Ordinary, rbLoc);
5208 }
5209
5210 // Use C++ overloaded-operator rules if either operand has record
5211 // type. The spec says to do this if either type is *overloadable*,
5212 // but enum types can't declare subscript operators or conversion
5213 // operators, so there's nothing interesting for overload resolution
5214 // to do if there aren't any record types involved.
5215 //
5216 // ObjC pointers have their own subscripting logic that is not tied
5217 // to overload resolution and so should not take this path.
5218 //
5219 // Issue a better diagnostic if we tried to pass multiple arguments to
5220 // a builtin subscript operator rather than diagnosing this as a generic
5221 // overload resolution failure.
5222 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5223 !base->getType()->isRecordType() &&
5224 !base->getType()->isObjCObjectPointerType()) {
5225 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5226 << base->getType() << base->getSourceRange();
5227 return ExprError();
5228 }
5229
5230 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5231 ((base->getType()->isRecordType() ||
5232 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5233 ArgExprs[0]->getType()->isRecordType())))) {
5234 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5235 }
5236
5237 ExprResult Res =
5238 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5239
5240 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5241 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5242
5243 return Res;
5244}
5245
5246ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5247 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5248 InitializationKind Kind =
5249 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5250 InitializationSequence InitSeq(*this, Entity, Kind, E);
5251 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5252}
5253
5254ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5255 Expr *RowIdx,
5256 SourceLocation RBLoc) {
5257 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5258 if (BaseR.isInvalid())
5259 return BaseR;
5260 Base = BaseR.get();
5261
5262 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5263 if (RowR.isInvalid())
5264 return RowR;
5265 RowIdx = RowR.get();
5266
5267 // Build an unanalyzed expression if any of the operands is type-dependent.
5268 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5269 return new (Context)
5270 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5271
5272 // Check that IndexExpr is an integer expression. If it is a constant
5273 // expression, check that it is less than Dim (= the number of elements in the
5274 // corresponding dimension).
5275 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5276 bool IsColumnIdx) -> Expr * {
5277 if (!IndexExpr->getType()->isIntegerType() &&
5278 !IndexExpr->isTypeDependent()) {
5279 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5280 << IsColumnIdx;
5281 return nullptr;
5282 }
5283
5284 if (std::optional<llvm::APSInt> Idx =
5285 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5286 if ((*Idx < 0 || *Idx >= Dim)) {
5287 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5288 << IsColumnIdx << Dim;
5289 return nullptr;
5290 }
5291 }
5292
5293 ExprResult ConvExpr = IndexExpr;
5294 assert(!ConvExpr.isInvalid() &&
5295 "should be able to convert any integer type to size type");
5296 return ConvExpr.get();
5297 };
5298
5299 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5300 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5301 if (!RowIdx)
5302 return ExprError();
5303
5304 QualType RowVecQT =
5305 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5306
5307 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5308}
5309
5310ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5311 Expr *ColumnIdx,
5312 SourceLocation RBLoc) {
5313 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5314 if (BaseR.isInvalid())
5315 return BaseR;
5316 Base = BaseR.get();
5317
5318 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5319 if (RowR.isInvalid())
5320 return RowR;
5321 RowIdx = RowR.get();
5322
5323 if (!ColumnIdx)
5324 return new (Context) MatrixSubscriptExpr(
5325 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5326
5327 // Build an unanalyzed expression if any of the operands is type-dependent.
5328 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5329 ColumnIdx->isTypeDependent())
5330 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5331 Context.DependentTy, RBLoc);
5332
5333 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5334 if (ColumnR.isInvalid())
5335 return ColumnR;
5336 ColumnIdx = ColumnR.get();
5337
5338 // Check that IndexExpr is an integer expression. If it is a constant
5339 // expression, check that it is less than Dim (= the number of elements in the
5340 // corresponding dimension).
5341 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5342 bool IsColumnIdx) -> Expr * {
5343 if (!IndexExpr->getType()->isIntegerType() &&
5344 !IndexExpr->isTypeDependent()) {
5345 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5346 << IsColumnIdx;
5347 return nullptr;
5348 }
5349
5350 if (std::optional<llvm::APSInt> Idx =
5351 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5352 if ((*Idx < 0 || *Idx >= Dim)) {
5353 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5354 << IsColumnIdx << Dim;
5355 return nullptr;
5356 }
5357 }
5358
5359 ExprResult ConvExpr = IndexExpr;
5360 assert(!ConvExpr.isInvalid() &&
5361 "should be able to convert any integer type to size type");
5362 return ConvExpr.get();
5363 };
5364
5365 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5366 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5367 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5368 if (!RowIdx || !ColumnIdx)
5369 return ExprError();
5370
5371 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5372 MTy->getElementType(), RBLoc);
5373}
5374
5375void Sema::CheckAddressOfNoDeref(const Expr *E) {
5376 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5377 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5378
5379 // For expressions like `&(*s).b`, the base is recorded and what should be
5380 // checked.
5381 const MemberExpr *Member = nullptr;
5382 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5383 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5384
5385 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5386}
5387
5388void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5389 if (isUnevaluatedContext())
5390 return;
5391
5392 QualType ResultTy = E->getType();
5393 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5394
5395 // Bail if the element is an array since it is not memory access.
5396 if (isa<ArrayType>(Val: ResultTy))
5397 return;
5398
5399 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5400 LastRecord.PossibleDerefs.insert(Ptr: E);
5401 return;
5402 }
5403
5404 // Check if the base type is a pointer to a member access of a struct
5405 // marked with noderef.
5406 const Expr *Base = E->getBase();
5407 QualType BaseTy = Base->getType();
5408 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5409 // Not a pointer access
5410 return;
5411
5412 const MemberExpr *Member = nullptr;
5413 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5414 Member->isArrow())
5415 Base = Member->getBase();
5416
5417 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5418 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5419 LastRecord.PossibleDerefs.insert(Ptr: E);
5420 }
5421}
5422
5423ExprResult
5424Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5425 Expr *Idx, SourceLocation RLoc) {
5426 Expr *LHSExp = Base;
5427 Expr *RHSExp = Idx;
5428
5429 ExprValueKind VK = VK_LValue;
5430 ExprObjectKind OK = OK_Ordinary;
5431
5432 // Per C++ core issue 1213, the result is an xvalue if either operand is
5433 // a non-lvalue array, and an lvalue otherwise.
5434 if (getLangOpts().CPlusPlus11) {
5435 for (auto *Op : {LHSExp, RHSExp}) {
5436 Op = Op->IgnoreImplicit();
5437 if (Op->getType()->isArrayType() && !Op->isLValue())
5438 VK = VK_XValue;
5439 }
5440 }
5441
5442 // Perform default conversions.
5443 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5444 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5445 if (Result.isInvalid())
5446 return ExprError();
5447 LHSExp = Result.get();
5448 }
5449 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5450 if (Result.isInvalid())
5451 return ExprError();
5452 RHSExp = Result.get();
5453
5454 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5455
5456 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5457 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5458 // in the subscript position. As a result, we need to derive the array base
5459 // and index from the expression types.
5460 Expr *BaseExpr, *IndexExpr;
5461 QualType ResultType;
5462 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5463 BaseExpr = LHSExp;
5464 IndexExpr = RHSExp;
5465 ResultType =
5466 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5467 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5468 BaseExpr = LHSExp;
5469 IndexExpr = RHSExp;
5470 ResultType = PTy->getPointeeType();
5471 } else if (const ObjCObjectPointerType *PTy =
5472 LHSTy->getAs<ObjCObjectPointerType>()) {
5473 BaseExpr = LHSExp;
5474 IndexExpr = RHSExp;
5475
5476 // Use custom logic if this should be the pseudo-object subscript
5477 // expression.
5478 if (!LangOpts.isSubscriptPointerArithmetic())
5479 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5480 getterMethod: nullptr, setterMethod: nullptr);
5481
5482 ResultType = PTy->getPointeeType();
5483 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5484 // Handle the uncommon case of "123[Ptr]".
5485 BaseExpr = RHSExp;
5486 IndexExpr = LHSExp;
5487 ResultType = PTy->getPointeeType();
5488 } else if (const ObjCObjectPointerType *PTy =
5489 RHSTy->getAs<ObjCObjectPointerType>()) {
5490 // Handle the uncommon case of "123[Ptr]".
5491 BaseExpr = RHSExp;
5492 IndexExpr = LHSExp;
5493 ResultType = PTy->getPointeeType();
5494 if (!LangOpts.isSubscriptPointerArithmetic()) {
5495 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5496 << ResultType << BaseExpr->getSourceRange();
5497 return ExprError();
5498 }
5499 } else if (LHSTy->isSubscriptableVectorType()) {
5500 if (LHSTy->isBuiltinType() &&
5501 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5502 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5503 if (BTy->isSVEBool())
5504 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5505 << LHSExp->getSourceRange()
5506 << RHSExp->getSourceRange());
5507 ResultType = BTy->getSveEltType(Ctx: Context);
5508 } else {
5509 const VectorType *VTy = LHSTy->getAs<VectorType>();
5510 ResultType = VTy->getElementType();
5511 }
5512 BaseExpr = LHSExp; // vectors: V[123]
5513 IndexExpr = RHSExp;
5514 // We apply C++ DR1213 to vector subscripting too.
5515 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5516 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5517 if (Materialized.isInvalid())
5518 return ExprError();
5519 LHSExp = Materialized.get();
5520 }
5521 VK = LHSExp->getValueKind();
5522 if (VK != VK_PRValue)
5523 OK = OK_VectorComponent;
5524
5525 QualType BaseType = BaseExpr->getType();
5526 Qualifiers BaseQuals = BaseType.getQualifiers();
5527 Qualifiers MemberQuals = ResultType.getQualifiers();
5528 Qualifiers Combined = BaseQuals + MemberQuals;
5529 if (Combined != MemberQuals)
5530 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5531 } else if (LHSTy->isArrayType()) {
5532 // If we see an array that wasn't promoted by
5533 // DefaultFunctionArrayLvalueConversion, it must be an array that
5534 // wasn't promoted because of the C90 rule that doesn't
5535 // allow promoting non-lvalue arrays. Warn, then
5536 // force the promotion here.
5537 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5538 << LHSExp->getSourceRange();
5539 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5540 CK: CK_ArrayToPointerDecay).get();
5541 LHSTy = LHSExp->getType();
5542
5543 BaseExpr = LHSExp;
5544 IndexExpr = RHSExp;
5545 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5546 } else if (RHSTy->isArrayType()) {
5547 // Same as previous, except for 123[f().a] case
5548 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5549 << RHSExp->getSourceRange();
5550 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5551 CK: CK_ArrayToPointerDecay).get();
5552 RHSTy = RHSExp->getType();
5553
5554 BaseExpr = RHSExp;
5555 IndexExpr = LHSExp;
5556 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5557 } else {
5558 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5559 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5560 }
5561 // C99 6.5.2.1p1
5562 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5563 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5564 << IndexExpr->getSourceRange());
5565
5566 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5567 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5568 !IndexExpr->isTypeDependent()) {
5569 std::optional<llvm::APSInt> IntegerContantExpr =
5570 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5571 if (!IntegerContantExpr.has_value() ||
5572 IntegerContantExpr.value().isNegative())
5573 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5574 }
5575
5576 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5577 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5578 // type. Note that Functions are not objects, and that (in C99 parlance)
5579 // incomplete types are not object types.
5580 if (ResultType->isFunctionType()) {
5581 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5582 << ResultType << BaseExpr->getSourceRange();
5583 return ExprError();
5584 }
5585
5586 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5587 // GNU extension: subscripting on pointer to void
5588 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5589 << BaseExpr->getSourceRange();
5590
5591 // C forbids expressions of unqualified void type from being l-values.
5592 // See IsCForbiddenLValueType.
5593 if (!ResultType.hasQualifiers())
5594 VK = VK_PRValue;
5595 } else if (!ResultType->isDependentType() &&
5596 !ResultType.isWebAssemblyReferenceType() &&
5597 RequireCompleteSizedType(
5598 Loc: LLoc, T: ResultType,
5599 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5600 return ExprError();
5601
5602 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5603 !ResultType.isCForbiddenLValueType());
5604
5605 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5606 FunctionScopes.size() > 1) {
5607 if (auto *TT =
5608 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5609 for (auto I = FunctionScopes.rbegin(),
5610 E = std::prev(x: FunctionScopes.rend());
5611 I != E; ++I) {
5612 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5613 if (CSI == nullptr)
5614 break;
5615 DeclContext *DC = nullptr;
5616 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5617 DC = LSI->CallOperator;
5618 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5619 DC = CRSI->TheCapturedDecl;
5620 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5621 DC = BSI->TheDecl;
5622 if (DC) {
5623 if (DC->containsDecl(D: TT->getDecl()))
5624 break;
5625 captureVariablyModifiedType(
5626 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5627 }
5628 }
5629 }
5630 }
5631
5632 return new (Context)
5633 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5634}
5635
5636bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5637 ParmVarDecl *Param, Expr *RewrittenInit,
5638 bool SkipImmediateInvocations) {
5639 if (Param->hasUnparsedDefaultArg()) {
5640 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5641 // If we've already cleared out the location for the default argument,
5642 // that means we're parsing it right now.
5643 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5644 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5645 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5646 Param->setInvalidDecl();
5647 return true;
5648 }
5649
5650 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5651 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5652 Diag(Loc: UnparsedDefaultArgLocs[Param],
5653 DiagID: diag::note_default_argument_declared_here);
5654 return true;
5655 }
5656
5657 if (Param->hasUninstantiatedDefaultArg()) {
5658 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5659 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5660 return true;
5661 }
5662
5663 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5664 assert(Init && "default argument but no initializer?");
5665
5666 // If the default expression creates temporaries, we need to
5667 // push them to the current stack of expression temporaries so they'll
5668 // be properly destroyed.
5669 // FIXME: We should really be rebuilding the default argument with new
5670 // bound temporaries; see the comment in PR5810.
5671 // We don't need to do that with block decls, though, because
5672 // blocks in default argument expression can never capture anything.
5673 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5674 // Set the "needs cleanups" bit regardless of whether there are
5675 // any explicit objects.
5676 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5677 // Append all the objects to the cleanup list. Right now, this
5678 // should always be a no-op, because blocks in default argument
5679 // expressions should never be able to capture anything.
5680 assert(!InitWithCleanup->getNumObjects() &&
5681 "default argument expression has capturing blocks?");
5682 }
5683 // C++ [expr.const]p15.1:
5684 // An expression or conversion is in an immediate function context if it is
5685 // potentially evaluated and [...] its innermost enclosing non-block scope
5686 // is a function parameter scope of an immediate function.
5687 EnterExpressionEvaluationContext EvalContext(
5688 *this,
5689 FD->isImmediateFunction()
5690 ? ExpressionEvaluationContext::ImmediateFunctionContext
5691 : ExpressionEvaluationContext::PotentiallyEvaluated,
5692 Param);
5693 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5694 SkipImmediateInvocations;
5695 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5696 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5697 });
5698 return false;
5699}
5700
5701struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5702 const ASTContext &Context;
5703 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5704 ShouldVisitImplicitCode = true;
5705 }
5706
5707 bool HasImmediateCalls = false;
5708
5709 bool VisitCallExpr(CallExpr *E) override {
5710 if (const FunctionDecl *FD = E->getDirectCallee())
5711 HasImmediateCalls |= FD->isImmediateFunction();
5712 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5713 }
5714
5715 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5716 if (const FunctionDecl *FD = E->getConstructor())
5717 HasImmediateCalls |= FD->isImmediateFunction();
5718 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5719 }
5720
5721 // SourceLocExpr are not immediate invocations
5722 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5723 // need to be rebuilt so that they refer to the correct SourceLocation and
5724 // DeclContext.
5725 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5726 HasImmediateCalls = true;
5727 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5728 }
5729
5730 // A nested lambda might have parameters with immediate invocations
5731 // in their default arguments.
5732 // The compound statement is not visited (as it does not constitute a
5733 // subexpression).
5734 // FIXME: We should consider visiting and transforming captures
5735 // with init expressions.
5736 bool VisitLambdaExpr(LambdaExpr *E) override {
5737 return VisitCXXMethodDecl(D: E->getCallOperator());
5738 }
5739
5740 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5741 return TraverseStmt(S: E->getExpr());
5742 }
5743
5744 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5745 return TraverseStmt(S: E->getExpr());
5746 }
5747};
5748
5749struct EnsureImmediateInvocationInDefaultArgs
5750 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5751 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5752 : TreeTransform(SemaRef) {}
5753
5754 bool AlwaysRebuild() { return true; }
5755
5756 // Lambda can only have immediate invocations in the default
5757 // args of their parameters, which is transformed upon calling the closure.
5758 // The body is not a subexpression, so we have nothing to do.
5759 // FIXME: Immediate calls in capture initializers should be transformed.
5760 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5761 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5762
5763 // Make sure we don't rebuild the this pointer as it would
5764 // cause it to incorrectly point it to the outermost class
5765 // in the case of nested struct initialization.
5766 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5767
5768 // Rewrite to source location to refer to the context in which they are used.
5769 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5770 DeclContext *DC = E->getParentContext();
5771 if (DC == SemaRef.CurContext)
5772 return E;
5773
5774 // FIXME: During instantiation, because the rebuild of defaults arguments
5775 // is not always done in the context of the template instantiator,
5776 // we run the risk of producing a dependent source location
5777 // that would never be rebuilt.
5778 // This usually happens during overload resolution, or in contexts
5779 // where the value of the source location does not matter.
5780 // However, we should find a better way to deal with source location
5781 // of function templates.
5782 if (!SemaRef.CurrentInstantiationScope ||
5783 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5784 DC = SemaRef.CurContext;
5785
5786 return getDerived().RebuildSourceLocExpr(
5787 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5788 }
5789};
5790
5791ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5792 FunctionDecl *FD, ParmVarDecl *Param,
5793 Expr *Init) {
5794 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5795
5796 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5797 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5798 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5799 InitializationContext =
5800 OutermostDeclarationWithDelayedImmediateInvocations();
5801 if (!InitializationContext.has_value())
5802 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5803
5804 if (!Init && !Param->hasUnparsedDefaultArg()) {
5805 // Mark that we are replacing a default argument first.
5806 // If we are instantiating a template we won't have to
5807 // retransform immediate calls.
5808 // C++ [expr.const]p15.1:
5809 // An expression or conversion is in an immediate function context if it
5810 // is potentially evaluated and [...] its innermost enclosing non-block
5811 // scope is a function parameter scope of an immediate function.
5812 EnterExpressionEvaluationContext EvalContext(
5813 *this,
5814 FD->isImmediateFunction()
5815 ? ExpressionEvaluationContext::ImmediateFunctionContext
5816 : ExpressionEvaluationContext::PotentiallyEvaluated,
5817 Param);
5818
5819 if (Param->hasUninstantiatedDefaultArg()) {
5820 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5821 return ExprError();
5822 }
5823 // CWG2631
5824 // An immediate invocation that is not evaluated where it appears is
5825 // evaluated and checked for whether it is a constant expression at the
5826 // point where the enclosing initializer is used in a function call.
5827 ImmediateCallVisitor V(getASTContext());
5828 if (!NestedDefaultChecking)
5829 V.TraverseDecl(D: Param);
5830
5831 // Rewrite the call argument that was created from the corresponding
5832 // parameter's default argument.
5833 if (V.HasImmediateCalls ||
5834 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5835 if (V.HasImmediateCalls)
5836 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5837 CallLoc, Param, CurContext};
5838 // Pass down lifetime extending flag, and collect temporaries in
5839 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5840 currentEvaluationContext().InLifetimeExtendingContext =
5841 parentEvaluationContext().InLifetimeExtendingContext;
5842 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5843 ExprResult Res;
5844 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5845 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5846 /*NotCopy=*/NotCopyInit: false);
5847 });
5848 if (Res.isInvalid())
5849 return ExprError();
5850 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5851 EqualLoc: Res.get()->getBeginLoc());
5852 if (Res.isInvalid())
5853 return ExprError();
5854 Init = Res.get();
5855 }
5856 }
5857
5858 if (CheckCXXDefaultArgExpr(
5859 CallLoc, FD, Param, RewrittenInit: Init,
5860 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5861 return ExprError();
5862
5863 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5864 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5865}
5866
5867static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5868 FieldDecl *Field) {
5869 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5870 return Pattern;
5871 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5872 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5873 DeclContext::lookup_result Lookup =
5874 ClassPattern->lookup(Name: Field->getDeclName());
5875 auto Rng = llvm::make_filter_range(
5876 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5877 if (Rng.empty())
5878 return nullptr;
5879 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5880 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5881 // && "Duplicated instantiation pattern for field decl");
5882 return cast<FieldDecl>(Val: *Rng.begin());
5883}
5884
5885ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5886 assert(Field->hasInClassInitializer());
5887
5888 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5889
5890 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5891
5892 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5893 InitializationContext =
5894 OutermostDeclarationWithDelayedImmediateInvocations();
5895 if (!InitializationContext.has_value())
5896 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5897
5898 Expr *Init = nullptr;
5899
5900 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5901 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5902 EnterExpressionEvaluationContext EvalContext(
5903 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5904
5905 if (!Field->getInClassInitializer()) {
5906 // Maybe we haven't instantiated the in-class initializer. Go check the
5907 // pattern FieldDecl to see if it has one.
5908 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5909 FieldDecl *Pattern =
5910 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5911 assert(Pattern && "We must have set the Pattern!");
5912 if (!Pattern->hasInClassInitializer() ||
5913 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5914 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5915 return ExprError();
5916 }
5917 }
5918 }
5919
5920 // CWG2631
5921 // An immediate invocation that is not evaluated where it appears is
5922 // evaluated and checked for whether it is a constant expression at the
5923 // point where the enclosing initializer is used in a [...] a constructor
5924 // definition, or an aggregate initialization.
5925 ImmediateCallVisitor V(getASTContext());
5926 if (!NestedDefaultChecking)
5927 V.TraverseDecl(D: Field);
5928
5929 // CWG1815
5930 // Support lifetime extension of temporary created by aggregate
5931 // initialization using a default member initializer. We should rebuild
5932 // the initializer in a lifetime extension context if the initializer
5933 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5934 // extension code recurses into the default initializer and does lifetime
5935 // extension when warranted.
5936 bool ContainsAnyTemporaries =
5937 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5938 if (Field->getInClassInitializer() &&
5939 !Field->getInClassInitializer()->containsErrors() &&
5940 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5941 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5942 CurContext};
5943 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5944 NestedDefaultChecking;
5945 // Pass down lifetime extending flag, and collect temporaries in
5946 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5947 currentEvaluationContext().InLifetimeExtendingContext =
5948 parentEvaluationContext().InLifetimeExtendingContext;
5949 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5950 ExprResult Res;
5951 runWithSufficientStackSpace(Loc, Fn: [&] {
5952 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5953 /*CXXDirectInit=*/NotCopyInit: false);
5954 });
5955 if (!Res.isInvalid())
5956 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5957 if (Res.isInvalid()) {
5958 Field->setInvalidDecl();
5959 return ExprError();
5960 }
5961 Init = Res.get();
5962 }
5963
5964 if (Field->getInClassInitializer()) {
5965 Expr *E = Init ? Init : Field->getInClassInitializer();
5966 if (!NestedDefaultChecking)
5967 runWithSufficientStackSpace(Loc, Fn: [&] {
5968 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5969 });
5970 if (isInLifetimeExtendingContext())
5971 DiscardCleanupsInEvaluationContext();
5972 // C++11 [class.base.init]p7:
5973 // The initialization of each base and member constitutes a
5974 // full-expression.
5975 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5976 if (Res.isInvalid()) {
5977 Field->setInvalidDecl();
5978 return ExprError();
5979 }
5980 Init = Res.get();
5981
5982 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5983 Field, UsedContext: InitializationContext->Context,
5984 RewrittenInitExpr: Init);
5985 }
5986
5987 // DR1351:
5988 // If the brace-or-equal-initializer of a non-static data member
5989 // invokes a defaulted default constructor of its class or of an
5990 // enclosing class in a potentially evaluated subexpression, the
5991 // program is ill-formed.
5992 //
5993 // This resolution is unworkable: the exception specification of the
5994 // default constructor can be needed in an unevaluated context, in
5995 // particular, in the operand of a noexcept-expression, and we can be
5996 // unable to compute an exception specification for an enclosed class.
5997 //
5998 // Any attempt to resolve the exception specification of a defaulted default
5999 // constructor before the initializer is lexically complete will ultimately
6000 // come here at which point we can diagnose it.
6001 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6002 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
6003 << OutermostClass << Field;
6004 Diag(Loc: Field->getEndLoc(),
6005 DiagID: diag::note_default_member_initializer_not_yet_parsed);
6006 // Recover by marking the field invalid, unless we're in a SFINAE context.
6007 if (!isSFINAEContext())
6008 Field->setInvalidDecl();
6009 return ExprError();
6010}
6011
6012VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
6013 const FunctionProtoType *Proto,
6014 Expr *Fn) {
6015 if (Proto && Proto->isVariadic()) {
6016 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6017 return VariadicCallType::Constructor;
6018 else if (Fn && Fn->getType()->isBlockPointerType())
6019 return VariadicCallType::Block;
6020 else if (FDecl) {
6021 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6022 if (Method->isInstance())
6023 return VariadicCallType::Method;
6024 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6025 return VariadicCallType::Method;
6026 return VariadicCallType::Function;
6027 }
6028 return VariadicCallType::DoesNotApply;
6029}
6030
6031namespace {
6032class FunctionCallCCC final : public FunctionCallFilterCCC {
6033public:
6034 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6035 unsigned NumArgs, MemberExpr *ME)
6036 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6037 FunctionName(FuncName) {}
6038
6039 bool ValidateCandidate(const TypoCorrection &candidate) override {
6040 if (!candidate.getCorrectionSpecifier() ||
6041 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6042 return false;
6043 }
6044
6045 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6046 }
6047
6048 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6049 return std::make_unique<FunctionCallCCC>(args&: *this);
6050 }
6051
6052private:
6053 const IdentifierInfo *const FunctionName;
6054};
6055}
6056
6057static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6058 FunctionDecl *FDecl,
6059 ArrayRef<Expr *> Args) {
6060 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6061 DeclarationName FuncName = FDecl->getDeclName();
6062 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6063
6064 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6065 if (TypoCorrection Corrected = S.CorrectTypo(
6066 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6067 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6068 Mode: CorrectTypoKind::ErrorRecovery)) {
6069 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6070 if (Corrected.isOverloaded()) {
6071 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6072 OverloadCandidateSet::iterator Best;
6073 for (NamedDecl *CD : Corrected) {
6074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6075 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6076 CandidateSet&: OCS);
6077 }
6078 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6079 case OR_Success:
6080 ND = Best->FoundDecl;
6081 Corrected.setCorrectionDecl(ND);
6082 break;
6083 default:
6084 break;
6085 }
6086 }
6087 ND = ND->getUnderlyingDecl();
6088 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6089 return Corrected;
6090 }
6091 }
6092 return TypoCorrection();
6093}
6094
6095// [C++26][[expr.unary.op]/p4
6096// A pointer to member is only formed when an explicit &
6097// is used and its operand is a qualified-id not enclosed in parentheses.
6098static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6099 if (!isa<ParenExpr>(Val: Fn))
6100 return false;
6101
6102 Fn = Fn->IgnoreParens();
6103
6104 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6105 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6106 return false;
6107 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6108 return DRE->hasQualifier();
6109 }
6110 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6111 return bool(OVL->getQualifier());
6112 return false;
6113}
6114
6115bool
6116Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6117 FunctionDecl *FDecl,
6118 const FunctionProtoType *Proto,
6119 ArrayRef<Expr *> Args,
6120 SourceLocation RParenLoc,
6121 bool IsExecConfig) {
6122 // Bail out early if calling a builtin with custom typechecking.
6123 // For HLSL builtin aliases, argument conversion is still needed because
6124 // overload resolution may have selected a conversion sequence (e.g.,
6125 // vector-to-scalar truncation) that must be applied before the custom
6126 // type checker runs.
6127 if (FDecl)
6128 if (unsigned ID = FDecl->getBuiltinID())
6129 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6130 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6131 return false;
6132
6133 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6134 // assignment, to the types of the corresponding parameter, ...
6135
6136 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6137 bool HasExplicitObjectParameter =
6138 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6139 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6140 unsigned NumParams = Proto->getNumParams();
6141 bool Invalid = false;
6142 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6143 unsigned FnKind = Fn->getType()->isBlockPointerType()
6144 ? 1 /* block */
6145 : (IsExecConfig ? 3 /* kernel function (exec config) */
6146 : 0 /* function */);
6147
6148 // If too few arguments are available (and we don't have default
6149 // arguments for the remaining parameters), don't make the call.
6150 if (Args.size() < NumParams) {
6151 if (Args.size() < MinArgs) {
6152 TypoCorrection TC;
6153 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6154 unsigned diag_id =
6155 MinArgs == NumParams && !Proto->isVariadic()
6156 ? diag::err_typecheck_call_too_few_args_suggest
6157 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6158 diagnoseTypo(
6159 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6160 << FnKind << MinArgs - ExplicitObjectParameterOffset
6161 << static_cast<unsigned>(Args.size()) -
6162 ExplicitObjectParameterOffset
6163 << HasExplicitObjectParameter << TC.getCorrectionRange());
6164 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6165 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6166 ->getDeclName())
6167 Diag(Loc: RParenLoc,
6168 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6169 ? diag::err_typecheck_call_too_few_args_one
6170 : diag::err_typecheck_call_too_few_args_at_least_one)
6171 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6172 << HasExplicitObjectParameter << Fn->getSourceRange();
6173 else
6174 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6175 ? diag::err_typecheck_call_too_few_args
6176 : diag::err_typecheck_call_too_few_args_at_least)
6177 << FnKind << MinArgs - ExplicitObjectParameterOffset
6178 << static_cast<unsigned>(Args.size()) -
6179 ExplicitObjectParameterOffset
6180 << HasExplicitObjectParameter << Fn->getSourceRange();
6181
6182 // Emit the location of the prototype.
6183 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6184 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6185 << FDecl << FDecl->getParametersSourceRange();
6186
6187 return true;
6188 }
6189 // We reserve space for the default arguments when we create
6190 // the call expression, before calling ConvertArgumentsForCall.
6191 assert((Call->getNumArgs() == NumParams) &&
6192 "We should have reserved space for the default arguments before!");
6193 }
6194
6195 // If too many are passed and not variadic, error on the extras and drop
6196 // them.
6197 if (Args.size() > NumParams) {
6198 if (!Proto->isVariadic()) {
6199 TypoCorrection TC;
6200 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6201 unsigned diag_id =
6202 MinArgs == NumParams && !Proto->isVariadic()
6203 ? diag::err_typecheck_call_too_many_args_suggest
6204 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6205 diagnoseTypo(
6206 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6207 << FnKind << NumParams - ExplicitObjectParameterOffset
6208 << static_cast<unsigned>(Args.size()) -
6209 ExplicitObjectParameterOffset
6210 << HasExplicitObjectParameter << TC.getCorrectionRange());
6211 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6212 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6213 ->getDeclName())
6214 Diag(Loc: Args[NumParams]->getBeginLoc(),
6215 DiagID: MinArgs == NumParams
6216 ? diag::err_typecheck_call_too_many_args_one
6217 : diag::err_typecheck_call_too_many_args_at_most_one)
6218 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6219 << static_cast<unsigned>(Args.size()) -
6220 ExplicitObjectParameterOffset
6221 << HasExplicitObjectParameter << Fn->getSourceRange()
6222 << SourceRange(Args[NumParams]->getBeginLoc(),
6223 Args.back()->getEndLoc());
6224 else
6225 Diag(Loc: Args[NumParams]->getBeginLoc(),
6226 DiagID: MinArgs == NumParams
6227 ? diag::err_typecheck_call_too_many_args
6228 : diag::err_typecheck_call_too_many_args_at_most)
6229 << FnKind << NumParams - ExplicitObjectParameterOffset
6230 << static_cast<unsigned>(Args.size()) -
6231 ExplicitObjectParameterOffset
6232 << HasExplicitObjectParameter << Fn->getSourceRange()
6233 << SourceRange(Args[NumParams]->getBeginLoc(),
6234 Args.back()->getEndLoc());
6235
6236 // Emit the location of the prototype.
6237 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6238 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6239 << FDecl << FDecl->getParametersSourceRange();
6240
6241 // This deletes the extra arguments.
6242 Call->shrinkNumArgs(NewNumArgs: NumParams);
6243 return true;
6244 }
6245 }
6246 SmallVector<Expr *, 8> AllArgs;
6247 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6248
6249 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6250 AllArgs, CallType);
6251 if (Invalid)
6252 return true;
6253 unsigned TotalNumArgs = AllArgs.size();
6254 for (unsigned i = 0; i < TotalNumArgs; ++i)
6255 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6256
6257 Call->computeDependence();
6258 return false;
6259}
6260
6261bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6262 const FunctionProtoType *Proto,
6263 unsigned FirstParam, ArrayRef<Expr *> Args,
6264 SmallVectorImpl<Expr *> &AllArgs,
6265 VariadicCallType CallType, bool AllowExplicit,
6266 bool IsListInitialization) {
6267 unsigned NumParams = Proto->getNumParams();
6268 bool Invalid = false;
6269 size_t ArgIx = 0;
6270 // Continue to check argument types (even if we have too few/many args).
6271 for (unsigned i = FirstParam; i < NumParams; i++) {
6272 QualType ProtoArgType = Proto->getParamType(i);
6273
6274 Expr *Arg;
6275 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6276 if (ArgIx < Args.size()) {
6277 Arg = Args[ArgIx++];
6278
6279 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6280 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6281 return true;
6282
6283 // Strip the unbridged-cast placeholder expression off, if applicable.
6284 bool CFAudited = false;
6285 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6286 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6287 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6288 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6289 else if (getLangOpts().ObjCAutoRefCount &&
6290 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6291 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6292 CFAudited = true;
6293
6294 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6295 ProtoArgType->isBlockPointerType())
6296 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6297 BE->getBlockDecl()->setDoesNotEscape();
6298 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6299 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6300 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6301 if (ArgExpr.isInvalid())
6302 return true;
6303 Arg = ArgExpr.getAs<Expr>();
6304 }
6305
6306 InitializedEntity Entity =
6307 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6308 Type: ProtoArgType)
6309 : InitializedEntity::InitializeParameter(
6310 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6311
6312 // Remember that parameter belongs to a CF audited API.
6313 if (CFAudited)
6314 Entity.setParameterCFAudited();
6315
6316 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6317 // function boundaries is a common oversight.
6318 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6319 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6320 bool isPedantic =
6321 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6322 Diag(Loc: Arg->getExprLoc(),
6323 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6324 : diag::warn_obt_discarded_at_function_boundary)
6325 << Arg->getType() << ProtoArgType;
6326 }
6327
6328 ExprResult ArgE = PerformCopyInitialization(
6329 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6330 if (ArgE.isInvalid())
6331 return true;
6332
6333 Arg = ArgE.getAs<Expr>();
6334 } else {
6335 assert(Param && "can't use default arguments without a known callee");
6336
6337 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6338 if (ArgExpr.isInvalid())
6339 return true;
6340
6341 Arg = ArgExpr.getAs<Expr>();
6342 }
6343
6344 // Check for array bounds violations for each argument to the call. This
6345 // check only triggers warnings when the argument isn't a more complex Expr
6346 // with its own checking, such as a BinaryOperator.
6347 CheckArrayAccess(E: Arg);
6348
6349 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6350 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6351
6352 AllArgs.push_back(Elt: Arg);
6353 }
6354
6355 // If this is a variadic call, handle args passed through "...".
6356 if (CallType != VariadicCallType::DoesNotApply) {
6357 // Assume that extern "C" functions with variadic arguments that
6358 // return __unknown_anytype aren't *really* variadic.
6359 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6360 FDecl->isExternC()) {
6361 for (Expr *A : Args.slice(N: ArgIx)) {
6362 QualType paramType; // ignored
6363 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6364 Invalid |= arg.isInvalid();
6365 AllArgs.push_back(Elt: arg.get());
6366 }
6367
6368 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6369 } else {
6370 for (Expr *A : Args.slice(N: ArgIx)) {
6371 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6372 Invalid |= Arg.isInvalid();
6373 AllArgs.push_back(Elt: Arg.get());
6374 }
6375 }
6376
6377 // Check for array bounds violations.
6378 for (Expr *A : Args.slice(N: ArgIx))
6379 CheckArrayAccess(E: A);
6380 }
6381 return Invalid;
6382}
6383
6384static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6385 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6386 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6387 TL = DTL.getOriginalLoc();
6388 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6389 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6390 << ATL.getLocalSourceRange();
6391}
6392
6393void
6394Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6395 ParmVarDecl *Param,
6396 const Expr *ArgExpr) {
6397 // Static array parameters are not supported in C++.
6398 if (!Param || getLangOpts().CPlusPlus)
6399 return;
6400
6401 QualType OrigTy = Param->getOriginalType();
6402
6403 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6404 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6405 return;
6406
6407 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6408 NPC: Expr::NPC_NeverValueDependent)) {
6409 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6410 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6411 return;
6412 }
6413
6414 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6415 if (!CAT)
6416 return;
6417
6418 const ConstantArrayType *ArgCAT =
6419 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6420 if (!ArgCAT)
6421 return;
6422
6423 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6424 T2: ArgCAT->getElementType())) {
6425 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6426 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6427 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6428 << (unsigned)CAT->getZExtSize() << 0;
6429 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6430 }
6431 return;
6432 }
6433
6434 std::optional<CharUnits> ArgSize =
6435 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6436 std::optional<CharUnits> ParmSize =
6437 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6438 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6439 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6440 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6441 << (unsigned)ParmSize->getQuantity() << 1;
6442 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6443 }
6444}
6445
6446/// Given a function expression of unknown-any type, try to rebuild it
6447/// to have a function type.
6448static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6449
6450/// Is the given type a placeholder that we need to lower out
6451/// immediately during argument processing?
6452static bool isPlaceholderToRemoveAsArg(QualType type) {
6453 // Placeholders are never sugared.
6454 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6455 if (!placeholder) return false;
6456
6457 switch (placeholder->getKind()) {
6458 // Ignore all the non-placeholder types.
6459#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6460 case BuiltinType::Id:
6461#include "clang/Basic/OpenCLImageTypes.def"
6462#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6463 case BuiltinType::Id:
6464#include "clang/Basic/OpenCLExtensionTypes.def"
6465 // In practice we'll never use this, since all SVE types are sugared
6466 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6467#define SVE_TYPE(Name, Id, SingletonId) \
6468 case BuiltinType::Id:
6469#include "clang/Basic/AArch64ACLETypes.def"
6470#define PPC_VECTOR_TYPE(Name, Id, Size) \
6471 case BuiltinType::Id:
6472#include "clang/Basic/PPCTypes.def"
6473#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6474#include "clang/Basic/RISCVVTypes.def"
6475#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6476#include "clang/Basic/WebAssemblyReferenceTypes.def"
6477#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6478#include "clang/Basic/AMDGPUTypes.def"
6479#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6480#include "clang/Basic/HLSLIntangibleTypes.def"
6481#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6482#include "clang/Basic/SPIRVTypes.def"
6483#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6484#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6485#include "clang/AST/BuiltinTypes.def"
6486 return false;
6487
6488 case BuiltinType::UnresolvedTemplate:
6489 // We cannot lower out overload sets; they might validly be resolved
6490 // by the call machinery.
6491 case BuiltinType::Overload:
6492 return false;
6493
6494 // Unbridged casts in ARC can be handled in some call positions and
6495 // should be left in place.
6496 case BuiltinType::ARCUnbridgedCast:
6497 return false;
6498
6499 // Pseudo-objects should be converted as soon as possible.
6500 case BuiltinType::PseudoObject:
6501 return true;
6502
6503 // The debugger mode could theoretically but currently does not try
6504 // to resolve unknown-typed arguments based on known parameter types.
6505 case BuiltinType::UnknownAny:
6506 return true;
6507
6508 // These are always invalid as call arguments and should be reported.
6509 case BuiltinType::BoundMember:
6510 case BuiltinType::BuiltinFn:
6511 case BuiltinType::IncompleteMatrixIdx:
6512 case BuiltinType::ArraySection:
6513 case BuiltinType::OMPArrayShaping:
6514 case BuiltinType::OMPIterator:
6515 return true;
6516
6517 }
6518 llvm_unreachable("bad builtin type kind");
6519}
6520
6521bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6522 // Apply this processing to all the arguments at once instead of
6523 // dying at the first failure.
6524 bool hasInvalid = false;
6525 for (size_t i = 0, e = args.size(); i != e; i++) {
6526 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6527 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6528 if (result.isInvalid()) hasInvalid = true;
6529 else args[i] = result.get();
6530 }
6531 }
6532 return hasInvalid;
6533}
6534
6535/// If a builtin function has a pointer argument with no explicit address
6536/// space, then it should be able to accept a pointer to any address
6537/// space as input. In order to do this, we need to replace the
6538/// standard builtin declaration with one that uses the same address space
6539/// as the call.
6540///
6541/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6542/// it does not contain any pointer arguments without
6543/// an address space qualifer. Otherwise the rewritten
6544/// FunctionDecl is returned.
6545/// TODO: Handle pointer return types.
6546static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6547 FunctionDecl *FDecl,
6548 MultiExprArg ArgExprs) {
6549
6550 QualType DeclType = FDecl->getType();
6551 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6552
6553 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6554 ArgExprs.size() < FT->getNumParams())
6555 return nullptr;
6556
6557 bool NeedsNewDecl = false;
6558 unsigned i = 0;
6559 SmallVector<QualType, 8> OverloadParams;
6560
6561 {
6562 // The lvalue conversions in this loop are only for type resolution and
6563 // don't actually occur.
6564 EnterExpressionEvaluationContext Unevaluated(
6565 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6566 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6567
6568 for (QualType ParamType : FT->param_types()) {
6569
6570 // Convert array arguments to pointer to simplify type lookup.
6571 ExprResult ArgRes =
6572 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6573 if (ArgRes.isInvalid())
6574 return nullptr;
6575 Expr *Arg = ArgRes.get();
6576 QualType ArgType = Arg->getType();
6577 if (!ParamType->isPointerType() ||
6578 ParamType->getPointeeType().hasAddressSpace() ||
6579 !ArgType->isPointerType() ||
6580 !ArgType->getPointeeType().hasAddressSpace() ||
6581 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6582 OverloadParams.push_back(Elt: ParamType);
6583 continue;
6584 }
6585
6586 QualType PointeeType = ParamType->getPointeeType();
6587 NeedsNewDecl = true;
6588 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6589
6590 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6591 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6592 }
6593 }
6594
6595 if (!NeedsNewDecl)
6596 return nullptr;
6597
6598 FunctionProtoType::ExtProtoInfo EPI;
6599 EPI.Variadic = FT->isVariadic();
6600 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6601 Args: OverloadParams, EPI);
6602 DeclContext *Parent = FDecl->getParent();
6603 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6604 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6605 N: FDecl->getIdentifier(), T: OverloadTy,
6606 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6607 isInlineSpecified: false,
6608 /*hasPrototype=*/hasWrittenPrototype: true);
6609 SmallVector<ParmVarDecl*, 16> Params;
6610 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6611 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6612 QualType ParamType = FT->getParamType(i);
6613 ParmVarDecl *Parm =
6614 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6615 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6616 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6617 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6618 Params.push_back(Elt: Parm);
6619 }
6620 OverloadDecl->setParams(Params);
6621 // We cannot merge host/device attributes of redeclarations. They have to
6622 // be consistent when created.
6623 if (Sema->LangOpts.CUDA) {
6624 if (FDecl->hasAttr<CUDAHostAttr>())
6625 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6626 if (FDecl->hasAttr<CUDADeviceAttr>())
6627 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6628 }
6629 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6630 return OverloadDecl;
6631}
6632
6633static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6634 FunctionDecl *Callee,
6635 MultiExprArg ArgExprs) {
6636 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6637 // similar attributes) really don't like it when functions are called with an
6638 // invalid number of args.
6639 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6640 /*PartialOverloading=*/false) &&
6641 !Callee->isVariadic())
6642 return;
6643 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6644 return;
6645
6646 if (const EnableIfAttr *Attr =
6647 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6648 S.Diag(Loc: Fn->getBeginLoc(),
6649 DiagID: isa<CXXMethodDecl>(Val: Callee)
6650 ? diag::err_ovl_no_viable_member_function_in_call
6651 : diag::err_ovl_no_viable_function_in_call)
6652 << Callee << Callee->getSourceRange();
6653 S.Diag(Loc: Callee->getLocation(),
6654 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6655 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6656 return;
6657 }
6658}
6659
6660static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6661 const UnresolvedMemberExpr *const UME, Sema &S) {
6662
6663 const auto GetFunctionLevelDCIfCXXClass =
6664 [](Sema &S) -> const CXXRecordDecl * {
6665 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6666 if (!DC || !DC->getParent())
6667 return nullptr;
6668
6669 // If the call to some member function was made from within a member
6670 // function body 'M' return return 'M's parent.
6671 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6672 return MD->getParent()->getCanonicalDecl();
6673 // else the call was made from within a default member initializer of a
6674 // class, so return the class.
6675 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6676 return RD->getCanonicalDecl();
6677 return nullptr;
6678 };
6679 // If our DeclContext is neither a member function nor a class (in the
6680 // case of a lambda in a default member initializer), we can't have an
6681 // enclosing 'this'.
6682
6683 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6684 if (!CurParentClass)
6685 return false;
6686
6687 // The naming class for implicit member functions call is the class in which
6688 // name lookup starts.
6689 const CXXRecordDecl *const NamingClass =
6690 UME->getNamingClass()->getCanonicalDecl();
6691 assert(NamingClass && "Must have naming class even for implicit access");
6692
6693 // If the unresolved member functions were found in a 'naming class' that is
6694 // related (either the same or derived from) to the class that contains the
6695 // member function that itself contained the implicit member access.
6696
6697 return CurParentClass == NamingClass ||
6698 CurParentClass->isDerivedFrom(Base: NamingClass);
6699}
6700
6701static void
6702tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6703 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6704
6705 if (!UME)
6706 return;
6707
6708 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6709 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6710 // already been captured, or if this is an implicit member function call (if
6711 // it isn't, an attempt to capture 'this' should already have been made).
6712 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6713 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6714 return;
6715
6716 // Check if the naming class in which the unresolved members were found is
6717 // related (same as or is a base of) to the enclosing class.
6718
6719 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6720 return;
6721
6722
6723 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6724 // If the enclosing function is not dependent, then this lambda is
6725 // capture ready, so if we can capture this, do so.
6726 if (!EnclosingFunctionCtx->isDependentContext()) {
6727 // If the current lambda and all enclosing lambdas can capture 'this' -
6728 // then go ahead and capture 'this' (since our unresolved overload set
6729 // contains at least one non-static member function).
6730 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6731 S.CheckCXXThisCapture(Loc: CallLoc);
6732 } else if (S.CurContext->isDependentContext()) {
6733 // ... since this is an implicit member reference, that might potentially
6734 // involve a 'this' capture, mark 'this' for potential capture in
6735 // enclosing lambdas.
6736 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6737 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6738 }
6739}
6740
6741// Once a call is fully resolved, warn for unqualified calls to specific
6742// C++ standard functions, like move and forward.
6743static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6744 const CallExpr *Call) {
6745 // We are only checking unary move and forward so exit early here.
6746 if (Call->getNumArgs() != 1)
6747 return;
6748
6749 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6750 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6751 return;
6752 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6753 if (!DRE || !DRE->getLocation().isValid())
6754 return;
6755
6756 if (DRE->getQualifier())
6757 return;
6758
6759 const FunctionDecl *FD = Call->getDirectCallee();
6760 if (!FD)
6761 return;
6762
6763 // Only warn for some functions deemed more frequent or problematic.
6764 unsigned BuiltinID = FD->getBuiltinID();
6765 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6766 return;
6767
6768 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6769 << FD->getQualifiedNameAsString()
6770 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6771}
6772
6773ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6774 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6775 Expr *ExecConfig) {
6776 ExprResult Call =
6777 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6778 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6779 if (Call.isInvalid())
6780 return Call;
6781
6782 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6783 // language modes.
6784 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6785 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6786 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6787 << ULE->getName();
6788 }
6789
6790 if (LangOpts.OpenMP)
6791 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6792 ExecConfig);
6793 if (LangOpts.CPlusPlus) {
6794 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6795 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6796
6797 // If we previously found that the id-expression of this call refers to a
6798 // consteval function but the call is dependent, we should not treat is an
6799 // an invalid immediate call.
6800 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6801 DRE && Call.get()->isValueDependent()) {
6802 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6803 }
6804 }
6805 return Call;
6806}
6807
6808// Any type that could be used to form a callable expression
6809static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6810 QualType T = E->getType();
6811 if (T->isDependentType())
6812 return true;
6813
6814 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6815 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6816 T->isFunctionType() || T->isFunctionReferenceType() ||
6817 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6818 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6819 return true;
6820
6821 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6822 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6823}
6824
6825ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6826 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6827 Expr *ExecConfig, bool IsExecConfig,
6828 bool AllowRecovery) {
6829 // Since this might be a postfix expression, get rid of ParenListExprs.
6830 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6831 if (Result.isInvalid()) return ExprError();
6832 Fn = Result.get();
6833
6834 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6835 // later, when we check boolean conditions, for now we merely forward it
6836 // without any additional checking.
6837 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6838 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6839 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6840
6841 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6842 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6843 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6844 return CallExpr::Create(
6845 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6846 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6847 }
6848 }
6849
6850 if (CheckArgsForPlaceholders(args: ArgExprs))
6851 return ExprError();
6852
6853 // The result of __builtin_counted_by_ref cannot be used as a function
6854 // argument. It allows leaking and modification of bounds safety information.
6855 for (const Expr *Arg : ArgExprs)
6856 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6857 K: BuiltinCountedByRefKind::FunctionArg))
6858 return ExprError();
6859
6860 if (getLangOpts().CPlusPlus) {
6861 // If this is a pseudo-destructor expression, build the call immediately.
6862 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6863 if (!ArgExprs.empty()) {
6864 // Pseudo-destructor calls should not have any arguments.
6865 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6866 << FixItHint::CreateRemoval(
6867 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6868 ArgExprs.back()->getEndLoc()));
6869 }
6870
6871 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6872 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6873 }
6874 if (Fn->getType() == Context.PseudoObjectTy) {
6875 ExprResult result = CheckPlaceholderExpr(E: Fn);
6876 if (result.isInvalid()) return ExprError();
6877 Fn = result.get();
6878 }
6879
6880 // Determine whether this is a dependent call inside a C++ template,
6881 // in which case we won't do any semantic analysis now.
6882 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6883 if (ExecConfig) {
6884 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6885 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6886 Ty: Context.DependentTy, VK: VK_PRValue,
6887 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6888 } else {
6889
6890 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6891 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6892 CallLoc: Fn->getBeginLoc());
6893
6894 // If the type of the function itself is not dependent
6895 // check that it is a reasonable as a function, as type deduction
6896 // later assume the CallExpr has a sensible TYPE.
6897 if (!MayBeFunctionType(Context, E: Fn))
6898 return ExprError(
6899 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6900 << Fn->getType() << Fn->getSourceRange());
6901
6902 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6903 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6904 }
6905 }
6906
6907 // Determine whether this is a call to an object (C++ [over.call.object]).
6908 if (Fn->getType()->isRecordType())
6909 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6910 RParenLoc);
6911
6912 if (Fn->getType() == Context.UnknownAnyTy) {
6913 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6914 if (result.isInvalid()) return ExprError();
6915 Fn = result.get();
6916 }
6917
6918 if (Fn->getType() == Context.BoundMemberTy) {
6919 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6920 RParenLoc, ExecConfig, IsExecConfig,
6921 AllowRecovery);
6922 }
6923 }
6924
6925 // Check for overloaded calls. This can happen even in C due to extensions.
6926 if (Fn->getType() == Context.OverloadTy) {
6927 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6928
6929 // We aren't supposed to apply this logic if there's an '&' involved.
6930 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6931 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6932 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6933 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6934 OverloadExpr *ovl = find.Expression;
6935 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6936 return BuildOverloadedCallExpr(
6937 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6938 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6939 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6940 RParenLoc, ExecConfig, IsExecConfig,
6941 AllowRecovery);
6942 }
6943 }
6944
6945 // If we're directly calling a function, get the appropriate declaration.
6946 if (Fn->getType() == Context.UnknownAnyTy) {
6947 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6948 if (result.isInvalid()) return ExprError();
6949 Fn = result.get();
6950 }
6951
6952 Expr *NakedFn = Fn->IgnoreParens();
6953
6954 bool CallingNDeclIndirectly = false;
6955 NamedDecl *NDecl = nullptr;
6956 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6957 if (UnOp->getOpcode() == UO_AddrOf) {
6958 CallingNDeclIndirectly = true;
6959 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6960 }
6961 }
6962
6963 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6964 NDecl = DRE->getDecl();
6965
6966 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6967 if (FDecl && FDecl->getBuiltinID()) {
6968 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6969 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6970 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
6971 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
6972 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
6973 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6974 }
6975 }
6976
6977 // Rewrite the function decl for this builtin by replacing parameters
6978 // with no explicit address space with the address space of the arguments
6979 // in ArgExprs.
6980 if ((FDecl =
6981 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6982 NDecl = FDecl;
6983 Fn = DeclRefExpr::Create(
6984 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6985 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
6986 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6987 }
6988 }
6989 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6990 NDecl = ME->getMemberDecl();
6991
6992 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6993 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6994 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6995 return ExprError();
6996
6997 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
6998
6999 // If this expression is a call to a builtin function in HIP compilation,
7000 // allow a pointer-type argument to default address space to be passed as a
7001 // pointer-type parameter to a non-default address space. If Arg is declared
7002 // in the default address space and Param is declared in a non-default
7003 // address space, perform an implicit address space cast to the parameter
7004 // type.
7005 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7006 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7007 ++Idx) {
7008 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7009 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7010 !ArgExprs[Idx]->getType()->isPointerType())
7011 continue;
7012
7013 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7014 auto ArgTy = ArgExprs[Idx]->getType();
7015 auto ArgPtTy = ArgTy->getPointeeType();
7016 auto ArgAS = ArgPtTy.getAddressSpace();
7017
7018 // Add address space cast if target address spaces are different
7019 bool NeedImplicitASC =
7020 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7021 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7022 // or from specific AS which has target AS matching that of Param.
7023 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7024 if (!NeedImplicitASC)
7025 continue;
7026
7027 // First, ensure that the Arg is an RValue.
7028 if (ArgExprs[Idx]->isGLValue()) {
7029 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7030 if (Res.isInvalid())
7031 return ExprError();
7032 ArgExprs[Idx] = Res.get();
7033 }
7034
7035 // Construct a new arg type with address space of Param
7036 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7037 ArgPtQuals.setAddressSpace(ParamAS);
7038 auto NewArgPtTy =
7039 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7040 auto NewArgTy =
7041 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7042 Qs: ArgTy.getQualifiers());
7043
7044 // Finally perform an implicit address space cast
7045 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7046 CK: CK_AddressSpaceConversion)
7047 .get();
7048 }
7049 }
7050 }
7051
7052 if (Context.isDependenceAllowed() &&
7053 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7054 assert(!getLangOpts().CPlusPlus);
7055 assert((Fn->containsErrors() ||
7056 llvm::any_of(ArgExprs,
7057 [](clang::Expr *E) { return E->containsErrors(); })) &&
7058 "should only occur in error-recovery path.");
7059 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7060 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7061 }
7062 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7063 Config: ExecConfig, IsExecConfig);
7064}
7065
7066Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7067 MultiExprArg CallArgs) {
7068 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7069 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7070 Sema::LookupOrdinaryName);
7071 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7072
7073 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7074 assert(BuiltInDecl && "failed to find builtin declaration");
7075
7076 ExprResult DeclRef =
7077 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7078 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7079
7080 ExprResult Call =
7081 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7082
7083 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7084 return Call.get();
7085}
7086
7087ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7088 SourceLocation BuiltinLoc,
7089 SourceLocation RParenLoc) {
7090 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7091 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7092}
7093
7094ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7095 SourceLocation BuiltinLoc,
7096 SourceLocation RParenLoc) {
7097 ExprValueKind VK = VK_PRValue;
7098 ExprObjectKind OK = OK_Ordinary;
7099 QualType SrcTy = E->getType();
7100 if (!SrcTy->isDependentType() &&
7101 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7102 return ExprError(
7103 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7104 << DestTy << SrcTy << E->getSourceRange());
7105 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7106}
7107
7108ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7109 SourceLocation BuiltinLoc,
7110 SourceLocation RParenLoc) {
7111 TypeSourceInfo *TInfo;
7112 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7113 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7114}
7115
7116ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7117 SourceLocation LParenLoc,
7118 ArrayRef<Expr *> Args,
7119 SourceLocation RParenLoc, Expr *Config,
7120 bool IsExecConfig, ADLCallKind UsesADL) {
7121 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7122 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7123
7124 auto IsSJLJ = [&] {
7125 switch (BuiltinID) {
7126 case Builtin::BI__builtin_longjmp:
7127 case Builtin::BI__builtin_setjmp:
7128 case Builtin::BI__sigsetjmp:
7129 case Builtin::BI_longjmp:
7130 case Builtin::BI_setjmp:
7131 case Builtin::BIlongjmp:
7132 case Builtin::BIsetjmp:
7133 case Builtin::BIsiglongjmp:
7134 case Builtin::BIsigsetjmp:
7135 return true;
7136 default:
7137 return false;
7138 }
7139 };
7140
7141 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7142 if (!CurrentDefer.empty() && IsSJLJ()) {
7143 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7144 // for more than just blocks (e.g. lambdas, nested classes...).
7145 Scope *DeferParent = CurrentDefer.back().first;
7146 Scope *Block = CurScope->getBlockParent();
7147 if (DeferParent->Contains(rhs: *CurScope) &&
7148 (!Block || !DeferParent->Contains(rhs: *Block)))
7149 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7150 }
7151
7152 // Functions with 'interrupt' attribute cannot be called directly.
7153 if (FDecl) {
7154 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7155 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7156 return ExprError();
7157 }
7158 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7159 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7160 return ExprError();
7161 }
7162 }
7163
7164 // X86 interrupt handlers may only call routines with attribute
7165 // no_caller_saved_registers since there is no efficient way to
7166 // save and restore the non-GPR state.
7167 if (auto *Caller = getCurFunctionDecl()) {
7168 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7169 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7170 const TargetInfo &TI = Context.getTargetInfo();
7171 bool HasNonGPRRegisters =
7172 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7173 if (HasNonGPRRegisters &&
7174 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7175 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7176 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7177 if (FDecl)
7178 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7179 }
7180 }
7181 }
7182
7183 // Extract the return type from the builtin function pointer type.
7184 QualType ResultTy;
7185 if (BuiltinID)
7186 ResultTy = FDecl->getCallResultType();
7187 else
7188 ResultTy = Context.BoolTy;
7189
7190 // Promote the function operand.
7191 // We special-case function promotion here because we only allow promoting
7192 // builtin functions to function pointers in the callee of a call.
7193 ExprResult Result;
7194 if (BuiltinID &&
7195 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7196 // FIXME Several builtins still have setType in
7197 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7198 // Builtins.td to ensure they are correct before removing setType calls.
7199 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7200 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7201 } else
7202 Result = CallExprUnaryConversions(E: Fn);
7203 if (Result.isInvalid())
7204 return ExprError();
7205 Fn = Result.get();
7206
7207 // Check for a valid function type, but only if it is not a builtin which
7208 // requires custom type checking. These will be handled by
7209 // CheckBuiltinFunctionCall below just after creation of the call expression.
7210 const FunctionType *FuncT = nullptr;
7211 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7212 retry:
7213 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7214 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7215 // have type pointer to function".
7216 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7217 if (!FuncT)
7218 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7219 << Fn->getType() << Fn->getSourceRange());
7220 } else if (const BlockPointerType *BPT =
7221 Fn->getType()->getAs<BlockPointerType>()) {
7222 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7223 } else {
7224 // Handle calls to expressions of unknown-any type.
7225 if (Fn->getType() == Context.UnknownAnyTy) {
7226 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7227 if (rewrite.isInvalid())
7228 return ExprError();
7229 Fn = rewrite.get();
7230 goto retry;
7231 }
7232
7233 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7234 << Fn->getType() << Fn->getSourceRange());
7235 }
7236 }
7237
7238 // Get the number of parameters in the function prototype, if any.
7239 // We will allocate space for max(Args.size(), NumParams) arguments
7240 // in the call expression.
7241 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7242 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7243
7244 CallExpr *TheCall;
7245 if (Config) {
7246 assert(UsesADL == ADLCallKind::NotADL &&
7247 "CUDAKernelCallExpr should not use ADL");
7248 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7249 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7250 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7251 } else {
7252 TheCall =
7253 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7254 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7255 }
7256
7257 // Bail out early if calling a builtin with custom type checking.
7258 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7259 // For HLSL builtin aliases, the call was resolved via overload resolution
7260 // which may have selected a conversion sequence (e.g., vector-to-scalar
7261 // truncation). Convert arguments to match the declared prototype before
7262 // the custom type checker runs, otherwise the builtin will operate on
7263 // the unconverted argument types.
7264 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7265 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7266 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7267 IsExecConfig))
7268 return ExprError();
7269 }
7270 }
7271 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7272 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7273 E = CheckForImmediateInvocation(E, Decl: FDecl);
7274 return E;
7275 }
7276
7277 if (getLangOpts().CUDA) {
7278 if (Config) {
7279 // CUDA: Kernel calls must be to global functions
7280 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7281 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7282 << FDecl << Fn->getSourceRange());
7283
7284 // CUDA: Kernel function must have 'void' return type
7285 if (!FuncT->getReturnType()->isVoidType() &&
7286 !FuncT->getReturnType()->getAs<AutoType>() &&
7287 !FuncT->getReturnType()->isInstantiationDependentType())
7288 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7289 << Fn->getType() << Fn->getSourceRange());
7290 } else {
7291 // CUDA: Calls to global functions must be configured
7292 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7293 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7294 << FDecl << Fn->getSourceRange());
7295 }
7296 }
7297
7298 // Check for a valid return type
7299 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7300 FD: FDecl))
7301 return ExprError();
7302
7303 // We know the result type of the call, set it.
7304 TheCall->setType(FuncT->getCallResultType(Context));
7305 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7306
7307 // WebAssembly tables can't be used as arguments.
7308 if (Context.getTargetInfo().getTriple().isWasm()) {
7309 for (const Expr *Arg : Args) {
7310 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7311 return ExprError(Diag(Loc: Arg->getExprLoc(),
7312 DiagID: diag::err_wasm_table_as_function_parameter));
7313 }
7314 }
7315 }
7316
7317 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7318 // replaces sampler DeclRefExprs with their integer initializers.
7319 if (getLangOpts().OpenCL && FDecl) {
7320 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7321 }
7322
7323 if (Proto) {
7324 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7325 IsExecConfig))
7326 return ExprError();
7327 } else {
7328 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7329
7330 if (FDecl) {
7331 // Check if we have too few/too many template arguments, based
7332 // on our knowledge of the function definition.
7333 const FunctionDecl *Def = nullptr;
7334 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7335 Proto = Def->getType()->getAs<FunctionProtoType>();
7336 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7337 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7338 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7339 }
7340
7341 // If the function we're calling isn't a function prototype, but we have
7342 // a function prototype from a prior declaratiom, use that prototype.
7343 if (!FDecl->hasPrototype())
7344 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7345 }
7346
7347 // If we still haven't found a prototype to use but there are arguments to
7348 // the call, diagnose this as calling a function without a prototype.
7349 // However, if we found a function declaration, check to see if
7350 // -Wdeprecated-non-prototype was disabled where the function was declared.
7351 // If so, we will silence the diagnostic here on the assumption that this
7352 // interface is intentional and the user knows what they're doing. We will
7353 // also silence the diagnostic if there is a function declaration but it
7354 // was implicitly defined (the user already gets diagnostics about the
7355 // creation of the implicit function declaration, so the additional warning
7356 // is not helpful).
7357 if (!Proto && !Args.empty() &&
7358 (!FDecl || (!FDecl->isImplicit() &&
7359 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7360 Loc: FDecl->getLocation()))))
7361 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7362 << (FDecl != nullptr) << FDecl;
7363
7364 // Promote the arguments (C99 6.5.2.2p6).
7365 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7366 Expr *Arg = Args[i];
7367
7368 if (Proto && i < Proto->getNumParams()) {
7369 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7370 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7371 ExprResult ArgE =
7372 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7373 if (ArgE.isInvalid())
7374 return true;
7375
7376 Arg = ArgE.getAs<Expr>();
7377
7378 } else {
7379 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7380
7381 if (ArgE.isInvalid())
7382 return true;
7383
7384 Arg = ArgE.getAs<Expr>();
7385 }
7386
7387 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7388 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7389 return ExprError();
7390
7391 TheCall->setArg(Arg: i, ArgExpr: Arg);
7392 }
7393 TheCall->computeDependence();
7394 }
7395
7396 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7397 if (Method->isImplicitObjectMemberFunction())
7398 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7399 << Fn->getSourceRange() << 0);
7400
7401 // Check for sentinels
7402 if (NDecl)
7403 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7404
7405 // Warn for unions passing across security boundary (CMSE).
7406 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7407 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7408 if (const auto *RT =
7409 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7410 if (RT->getDecl()->isOrContainsUnion())
7411 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7412 << 0 << i;
7413 }
7414 }
7415 }
7416
7417 // Do special checking on direct calls to functions.
7418 if (FDecl) {
7419 if (CheckFunctionCall(FDecl, TheCall, Proto))
7420 return ExprError();
7421
7422 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7423 checkFortifiedLibcArgument(FD: FDecl, TheCall);
7424
7425 if (BuiltinID)
7426 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7427 } else if (NDecl) {
7428 if (CheckPointerCall(NDecl, TheCall, Proto))
7429 return ExprError();
7430 } else {
7431 if (CheckOtherCall(TheCall, Proto))
7432 return ExprError();
7433 }
7434
7435 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7436}
7437
7438ExprResult
7439Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7440 SourceLocation RParenLoc, Expr *InitExpr) {
7441 assert(Ty && "ActOnCompoundLiteral(): missing type");
7442 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7443
7444 TypeSourceInfo *TInfo;
7445 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7446 if (!TInfo)
7447 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7448
7449 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7450}
7451
7452ExprResult
7453Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7454 SourceLocation RParenLoc, Expr *LiteralExpr) {
7455 QualType literalType = TInfo->getType();
7456
7457 if (literalType->isArrayType()) {
7458 if (RequireCompleteSizedType(
7459 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7460 DiagID: diag::err_array_incomplete_or_sizeless_type,
7461 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7462 return ExprError();
7463 if (literalType->isVariableArrayType()) {
7464 // C23 6.7.10p4: An entity of variable length array type shall not be
7465 // initialized except by an empty initializer.
7466 //
7467 // The C extension warnings are issued from ParseBraceInitializer() and
7468 // do not need to be issued here. However, we continue to issue an error
7469 // in the case there are initializers or we are compiling C++. We allow
7470 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7471 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7472 // FIXME: should we allow this construct in C++ when it makes sense to do
7473 // so?
7474 //
7475 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7476 // shall specify an object type or an array of unknown size, but not a
7477 // variable length array type. This seems odd, as it allows 'int a[size] =
7478 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7479 // says, this is what's implemented here for C (except for the extension
7480 // that permits constant foldable size arrays)
7481
7482 auto diagID = LangOpts.CPlusPlus
7483 ? diag::err_variable_object_no_init
7484 : diag::err_compound_literal_with_vla_type;
7485 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7486 FailedFoldDiagID: diagID))
7487 return ExprError();
7488 }
7489 } else if (!literalType->isDependentType() &&
7490 RequireCompleteType(Loc: LParenLoc, T: literalType,
7491 DiagID: diag::err_typecheck_decl_incomplete_type,
7492 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7493 return ExprError();
7494
7495 InitializedEntity Entity
7496 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7497 InitializationKind Kind
7498 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7499 TypeRange: SourceRange(LParenLoc, RParenLoc),
7500 /*InitList=*/true);
7501 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7502 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7503 ResultType: &literalType);
7504 if (Result.isInvalid())
7505 return ExprError();
7506 LiteralExpr = Result.get();
7507
7508 // We treat the compound literal as being at file scope if it's not in a
7509 // function or method body, or within the function's prototype scope. This
7510 // means the following compound literal is not at file scope:
7511 // void func(char *para[(int [1]){ 0 }[0]);
7512 const Scope *S = getCurScope();
7513 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7514 !S->isInCFunctionScope() &&
7515 (!S || !S->isFunctionPrototypeScope());
7516
7517 // In C, compound literals are l-values for some reason.
7518 // For GCC compatibility, in C++, file-scope array compound literals with
7519 // constant initializers are also l-values, and compound literals are
7520 // otherwise prvalues.
7521 //
7522 // (GCC also treats C++ list-initialized file-scope array prvalues with
7523 // constant initializers as l-values, but that's non-conforming, so we don't
7524 // follow it there.)
7525 //
7526 // FIXME: It would be better to handle the lvalue cases as materializing and
7527 // lifetime-extending a temporary object, but our materialized temporaries
7528 // representation only supports lifetime extension from a variable, not "out
7529 // of thin air".
7530 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7531 // is bound to the result of applying array-to-pointer decay to the compound
7532 // literal.
7533 // FIXME: GCC supports compound literals of reference type, which should
7534 // obviously have a value kind derived from the kind of reference involved.
7535 ExprValueKind VK =
7536 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7537 ? VK_PRValue
7538 : VK_LValue;
7539
7540 // C99 6.5.2.5
7541 // "If the compound literal occurs outside the body of a function, the
7542 // initializer list shall consist of constant expressions."
7543 if (IsFileScope)
7544 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7545 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7546 Expr *Init = ILE->getInit(Init: i);
7547 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7548 !Init->isConstantInitializer(Ctx&: Context)) {
7549 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7550 << Init->getSourceBitField();
7551 return ExprError();
7552 }
7553
7554 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7555 }
7556
7557 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7558 LiteralExpr, IsFileScope);
7559 if (IsFileScope) {
7560 if (!LiteralExpr->isTypeDependent() &&
7561 !LiteralExpr->isValueDependent() &&
7562 !literalType->isDependentType()) // C99 6.5.2.5p3
7563 if (CheckForConstantInitializer(Init: LiteralExpr))
7564 return ExprError();
7565 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7566 literalType.getAddressSpace() != LangAS::Default) {
7567 // Embedded-C extensions to C99 6.5.2.5:
7568 // "If the compound literal occurs inside the body of a function, the
7569 // type name shall not be qualified by an address-space qualifier."
7570 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7571 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7572 return ExprError();
7573 }
7574
7575 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7576 // Compound literals that have automatic storage duration are destroyed at
7577 // the end of the scope in C; in C++, they're just temporaries.
7578
7579 // Emit diagnostics if it is or contains a C union type that is non-trivial
7580 // to destruct.
7581 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7582 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7583 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7584 NonTrivialKind: NTCUK_Destruct);
7585
7586 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7587 if (literalType.isDestructedType()) {
7588 Cleanup.setExprNeedsCleanups(true);
7589 ExprCleanupObjects.push_back(Elt: E);
7590 getCurFunction()->setHasBranchProtectedScope();
7591 }
7592 }
7593
7594 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7595 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7596 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7597 Loc: E->getInitializer()->getExprLoc());
7598
7599 return MaybeBindToTemporary(E);
7600}
7601
7602ExprResult
7603Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7604 SourceLocation RBraceLoc) {
7605 // Only produce each kind of designated initialization diagnostic once.
7606 SourceLocation FirstDesignator;
7607 bool DiagnosedArrayDesignator = false;
7608 bool DiagnosedNestedDesignator = false;
7609 bool DiagnosedMixedDesignator = false;
7610
7611 // Check that any designated initializers are syntactically valid in the
7612 // current language mode.
7613 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7614 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7615 if (FirstDesignator.isInvalid())
7616 FirstDesignator = DIE->getBeginLoc();
7617
7618 if (!getLangOpts().CPlusPlus)
7619 break;
7620
7621 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7622 DiagnosedNestedDesignator = true;
7623 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7624 << DIE->getDesignatorsSourceRange();
7625 }
7626
7627 for (auto &Desig : DIE->designators()) {
7628 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7629 DiagnosedArrayDesignator = true;
7630 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7631 << Desig.getSourceRange();
7632 }
7633 }
7634
7635 if (!DiagnosedMixedDesignator &&
7636 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7637 DiagnosedMixedDesignator = true;
7638 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7639 << DIE->getSourceRange();
7640 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7641 << InitArgList[0]->getSourceRange();
7642 }
7643 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7644 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7645 DiagnosedMixedDesignator = true;
7646 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7647 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7648 << DIE->getSourceRange();
7649 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7650 << InitArgList[I]->getSourceRange();
7651 }
7652 }
7653
7654 if (FirstDesignator.isValid()) {
7655 // Only diagnose designated initiaization as a C++20 extension if we didn't
7656 // already diagnose use of (non-C++20) C99 designator syntax.
7657 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7658 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7659 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7660 ? diag::warn_cxx17_compat_designated_init
7661 : diag::ext_cxx_designated_init);
7662 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7663 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7664 }
7665 }
7666
7667 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7668}
7669
7670ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7671 MultiExprArg InitArgList,
7672 SourceLocation RBraceLoc, bool IsExplicit) {
7673 // Semantic analysis for initializers is done by ActOnDeclarator() and
7674 // CheckInitializer() - it requires knowledge of the object being initialized.
7675
7676 // Immediately handle non-overload placeholders. Overloads can be
7677 // resolved contextually, but everything else here can't.
7678 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7679 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7680 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7681
7682 // Ignore failures; dropping the entire initializer list because
7683 // of one failure would be terrible for indexing/etc.
7684 if (result.isInvalid()) continue;
7685
7686 InitArgList[I] = result.get();
7687 }
7688 }
7689
7690 InitListExpr *E = new (Context)
7691 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7692 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7693 return E;
7694}
7695
7696void Sema::maybeExtendBlockObject(ExprResult &E) {
7697 assert(E.get()->getType()->isBlockPointerType());
7698 assert(E.get()->isPRValue());
7699
7700 // Only do this in an r-value context.
7701 if (!getLangOpts().ObjCAutoRefCount) return;
7702
7703 E = ImplicitCastExpr::Create(
7704 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7705 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7706 Cleanup.setExprNeedsCleanups(true);
7707}
7708
7709CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7710 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7711 // Also, callers should have filtered out the invalid cases with
7712 // pointers. Everything else should be possible.
7713
7714 QualType SrcTy = Src.get()->getType();
7715 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7716 return CK_NoOp;
7717
7718 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7719 case Type::STK_MemberPointer:
7720 llvm_unreachable("member pointer type in C");
7721
7722 case Type::STK_CPointer:
7723 case Type::STK_BlockPointer:
7724 case Type::STK_ObjCObjectPointer:
7725 switch (DestTy->getScalarTypeKind()) {
7726 case Type::STK_CPointer: {
7727 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7728 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7729 if (SrcAS != DestAS)
7730 return CK_AddressSpaceConversion;
7731 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7732 return CK_NoOp;
7733 return CK_BitCast;
7734 }
7735 case Type::STK_BlockPointer:
7736 return (SrcKind == Type::STK_BlockPointer
7737 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7738 case Type::STK_ObjCObjectPointer:
7739 if (SrcKind == Type::STK_ObjCObjectPointer)
7740 return CK_BitCast;
7741 if (SrcKind == Type::STK_CPointer)
7742 return CK_CPointerToObjCPointerCast;
7743 maybeExtendBlockObject(E&: Src);
7744 return CK_BlockPointerToObjCPointerCast;
7745 case Type::STK_Bool:
7746 return CK_PointerToBoolean;
7747 case Type::STK_Integral:
7748 return CK_PointerToIntegral;
7749 case Type::STK_Floating:
7750 case Type::STK_FloatingComplex:
7751 case Type::STK_IntegralComplex:
7752 case Type::STK_MemberPointer:
7753 case Type::STK_FixedPoint:
7754 llvm_unreachable("illegal cast from pointer");
7755 }
7756 llvm_unreachable("Should have returned before this");
7757
7758 case Type::STK_FixedPoint:
7759 switch (DestTy->getScalarTypeKind()) {
7760 case Type::STK_FixedPoint:
7761 return CK_FixedPointCast;
7762 case Type::STK_Bool:
7763 return CK_FixedPointToBoolean;
7764 case Type::STK_Integral:
7765 return CK_FixedPointToIntegral;
7766 case Type::STK_Floating:
7767 return CK_FixedPointToFloating;
7768 case Type::STK_IntegralComplex:
7769 case Type::STK_FloatingComplex:
7770 Diag(Loc: Src.get()->getExprLoc(),
7771 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7772 << DestTy;
7773 return CK_IntegralCast;
7774 case Type::STK_CPointer:
7775 case Type::STK_ObjCObjectPointer:
7776 case Type::STK_BlockPointer:
7777 case Type::STK_MemberPointer:
7778 llvm_unreachable("illegal cast to pointer type");
7779 }
7780 llvm_unreachable("Should have returned before this");
7781
7782 case Type::STK_Bool: // casting from bool is like casting from an integer
7783 case Type::STK_Integral:
7784 switch (DestTy->getScalarTypeKind()) {
7785 case Type::STK_CPointer:
7786 case Type::STK_ObjCObjectPointer:
7787 case Type::STK_BlockPointer:
7788 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7789 NPC: Expr::NPC_ValueDependentIsNull))
7790 return CK_NullToPointer;
7791 return CK_IntegralToPointer;
7792 case Type::STK_Bool:
7793 return CK_IntegralToBoolean;
7794 case Type::STK_Integral:
7795 return CK_IntegralCast;
7796 case Type::STK_Floating:
7797 return CK_IntegralToFloating;
7798 case Type::STK_IntegralComplex:
7799 Src = ImpCastExprToType(E: Src.get(),
7800 Type: DestTy->castAs<ComplexType>()->getElementType(),
7801 CK: CK_IntegralCast);
7802 return CK_IntegralRealToComplex;
7803 case Type::STK_FloatingComplex:
7804 Src = ImpCastExprToType(E: Src.get(),
7805 Type: DestTy->castAs<ComplexType>()->getElementType(),
7806 CK: CK_IntegralToFloating);
7807 return CK_FloatingRealToComplex;
7808 case Type::STK_MemberPointer:
7809 llvm_unreachable("member pointer type in C");
7810 case Type::STK_FixedPoint:
7811 return CK_IntegralToFixedPoint;
7812 }
7813 llvm_unreachable("Should have returned before this");
7814
7815 case Type::STK_Floating:
7816 switch (DestTy->getScalarTypeKind()) {
7817 case Type::STK_Floating:
7818 return CK_FloatingCast;
7819 case Type::STK_Bool:
7820 return CK_FloatingToBoolean;
7821 case Type::STK_Integral:
7822 return CK_FloatingToIntegral;
7823 case Type::STK_FloatingComplex:
7824 Src = ImpCastExprToType(E: Src.get(),
7825 Type: DestTy->castAs<ComplexType>()->getElementType(),
7826 CK: CK_FloatingCast);
7827 return CK_FloatingRealToComplex;
7828 case Type::STK_IntegralComplex:
7829 Src = ImpCastExprToType(E: Src.get(),
7830 Type: DestTy->castAs<ComplexType>()->getElementType(),
7831 CK: CK_FloatingToIntegral);
7832 return CK_IntegralRealToComplex;
7833 case Type::STK_CPointer:
7834 case Type::STK_ObjCObjectPointer:
7835 case Type::STK_BlockPointer:
7836 llvm_unreachable("valid float->pointer cast?");
7837 case Type::STK_MemberPointer:
7838 llvm_unreachable("member pointer type in C");
7839 case Type::STK_FixedPoint:
7840 return CK_FloatingToFixedPoint;
7841 }
7842 llvm_unreachable("Should have returned before this");
7843
7844 case Type::STK_FloatingComplex:
7845 switch (DestTy->getScalarTypeKind()) {
7846 case Type::STK_FloatingComplex:
7847 return CK_FloatingComplexCast;
7848 case Type::STK_IntegralComplex:
7849 return CK_FloatingComplexToIntegralComplex;
7850 case Type::STK_Floating: {
7851 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7852 if (Context.hasSameType(T1: ET, T2: DestTy))
7853 return CK_FloatingComplexToReal;
7854 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7855 return CK_FloatingCast;
7856 }
7857 case Type::STK_Bool:
7858 return CK_FloatingComplexToBoolean;
7859 case Type::STK_Integral:
7860 Src = ImpCastExprToType(E: Src.get(),
7861 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7862 CK: CK_FloatingComplexToReal);
7863 return CK_FloatingToIntegral;
7864 case Type::STK_CPointer:
7865 case Type::STK_ObjCObjectPointer:
7866 case Type::STK_BlockPointer:
7867 llvm_unreachable("valid complex float->pointer cast?");
7868 case Type::STK_MemberPointer:
7869 llvm_unreachable("member pointer type in C");
7870 case Type::STK_FixedPoint:
7871 Diag(Loc: Src.get()->getExprLoc(),
7872 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7873 << SrcTy;
7874 return CK_IntegralCast;
7875 }
7876 llvm_unreachable("Should have returned before this");
7877
7878 case Type::STK_IntegralComplex:
7879 switch (DestTy->getScalarTypeKind()) {
7880 case Type::STK_FloatingComplex:
7881 return CK_IntegralComplexToFloatingComplex;
7882 case Type::STK_IntegralComplex:
7883 return CK_IntegralComplexCast;
7884 case Type::STK_Integral: {
7885 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7886 if (Context.hasSameType(T1: ET, T2: DestTy))
7887 return CK_IntegralComplexToReal;
7888 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7889 return CK_IntegralCast;
7890 }
7891 case Type::STK_Bool:
7892 return CK_IntegralComplexToBoolean;
7893 case Type::STK_Floating:
7894 Src = ImpCastExprToType(E: Src.get(),
7895 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7896 CK: CK_IntegralComplexToReal);
7897 return CK_IntegralToFloating;
7898 case Type::STK_CPointer:
7899 case Type::STK_ObjCObjectPointer:
7900 case Type::STK_BlockPointer:
7901 llvm_unreachable("valid complex int->pointer cast?");
7902 case Type::STK_MemberPointer:
7903 llvm_unreachable("member pointer type in C");
7904 case Type::STK_FixedPoint:
7905 Diag(Loc: Src.get()->getExprLoc(),
7906 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7907 << SrcTy;
7908 return CK_IntegralCast;
7909 }
7910 llvm_unreachable("Should have returned before this");
7911 }
7912
7913 llvm_unreachable("Unhandled scalar cast");
7914}
7915
7916static bool breakDownVectorType(QualType type, uint64_t &len,
7917 QualType &eltType) {
7918 // Vectors are simple.
7919 if (const VectorType *vecType = type->getAs<VectorType>()) {
7920 len = vecType->getNumElements();
7921 eltType = vecType->getElementType();
7922 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7923 return true;
7924 }
7925
7926 // We allow lax conversion to and from non-vector types, but only if
7927 // they're real types (i.e. non-complex, non-pointer scalar types).
7928 if (!type->isRealType()) return false;
7929
7930 len = 1;
7931 eltType = type;
7932 return true;
7933}
7934
7935bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7936 assert(srcTy->isVectorType() || destTy->isVectorType());
7937
7938 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7939 if (!FirstType->isSVESizelessBuiltinType())
7940 return false;
7941
7942 const auto *VecTy = SecondType->getAs<VectorType>();
7943 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7944 };
7945
7946 return ValidScalableConversion(srcTy, destTy) ||
7947 ValidScalableConversion(destTy, srcTy);
7948}
7949
7950bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7951 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7952 return false;
7953
7954 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7955 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7956
7957 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7958 matSrcType->getNumColumns() == matDestType->getNumColumns();
7959}
7960
7961bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7962 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7963
7964 uint64_t SrcLen, DestLen;
7965 QualType SrcEltTy, DestEltTy;
7966 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7967 return false;
7968 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7969 return false;
7970
7971 // ASTContext::getTypeSize will return the size rounded up to a
7972 // power of 2, so instead of using that, we need to use the raw
7973 // element size multiplied by the element count.
7974 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7975 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7976
7977 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7978}
7979
7980bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7981 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7982 "expected at least one type to be a vector here");
7983
7984 bool IsSrcTyAltivec =
7985 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7986 VectorKind::AltiVecVector) ||
7987 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7988 VectorKind::AltiVecBool) ||
7989 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7990 VectorKind::AltiVecPixel));
7991
7992 bool IsDestTyAltivec = DestTy->isVectorType() &&
7993 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7994 VectorKind::AltiVecVector) ||
7995 (DestTy->castAs<VectorType>()->getVectorKind() ==
7996 VectorKind::AltiVecBool) ||
7997 (DestTy->castAs<VectorType>()->getVectorKind() ==
7998 VectorKind::AltiVecPixel));
7999
8000 return (IsSrcTyAltivec || IsDestTyAltivec);
8001}
8002
8003bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8004 assert(destTy->isVectorType() || srcTy->isVectorType());
8005
8006 // Disallow lax conversions between scalars and ExtVectors (these
8007 // conversions are allowed for other vector types because common headers
8008 // depend on them). Most scalar OP ExtVector cases are handled by the
8009 // splat path anyway, which does what we want (convert, not bitcast).
8010 // What this rules out for ExtVectors is crazy things like char4*float.
8011 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8012 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8013
8014 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8015}
8016
8017bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8018 assert(destTy->isVectorType() || srcTy->isVectorType());
8019
8020 switch (Context.getLangOpts().getLaxVectorConversions()) {
8021 case LangOptions::LaxVectorConversionKind::None:
8022 return false;
8023
8024 case LangOptions::LaxVectorConversionKind::Integer:
8025 if (!srcTy->isIntegralOrEnumerationType()) {
8026 auto *Vec = srcTy->getAs<VectorType>();
8027 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8028 return false;
8029 }
8030 if (!destTy->isIntegralOrEnumerationType()) {
8031 auto *Vec = destTy->getAs<VectorType>();
8032 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8033 return false;
8034 }
8035 // OK, integer (vector) -> integer (vector) bitcast.
8036 break;
8037
8038 case LangOptions::LaxVectorConversionKind::All:
8039 break;
8040 }
8041
8042 return areLaxCompatibleVectorTypes(srcTy, destTy);
8043}
8044
8045bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8046 CastKind &Kind) {
8047 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8048 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8049 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8050 << DestTy << SrcTy << R;
8051 }
8052 } else if (SrcTy->isMatrixType()) {
8053 return Diag(Loc: R.getBegin(),
8054 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8055 << SrcTy << DestTy << R;
8056 } else if (DestTy->isMatrixType()) {
8057 return Diag(Loc: R.getBegin(),
8058 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8059 << DestTy << SrcTy << R;
8060 }
8061
8062 Kind = CK_MatrixCast;
8063 return false;
8064}
8065
8066bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8067 CastKind &Kind) {
8068 assert(VectorTy->isVectorType() && "Not a vector type!");
8069
8070 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8071 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8072 return Diag(Loc: R.getBegin(),
8073 DiagID: Ty->isVectorType() ?
8074 diag::err_invalid_conversion_between_vectors :
8075 diag::err_invalid_conversion_between_vector_and_integer)
8076 << VectorTy << Ty << R;
8077 } else
8078 return Diag(Loc: R.getBegin(),
8079 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8080 << VectorTy << Ty << R;
8081
8082 Kind = CK_BitCast;
8083 return false;
8084}
8085
8086ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8087 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8088
8089 if (DestElemTy == SplattedExpr->getType())
8090 return SplattedExpr;
8091
8092 assert(DestElemTy->isFloatingType() ||
8093 DestElemTy->isIntegralOrEnumerationType());
8094
8095 CastKind CK;
8096 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8097 // OpenCL requires that we convert `true` boolean expressions to -1, but
8098 // only when splatting vectors.
8099 if (DestElemTy->isFloatingType()) {
8100 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8101 // in two steps: boolean to signed integral, then to floating.
8102 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8103 CK: CK_BooleanToSignedIntegral);
8104 SplattedExpr = CastExprRes.get();
8105 CK = CK_IntegralToFloating;
8106 } else {
8107 CK = CK_BooleanToSignedIntegral;
8108 }
8109 } else {
8110 ExprResult CastExprRes = SplattedExpr;
8111 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8112 if (CastExprRes.isInvalid())
8113 return ExprError();
8114 SplattedExpr = CastExprRes.get();
8115 }
8116 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8117}
8118
8119ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8120 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8121
8122 if (DestElemTy == SplattedExpr->getType())
8123 return SplattedExpr;
8124
8125 assert(DestElemTy->isFloatingType() ||
8126 DestElemTy->isIntegralOrEnumerationType());
8127
8128 ExprResult CastExprRes = SplattedExpr;
8129 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8130 if (CastExprRes.isInvalid())
8131 return ExprError();
8132 SplattedExpr = CastExprRes.get();
8133
8134 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8135}
8136
8137ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8138 Expr *CastExpr, CastKind &Kind) {
8139 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8140
8141 QualType SrcTy = CastExpr->getType();
8142
8143 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8144 // an ExtVectorType.
8145 // In OpenCL, casts between vectors of different types are not allowed.
8146 // (See OpenCL 6.2).
8147 if (SrcTy->isVectorType()) {
8148 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8149 (getLangOpts().OpenCL &&
8150 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8151 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8152 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8153 << DestTy << SrcTy << R;
8154 return ExprError();
8155 }
8156 Kind = CK_BitCast;
8157 return CastExpr;
8158 }
8159
8160 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8161 // conversion will take place first from scalar to elt type, and then
8162 // splat from elt type to vector.
8163 if (SrcTy->isPointerType())
8164 return Diag(Loc: R.getBegin(),
8165 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8166 << DestTy << SrcTy << R;
8167
8168 Kind = CK_VectorSplat;
8169 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8170}
8171
8172/// Check that a call to alloc_size function specifies sufficient space for the
8173/// destination type.
8174static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8175 const Expr *E) {
8176 QualType SourceType = E->getType();
8177 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8178 DestType == SourceType)
8179 return;
8180
8181 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8182 if (!CE)
8183 return;
8184
8185 // Find the total size allocated by the function call.
8186 if (!CE->getCalleeAllocSizeAttr())
8187 return;
8188 std::optional<llvm::APInt> AllocSize =
8189 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8190 // Allocations of size zero are permitted as a special case. They are usually
8191 // done intentionally.
8192 if (!AllocSize || AllocSize->isZero())
8193 return;
8194 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8195
8196 QualType TargetType = DestType->getPointeeType();
8197 // Find the destination size. As a special case function types have size of
8198 // one byte to match the sizeof operator behavior.
8199 auto LhsSize = TargetType->isFunctionType()
8200 ? CharUnits::One()
8201 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8202 if (LhsSize && Size < LhsSize)
8203 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8204 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8205}
8206
8207ExprResult
8208Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8209 Declarator &D, ParsedType &Ty,
8210 SourceLocation RParenLoc, Expr *CastExpr) {
8211 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8212 "ActOnCastExpr(): missing type or expr");
8213
8214 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8215 if (D.isInvalidType())
8216 return ExprError();
8217
8218 if (getLangOpts().CPlusPlus) {
8219 // Check that there are no default arguments (C++ only).
8220 CheckExtraCXXDefaultArguments(D);
8221 }
8222
8223 checkUnusedDeclAttributes(D);
8224
8225 QualType castType = castTInfo->getType();
8226 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8227
8228 bool isVectorLiteral = false;
8229
8230 // Check for an altivec or OpenCL literal,
8231 // i.e. all the elements are integer constants.
8232 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8233 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8234 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8235 && castType->isVectorType() && (PE || PLE)) {
8236 if (PLE && PLE->getNumExprs() == 0) {
8237 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8238 return ExprError();
8239 }
8240 if (PE || PLE->getNumExprs() == 1) {
8241 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8242 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8243 isVectorLiteral = true;
8244 }
8245 else
8246 isVectorLiteral = true;
8247 }
8248
8249 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8250 // then handle it as such.
8251 if (isVectorLiteral)
8252 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8253
8254 // If the Expr being casted is a ParenListExpr, handle it specially.
8255 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8256 // sequence of BinOp comma operators.
8257 if (isa<ParenListExpr>(Val: CastExpr)) {
8258 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8259 if (Result.isInvalid()) return ExprError();
8260 CastExpr = Result.get();
8261 }
8262
8263 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8264 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8265
8266 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8267
8268 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8269
8270 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8271
8272 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8273
8274 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8275}
8276
8277ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8278 SourceLocation RParenLoc, Expr *E,
8279 TypeSourceInfo *TInfo) {
8280 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8281 "Expected paren or paren list expression");
8282
8283 Expr **exprs;
8284 unsigned numExprs;
8285 Expr *subExpr;
8286 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8287 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8288 LiteralLParenLoc = PE->getLParenLoc();
8289 LiteralRParenLoc = PE->getRParenLoc();
8290 exprs = PE->getExprs();
8291 numExprs = PE->getNumExprs();
8292 } else { // isa<ParenExpr> by assertion at function entrance
8293 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8294 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8295 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8296 exprs = &subExpr;
8297 numExprs = 1;
8298 }
8299
8300 QualType Ty = TInfo->getType();
8301 assert(Ty->isVectorType() && "Expected vector type");
8302
8303 SmallVector<Expr *, 8> initExprs;
8304 const VectorType *VTy = Ty->castAs<VectorType>();
8305 unsigned numElems = VTy->getNumElements();
8306
8307 // '(...)' form of vector initialization in AltiVec: the number of
8308 // initializers must be one or must match the size of the vector.
8309 // If a single value is specified in the initializer then it will be
8310 // replicated to all the components of the vector
8311 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8312 SrcTy: VTy->getElementType()))
8313 return ExprError();
8314 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8315 // The number of initializers must be one or must match the size of the
8316 // vector. If a single value is specified in the initializer then it will
8317 // be replicated to all the components of the vector
8318 if (numExprs == 1) {
8319 QualType ElemTy = VTy->getElementType();
8320 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8321 if (Literal.isInvalid())
8322 return ExprError();
8323 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8324 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8325 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8326 }
8327 else if (numExprs < numElems) {
8328 Diag(Loc: E->getExprLoc(),
8329 DiagID: diag::err_incorrect_number_of_vector_initializers);
8330 return ExprError();
8331 }
8332 else
8333 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8334 }
8335 else {
8336 // For OpenCL, when the number of initializers is a single value,
8337 // it will be replicated to all components of the vector.
8338 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8339 numExprs == 1) {
8340 QualType SrcTy = exprs[0]->getType();
8341 if (!SrcTy->isArithmeticType()) {
8342 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8343 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8344 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8345 return ExprError();
8346 }
8347 QualType ElemTy = VTy->getElementType();
8348 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8349 if (Literal.isInvalid())
8350 return ExprError();
8351 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8352 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8353 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8354 }
8355
8356 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8357 }
8358 // FIXME: This means that pretty-printing the final AST will produce curly
8359 // braces instead of the original commas.
8360 InitListExpr *initE =
8361 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8362 LiteralRParenLoc, /*isExplicit=*/false);
8363 initE->setType(Ty);
8364 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8365}
8366
8367ExprResult
8368Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8369 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8370 if (!E)
8371 return OrigExpr;
8372
8373 ExprResult Result(E->getExpr(Init: 0));
8374
8375 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8376 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8377 RHSExpr: E->getExpr(Init: i));
8378
8379 if (Result.isInvalid()) return ExprError();
8380
8381 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8382}
8383
8384ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8385 SourceLocation R,
8386 MultiExprArg Val) {
8387 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8388}
8389
8390ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8391 unsigned NumUserSpecifiedExprs,
8392 SourceLocation InitLoc,
8393 SourceLocation LParenLoc,
8394 SourceLocation RParenLoc) {
8395 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8396 InitLoc, LParenLoc, RParenLoc);
8397}
8398
8399bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8400 SourceLocation QuestionLoc) {
8401 const Expr *NullExpr = LHSExpr;
8402 const Expr *NonPointerExpr = RHSExpr;
8403 Expr::NullPointerConstantKind NullKind =
8404 NullExpr->isNullPointerConstant(Ctx&: Context,
8405 NPC: Expr::NPC_ValueDependentIsNotNull);
8406
8407 if (NullKind == Expr::NPCK_NotNull) {
8408 NullExpr = RHSExpr;
8409 NonPointerExpr = LHSExpr;
8410 NullKind =
8411 NullExpr->isNullPointerConstant(Ctx&: Context,
8412 NPC: Expr::NPC_ValueDependentIsNotNull);
8413 }
8414
8415 if (NullKind == Expr::NPCK_NotNull)
8416 return false;
8417
8418 if (NullKind == Expr::NPCK_ZeroExpression)
8419 return false;
8420
8421 if (NullKind == Expr::NPCK_ZeroLiteral) {
8422 // In this case, check to make sure that we got here from a "NULL"
8423 // string in the source code.
8424 NullExpr = NullExpr->IgnoreParenImpCasts();
8425 SourceLocation loc = NullExpr->getExprLoc();
8426 if (!findMacroSpelling(loc, name: "NULL"))
8427 return false;
8428 }
8429
8430 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8431 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8432 << NonPointerExpr->getType() << DiagType
8433 << NonPointerExpr->getSourceRange();
8434 return true;
8435}
8436
8437/// Return false if the condition expression is valid, true otherwise.
8438static bool checkCondition(Sema &S, const Expr *Cond,
8439 SourceLocation QuestionLoc) {
8440 QualType CondTy = Cond->getType();
8441
8442 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8443 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8444 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8445 << CondTy << Cond->getSourceRange();
8446 return true;
8447 }
8448
8449 // C99 6.5.15p2
8450 if (CondTy->isScalarType()) return false;
8451
8452 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8453 << CondTy << Cond->getSourceRange();
8454 return true;
8455}
8456
8457/// Return false if the NullExpr can be promoted to PointerTy,
8458/// true otherwise.
8459static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8460 QualType PointerTy) {
8461 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8462 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8463 NPC: Expr::NPC_ValueDependentIsNull))
8464 return true;
8465
8466 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8467 return false;
8468}
8469
8470/// Checks compatibility between two pointers and return the resulting
8471/// type.
8472static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8473 ExprResult &RHS,
8474 SourceLocation Loc) {
8475 QualType LHSTy = LHS.get()->getType();
8476 QualType RHSTy = RHS.get()->getType();
8477
8478 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8479 // Two identical pointers types are always compatible.
8480 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8481 }
8482
8483 QualType lhptee, rhptee;
8484
8485 // Get the pointee types.
8486 bool IsBlockPointer = false;
8487 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8488 lhptee = LHSBTy->getPointeeType();
8489 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8490 IsBlockPointer = true;
8491 } else {
8492 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8493 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8494 }
8495
8496 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8497 // differently qualified versions of compatible types, the result type is
8498 // a pointer to an appropriately qualified version of the composite
8499 // type.
8500
8501 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8502 // clause doesn't make sense for our extensions. E.g. address space 2 should
8503 // be incompatible with address space 3: they may live on different devices or
8504 // anything.
8505 Qualifiers lhQual = lhptee.getQualifiers();
8506 Qualifiers rhQual = rhptee.getQualifiers();
8507
8508 LangAS ResultAddrSpace = LangAS::Default;
8509 LangAS LAddrSpace = lhQual.getAddressSpace();
8510 LangAS RAddrSpace = rhQual.getAddressSpace();
8511
8512 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8513 // spaces is disallowed.
8514 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8515 ResultAddrSpace = LAddrSpace;
8516 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8517 ResultAddrSpace = RAddrSpace;
8518 else {
8519 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8520 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8521 << RHS.get()->getSourceRange();
8522 return QualType();
8523 }
8524
8525 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8526 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8527 lhQual.removeCVRQualifiers();
8528 rhQual.removeCVRQualifiers();
8529
8530 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8531 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8532 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8533 << RHS.get()->getSourceRange();
8534 return QualType();
8535 }
8536
8537 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8538 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8539 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8540 // qual types are compatible iff
8541 // * corresponded types are compatible
8542 // * CVR qualifiers are equal
8543 // * address spaces are equal
8544 // Thus for conditional operator we merge CVR and address space unqualified
8545 // pointees and if there is a composite type we return a pointer to it with
8546 // merged qualifiers.
8547 LHSCastKind =
8548 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8549 RHSCastKind =
8550 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8551 lhQual.removeAddressSpace();
8552 rhQual.removeAddressSpace();
8553
8554 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8555 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8556
8557 QualType CompositeTy = S.Context.mergeTypes(
8558 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8559 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8560
8561 if (CompositeTy.isNull()) {
8562 // In this situation, we assume void* type. No especially good
8563 // reason, but this is what gcc does, and we do have to pick
8564 // to get a consistent AST.
8565 QualType incompatTy;
8566 incompatTy = S.Context.getPointerType(
8567 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8568 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8569 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8570
8571 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8572 // for casts between types with incompatible address space qualifiers.
8573 // For the following code the compiler produces casts between global and
8574 // local address spaces of the corresponded innermost pointees:
8575 // local int *global *a;
8576 // global int *global *b;
8577 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8578 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8579 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8580 << RHS.get()->getSourceRange();
8581
8582 return incompatTy;
8583 }
8584
8585 // The pointer types are compatible.
8586 // In case of OpenCL ResultTy should have the address space qualifier
8587 // which is a superset of address spaces of both the 2nd and the 3rd
8588 // operands of the conditional operator.
8589 QualType ResultTy = [&, ResultAddrSpace]() {
8590 if (S.getLangOpts().OpenCL) {
8591 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8592 CompositeQuals.setAddressSpace(ResultAddrSpace);
8593 return S.Context
8594 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8595 .withCVRQualifiers(CVR: MergedCVRQual);
8596 }
8597 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8598 }();
8599 if (IsBlockPointer)
8600 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8601 else
8602 ResultTy = S.Context.getPointerType(T: ResultTy);
8603
8604 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8605 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8606 return ResultTy;
8607}
8608
8609/// Return the resulting type when the operands are both block pointers.
8610static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8611 ExprResult &LHS,
8612 ExprResult &RHS,
8613 SourceLocation Loc) {
8614 QualType LHSTy = LHS.get()->getType();
8615 QualType RHSTy = RHS.get()->getType();
8616
8617 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8618 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8619 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8620 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8621 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8622 return destType;
8623 }
8624 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8625 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8626 << RHS.get()->getSourceRange();
8627 return QualType();
8628 }
8629
8630 // We have 2 block pointer types.
8631 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8632}
8633
8634/// Return the resulting type when the operands are both pointers.
8635static QualType
8636checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8637 ExprResult &RHS,
8638 SourceLocation Loc) {
8639 // get the pointer types
8640 QualType LHSTy = LHS.get()->getType();
8641 QualType RHSTy = RHS.get()->getType();
8642
8643 // get the "pointed to" types
8644 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8645 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8646
8647 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8648 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8649 // Figure out necessary qualifiers (C99 6.5.15p6)
8650 QualType destPointee
8651 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8652 QualType destType = S.Context.getPointerType(T: destPointee);
8653 // Add qualifiers if necessary.
8654 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8655 // Promote to void*.
8656 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8657 return destType;
8658 }
8659 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8660 QualType destPointee
8661 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8662 QualType destType = S.Context.getPointerType(T: destPointee);
8663 // Add qualifiers if necessary.
8664 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8665 // Promote to void*.
8666 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8667 return destType;
8668 }
8669
8670 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8671}
8672
8673/// Return false if the first expression is not an integer and the second
8674/// expression is not a pointer, true otherwise.
8675static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8676 Expr* PointerExpr, SourceLocation Loc,
8677 bool IsIntFirstExpr) {
8678 if (!PointerExpr->getType()->isPointerType() ||
8679 !Int.get()->getType()->isIntegerType())
8680 return false;
8681
8682 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8683 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8684
8685 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8686 << Expr1->getType() << Expr2->getType()
8687 << Expr1->getSourceRange() << Expr2->getSourceRange();
8688 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8689 CK: CK_IntegralToPointer);
8690 return true;
8691}
8692
8693/// Simple conversion between integer and floating point types.
8694///
8695/// Used when handling the OpenCL conditional operator where the
8696/// condition is a vector while the other operands are scalar.
8697///
8698/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8699/// types are either integer or floating type. Between the two
8700/// operands, the type with the higher rank is defined as the "result
8701/// type". The other operand needs to be promoted to the same type. No
8702/// other type promotion is allowed. We cannot use
8703/// UsualArithmeticConversions() for this purpose, since it always
8704/// promotes promotable types.
8705static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8706 ExprResult &RHS,
8707 SourceLocation QuestionLoc) {
8708 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8709 if (LHS.isInvalid())
8710 return QualType();
8711 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8712 if (RHS.isInvalid())
8713 return QualType();
8714
8715 // For conversion purposes, we ignore any qualifiers.
8716 // For example, "const float" and "float" are equivalent.
8717 QualType LHSType =
8718 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8719 QualType RHSType =
8720 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8721
8722 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8723 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8724 << LHSType << LHS.get()->getSourceRange();
8725 return QualType();
8726 }
8727
8728 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8729 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8730 << RHSType << RHS.get()->getSourceRange();
8731 return QualType();
8732 }
8733
8734 // If both types are identical, no conversion is needed.
8735 if (LHSType == RHSType)
8736 return LHSType;
8737
8738 // Now handle "real" floating types (i.e. float, double, long double).
8739 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8740 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8741 /*IsCompAssign = */ false);
8742
8743 // Finally, we have two differing integer types.
8744 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8745 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8746}
8747
8748/// Convert scalar operands to a vector that matches the
8749/// condition in length.
8750///
8751/// Used when handling the OpenCL conditional operator where the
8752/// condition is a vector while the other operands are scalar.
8753///
8754/// We first compute the "result type" for the scalar operands
8755/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8756/// into a vector of that type where the length matches the condition
8757/// vector type. s6.11.6 requires that the element types of the result
8758/// and the condition must have the same number of bits.
8759static QualType
8760OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8761 QualType CondTy, SourceLocation QuestionLoc) {
8762 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8763 if (ResTy.isNull()) return QualType();
8764
8765 const VectorType *CV = CondTy->getAs<VectorType>();
8766 assert(CV);
8767
8768 // Determine the vector result type
8769 unsigned NumElements = CV->getNumElements();
8770 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8771
8772 // Ensure that all types have the same number of bits
8773 if (S.Context.getTypeSize(T: CV->getElementType())
8774 != S.Context.getTypeSize(T: ResTy)) {
8775 // Since VectorTy is created internally, it does not pretty print
8776 // with an OpenCL name. Instead, we just print a description.
8777 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8778 SmallString<64> Str;
8779 llvm::raw_svector_ostream OS(Str);
8780 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8781 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8782 << CondTy << OS.str();
8783 return QualType();
8784 }
8785
8786 // Convert operands to the vector result type
8787 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8788 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8789
8790 return VectorTy;
8791}
8792
8793/// Return false if this is a valid OpenCL condition vector
8794static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8795 SourceLocation QuestionLoc) {
8796 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8797 // integral type.
8798 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8799 assert(CondTy);
8800 QualType EleTy = CondTy->getElementType();
8801 if (EleTy->isIntegerType()) return false;
8802
8803 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8804 << Cond->getType() << Cond->getSourceRange();
8805 return true;
8806}
8807
8808/// Return false if the vector condition type and the vector
8809/// result type are compatible.
8810///
8811/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8812/// number of elements, and their element types have the same number
8813/// of bits.
8814static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8815 SourceLocation QuestionLoc) {
8816 const VectorType *CV = CondTy->getAs<VectorType>();
8817 const VectorType *RV = VecResTy->getAs<VectorType>();
8818 assert(CV && RV);
8819
8820 if (CV->getNumElements() != RV->getNumElements()) {
8821 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8822 << CondTy << VecResTy;
8823 return true;
8824 }
8825
8826 QualType CVE = CV->getElementType();
8827 QualType RVE = RV->getElementType();
8828
8829 // Boolean vectors are permitted outside of OpenCL mode.
8830 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8831 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8832 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8833 << CondTy << VecResTy;
8834 return true;
8835 }
8836
8837 return false;
8838}
8839
8840/// Return the resulting type for the conditional operator in
8841/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8842/// s6.3.i) when the condition is a vector type.
8843static QualType
8844OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8845 ExprResult &LHS, ExprResult &RHS,
8846 SourceLocation QuestionLoc) {
8847 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8848 if (Cond.isInvalid())
8849 return QualType();
8850 QualType CondTy = Cond.get()->getType();
8851
8852 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8853 return QualType();
8854
8855 // If either operand is a vector then find the vector type of the
8856 // result as specified in OpenCL v1.1 s6.3.i.
8857 if (LHS.get()->getType()->isVectorType() ||
8858 RHS.get()->getType()->isVectorType()) {
8859 bool IsBoolVecLang =
8860 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8861 QualType VecResTy =
8862 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8863 /*isCompAssign*/ IsCompAssign: false,
8864 /*AllowBothBool*/ true,
8865 /*AllowBoolConversions*/ AllowBoolConversion: false,
8866 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8867 /*ReportInvalid*/ true);
8868 if (VecResTy.isNull())
8869 return QualType();
8870 // The result type must match the condition type as specified in
8871 // OpenCL v1.1 s6.11.6.
8872 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8873 return QualType();
8874 return VecResTy;
8875 }
8876
8877 // Both operands are scalar.
8878 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8879}
8880
8881/// Return true if the Expr is block type
8882static bool checkBlockType(Sema &S, const Expr *E) {
8883 if (E->getType()->isBlockPointerType()) {
8884 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8885 return true;
8886 }
8887
8888 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8889 QualType Ty = CE->getCallee()->getType();
8890 if (Ty->isBlockPointerType()) {
8891 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8892 return true;
8893 }
8894 }
8895 return false;
8896}
8897
8898/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8899/// In that case, LHS = cond.
8900/// C99 6.5.15
8901QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8902 ExprResult &RHS, ExprValueKind &VK,
8903 ExprObjectKind &OK,
8904 SourceLocation QuestionLoc) {
8905
8906 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8907 if (!LHSResult.isUsable()) return QualType();
8908 LHS = LHSResult;
8909
8910 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8911 if (!RHSResult.isUsable()) return QualType();
8912 RHS = RHSResult;
8913
8914 // C++ is sufficiently different to merit its own checker.
8915 if (getLangOpts().CPlusPlus)
8916 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8917
8918 VK = VK_PRValue;
8919 OK = OK_Ordinary;
8920
8921 if (Context.isDependenceAllowed() &&
8922 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8923 RHS.get()->isTypeDependent())) {
8924 assert(!getLangOpts().CPlusPlus);
8925 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8926 RHS.get()->containsErrors()) &&
8927 "should only occur in error-recovery path.");
8928 return Context.DependentTy;
8929 }
8930
8931 // The OpenCL operator with a vector condition is sufficiently
8932 // different to merit its own checker.
8933 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8934 Cond.get()->getType()->isExtVectorType())
8935 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8936
8937 // First, check the condition.
8938 Cond = UsualUnaryConversions(E: Cond.get());
8939 if (Cond.isInvalid())
8940 return QualType();
8941 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8942 return QualType();
8943
8944 // Handle vectors.
8945 if (LHS.get()->getType()->isVectorType() ||
8946 RHS.get()->getType()->isVectorType())
8947 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8948 /*AllowBothBool*/ true,
8949 /*AllowBoolConversions*/ AllowBoolConversion: false,
8950 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8951 /*ReportInvalid*/ true);
8952
8953 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8954 ACK: ArithConvKind::Conditional);
8955 if (LHS.isInvalid() || RHS.isInvalid())
8956 return QualType();
8957
8958 // WebAssembly tables are not allowed as conditional LHS or RHS.
8959 QualType LHSTy = LHS.get()->getType();
8960 QualType RHSTy = RHS.get()->getType();
8961 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8962 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8963 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8964 return QualType();
8965 }
8966
8967 // Diagnose attempts to convert between __ibm128, __float128 and long double
8968 // where such conversions currently can't be handled.
8969 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8970 Diag(Loc: QuestionLoc,
8971 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8973 return QualType();
8974 }
8975
8976 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8977 // selection operator (?:).
8978 if (getLangOpts().OpenCL &&
8979 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8980 return QualType();
8981 }
8982
8983 // If both operands have arithmetic type, do the usual arithmetic conversions
8984 // to find a common type: C99 6.5.15p3,5.
8985 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8986 // Disallow invalid arithmetic conversions, such as those between bit-
8987 // precise integers types of different sizes, or between a bit-precise
8988 // integer and another type.
8989 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8990 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8991 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8992 << RHS.get()->getSourceRange();
8993 return QualType();
8994 }
8995
8996 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8997 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
8998
8999 return ResTy;
9000 }
9001
9002 // If both operands are the same structure or union type, the result is that
9003 // type.
9004 // FIXME: Type of conditional expression must be complete in C mode.
9005 if (LHSTy->isRecordType() &&
9006 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
9007 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9008 Y: RHSTy.getUnqualifiedType());
9009
9010 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9011 // The following || allows only one side to be void (a GCC-ism).
9012 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9013 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9014 // UsualArithmeticConversions already handled the case where both sides
9015 // are the same type.
9016 } else if (RHSTy->isVoidType()) {
9017 ResTy = RHSTy;
9018 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9019 << RHS.get()->getSourceRange();
9020 } else {
9021 ResTy = LHSTy;
9022 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9023 << LHS.get()->getSourceRange();
9024 }
9025 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9026 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9027 return ResTy;
9028 }
9029
9030 // C23 6.5.15p7:
9031 // ... if both the second and third operands have nullptr_t type, the
9032 // result also has that type.
9033 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9034 return ResTy;
9035
9036 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9037 // the type of the other operand."
9038 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9039 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9040
9041 // All objective-c pointer type analysis is done here.
9042 QualType compositeType =
9043 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9044 if (LHS.isInvalid() || RHS.isInvalid())
9045 return QualType();
9046 if (!compositeType.isNull())
9047 return compositeType;
9048
9049
9050 // Handle block pointer types.
9051 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9052 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9053 Loc: QuestionLoc);
9054
9055 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9056 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9057 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9058 Loc: QuestionLoc);
9059
9060 // GCC compatibility: soften pointer/integer mismatch. Note that
9061 // null pointers have been filtered out by this point.
9062 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9063 /*IsIntFirstExpr=*/true))
9064 return RHSTy;
9065 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9066 /*IsIntFirstExpr=*/false))
9067 return LHSTy;
9068
9069 // Emit a better diagnostic if one of the expressions is a null pointer
9070 // constant and the other is not a pointer type. In this case, the user most
9071 // likely forgot to take the address of the other expression.
9072 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9073 return QualType();
9074
9075 // Finally, if the LHS and RHS types are canonically the same type, we can
9076 // use the common sugared type.
9077 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9078 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9079
9080 // Otherwise, the operands are not compatible.
9081 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9082 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9083 << RHS.get()->getSourceRange();
9084 return QualType();
9085}
9086
9087/// SuggestParentheses - Emit a note with a fixit hint that wraps
9088/// ParenRange in parentheses.
9089static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9090 const PartialDiagnostic &Note,
9091 SourceRange ParenRange) {
9092 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9093 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9094 EndLoc.isValid()) {
9095 Self.Diag(Loc, PD: Note)
9096 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9097 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9098 } else {
9099 // We can't display the parentheses, so just show the bare note.
9100 Self.Diag(Loc, PD: Note) << ParenRange;
9101 }
9102}
9103
9104static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9105 return BinaryOperator::isAdditiveOp(Opc) ||
9106 BinaryOperator::isMultiplicativeOp(Opc) ||
9107 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9108 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9109 // not any of the logical operators. Bitwise-xor is commonly used as a
9110 // logical-xor because there is no logical-xor operator. The logical
9111 // operators, including uses of xor, have a high false positive rate for
9112 // precedence warnings.
9113}
9114
9115/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9116/// expression, either using a built-in or overloaded operator,
9117/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9118/// expression.
9119static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9120 const Expr **RHSExprs) {
9121 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9122 E = E->IgnoreImpCasts();
9123 E = E->IgnoreConversionOperatorSingleStep();
9124 E = E->IgnoreImpCasts();
9125 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9126 E = MTE->getSubExpr();
9127 E = E->IgnoreImpCasts();
9128 }
9129
9130 // Built-in binary operator.
9131 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9132 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9133 *Opcode = OP->getOpcode();
9134 *RHSExprs = OP->getRHS();
9135 return true;
9136 }
9137
9138 // Overloaded operator.
9139 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9140 if (Call->getNumArgs() != 2)
9141 return false;
9142
9143 // Make sure this is really a binary operator that is safe to pass into
9144 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9145 OverloadedOperatorKind OO = Call->getOperator();
9146 if (OO < OO_Plus || OO > OO_Arrow ||
9147 OO == OO_PlusPlus || OO == OO_MinusMinus)
9148 return false;
9149
9150 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9151 if (IsArithmeticOp(Opc: OpKind)) {
9152 *Opcode = OpKind;
9153 *RHSExprs = Call->getArg(Arg: 1);
9154 return true;
9155 }
9156 }
9157
9158 return false;
9159}
9160
9161/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9162/// or is a logical expression such as (x==y) which has int type, but is
9163/// commonly interpreted as boolean.
9164static bool ExprLooksBoolean(const Expr *E) {
9165 E = E->IgnoreParenImpCasts();
9166
9167 if (E->getType()->isBooleanType())
9168 return true;
9169 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9170 return OP->isComparisonOp() || OP->isLogicalOp();
9171 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9172 return OP->getOpcode() == UO_LNot;
9173 if (E->getType()->isPointerType())
9174 return true;
9175 // FIXME: What about overloaded operator calls returning "unspecified boolean
9176 // type"s (commonly pointer-to-members)?
9177
9178 return false;
9179}
9180
9181/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9182/// and binary operator are mixed in a way that suggests the programmer assumed
9183/// the conditional operator has higher precedence, for example:
9184/// "int x = a + someBinaryCondition ? 1 : 2".
9185static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9186 Expr *Condition, const Expr *LHSExpr,
9187 const Expr *RHSExpr) {
9188 BinaryOperatorKind CondOpcode;
9189 const Expr *CondRHS;
9190
9191 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9192 return;
9193 if (!ExprLooksBoolean(E: CondRHS))
9194 return;
9195
9196 // The condition is an arithmetic binary expression, with a right-
9197 // hand side that looks boolean, so warn.
9198
9199 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9200 ? diag::warn_precedence_bitwise_conditional
9201 : diag::warn_precedence_conditional;
9202
9203 Self.Diag(Loc: OpLoc, DiagID)
9204 << Condition->getSourceRange()
9205 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9206
9207 SuggestParentheses(
9208 Self, Loc: OpLoc,
9209 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9210 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9211 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9212
9213 SuggestParentheses(Self, Loc: OpLoc,
9214 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9215 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9216}
9217
9218/// Compute the nullability of a conditional expression.
9219static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9220 QualType LHSTy, QualType RHSTy,
9221 ASTContext &Ctx) {
9222 if (!ResTy->isAnyPointerType())
9223 return ResTy;
9224
9225 auto GetNullability = [](QualType Ty) {
9226 NullabilityKindOrNone Kind = Ty->getNullability();
9227 if (Kind) {
9228 // For our purposes, treat _Nullable_result as _Nullable.
9229 if (*Kind == NullabilityKind::NullableResult)
9230 return NullabilityKind::Nullable;
9231 return *Kind;
9232 }
9233 return NullabilityKind::Unspecified;
9234 };
9235
9236 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9237 NullabilityKind MergedKind;
9238
9239 // Compute nullability of a binary conditional expression.
9240 if (IsBin) {
9241 if (LHSKind == NullabilityKind::NonNull)
9242 MergedKind = NullabilityKind::NonNull;
9243 else
9244 MergedKind = RHSKind;
9245 // Compute nullability of a normal conditional expression.
9246 } else {
9247 if (LHSKind == NullabilityKind::Nullable ||
9248 RHSKind == NullabilityKind::Nullable)
9249 MergedKind = NullabilityKind::Nullable;
9250 else if (LHSKind == NullabilityKind::NonNull)
9251 MergedKind = RHSKind;
9252 else if (RHSKind == NullabilityKind::NonNull)
9253 MergedKind = LHSKind;
9254 else
9255 MergedKind = NullabilityKind::Unspecified;
9256 }
9257
9258 // Return if ResTy already has the correct nullability.
9259 if (GetNullability(ResTy) == MergedKind)
9260 return ResTy;
9261
9262 // Strip all nullability from ResTy.
9263 while (ResTy->getNullability())
9264 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9265
9266 // Create a new AttributedType with the new nullability kind.
9267 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9268}
9269
9270ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9271 SourceLocation ColonLoc,
9272 Expr *CondExpr, Expr *LHSExpr,
9273 Expr *RHSExpr) {
9274 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9275 // was the condition.
9276 OpaqueValueExpr *opaqueValue = nullptr;
9277 Expr *commonExpr = nullptr;
9278 if (!LHSExpr) {
9279 commonExpr = CondExpr;
9280 // Lower out placeholder types first. This is important so that we don't
9281 // try to capture a placeholder. This happens in few cases in C++; such
9282 // as Objective-C++'s dictionary subscripting syntax.
9283 if (commonExpr->hasPlaceholderType()) {
9284 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9285 if (!result.isUsable()) return ExprError();
9286 commonExpr = result.get();
9287 }
9288 // We usually want to apply unary conversions *before* saving, except
9289 // in the special case of a C++ l-value conditional.
9290 if (!(getLangOpts().CPlusPlus
9291 && !commonExpr->isTypeDependent()
9292 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9293 && commonExpr->isGLValue()
9294 && commonExpr->isOrdinaryOrBitFieldObject()
9295 && RHSExpr->isOrdinaryOrBitFieldObject()
9296 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9297 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9298 if (commonRes.isInvalid())
9299 return ExprError();
9300 commonExpr = commonRes.get();
9301 }
9302
9303 // If the common expression is a class or array prvalue, materialize it
9304 // so that we can safely refer to it multiple times.
9305 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9306 commonExpr->getType()->isArrayType())) {
9307 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9308 if (MatExpr.isInvalid())
9309 return ExprError();
9310 commonExpr = MatExpr.get();
9311 }
9312
9313 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9314 commonExpr->getType(),
9315 commonExpr->getValueKind(),
9316 commonExpr->getObjectKind(),
9317 commonExpr);
9318 LHSExpr = CondExpr = opaqueValue;
9319 }
9320
9321 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9322 ExprValueKind VK = VK_PRValue;
9323 ExprObjectKind OK = OK_Ordinary;
9324 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9325 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9326 VK, OK, QuestionLoc);
9327 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9328 RHS.isInvalid())
9329 return ExprError();
9330
9331 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9332 RHSExpr: RHS.get());
9333
9334 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9335
9336 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9337 Ctx&: Context);
9338
9339 if (!commonExpr)
9340 return new (Context)
9341 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9342 RHS.get(), result, VK, OK);
9343
9344 return new (Context) BinaryConditionalOperator(
9345 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9346 ColonLoc, result, VK, OK);
9347}
9348
9349bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9350 unsigned FromAttributes = 0, ToAttributes = 0;
9351 if (const auto *FromFn =
9352 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9353 FromAttributes =
9354 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9355 if (const auto *ToFn =
9356 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9357 ToAttributes =
9358 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9359
9360 return FromAttributes != ToAttributes;
9361}
9362
9363// checkPointerTypesForAssignment - This is a very tricky routine (despite
9364// being closely modeled after the C99 spec:-). The odd characteristic of this
9365// routine is it effectively iqnores the qualifiers on the top level pointee.
9366// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9367// FIXME: add a couple examples in this comment.
9368static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9369 QualType LHSType,
9370 QualType RHSType,
9371 SourceLocation Loc) {
9372 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9373 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9374
9375 // get the "pointed to" type (ignoring qualifiers at the top level)
9376 const Type *lhptee, *rhptee;
9377 Qualifiers lhq, rhq;
9378 std::tie(args&: lhptee, args&: lhq) =
9379 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9380 std::tie(args&: rhptee, args&: rhq) =
9381 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9382
9383 AssignConvertType ConvTy = AssignConvertType::Compatible;
9384
9385 // C99 6.5.16.1p1: This following citation is common to constraints
9386 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9387 // qualifiers of the type *pointed to* by the right;
9388
9389 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9390 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9391 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9392 // Ignore lifetime for further calculation.
9393 lhq.removeObjCLifetime();
9394 rhq.removeObjCLifetime();
9395 }
9396
9397 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9398 // Treat address-space mismatches as fatal.
9399 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9400 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9401
9402 // It's okay to add or remove GC or lifetime qualifiers when converting to
9403 // and from void*.
9404 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9405 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9406 Ctx: S.getASTContext()) &&
9407 (lhptee->isVoidType() || rhptee->isVoidType()))
9408 ; // keep old
9409
9410 // Treat lifetime mismatches as fatal.
9411 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9412 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9413
9414 // Treat pointer-auth mismatches as fatal.
9415 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9416 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9417
9418 // For GCC/MS compatibility, other qualifier mismatches are treated
9419 // as still compatible in C.
9420 else
9421 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9422 }
9423
9424 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9425 // incomplete type and the other is a pointer to a qualified or unqualified
9426 // version of void...
9427 if (lhptee->isVoidType()) {
9428 if (rhptee->isIncompleteOrObjectType())
9429 return ConvTy;
9430
9431 // As an extension, we allow cast to/from void* to function pointer.
9432 assert(rhptee->isFunctionType());
9433 return AssignConvertType::FunctionVoidPointer;
9434 }
9435
9436 if (rhptee->isVoidType()) {
9437 // In C, void * to another pointer type is compatible, but we want to note
9438 // that there will be an implicit conversion happening here.
9439 if (lhptee->isIncompleteOrObjectType())
9440 return ConvTy == AssignConvertType::Compatible &&
9441 !S.getLangOpts().CPlusPlus
9442 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9443 : ConvTy;
9444
9445 // As an extension, we allow cast to/from void* to function pointer.
9446 assert(lhptee->isFunctionType());
9447 return AssignConvertType::FunctionVoidPointer;
9448 }
9449
9450 if (!S.Diags.isIgnored(
9451 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9452 Loc) &&
9453 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9454 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9455 return AssignConvertType::IncompatibleFunctionPointerStrict;
9456
9457 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9458 // unqualified versions of compatible types, ...
9459 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9460
9461 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9462 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9463 QualType LUnderlying =
9464 ltrans->isOverflowBehaviorType()
9465 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9466 : ltrans;
9467 QualType RUnderlying =
9468 rtrans->isOverflowBehaviorType()
9469 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9470 : rtrans;
9471
9472 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9473 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9474
9475 ltrans = LUnderlying;
9476 rtrans = RUnderlying;
9477 }
9478 }
9479
9480 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9481 // Check if the pointee types are compatible ignoring the sign.
9482 // We explicitly check for char so that we catch "char" vs
9483 // "unsigned char" on systems where "char" is unsigned.
9484 if (lhptee->isCharType())
9485 ltrans = S.Context.UnsignedCharTy;
9486 else if (lhptee->hasSignedIntegerRepresentation())
9487 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9488
9489 if (rhptee->isCharType())
9490 rtrans = S.Context.UnsignedCharTy;
9491 else if (rhptee->hasSignedIntegerRepresentation())
9492 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9493
9494 if (ltrans == rtrans) {
9495 // Types are compatible ignoring the sign. Qualifier incompatibility
9496 // takes priority over sign incompatibility because the sign
9497 // warning can be disabled.
9498 if (!S.IsAssignConvertCompatible(ConvTy))
9499 return ConvTy;
9500
9501 return AssignConvertType::IncompatiblePointerSign;
9502 }
9503
9504 // If we are a multi-level pointer, it's possible that our issue is simply
9505 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9506 // the eventual target type is the same and the pointers have the same
9507 // level of indirection, this must be the issue.
9508 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9509 do {
9510 std::tie(args&: lhptee, args&: lhq) =
9511 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9512 std::tie(args&: rhptee, args&: rhq) =
9513 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9514
9515 // Inconsistent address spaces at this point is invalid, even if the
9516 // address spaces would be compatible.
9517 // FIXME: This doesn't catch address space mismatches for pointers of
9518 // different nesting levels, like:
9519 // __local int *** a;
9520 // int ** b = a;
9521 // It's not clear how to actually determine when such pointers are
9522 // invalidly incompatible.
9523 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9524 return AssignConvertType::
9525 IncompatibleNestedPointerAddressSpaceMismatch;
9526
9527 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9528
9529 if (lhptee == rhptee)
9530 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9531 }
9532
9533 // General pointer incompatibility takes priority over qualifiers.
9534 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9535 return AssignConvertType::IncompatibleFunctionPointer;
9536 return AssignConvertType::IncompatiblePointer;
9537 }
9538 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9539 // hasSameType, so we can skip further checks.
9540 const auto *LFT = ltrans->getAs<FunctionType>();
9541 const auto *RFT = rtrans->getAs<FunctionType>();
9542 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9543 // The invocation of IsFunctionConversion below will try to transform rtrans
9544 // to obtain an exact match for ltrans. This should not fail because of
9545 // mismatches in result type and parameter types, they were already checked
9546 // by typesAreCompatible above. So we will recreate rtrans (or where
9547 // appropriate ltrans) using the result type and parameter types from ltrans
9548 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9549 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9550 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9551 if (LFPT && RFPT) {
9552 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9553 Args: LFPT->getParamTypes(),
9554 EPI: RFPT->getExtProtoInfo());
9555 } else if (LFPT) {
9556 FunctionProtoType::ExtProtoInfo EPI;
9557 EPI.ExtInfo = RFT->getExtInfo();
9558 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9559 Args: LFPT->getParamTypes(), EPI);
9560 } else if (RFPT) {
9561 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9562 // all of its ExtProtoInfo. Transform ltrans instead.
9563 FunctionProtoType::ExtProtoInfo EPI;
9564 EPI.ExtInfo = LFT->getExtInfo();
9565 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9566 Args: RFPT->getParamTypes(), EPI);
9567 } else {
9568 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9569 Info: RFT->getExtInfo());
9570 }
9571 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9572 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9573 return AssignConvertType::IncompatibleFunctionPointer;
9574 }
9575 return ConvTy;
9576}
9577
9578/// checkBlockPointerTypesForAssignment - This routine determines whether two
9579/// block pointer types are compatible or whether a block and normal pointer
9580/// are compatible. It is more restrict than comparing two function pointer
9581// types.
9582static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9583 QualType LHSType,
9584 QualType RHSType) {
9585 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9586 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9587
9588 QualType lhptee, rhptee;
9589
9590 // get the "pointed to" type (ignoring qualifiers at the top level)
9591 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9592 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9593
9594 // In C++, the types have to match exactly.
9595 if (S.getLangOpts().CPlusPlus)
9596 return AssignConvertType::IncompatibleBlockPointer;
9597
9598 AssignConvertType ConvTy = AssignConvertType::Compatible;
9599
9600 // For blocks we enforce that qualifiers are identical.
9601 Qualifiers LQuals = lhptee.getLocalQualifiers();
9602 Qualifiers RQuals = rhptee.getLocalQualifiers();
9603 if (S.getLangOpts().OpenCL) {
9604 LQuals.removeAddressSpace();
9605 RQuals.removeAddressSpace();
9606 }
9607 if (LQuals != RQuals)
9608 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9609
9610 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9611 // assignment.
9612 // The current behavior is similar to C++ lambdas. A block might be
9613 // assigned to a variable iff its return type and parameters are compatible
9614 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9615 // an assignment. Presumably it should behave in way that a function pointer
9616 // assignment does in C, so for each parameter and return type:
9617 // * CVR and address space of LHS should be a superset of CVR and address
9618 // space of RHS.
9619 // * unqualified types should be compatible.
9620 if (S.getLangOpts().OpenCL) {
9621 if (!S.Context.typesAreBlockPointerCompatible(
9622 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9623 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9624 return AssignConvertType::IncompatibleBlockPointer;
9625 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9626 return AssignConvertType::IncompatibleBlockPointer;
9627
9628 return ConvTy;
9629}
9630
9631/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9632/// for assignment compatibility.
9633static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9634 QualType LHSType,
9635 QualType RHSType) {
9636 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9637 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9638
9639 if (LHSType->isObjCBuiltinType()) {
9640 // Class is not compatible with ObjC object pointers.
9641 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9642 !RHSType->isObjCQualifiedClassType())
9643 return AssignConvertType::IncompatiblePointer;
9644 return AssignConvertType::Compatible;
9645 }
9646 if (RHSType->isObjCBuiltinType()) {
9647 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9648 !LHSType->isObjCQualifiedClassType())
9649 return AssignConvertType::IncompatiblePointer;
9650 return AssignConvertType::Compatible;
9651 }
9652 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9653 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9654
9655 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9656 // make an exception for id<P>
9657 !LHSType->isObjCQualifiedIdType())
9658 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9659
9660 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9661 return AssignConvertType::Compatible;
9662 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9663 return AssignConvertType::IncompatibleObjCQualifiedId;
9664 return AssignConvertType::IncompatiblePointer;
9665}
9666
9667AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9668 QualType LHSType,
9669 QualType RHSType) {
9670 // Fake up an opaque expression. We don't actually care about what
9671 // cast operations are required, so if CheckAssignmentConstraints
9672 // adds casts to this they'll be wasted, but fortunately that doesn't
9673 // usually happen on valid code.
9674 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9675 ExprResult RHSPtr = &RHSExpr;
9676 CastKind K;
9677
9678 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9679}
9680
9681/// This helper function returns true if QT is a vector type that has element
9682/// type ElementType.
9683static bool isVector(QualType QT, QualType ElementType) {
9684 if (const VectorType *VT = QT->getAs<VectorType>())
9685 return VT->getElementType().getCanonicalType() == ElementType;
9686 return false;
9687}
9688
9689/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9690/// has code to accommodate several GCC extensions when type checking
9691/// pointers. Here are some objectionable examples that GCC considers warnings:
9692///
9693/// int a, *pint;
9694/// short *pshort;
9695/// struct foo *pfoo;
9696///
9697/// pint = pshort; // warning: assignment from incompatible pointer type
9698/// a = pint; // warning: assignment makes integer from pointer without a cast
9699/// pint = a; // warning: assignment makes pointer from integer without a cast
9700/// pint = pfoo; // warning: assignment from incompatible pointer type
9701///
9702/// As a result, the code for dealing with pointers is more complex than the
9703/// C99 spec dictates.
9704///
9705/// Sets 'Kind' for any result kind except Incompatible.
9706AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9707 ExprResult &RHS,
9708 CastKind &Kind,
9709 bool ConvertRHS) {
9710 QualType RHSType = RHS.get()->getType();
9711 QualType OrigLHSType = LHSType;
9712
9713 // Get canonical types. We're not formatting these types, just comparing
9714 // them.
9715 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9716 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9717
9718 // Common case: no conversion required.
9719 if (LHSType == RHSType) {
9720 Kind = CK_NoOp;
9721 return AssignConvertType::Compatible;
9722 }
9723
9724 // If the LHS has an __auto_type, there are no additional type constraints
9725 // to be worried about.
9726 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9727 if (AT->isGNUAutoType()) {
9728 Kind = CK_NoOp;
9729 return AssignConvertType::Compatible;
9730 }
9731 }
9732
9733 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9734 switch (OBTResult) {
9735 case ASTContext::OBTAssignResult::IncompatibleKinds:
9736 Kind = CK_NoOp;
9737 return AssignConvertType::IncompatibleOBTKinds;
9738 case ASTContext::OBTAssignResult::Discards:
9739 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9740 return AssignConvertType::CompatibleOBTDiscards;
9741 case ASTContext::OBTAssignResult::Compatible:
9742 case ASTContext::OBTAssignResult::NotApplicable:
9743 break;
9744 }
9745
9746 // Check for incompatible OBT types in pointer pointee types
9747 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9748 QualType LHSPointee = LHSType->getPointeeType();
9749 QualType RHSPointee = RHSType->getPointeeType();
9750 if ((LHSPointee->isOverflowBehaviorType() ||
9751 RHSPointee->isOverflowBehaviorType()) &&
9752 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9753 Kind = CK_NoOp;
9754 return AssignConvertType::IncompatibleOBTKinds;
9755 }
9756 }
9757
9758 // If we have an atomic type, try a non-atomic assignment, then just add an
9759 // atomic qualification step.
9760 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9761 AssignConvertType Result =
9762 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9763 if (!IsAssignConvertCompatible(ConvTy: Result))
9764 return Result;
9765 if (Kind != CK_NoOp && ConvertRHS)
9766 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9767 Kind = CK_NonAtomicToAtomic;
9768 return Result;
9769 }
9770
9771 // If the left-hand side is a reference type, then we are in a
9772 // (rare!) case where we've allowed the use of references in C,
9773 // e.g., as a parameter type in a built-in function. In this case,
9774 // just make sure that the type referenced is compatible with the
9775 // right-hand side type. The caller is responsible for adjusting
9776 // LHSType so that the resulting expression does not have reference
9777 // type.
9778 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9779 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9780 Kind = CK_LValueBitCast;
9781 return AssignConvertType::Compatible;
9782 }
9783 return AssignConvertType::Incompatible;
9784 }
9785
9786 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9787 // of an ExtVector type to the same ExtVector type.
9788 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9789 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9790 // Implicit conversions require the same number of elements.
9791 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9792 return AssignConvertType::Incompatible;
9793
9794 if (LHSType->isExtVectorBoolType() &&
9795 RHSExtType->getElementType()->isIntegerType()) {
9796 Kind = CK_IntegralToBoolean;
9797 return AssignConvertType::Compatible;
9798 }
9799 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9800 if (Context.getLangOpts().OpenCL &&
9801 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9802 Kind = CK_BitCast;
9803 return AssignConvertType::Compatible;
9804 }
9805 return AssignConvertType::Incompatible;
9806 }
9807 if (RHSType->isArithmeticType()) {
9808 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9809 if (ConvertRHS)
9810 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9811 Kind = CK_VectorSplat;
9812 return AssignConvertType::Compatible;
9813 }
9814 }
9815
9816 // Conversions to or from vector type.
9817 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9818 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9819 // Allow assignments of an AltiVec vector type to an equivalent GCC
9820 // vector type and vice versa
9821 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9822 Kind = CK_BitCast;
9823 return AssignConvertType::Compatible;
9824 }
9825
9826 // If we are allowing lax vector conversions, and LHS and RHS are both
9827 // vectors, the total size only needs to be the same. This is a bitcast;
9828 // no bits are changed but the result type is different.
9829 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9830 // The default for lax vector conversions with Altivec vectors will
9831 // change, so if we are converting between vector types where
9832 // at least one is an Altivec vector, emit a warning.
9833 if (Context.getTargetInfo().getTriple().isPPC() &&
9834 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9835 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9836 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9837 << RHSType << LHSType;
9838 Kind = CK_BitCast;
9839 return AssignConvertType::IncompatibleVectors;
9840 }
9841 }
9842
9843 // When the RHS comes from another lax conversion (e.g. binops between
9844 // scalars and vectors) the result is canonicalized as a vector. When the
9845 // LHS is also a vector, the lax is allowed by the condition above. Handle
9846 // the case where LHS is a scalar.
9847 if (LHSType->isScalarType()) {
9848 const VectorType *VecType = RHSType->getAs<VectorType>();
9849 if (VecType && VecType->getNumElements() == 1 &&
9850 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9851 if (Context.getTargetInfo().getTriple().isPPC() &&
9852 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9853 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9854 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9855 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9856 << RHSType << LHSType;
9857 ExprResult *VecExpr = &RHS;
9858 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9859 Kind = CK_BitCast;
9860 return AssignConvertType::Compatible;
9861 }
9862 }
9863
9864 // Allow assignments between fixed-length and sizeless SVE vectors.
9865 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9866 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9867 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9868 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9869 Kind = CK_BitCast;
9870 return AssignConvertType::Compatible;
9871 }
9872
9873 // Allow assignments between fixed-length and sizeless RVV vectors.
9874 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9875 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9876 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9877 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9878 Kind = CK_BitCast;
9879 return AssignConvertType::Compatible;
9880 }
9881 }
9882
9883 return AssignConvertType::Incompatible;
9884 }
9885
9886 // Diagnose attempts to convert between __ibm128, __float128 and long double
9887 // where such conversions currently can't be handled.
9888 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9889 return AssignConvertType::Incompatible;
9890
9891 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9892 // discards the imaginary part.
9893 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9894 !LHSType->getAs<ComplexType>())
9895 return AssignConvertType::Incompatible;
9896
9897 // Arithmetic conversions.
9898 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9899 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9900 if (ConvertRHS)
9901 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9902 return AssignConvertType::Compatible;
9903 }
9904
9905 // Conversions to normal pointers.
9906 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9907 // U* -> T*
9908 if (isa<PointerType>(Val: RHSType)) {
9909 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9910 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9911 if (AddrSpaceL != AddrSpaceR)
9912 Kind = CK_AddressSpaceConversion;
9913 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9914 Kind = CK_NoOp;
9915 else
9916 Kind = CK_BitCast;
9917 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9918 Loc: RHS.get()->getBeginLoc());
9919 }
9920
9921 // int -> T*
9922 if (RHSType->isIntegerType()) {
9923 Kind = CK_IntegralToPointer; // FIXME: null?
9924 return AssignConvertType::IntToPointer;
9925 }
9926
9927 // C pointers are not compatible with ObjC object pointers,
9928 // with two exceptions:
9929 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9930 // - conversions to void*
9931 if (LHSPointer->getPointeeType()->isVoidType()) {
9932 Kind = CK_BitCast;
9933 return AssignConvertType::Compatible;
9934 }
9935
9936 // - conversions from 'Class' to the redefinition type
9937 if (RHSType->isObjCClassType() &&
9938 Context.hasSameType(T1: LHSType,
9939 T2: Context.getObjCClassRedefinitionType())) {
9940 Kind = CK_BitCast;
9941 return AssignConvertType::Compatible;
9942 }
9943
9944 Kind = CK_BitCast;
9945 return AssignConvertType::IncompatiblePointer;
9946 }
9947
9948 // U^ -> void*
9949 if (RHSType->getAs<BlockPointerType>()) {
9950 if (LHSPointer->getPointeeType()->isVoidType()) {
9951 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9952 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9953 ->getPointeeType()
9954 .getAddressSpace();
9955 Kind =
9956 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9957 return AssignConvertType::Compatible;
9958 }
9959 }
9960
9961 return AssignConvertType::Incompatible;
9962 }
9963
9964 // Conversions to block pointers.
9965 if (isa<BlockPointerType>(Val: LHSType)) {
9966 // U^ -> T^
9967 if (RHSType->isBlockPointerType()) {
9968 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9969 ->getPointeeType()
9970 .getAddressSpace();
9971 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9972 ->getPointeeType()
9973 .getAddressSpace();
9974 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9975 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9976 }
9977
9978 // int or null -> T^
9979 if (RHSType->isIntegerType()) {
9980 Kind = CK_IntegralToPointer; // FIXME: null
9981 return AssignConvertType::IntToBlockPointer;
9982 }
9983
9984 // id -> T^
9985 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9986 Kind = CK_AnyPointerToBlockPointerCast;
9987 return AssignConvertType::Compatible;
9988 }
9989
9990 // void* -> T^
9991 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9992 if (RHSPT->getPointeeType()->isVoidType()) {
9993 Kind = CK_AnyPointerToBlockPointerCast;
9994 return AssignConvertType::Compatible;
9995 }
9996
9997 return AssignConvertType::Incompatible;
9998 }
9999
10000 // Conversions to Objective-C pointers.
10001 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10002 // A* -> B*
10003 if (RHSType->isObjCObjectPointerType()) {
10004 Kind = CK_BitCast;
10005 AssignConvertType result =
10006 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10007 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10008 result == AssignConvertType::Compatible &&
10009 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10010 result = AssignConvertType::IncompatibleObjCWeakRef;
10011 return result;
10012 }
10013
10014 // int or null -> A*
10015 if (RHSType->isIntegerType()) {
10016 Kind = CK_IntegralToPointer; // FIXME: null
10017 return AssignConvertType::IntToPointer;
10018 }
10019
10020 // In general, C pointers are not compatible with ObjC object pointers,
10021 // with two exceptions:
10022 if (isa<PointerType>(Val: RHSType)) {
10023 Kind = CK_CPointerToObjCPointerCast;
10024
10025 // - conversions from 'void*'
10026 if (RHSType->isVoidPointerType()) {
10027 return AssignConvertType::Compatible;
10028 }
10029
10030 // - conversions to 'Class' from its redefinition type
10031 if (LHSType->isObjCClassType() &&
10032 Context.hasSameType(T1: RHSType,
10033 T2: Context.getObjCClassRedefinitionType())) {
10034 return AssignConvertType::Compatible;
10035 }
10036
10037 return AssignConvertType::IncompatiblePointer;
10038 }
10039
10040 // Only under strict condition T^ is compatible with an Objective-C pointer.
10041 if (RHSType->isBlockPointerType() &&
10042 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10043 if (ConvertRHS)
10044 maybeExtendBlockObject(E&: RHS);
10045 Kind = CK_BlockPointerToObjCPointerCast;
10046 return AssignConvertType::Compatible;
10047 }
10048
10049 return AssignConvertType::Incompatible;
10050 }
10051
10052 // Conversion to nullptr_t (C23 only)
10053 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10054 RHS.get()->isNullPointerConstant(Ctx&: Context,
10055 NPC: Expr::NPC_ValueDependentIsNull)) {
10056 // null -> nullptr_t
10057 Kind = CK_NullToPointer;
10058 return AssignConvertType::Compatible;
10059 }
10060
10061 // Conversions from pointers that are not covered by the above.
10062 if (isa<PointerType>(Val: RHSType)) {
10063 // T* -> _Bool
10064 if (LHSType == Context.BoolTy) {
10065 Kind = CK_PointerToBoolean;
10066 return AssignConvertType::Compatible;
10067 }
10068
10069 // T* -> int
10070 if (LHSType->isIntegerType()) {
10071 Kind = CK_PointerToIntegral;
10072 return AssignConvertType::PointerToInt;
10073 }
10074
10075 return AssignConvertType::Incompatible;
10076 }
10077
10078 // Conversions from Objective-C pointers that are not covered by the above.
10079 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10080 // T* -> _Bool
10081 if (LHSType == Context.BoolTy) {
10082 Kind = CK_PointerToBoolean;
10083 return AssignConvertType::Compatible;
10084 }
10085
10086 // T* -> int
10087 if (LHSType->isIntegerType()) {
10088 Kind = CK_PointerToIntegral;
10089 return AssignConvertType::PointerToInt;
10090 }
10091
10092 return AssignConvertType::Incompatible;
10093 }
10094
10095 // struct A -> struct B
10096 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10097 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10098 Kind = CK_NoOp;
10099 return AssignConvertType::Compatible;
10100 }
10101 }
10102
10103 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10104 Kind = CK_IntToOCLSampler;
10105 return AssignConvertType::Compatible;
10106 }
10107
10108 return AssignConvertType::Incompatible;
10109}
10110
10111/// Constructs a transparent union from an expression that is
10112/// used to initialize the transparent union.
10113static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10114 ExprResult &EResult, QualType UnionType,
10115 FieldDecl *Field) {
10116 // Build an initializer list that designates the appropriate member
10117 // of the transparent union.
10118 Expr *E = EResult.get();
10119 InitListExpr *Initializer = new (C) InitListExpr(
10120 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10121 Initializer->setType(UnionType);
10122 Initializer->setInitializedFieldInUnion(Field);
10123
10124 // Build a compound literal constructing a value of the transparent
10125 // union type from this initializer list.
10126 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10127 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10128 VK_PRValue, Initializer, false);
10129}
10130
10131AssignConvertType
10132Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10133 ExprResult &RHS) {
10134 QualType RHSType = RHS.get()->getType();
10135
10136 // If the ArgType is a Union type, we want to handle a potential
10137 // transparent_union GCC extension.
10138 const RecordType *UT = ArgType->getAsUnionType();
10139 if (!UT)
10140 return AssignConvertType::Incompatible;
10141
10142 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10143 if (!UD->hasAttr<TransparentUnionAttr>())
10144 return AssignConvertType::Incompatible;
10145
10146 // The field to initialize within the transparent union.
10147 FieldDecl *InitField = nullptr;
10148 // It's compatible if the expression matches any of the fields.
10149 for (auto *it : UD->fields()) {
10150 if (it->getType()->isPointerType()) {
10151 // If the transparent union contains a pointer type, we allow:
10152 // 1) void pointer
10153 // 2) null pointer constant
10154 if (RHSType->isPointerType())
10155 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10156 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10157 InitField = it;
10158 break;
10159 }
10160
10161 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10162 NPC: Expr::NPC_ValueDependentIsNull)) {
10163 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10164 CK: CK_NullToPointer);
10165 InitField = it;
10166 break;
10167 }
10168 }
10169
10170 CastKind Kind;
10171 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10172 AssignConvertType::Compatible) {
10173 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10174 InitField = it;
10175 break;
10176 }
10177 }
10178
10179 if (!InitField)
10180 return AssignConvertType::Incompatible;
10181
10182 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10183 return AssignConvertType::Compatible;
10184}
10185
10186AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10187 ExprResult &CallerRHS,
10188 bool Diagnose,
10189 bool DiagnoseCFAudited,
10190 bool ConvertRHS) {
10191 // We need to be able to tell the caller whether we diagnosed a problem, if
10192 // they ask us to issue diagnostics.
10193 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10194
10195 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10196 // we can't avoid *all* modifications at the moment, so we need some somewhere
10197 // to put the updated value.
10198 ExprResult LocalRHS = CallerRHS;
10199 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10200
10201 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10202 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10203 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10204 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10205 Diag(Loc: RHS.get()->getExprLoc(),
10206 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10207 << RHS.get()->getSourceRange();
10208 }
10209 }
10210 }
10211
10212 if (getLangOpts().CPlusPlus) {
10213 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10214 // C++ 5.17p3: If the left operand is not of class type, the
10215 // expression is implicitly converted (C++ 4) to the
10216 // cv-unqualified type of the left operand.
10217 QualType RHSType = RHS.get()->getType();
10218 if (Diagnose) {
10219 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10220 Action: AssignmentAction::Assigning);
10221 } else {
10222 ImplicitConversionSequence ICS =
10223 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10224 /*SuppressUserConversions=*/false,
10225 AllowExplicit: AllowedExplicit::None,
10226 /*InOverloadResolution=*/false,
10227 /*CStyle=*/false,
10228 /*AllowObjCWritebackConversion=*/false);
10229 if (ICS.isFailure())
10230 return AssignConvertType::Incompatible;
10231 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10232 ICS, Action: AssignmentAction::Assigning);
10233 }
10234 if (RHS.isInvalid())
10235 return AssignConvertType::Incompatible;
10236 AssignConvertType result = AssignConvertType::Compatible;
10237 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10238 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10239 result = AssignConvertType::IncompatibleObjCWeakRef;
10240
10241 // Check if OBT is being discarded during assignment
10242 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10243 if (RHSType->isOverflowBehaviorType() &&
10244 !LHSType->isOverflowBehaviorType()) {
10245 result = AssignConvertType::CompatibleOBTDiscards;
10246 }
10247
10248 return result;
10249 }
10250
10251 // FIXME: Currently, we fall through and treat C++ classes like C
10252 // structures.
10253 // FIXME: We also fall through for atomics; not sure what should
10254 // happen there, though.
10255 } else if (RHS.get()->getType() == Context.OverloadTy) {
10256 // As a set of extensions to C, we support overloading on functions. These
10257 // functions need to be resolved here.
10258 DeclAccessPair DAP;
10259 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10260 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10261 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10262 else
10263 return AssignConvertType::Incompatible;
10264 }
10265
10266 // For HLSL records, insert derived-to-base conversion if needed.
10267 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10268 QualType RHSType = RHS.get()->getType();
10269 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10270 CXXBasePaths Paths;
10271 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10272 CXXCastPath CastPath;
10273 BuildBasePathArray(Paths, BasePath&: CastPath);
10274 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10275 BasePath: &CastPath);
10276 }
10277 }
10278 }
10279
10280 // This check seems unnatural, however it is necessary to ensure the proper
10281 // conversion of functions/arrays. If the conversion were done for all
10282 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10283 // expressions that suppress this implicit conversion (&, sizeof). This needs
10284 // to happen before we check for null pointer conversions because C does not
10285 // undergo the same implicit conversions as C++ does above (by the calls to
10286 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10287 // lvalue to rvalue cast before checking for null pointer constraints. This
10288 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10289 //
10290 // Suppress this for references: C++ 8.5.3p5.
10291 if (!LHSType->isReferenceType()) {
10292 // FIXME: We potentially allocate here even if ConvertRHS is false.
10293 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10294 if (RHS.isInvalid())
10295 return AssignConvertType::Incompatible;
10296 }
10297
10298 // The constraints are expressed in terms of the atomic, qualified, or
10299 // unqualified type of the LHS.
10300 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10301
10302 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10303 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10304 if ((LHSTypeAfterConversion->isPointerType() ||
10305 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10306 LHSTypeAfterConversion->isBlockPointerType()) &&
10307 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10308 RHS.get()->isNullPointerConstant(Ctx&: Context,
10309 NPC: Expr::NPC_ValueDependentIsNull))) {
10310 AssignConvertType Ret = AssignConvertType::Compatible;
10311 if (Diagnose || ConvertRHS) {
10312 CastKind Kind;
10313 CXXCastPath Path;
10314 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10315 /*IgnoreBaseAccess=*/false, Diagnose);
10316
10317 // If there is a conversion of some kind, check to see what kind of
10318 // pointer conversion happened so we can diagnose a C++ compatibility
10319 // diagnostic if the conversion is invalid. This only matters if the RHS
10320 // is some kind of void pointer. We have a carve-out when the RHS is from
10321 // a macro expansion because the use of a macro may indicate different
10322 // code between C and C++. Consider: char *s = NULL; where NULL is
10323 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10324 // C++, which is valid in C++.
10325 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10326 !RHS.get()->getBeginLoc().isMacroID()) {
10327 QualType CanRHS =
10328 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10329 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10330 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10331 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10332 Loc: RHS.get()->getExprLoc());
10333 // Anything that's not considered perfectly compatible would be
10334 // incompatible in C++.
10335 if (Ret != AssignConvertType::Compatible)
10336 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10337 }
10338 }
10339
10340 if (ConvertRHS)
10341 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10342 }
10343 return Ret;
10344 }
10345 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10346 // unqualified bool, and the right operand is a pointer or its type is
10347 // nullptr_t.
10348 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10349 RHS.get()->getType()->isNullPtrType()) {
10350 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10351 // only handles nullptr -> _Bool due to needing an extra conversion
10352 // step.
10353 // We model this by converting from nullptr -> void * and then let the
10354 // conversion from void * -> _Bool happen naturally.
10355 if (Diagnose || ConvertRHS) {
10356 CastKind Kind;
10357 CXXCastPath Path;
10358 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10359 /*IgnoreBaseAccess=*/false, Diagnose);
10360 if (ConvertRHS)
10361 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10362 BasePath: &Path);
10363 }
10364 }
10365
10366 // OpenCL queue_t type assignment.
10367 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10368 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10369 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10370 return AssignConvertType::Compatible;
10371 }
10372
10373 CastKind Kind;
10374 AssignConvertType result =
10375 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10376
10377 // If assigning a void * created by an allocation function call to some other
10378 // type, check that the allocated size is sufficient for that type.
10379 if (result != AssignConvertType::Incompatible &&
10380 RHS.get()->getType()->isVoidPointerType())
10381 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10382
10383 // C99 6.5.16.1p2: The value of the right operand is converted to the
10384 // type of the assignment expression.
10385 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10386 // so that we can use references in built-in functions even in C.
10387 // The getNonReferenceType() call makes sure that the resulting expression
10388 // does not have reference type.
10389 if (result != AssignConvertType::Incompatible &&
10390 RHS.get()->getType() != LHSType) {
10391 QualType Ty = LHSType.getNonLValueExprType(Context);
10392 Expr *E = RHS.get();
10393
10394 // Check for various Objective-C errors. If we are not reporting
10395 // diagnostics and just checking for errors, e.g., during overload
10396 // resolution, return Incompatible to indicate the failure.
10397 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10398 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10399 CCK: CheckedConversionKind::Implicit, Diagnose,
10400 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10401 if (!Diagnose)
10402 return AssignConvertType::Incompatible;
10403 }
10404 if (getLangOpts().ObjC &&
10405 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10406 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10407 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10408 if (!Diagnose)
10409 return AssignConvertType::Incompatible;
10410 // Replace the expression with a corrected version and continue so we
10411 // can find further errors.
10412 RHS = E;
10413 return AssignConvertType::Compatible;
10414 }
10415
10416 if (ConvertRHS)
10417 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10418 }
10419
10420 return result;
10421}
10422
10423namespace {
10424/// The original operand to an operator, prior to the application of the usual
10425/// arithmetic conversions and converting the arguments of a builtin operator
10426/// candidate.
10427struct OriginalOperand {
10428 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10429 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10430 Op = MTE->getSubExpr();
10431 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10432 Op = BTE->getSubExpr();
10433 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10434 Orig = ICE->getSubExprAsWritten();
10435 Conversion = ICE->getConversionFunction();
10436 }
10437 }
10438
10439 QualType getType() const { return Orig->getType(); }
10440
10441 Expr *Orig;
10442 NamedDecl *Conversion;
10443};
10444}
10445
10446QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10447 ExprResult &RHS) {
10448 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10449
10450 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10451 << OrigLHS.getType() << OrigRHS.getType()
10452 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10453
10454 // If a user-defined conversion was applied to either of the operands prior
10455 // to applying the built-in operator rules, tell the user about it.
10456 if (OrigLHS.Conversion) {
10457 Diag(Loc: OrigLHS.Conversion->getLocation(),
10458 DiagID: diag::note_typecheck_invalid_operands_converted)
10459 << 0 << LHS.get()->getType();
10460 }
10461 if (OrigRHS.Conversion) {
10462 Diag(Loc: OrigRHS.Conversion->getLocation(),
10463 DiagID: diag::note_typecheck_invalid_operands_converted)
10464 << 1 << RHS.get()->getType();
10465 }
10466
10467 return QualType();
10468}
10469
10470QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10471 ExprResult &RHS) {
10472 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10473 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10474
10475 bool LHSNatVec = LHSType->isVectorType();
10476 bool RHSNatVec = RHSType->isVectorType();
10477
10478 if (!(LHSNatVec && RHSNatVec)) {
10479 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10480 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10481 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10482 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10483 << Vector->getSourceRange();
10484 return QualType();
10485 }
10486
10487 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10488 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10489 << RHS.get()->getSourceRange();
10490
10491 return QualType();
10492}
10493
10494/// Try to convert a value of non-vector type to a vector type by converting
10495/// the type to the element type of the vector and then performing a splat.
10496/// If the language is OpenCL, we only use conversions that promote scalar
10497/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10498/// for float->int.
10499///
10500/// OpenCL V2.0 6.2.6.p2:
10501/// An error shall occur if any scalar operand type has greater rank
10502/// than the type of the vector element.
10503///
10504/// \param scalar - if non-null, actually perform the conversions
10505/// \return true if the operation fails (but without diagnosing the failure)
10506static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10507 QualType scalarTy,
10508 QualType vectorEltTy,
10509 QualType vectorTy,
10510 unsigned &DiagID) {
10511 // The conversion to apply to the scalar before splatting it,
10512 // if necessary.
10513 CastKind scalarCast = CK_NoOp;
10514
10515 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10516 scalarCast = CK_IntegralToBoolean;
10517 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10518 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10519 (scalarTy->isIntegerType() &&
10520 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10521 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10522 return true;
10523 }
10524 if (!scalarTy->isIntegralType(Ctx: S.Context))
10525 return true;
10526 scalarCast = CK_IntegralCast;
10527 } else if (vectorEltTy->isRealFloatingType()) {
10528 if (scalarTy->isRealFloatingType()) {
10529 if (S.getLangOpts().OpenCL &&
10530 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10531 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10532 return true;
10533 }
10534 scalarCast = CK_FloatingCast;
10535 }
10536 else if (scalarTy->isIntegralType(Ctx: S.Context))
10537 scalarCast = CK_IntegralToFloating;
10538 else
10539 return true;
10540 } else {
10541 return true;
10542 }
10543
10544 // Adjust scalar if desired.
10545 if (scalar) {
10546 if (scalarCast != CK_NoOp)
10547 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10548 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10549 }
10550 return false;
10551}
10552
10553/// Convert vector E to a vector with the same number of elements but different
10554/// element type.
10555static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10556 const auto *VecTy = E->getType()->getAs<VectorType>();
10557 assert(VecTy && "Expression E must be a vector");
10558 QualType NewVecTy =
10559 VecTy->isExtVectorType()
10560 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10561 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10562 VecKind: VecTy->getVectorKind());
10563
10564 // Look through the implicit cast. Return the subexpression if its type is
10565 // NewVecTy.
10566 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10567 if (ICE->getSubExpr()->getType() == NewVecTy)
10568 return ICE->getSubExpr();
10569
10570 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10571 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10572}
10573
10574/// Test if a (constant) integer Int can be casted to another integer type
10575/// IntTy without losing precision.
10576static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10577 QualType OtherIntTy) {
10578 Expr *E = Int->get();
10579 if (E->containsErrors() || E->isInstantiationDependent())
10580 return false;
10581
10582 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10583
10584 // Reject cases where the value of the Int is unknown as that would
10585 // possibly cause truncation, but accept cases where the scalar can be
10586 // demoted without loss of precision.
10587 Expr::EvalResult EVResult;
10588 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10589 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10590 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10591 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10592
10593 if (CstInt) {
10594 // If the scalar is constant and is of a higher order and has more active
10595 // bits that the vector element type, reject it.
10596 llvm::APSInt Result = EVResult.Val.getInt();
10597 unsigned NumBits = IntSigned
10598 ? (Result.isNegative() ? Result.getSignificantBits()
10599 : Result.getActiveBits())
10600 : Result.getActiveBits();
10601 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10602 return true;
10603
10604 // If the signedness of the scalar type and the vector element type
10605 // differs and the number of bits is greater than that of the vector
10606 // element reject it.
10607 return (IntSigned != OtherIntSigned &&
10608 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10609 }
10610
10611 // Reject cases where the value of the scalar is not constant and it's
10612 // order is greater than that of the vector element type.
10613 return (Order < 0);
10614}
10615
10616/// Test if a (constant) integer Int can be casted to floating point type
10617/// FloatTy without losing precision.
10618static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10619 QualType FloatTy) {
10620 if (Int->get()->containsErrors())
10621 return false;
10622
10623 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10624
10625 // Determine if the integer constant can be expressed as a floating point
10626 // number of the appropriate type.
10627 Expr::EvalResult EVResult;
10628 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10629
10630 uint64_t Bits = 0;
10631 if (CstInt) {
10632 // Reject constants that would be truncated if they were converted to
10633 // the floating point type. Test by simple to/from conversion.
10634 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10635 // could be avoided if there was a convertFromAPInt method
10636 // which could signal back if implicit truncation occurred.
10637 llvm::APSInt Result = EVResult.Val.getInt();
10638 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10639 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10640 RM: llvm::APFloat::rmTowardZero);
10641 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10642 !IntTy->hasSignedIntegerRepresentation());
10643 bool Ignored = false;
10644 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10645 IsExact: &Ignored);
10646 if (Result != ConvertBack)
10647 return true;
10648 } else {
10649 // Reject types that cannot be fully encoded into the mantissa of
10650 // the float.
10651 Bits = S.Context.getTypeSize(T: IntTy);
10652 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10653 S.Context.getFloatTypeSemantics(T: FloatTy));
10654 if (Bits > FloatPrec)
10655 return true;
10656 }
10657
10658 return false;
10659}
10660
10661/// Attempt to convert and splat Scalar into a vector whose types matches
10662/// Vector following GCC conversion rules. The rule is that implicit
10663/// conversion can occur when Scalar can be casted to match Vector's element
10664/// type without causing truncation of Scalar.
10665static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10666 ExprResult *Vector) {
10667 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10668 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10669 QualType VectorEltTy;
10670
10671 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10672 assert(!isa<ExtVectorType>(VT) &&
10673 "ExtVectorTypes should not be handled here!");
10674 VectorEltTy = VT->getElementType();
10675 } else if (VectorTy->isSveVLSBuiltinType()) {
10676 VectorEltTy =
10677 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10678 } else {
10679 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10680 }
10681
10682 // Reject cases where the vector element type or the scalar element type are
10683 // not integral or floating point types.
10684 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10685 return true;
10686
10687 // The conversion to apply to the scalar before splatting it,
10688 // if necessary.
10689 CastKind ScalarCast = CK_NoOp;
10690
10691 // Accept cases where the vector elements are integers and the scalar is
10692 // an integer.
10693 // FIXME: Notionally if the scalar was a floating point value with a precise
10694 // integral representation, we could cast it to an appropriate integer
10695 // type and then perform the rest of the checks here. GCC will perform
10696 // this conversion in some cases as determined by the input language.
10697 // We should accept it on a language independent basis.
10698 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10699 ScalarTy->isIntegralType(Ctx: S.Context) &&
10700 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10701
10702 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10703 return true;
10704
10705 ScalarCast = CK_IntegralCast;
10706 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10707 ScalarTy->isRealFloatingType()) {
10708 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10709 ScalarCast = CK_FloatingToIntegral;
10710 else
10711 return true;
10712 } else if (VectorEltTy->isRealFloatingType()) {
10713 if (ScalarTy->isRealFloatingType()) {
10714
10715 // Reject cases where the scalar type is not a constant and has a higher
10716 // Order than the vector element type.
10717 llvm::APFloat Result(0.0);
10718
10719 // Determine whether this is a constant scalar. In the event that the
10720 // value is dependent (and thus cannot be evaluated by the constant
10721 // evaluator), skip the evaluation. This will then diagnose once the
10722 // expression is instantiated.
10723 bool CstScalar = Scalar->get()->isValueDependent() ||
10724 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10725 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10726 if (!CstScalar && Order < 0)
10727 return true;
10728
10729 // If the scalar cannot be safely casted to the vector element type,
10730 // reject it.
10731 if (CstScalar) {
10732 bool Truncated = false;
10733 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10734 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10735 if (Truncated)
10736 return true;
10737 }
10738
10739 ScalarCast = CK_FloatingCast;
10740 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10741 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10742 return true;
10743
10744 ScalarCast = CK_IntegralToFloating;
10745 } else
10746 return true;
10747 } else if (ScalarTy->isEnumeralType())
10748 return true;
10749
10750 // Adjust scalar if desired.
10751 if (ScalarCast != CK_NoOp)
10752 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10753 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10754 return false;
10755}
10756
10757QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10758 SourceLocation Loc, bool IsCompAssign,
10759 bool AllowBothBool,
10760 bool AllowBoolConversions,
10761 bool AllowBoolOperation,
10762 bool ReportInvalid) {
10763 if (!IsCompAssign) {
10764 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10765 if (LHS.isInvalid())
10766 return QualType();
10767 }
10768 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10769 if (RHS.isInvalid())
10770 return QualType();
10771
10772 // For conversion purposes, we ignore any qualifiers.
10773 // For example, "const float" and "float" are equivalent.
10774 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10775 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10776
10777 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10778 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10779 assert(LHSVecType || RHSVecType);
10780
10781 if (getLangOpts().HLSL)
10782 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10783 IsCompAssign);
10784
10785 // Any operation with MFloat8 type is only possible with C intrinsics
10786 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10787 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10788 return InvalidOperands(Loc, LHS, RHS);
10789
10790 // AltiVec-style "vector bool op vector bool" combinations are allowed
10791 // for some operators but not others.
10792 if (!AllowBothBool && LHSVecType &&
10793 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10794 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10795 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10796
10797 // This operation may not be performed on boolean vectors.
10798 if (!AllowBoolOperation &&
10799 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10800 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10801
10802 // If the vector types are identical, return.
10803 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10804 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10805
10806 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10807 if (LHSVecType && RHSVecType &&
10808 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10809 if (isa<ExtVectorType>(Val: LHSVecType)) {
10810 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10811 return LHSType;
10812 }
10813
10814 if (!IsCompAssign)
10815 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10816 return RHSType;
10817 }
10818
10819 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10820 // can be mixed, with the result being the non-bool type. The non-bool
10821 // operand must have integer element type.
10822 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10823 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10824 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10825 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10826 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10827 LHSVecType->getElementType()->isIntegerType() &&
10828 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10829 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10830 return LHSType;
10831 }
10832 if (!IsCompAssign &&
10833 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10834 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10835 RHSVecType->getElementType()->isIntegerType()) {
10836 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10837 return RHSType;
10838 }
10839 }
10840
10841 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10842 // invalid since the ambiguity can affect the ABI.
10843 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10844 unsigned &SVEorRVV) {
10845 const VectorType *VecType = SecondType->getAs<VectorType>();
10846 SVEorRVV = 0;
10847 if (FirstType->isSizelessBuiltinType() && VecType) {
10848 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10849 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10850 return true;
10851 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10852 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10853 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10854 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10855 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10856 SVEorRVV = 1;
10857 return true;
10858 }
10859 }
10860
10861 return false;
10862 };
10863
10864 unsigned SVEorRVV;
10865 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10866 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10867 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10868 << SVEorRVV << LHSType << RHSType;
10869 return QualType();
10870 }
10871
10872 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10873 // invalid since the ambiguity can affect the ABI.
10874 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10875 unsigned &SVEorRVV) {
10876 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10877 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10878
10879 SVEorRVV = 0;
10880 if (FirstVecType && SecondVecType) {
10881 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10882 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10883 SecondVecType->getVectorKind() ==
10884 VectorKind::SveFixedLengthPredicate)
10885 return true;
10886 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10887 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10888 SecondVecType->getVectorKind() ==
10889 VectorKind::RVVFixedLengthMask_1 ||
10890 SecondVecType->getVectorKind() ==
10891 VectorKind::RVVFixedLengthMask_2 ||
10892 SecondVecType->getVectorKind() ==
10893 VectorKind::RVVFixedLengthMask_4) {
10894 SVEorRVV = 1;
10895 return true;
10896 }
10897 }
10898 return false;
10899 }
10900
10901 if (SecondVecType &&
10902 SecondVecType->getVectorKind() == VectorKind::Generic) {
10903 if (FirstType->isSVESizelessBuiltinType())
10904 return true;
10905 if (FirstType->isRVVSizelessBuiltinType()) {
10906 SVEorRVV = 1;
10907 return true;
10908 }
10909 }
10910
10911 return false;
10912 };
10913
10914 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10915 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10916 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10917 << SVEorRVV << LHSType << RHSType;
10918 return QualType();
10919 }
10920
10921 // If there's a vector type and a scalar, try to convert the scalar to
10922 // the vector element type and splat.
10923 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10924 if (!RHSVecType) {
10925 if (isa<ExtVectorType>(Val: LHSVecType)) {
10926 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10927 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10928 DiagID))
10929 return LHSType;
10930 } else {
10931 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10932 return LHSType;
10933 }
10934 }
10935 if (!LHSVecType) {
10936 if (isa<ExtVectorType>(Val: RHSVecType)) {
10937 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10938 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10939 vectorTy: RHSType, DiagID))
10940 return RHSType;
10941 } else {
10942 if (LHS.get()->isLValue() ||
10943 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10944 return RHSType;
10945 }
10946 }
10947
10948 // FIXME: The code below also handles conversion between vectors and
10949 // non-scalars, we should break this down into fine grained specific checks
10950 // and emit proper diagnostics.
10951 QualType VecType = LHSVecType ? LHSType : RHSType;
10952 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10953 QualType OtherType = LHSVecType ? RHSType : LHSType;
10954 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10955 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10956 if (Context.getTargetInfo().getTriple().isPPC() &&
10957 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10958 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10959 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10960 // If we're allowing lax vector conversions, only the total (data) size
10961 // needs to be the same. For non compound assignment, if one of the types is
10962 // scalar, the result is always the vector type.
10963 if (!IsCompAssign) {
10964 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10965 return VecType;
10966 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10967 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10968 // type. Note that this is already done by non-compound assignments in
10969 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10970 // <1 x T> -> T. The result is also a vector type.
10971 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10972 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10973 ExprResult *RHSExpr = &RHS;
10974 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10975 return VecType;
10976 }
10977 }
10978
10979 // Okay, the expression is invalid.
10980
10981 // If there's a non-vector, non-real operand, diagnose that.
10982 if ((!RHSVecType && !RHSType->isRealType()) ||
10983 (!LHSVecType && !LHSType->isRealType())) {
10984 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10985 << LHSType << RHSType
10986 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10987 return QualType();
10988 }
10989
10990 // OpenCL V1.1 6.2.6.p1:
10991 // If the operands are of more than one vector type, then an error shall
10992 // occur. Implicit conversions between vector types are not permitted, per
10993 // section 6.2.1.
10994 if (getLangOpts().OpenCL &&
10995 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
10996 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
10997 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
10998 << RHSType;
10999 return QualType();
11000 }
11001
11002
11003 // If there is a vector type that is not a ExtVector and a scalar, we reach
11004 // this point if scalar could not be converted to the vector's element type
11005 // without truncation.
11006 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11007 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11008 QualType Scalar = LHSVecType ? RHSType : LHSType;
11009 QualType Vector = LHSVecType ? LHSType : RHSType;
11010 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11011 Diag(Loc,
11012 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11013 << ScalarOrVector << Scalar << Vector;
11014
11015 return QualType();
11016 }
11017
11018 // Otherwise, use the generic diagnostic.
11019 Diag(Loc, DiagID)
11020 << LHSType << RHSType
11021 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11022 return QualType();
11023}
11024
11025QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11026 SourceLocation Loc,
11027 bool IsCompAssign,
11028 ArithConvKind OperationKind) {
11029 if (!IsCompAssign) {
11030 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11031 if (LHS.isInvalid())
11032 return QualType();
11033 }
11034 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11035 if (RHS.isInvalid())
11036 return QualType();
11037
11038 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11039 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11040
11041 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11042 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11043
11044 unsigned DiagID = diag::err_typecheck_invalid_operands;
11045 if ((OperationKind == ArithConvKind::Arithmetic) &&
11046 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11047 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11048 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11049 << RHS.get()->getSourceRange();
11050 return QualType();
11051 }
11052
11053 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11054 return LHSType;
11055
11056 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11057 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11058 return LHSType;
11059 }
11060 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11061 if (LHS.get()->isLValue() ||
11062 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11063 return RHSType;
11064 }
11065
11066 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11067 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11068 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11069 << LHSType << RHSType << LHS.get()->getSourceRange()
11070 << RHS.get()->getSourceRange();
11071 return QualType();
11072 }
11073
11074 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11075 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11076 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11077 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11078 << LHSType << RHSType << LHS.get()->getSourceRange()
11079 << RHS.get()->getSourceRange();
11080 return QualType();
11081 }
11082
11083 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11084 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11085 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11086 bool ScalarOrVector =
11087 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11088
11089 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11090 << ScalarOrVector << Scalar << Vector;
11091
11092 return QualType();
11093 }
11094
11095 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11096 << RHS.get()->getSourceRange();
11097 return QualType();
11098}
11099
11100// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11101// expression. These are mainly cases where the null pointer is used as an
11102// integer instead of a pointer.
11103static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11104 SourceLocation Loc, bool IsCompare) {
11105 // The canonical way to check for a GNU null is with isNullPointerConstant,
11106 // but we use a bit of a hack here for speed; this is a relatively
11107 // hot path, and isNullPointerConstant is slow.
11108 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11109 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11110
11111 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11112
11113 // Avoid analyzing cases where the result will either be invalid (and
11114 // diagnosed as such) or entirely valid and not something to warn about.
11115 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11116 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11117 return;
11118
11119 // Comparison operations would not make sense with a null pointer no matter
11120 // what the other expression is.
11121 if (!IsCompare) {
11122 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11123 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11124 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11125 return;
11126 }
11127
11128 // The rest of the operations only make sense with a null pointer
11129 // if the other expression is a pointer.
11130 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11131 NonNullType->canDecayToPointerType())
11132 return;
11133
11134 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11135 << LHSNull /* LHS is NULL */ << NonNullType
11136 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11137}
11138
11139static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11140 SourceLocation OpLoc) {
11141 // If the divisor is real, then this is real/real or complex/real division.
11142 // Either way there can be no precision loss.
11143 auto *CT = DivisorTy->getAs<ComplexType>();
11144 if (!CT)
11145 return;
11146
11147 QualType ElementType = CT->getElementType().getCanonicalType();
11148 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11149 LangOptions::ComplexRangeKind::CX_Promoted;
11150 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11151 return;
11152
11153 ASTContext &Ctx = S.getASTContext();
11154 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11155 const llvm::fltSemantics &ElementTypeSemantics =
11156 Ctx.getFloatTypeSemantics(T: ElementType);
11157 const llvm::fltSemantics &HigherElementTypeSemantics =
11158 Ctx.getFloatTypeSemantics(T: HigherElementType);
11159
11160 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11161 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11162 (HigherElementType == Ctx.LongDoubleTy &&
11163 !Ctx.getTargetInfo().hasLongDoubleType())) {
11164 // Retain the location of the first use of higher precision type.
11165 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11166 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11167 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11168 if (Type == HigherElementType) {
11169 Num++;
11170 return;
11171 }
11172 }
11173 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11174 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11175 }
11176}
11177
11178static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11179 SourceLocation Loc) {
11180 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11181 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11182 if (!LUE || !RUE)
11183 return;
11184 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11185 RUE->getKind() != UETT_SizeOf)
11186 return;
11187
11188 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11189 QualType LHSTy = LHSArg->getType();
11190 QualType RHSTy;
11191
11192 if (RUE->isArgumentType())
11193 RHSTy = RUE->getArgumentType().getNonReferenceType();
11194 else
11195 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11196
11197 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11198 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11199 return;
11200
11201 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11202 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11203 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11204 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11205 << LHSArgDecl;
11206 }
11207 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11208 QualType ArrayElemTy = ArrayTy->getElementType();
11209 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11210 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11211 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11212 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11213 return;
11214 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11215 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11216 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11217 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11218 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11219 << LHSArgDecl;
11220 }
11221
11222 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11223 }
11224}
11225
11226static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11227 ExprResult &RHS,
11228 SourceLocation Loc, bool IsDiv) {
11229 // Check for division/remainder by zero.
11230 Expr::EvalResult RHSValue;
11231 if (!RHS.get()->isValueDependent() &&
11232 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11233 RHSValue.Val.getInt() == 0)
11234 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11235 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11236 << IsDiv << RHS.get()->getSourceRange());
11237}
11238
11239static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11240 const ExprResult &LHS, const ExprResult &RHS,
11241 BinaryOperatorKind Opc) {
11242 if (!LHS.isUsable() || !RHS.isUsable())
11243 return;
11244 const Expr *LHSExpr = LHS.get();
11245 const Expr *RHSExpr = RHS.get();
11246 const QualType LHSType = LHSExpr->getType();
11247 const QualType RHSType = RHSExpr->getType();
11248 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11249 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11250 if (!LHSIsScoped && !RHSIsScoped)
11251 return;
11252 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11253 return;
11254 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11255 return;
11256 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11257 return;
11258 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11259 SourceLocation BeginLoc = expr->getBeginLoc();
11260 QualType IntType = type->castAs<EnumType>()
11261 ->getDecl()
11262 ->getDefinitionOrSelf()
11263 ->getIntegerType();
11264 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11265 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11266 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11267 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11268 };
11269 if (LHSIsScoped) {
11270 DiagnosticHelper(LHSExpr, LHSType);
11271 }
11272 if (RHSIsScoped) {
11273 DiagnosticHelper(RHSExpr, RHSType);
11274 }
11275}
11276
11277QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11278 SourceLocation Loc,
11279 BinaryOperatorKind Opc) {
11280 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11281 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11282
11283 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11284
11285 QualType LHSTy = LHS.get()->getType();
11286 QualType RHSTy = RHS.get()->getType();
11287 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11288 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11289 /*AllowBothBool*/ getLangOpts().AltiVec,
11290 /*AllowBoolConversions*/ false,
11291 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11292 /*ReportInvalid*/ true);
11293 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11294 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11295 OperationKind: ArithConvKind::Arithmetic);
11296 if (!IsDiv &&
11297 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11298 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11299 // For division, only matrix-by-scalar is supported. Other combinations with
11300 // matrix types are invalid.
11301 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11302 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11303
11304 QualType compType = UsualArithmeticConversions(
11305 LHS, RHS, Loc,
11306 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11307 if (LHS.isInvalid() || RHS.isInvalid())
11308 return QualType();
11309
11310 if (compType.isNull() || !compType->isArithmeticType()) {
11311 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11312 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11313 return ResultTy;
11314 }
11315 if (IsDiv) {
11316 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11317 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11318 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11319 }
11320 return compType;
11321}
11322
11323QualType Sema::CheckRemainderOperands(
11324 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11325 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11326
11327 // Note: This check is here to simplify the double exclusions of
11328 // scalar and vector HLSL checks. No getLangOpts().HLSL
11329 // is needed since all languages exlcude doubles.
11330 if (LHS.get()->getType()->isDoubleType() ||
11331 RHS.get()->getType()->isDoubleType() ||
11332 (LHS.get()->getType()->isVectorType() && LHS.get()
11333 ->getType()
11334 ->getAs<VectorType>()
11335 ->getElementType()
11336 ->isDoubleType()) ||
11337 (RHS.get()->getType()->isVectorType() && RHS.get()
11338 ->getType()
11339 ->getAs<VectorType>()
11340 ->getElementType()
11341 ->isDoubleType()))
11342 return InvalidOperands(Loc, LHS, RHS);
11343
11344 if (LHS.get()->getType()->isVectorType() ||
11345 RHS.get()->getType()->isVectorType()) {
11346 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11347 RHS.get()->getType()->hasIntegerRepresentation()) ||
11348 (getLangOpts().HLSL &&
11349 (LHS.get()->getType()->hasFloatingRepresentation() ||
11350 RHS.get()->getType()->hasFloatingRepresentation())))
11351 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11352 /*AllowBothBool*/ getLangOpts().AltiVec,
11353 /*AllowBoolConversions*/ false,
11354 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11355 /*ReportInvalid*/ true);
11356 return InvalidOperands(Loc, LHS, RHS);
11357 }
11358
11359 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11360 RHS.get()->getType()->isSveVLSBuiltinType()) {
11361 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11362 RHS.get()->getType()->hasIntegerRepresentation())
11363 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11364 OperationKind: ArithConvKind::Arithmetic);
11365
11366 return InvalidOperands(Loc, LHS, RHS);
11367 }
11368
11369 QualType compType = UsualArithmeticConversions(
11370 LHS, RHS, Loc,
11371 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11372 if (LHS.isInvalid() || RHS.isInvalid())
11373 return QualType();
11374
11375 if (compType.isNull() ||
11376 (!compType->isIntegerType() &&
11377 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11378 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11379 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11380 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11381 return ResultTy;
11382 }
11383 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11384 return compType;
11385}
11386
11387/// Diagnose invalid arithmetic on two void pointers.
11388static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11389 Expr *LHSExpr, Expr *RHSExpr) {
11390 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11391 ? diag::err_typecheck_pointer_arith_void_type
11392 : diag::ext_gnu_void_ptr)
11393 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11394 << RHSExpr->getSourceRange();
11395}
11396
11397/// Diagnose invalid arithmetic on a void pointer.
11398static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11399 Expr *Pointer) {
11400 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11401 ? diag::err_typecheck_pointer_arith_void_type
11402 : diag::ext_gnu_void_ptr)
11403 << 0 /* one pointer */ << Pointer->getSourceRange();
11404}
11405
11406/// Diagnose invalid arithmetic on a null pointer.
11407///
11408/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11409/// idiom, which we recognize as a GNU extension.
11410///
11411static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11412 Expr *Pointer, bool IsGNUIdiom) {
11413 if (IsGNUIdiom)
11414 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11415 << Pointer->getSourceRange();
11416 else
11417 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11418 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11419}
11420
11421/// Diagnose invalid subraction on a null pointer.
11422///
11423static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11424 Expr *Pointer, bool BothNull) {
11425 // Null - null is valid in C++ [expr.add]p7
11426 if (BothNull && S.getLangOpts().CPlusPlus)
11427 return;
11428
11429 // Is this s a macro from a system header?
11430 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11431 return;
11432
11433 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11434 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11435 << S.getLangOpts().CPlusPlus
11436 << Pointer->getSourceRange());
11437}
11438
11439/// Diagnose invalid arithmetic on two function pointers.
11440static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11441 Expr *LHS, Expr *RHS) {
11442 assert(LHS->getType()->isAnyPointerType());
11443 assert(RHS->getType()->isAnyPointerType());
11444 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11445 ? diag::err_typecheck_pointer_arith_function_type
11446 : diag::ext_gnu_ptr_func_arith)
11447 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11448 // We only show the second type if it differs from the first.
11449 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11450 T2: RHS->getType())
11451 << RHS->getType()->getPointeeType()
11452 << LHS->getSourceRange() << RHS->getSourceRange();
11453}
11454
11455/// Diagnose invalid arithmetic on a function pointer.
11456static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11457 Expr *Pointer) {
11458 assert(Pointer->getType()->isAnyPointerType());
11459 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11460 ? diag::err_typecheck_pointer_arith_function_type
11461 : diag::ext_gnu_ptr_func_arith)
11462 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11463 << 0 /* one pointer, so only one type */
11464 << Pointer->getSourceRange();
11465}
11466
11467/// Emit error if Operand is incomplete pointer type
11468///
11469/// \returns True if pointer has incomplete type
11470static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11471 Expr *Operand) {
11472 QualType ResType = Operand->getType();
11473 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11474 ResType = ResAtomicType->getValueType();
11475
11476 assert(ResType->isAnyPointerType());
11477 QualType PointeeTy = ResType->getPointeeType();
11478 return S.RequireCompleteSizedType(
11479 Loc, T: PointeeTy,
11480 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11481 Args: Operand->getSourceRange());
11482}
11483
11484/// Check the validity of an arithmetic pointer operand.
11485///
11486/// If the operand has pointer type, this code will check for pointer types
11487/// which are invalid in arithmetic operations. These will be diagnosed
11488/// appropriately, including whether or not the use is supported as an
11489/// extension.
11490///
11491/// \returns True when the operand is valid to use (even if as an extension).
11492static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11493 Expr *Operand) {
11494 QualType ResType = Operand->getType();
11495 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11496 ResType = ResAtomicType->getValueType();
11497
11498 if (!ResType->isAnyPointerType()) return true;
11499
11500 QualType PointeeTy = ResType->getPointeeType();
11501 if (PointeeTy->isVoidType()) {
11502 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11503 return !S.getLangOpts().CPlusPlus;
11504 }
11505 if (PointeeTy->isFunctionType()) {
11506 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11507 return !S.getLangOpts().CPlusPlus;
11508 }
11509
11510 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11511
11512 return true;
11513}
11514
11515/// Check the validity of a binary arithmetic operation w.r.t. pointer
11516/// operands.
11517///
11518/// This routine will diagnose any invalid arithmetic on pointer operands much
11519/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11520/// for emitting a single diagnostic even for operations where both LHS and RHS
11521/// are (potentially problematic) pointers.
11522///
11523/// \returns True when the operand is valid to use (even if as an extension).
11524static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11525 Expr *LHSExpr, Expr *RHSExpr) {
11526 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11527 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11528 if (!isLHSPointer && !isRHSPointer) return true;
11529
11530 QualType LHSPointeeTy, RHSPointeeTy;
11531 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11532 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11533
11534 // if both are pointers check if operation is valid wrt address spaces
11535 if (isLHSPointer && isRHSPointer) {
11536 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11537 Ctx: S.getASTContext())) {
11538 S.Diag(Loc,
11539 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11540 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11541 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11542 return false;
11543 }
11544 }
11545
11546 // Check for arithmetic on pointers to incomplete types.
11547 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11548 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11549 if (isLHSVoidPtr || isRHSVoidPtr) {
11550 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11551 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11552 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11553
11554 return !S.getLangOpts().CPlusPlus;
11555 }
11556
11557 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11558 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11559 if (isLHSFuncPtr || isRHSFuncPtr) {
11560 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11561 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11562 Pointer: RHSExpr);
11563 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11564
11565 return !S.getLangOpts().CPlusPlus;
11566 }
11567
11568 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11569 return false;
11570 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11571 return false;
11572
11573 return true;
11574}
11575
11576/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11577/// literal.
11578static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11579 Expr *LHSExpr, Expr *RHSExpr) {
11580 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11581 Expr* IndexExpr = RHSExpr;
11582 if (!StrExpr) {
11583 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11584 IndexExpr = LHSExpr;
11585 }
11586
11587 bool IsStringPlusInt = StrExpr &&
11588 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11589 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11590 return;
11591
11592 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11593 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11594 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11595
11596 // Only print a fixit for "str" + int, not for int + "str".
11597 if (IndexExpr == RHSExpr) {
11598 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11599 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11600 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11601 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11602 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11603 } else
11604 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11605}
11606
11607/// Emit a warning when adding a char literal to a string.
11608static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11609 Expr *LHSExpr, Expr *RHSExpr) {
11610 const Expr *StringRefExpr = LHSExpr;
11611 const CharacterLiteral *CharExpr =
11612 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11613
11614 if (!CharExpr) {
11615 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11616 StringRefExpr = RHSExpr;
11617 }
11618
11619 if (!CharExpr || !StringRefExpr)
11620 return;
11621
11622 const QualType StringType = StringRefExpr->getType();
11623
11624 // Return if not a PointerType.
11625 if (!StringType->isAnyPointerType())
11626 return;
11627
11628 // Return if not a CharacterType.
11629 if (!StringType->getPointeeType()->isAnyCharacterType())
11630 return;
11631
11632 ASTContext &Ctx = Self.getASTContext();
11633 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11634
11635 const QualType CharType = CharExpr->getType();
11636 if (!CharType->isAnyCharacterType() &&
11637 CharType->isIntegerType() &&
11638 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11639 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11640 << DiagRange << Ctx.CharTy;
11641 } else {
11642 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11643 << DiagRange << CharExpr->getType();
11644 }
11645
11646 // Only print a fixit for str + char, not for char + str.
11647 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11648 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11649 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11650 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11651 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11652 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11653 } else {
11654 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11655 }
11656}
11657
11658/// Emit error when two pointers are incompatible.
11659static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11660 Expr *LHSExpr, Expr *RHSExpr) {
11661 assert(LHSExpr->getType()->isAnyPointerType());
11662 assert(RHSExpr->getType()->isAnyPointerType());
11663 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11664 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11665 << RHSExpr->getSourceRange();
11666}
11667
11668// C99 6.5.6
11669QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11670 SourceLocation Loc, BinaryOperatorKind Opc,
11671 QualType* CompLHSTy) {
11672 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11673
11674 if (LHS.get()->getType()->isVectorType() ||
11675 RHS.get()->getType()->isVectorType()) {
11676 QualType compType =
11677 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11678 /*AllowBothBool*/ getLangOpts().AltiVec,
11679 /*AllowBoolConversions*/ getLangOpts().ZVector,
11680 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11681 /*ReportInvalid*/ true);
11682 if (CompLHSTy) *CompLHSTy = compType;
11683 return compType;
11684 }
11685
11686 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11687 RHS.get()->getType()->isSveVLSBuiltinType()) {
11688 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11689 OperationKind: ArithConvKind::Arithmetic);
11690 if (CompLHSTy)
11691 *CompLHSTy = compType;
11692 return compType;
11693 }
11694
11695 if (LHS.get()->getType()->isConstantMatrixType() ||
11696 RHS.get()->getType()->isConstantMatrixType()) {
11697 QualType compType =
11698 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11699 if (CompLHSTy)
11700 *CompLHSTy = compType;
11701 return compType;
11702 }
11703
11704 QualType compType = UsualArithmeticConversions(
11705 LHS, RHS, Loc,
11706 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11707 if (LHS.isInvalid() || RHS.isInvalid())
11708 return QualType();
11709
11710 // Diagnose "string literal" '+' int and string '+' "char literal".
11711 if (Opc == BO_Add) {
11712 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11713 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11714 }
11715
11716 // handle the common case first (both operands are arithmetic).
11717 if (!compType.isNull() && compType->isArithmeticType()) {
11718 if (CompLHSTy) *CompLHSTy = compType;
11719 return compType;
11720 }
11721
11722 // Type-checking. Ultimately the pointer's going to be in PExp;
11723 // note that we bias towards the LHS being the pointer.
11724 Expr *PExp = LHS.get(), *IExp = RHS.get();
11725
11726 bool isObjCPointer;
11727 if (PExp->getType()->isPointerType()) {
11728 isObjCPointer = false;
11729 } else if (PExp->getType()->isObjCObjectPointerType()) {
11730 isObjCPointer = true;
11731 } else {
11732 std::swap(a&: PExp, b&: IExp);
11733 if (PExp->getType()->isPointerType()) {
11734 isObjCPointer = false;
11735 } else if (PExp->getType()->isObjCObjectPointerType()) {
11736 isObjCPointer = true;
11737 } else {
11738 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11739 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11740 return ResultTy;
11741 }
11742 }
11743 assert(PExp->getType()->isAnyPointerType());
11744
11745 if (!IExp->getType()->isIntegerType())
11746 return InvalidOperands(Loc, LHS, RHS);
11747
11748 // Adding to a null pointer results in undefined behavior.
11749 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11750 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11751 // In C++ adding zero to a null pointer is defined.
11752 Expr::EvalResult KnownVal;
11753 if (!getLangOpts().CPlusPlus ||
11754 (!IExp->isValueDependent() &&
11755 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11756 KnownVal.Val.getInt() != 0))) {
11757 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11758 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11759 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11760 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11761 }
11762 }
11763
11764 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11765 return QualType();
11766
11767 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11768 return QualType();
11769
11770 // Arithmetic on label addresses is normally allowed, except when we add
11771 // a ptrauth signature to the addresses.
11772 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11773 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11774 << /*addition*/ 1;
11775 return QualType();
11776 }
11777
11778 // Check array bounds for pointer arithemtic
11779 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11780
11781 if (CompLHSTy) {
11782 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11783 if (LHSTy.isNull()) {
11784 LHSTy = LHS.get()->getType();
11785 if (Context.isPromotableIntegerType(T: LHSTy))
11786 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11787 }
11788 *CompLHSTy = LHSTy;
11789 }
11790
11791 return PExp->getType();
11792}
11793
11794// C99 6.5.6
11795QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11796 SourceLocation Loc,
11797 BinaryOperatorKind Opc,
11798 QualType *CompLHSTy) {
11799 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11800
11801 if (LHS.get()->getType()->isVectorType() ||
11802 RHS.get()->getType()->isVectorType()) {
11803 QualType compType =
11804 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11805 /*AllowBothBool*/ getLangOpts().AltiVec,
11806 /*AllowBoolConversions*/ getLangOpts().ZVector,
11807 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11808 /*ReportInvalid*/ true);
11809 if (CompLHSTy) *CompLHSTy = compType;
11810 return compType;
11811 }
11812
11813 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11814 RHS.get()->getType()->isSveVLSBuiltinType()) {
11815 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11816 OperationKind: ArithConvKind::Arithmetic);
11817 if (CompLHSTy)
11818 *CompLHSTy = compType;
11819 return compType;
11820 }
11821
11822 if (LHS.get()->getType()->isConstantMatrixType() ||
11823 RHS.get()->getType()->isConstantMatrixType()) {
11824 QualType compType =
11825 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11826 if (CompLHSTy)
11827 *CompLHSTy = compType;
11828 return compType;
11829 }
11830
11831 QualType compType = UsualArithmeticConversions(
11832 LHS, RHS, Loc,
11833 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11834 if (LHS.isInvalid() || RHS.isInvalid())
11835 return QualType();
11836
11837 // Enforce type constraints: C99 6.5.6p3.
11838
11839 // Handle the common case first (both operands are arithmetic).
11840 if (!compType.isNull() && compType->isArithmeticType()) {
11841 if (CompLHSTy) *CompLHSTy = compType;
11842 return compType;
11843 }
11844
11845 // Either ptr - int or ptr - ptr.
11846 if (LHS.get()->getType()->isAnyPointerType()) {
11847 QualType lpointee = LHS.get()->getType()->getPointeeType();
11848
11849 // Diagnose bad cases where we step over interface counts.
11850 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11851 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11852 return QualType();
11853
11854 // Arithmetic on label addresses is normally allowed, except when we add
11855 // a ptrauth signature to the addresses.
11856 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11857 getLangOpts().PointerAuthIndirectGotos) {
11858 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11859 << /*subtraction*/ 0;
11860 return QualType();
11861 }
11862
11863 // The result type of a pointer-int computation is the pointer type.
11864 if (RHS.get()->getType()->isIntegerType()) {
11865 // Subtracting from a null pointer should produce a warning.
11866 // The last argument to the diagnose call says this doesn't match the
11867 // GNU int-to-pointer idiom.
11868 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11869 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11870 // In C++ adding zero to a null pointer is defined.
11871 Expr::EvalResult KnownVal;
11872 if (!getLangOpts().CPlusPlus ||
11873 (!RHS.get()->isValueDependent() &&
11874 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11875 KnownVal.Val.getInt() != 0))) {
11876 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11877 }
11878 }
11879
11880 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11881 return QualType();
11882
11883 // Check array bounds for pointer arithemtic
11884 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11885 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11886
11887 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11888 return LHS.get()->getType();
11889 }
11890
11891 // Handle pointer-pointer subtractions.
11892 if (const PointerType *RHSPTy
11893 = RHS.get()->getType()->getAs<PointerType>()) {
11894 QualType rpointee = RHSPTy->getPointeeType();
11895
11896 if (getLangOpts().CPlusPlus) {
11897 // Pointee types must be the same: C++ [expr.add]
11898 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11899 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11900 }
11901 } else {
11902 // Pointee types must be compatible C99 6.5.6p3
11903 if (!Context.typesAreCompatible(
11904 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11905 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11906 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11907 return QualType();
11908 }
11909 }
11910
11911 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11912 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11913 return QualType();
11914
11915 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11916 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11917 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11918 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11919
11920 // Subtracting nullptr or from nullptr is suspect
11921 if (LHSIsNullPtr)
11922 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11923 if (RHSIsNullPtr)
11924 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11925
11926 // The pointee type may have zero size. As an extension, a structure or
11927 // union may have zero size or an array may have zero length. In this
11928 // case subtraction does not make sense.
11929 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11930 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11931 if (ElementSize.isZero()) {
11932 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11933 << rpointee.getUnqualifiedType()
11934 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11935 }
11936 }
11937
11938 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11939 return Context.getPointerDiffType();
11940 }
11941 }
11942
11943 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11944 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11945 return ResultTy;
11946}
11947
11948static bool isScopedEnumerationType(QualType T) {
11949 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11950 return ET->getDecl()->isScoped();
11951 return false;
11952}
11953
11954static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11955 SourceLocation Loc, BinaryOperatorKind Opc,
11956 QualType LHSType) {
11957 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11958 // so skip remaining warnings as we don't want to modify values within Sema.
11959 if (S.getLangOpts().OpenCL)
11960 return;
11961
11962 if (Opc == BO_Shr &&
11963 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11964 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11965
11966 // Check right/shifter operand
11967 Expr::EvalResult RHSResult;
11968 if (RHS.get()->isValueDependent() ||
11969 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11970 return;
11971 llvm::APSInt Right = RHSResult.Val.getInt();
11972
11973 if (Right.isNegative()) {
11974 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11975 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11976 << RHS.get()->getSourceRange());
11977 return;
11978 }
11979
11980 QualType LHSExprType = LHS.get()->getType();
11981 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11982 if (LHSExprType->isBitIntType())
11983 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11984 else if (LHSExprType->isFixedPointType()) {
11985 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11986 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11987 }
11988 if (Right.uge(RHS: LeftSize)) {
11989 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11990 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
11991 << RHS.get()->getSourceRange());
11992 return;
11993 }
11994
11995 // FIXME: We probably need to handle fixed point types specially here.
11996 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11997 return;
11998
11999 // When left shifting an ICE which is signed, we can check for overflow which
12000 // according to C++ standards prior to C++2a has undefined behavior
12001 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12002 // more than the maximum value representable in the result type, so never
12003 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12004 // expression is still probably a bug.)
12005 Expr::EvalResult LHSResult;
12006 if (LHS.get()->isValueDependent() ||
12007 LHSType->hasUnsignedIntegerRepresentation() ||
12008 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12009 return;
12010 llvm::APSInt Left = LHSResult.Val.getInt();
12011
12012 // Don't warn if signed overflow is defined, then all the rest of the
12013 // diagnostics will not be triggered because the behavior is defined.
12014 // Also don't warn in C++20 mode (and newer), as signed left shifts
12015 // always wrap and never overflow.
12016 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12017 return;
12018
12019 // If LHS does not have a non-negative value then, the
12020 // behavior is undefined before C++2a. Warn about it.
12021 if (Left.isNegative()) {
12022 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
12023 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
12024 << LHS.get()->getSourceRange());
12025 return;
12026 }
12027
12028 llvm::APInt ResultBits =
12029 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12030 if (ResultBits.ule(RHS: LeftSize))
12031 return;
12032 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12033 Result = Result.shl(ShiftAmt: Right);
12034
12035 // Print the bit representation of the signed integer as an unsigned
12036 // hexadecimal number.
12037 SmallString<40> HexResult;
12038 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12039
12040 // If we are only missing a sign bit, this is less likely to result in actual
12041 // bugs -- if the result is cast back to an unsigned type, it will have the
12042 // expected value. Thus we place this behind a different warning that can be
12043 // turned off separately if needed.
12044 if (ResultBits - 1 == LeftSize) {
12045 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12046 << HexResult << LHSType
12047 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12048 return;
12049 }
12050
12051 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12052 << HexResult.str() << Result.getSignificantBits() << LHSType
12053 << Left.getBitWidth() << LHS.get()->getSourceRange()
12054 << RHS.get()->getSourceRange();
12055}
12056
12057/// Return the resulting type when a vector is shifted
12058/// by a scalar or vector shift amount.
12059static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12060 SourceLocation Loc, bool IsCompAssign) {
12061 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12062 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12063 !LHS.get()->getType()->isVectorType()) {
12064 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12065 << RHS.get()->getType() << LHS.get()->getType()
12066 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12067 return QualType();
12068 }
12069
12070 if (!IsCompAssign) {
12071 LHS = S.UsualUnaryConversions(E: LHS.get());
12072 if (LHS.isInvalid()) return QualType();
12073 }
12074
12075 RHS = S.UsualUnaryConversions(E: RHS.get());
12076 if (RHS.isInvalid()) return QualType();
12077
12078 QualType LHSType = LHS.get()->getType();
12079 // Note that LHS might be a scalar because the routine calls not only in
12080 // OpenCL case.
12081 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12082 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12083
12084 // Note that RHS might not be a vector.
12085 QualType RHSType = RHS.get()->getType();
12086 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12087 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12088
12089 // Do not allow shifts for boolean vectors.
12090 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12091 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12092 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12093 << LHS.get()->getType() << RHS.get()->getType()
12094 << LHS.get()->getSourceRange();
12095 return QualType();
12096 }
12097
12098 // The operands need to be integers.
12099 if (!LHSEleType->isIntegerType()) {
12100 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12101 << LHS.get()->getType() << LHS.get()->getSourceRange();
12102 return QualType();
12103 }
12104
12105 if (!RHSEleType->isIntegerType()) {
12106 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12107 << RHS.get()->getType() << RHS.get()->getSourceRange();
12108 return QualType();
12109 }
12110
12111 if (!LHSVecTy) {
12112 assert(RHSVecTy);
12113 if (IsCompAssign)
12114 return RHSType;
12115 if (LHSEleType != RHSEleType) {
12116 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12117 LHSEleType = RHSEleType;
12118 }
12119 QualType VecTy =
12120 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12121 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12122 LHSType = VecTy;
12123 } else if (RHSVecTy) {
12124 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12125 // are applied component-wise. So if RHS is a vector, then ensure
12126 // that the number of elements is the same as LHS...
12127 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12128 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12129 << LHS.get()->getType() << RHS.get()->getType()
12130 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12131 return QualType();
12132 }
12133 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12134 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12135 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12136 if (LHSBT != RHSBT &&
12137 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12138 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12139 << LHS.get()->getType() << RHS.get()->getType()
12140 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12141 }
12142 }
12143 } else {
12144 // ...else expand RHS to match the number of elements in LHS.
12145 QualType VecTy =
12146 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12147 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12148 }
12149
12150 return LHSType;
12151}
12152
12153static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12154 ExprResult &RHS, SourceLocation Loc,
12155 bool IsCompAssign) {
12156 if (!IsCompAssign) {
12157 LHS = S.UsualUnaryConversions(E: LHS.get());
12158 if (LHS.isInvalid())
12159 return QualType();
12160 }
12161
12162 RHS = S.UsualUnaryConversions(E: RHS.get());
12163 if (RHS.isInvalid())
12164 return QualType();
12165
12166 QualType LHSType = LHS.get()->getType();
12167 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12168 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12169 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12170 : LHSType;
12171
12172 // Note that RHS might not be a vector
12173 QualType RHSType = RHS.get()->getType();
12174 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12175 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12176 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12177 : RHSType;
12178
12179 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12180 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12181 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12182 << LHSType << RHSType << LHS.get()->getSourceRange();
12183 return QualType();
12184 }
12185
12186 if (!LHSEleType->isIntegerType()) {
12187 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12188 << LHS.get()->getType() << LHS.get()->getSourceRange();
12189 return QualType();
12190 }
12191
12192 if (!RHSEleType->isIntegerType()) {
12193 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12194 << RHS.get()->getType() << RHS.get()->getSourceRange();
12195 return QualType();
12196 }
12197
12198 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12199 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12200 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12201 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12202 << LHSType << RHSType << LHS.get()->getSourceRange()
12203 << RHS.get()->getSourceRange();
12204 return QualType();
12205 }
12206
12207 if (!LHSType->isSveVLSBuiltinType()) {
12208 assert(RHSType->isSveVLSBuiltinType());
12209 if (IsCompAssign)
12210 return RHSType;
12211 if (LHSEleType != RHSEleType) {
12212 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12213 LHSEleType = RHSEleType;
12214 }
12215 const llvm::ElementCount VecSize =
12216 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12217 QualType VecTy =
12218 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12219 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12220 LHSType = VecTy;
12221 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12222 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12223 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12224 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12225 << LHSType << RHSType << LHS.get()->getSourceRange()
12226 << RHS.get()->getSourceRange();
12227 return QualType();
12228 }
12229 } else {
12230 const llvm::ElementCount VecSize =
12231 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12232 if (LHSEleType != RHSEleType) {
12233 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12234 RHSEleType = LHSEleType;
12235 }
12236 QualType VecTy =
12237 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12238 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12239 }
12240
12241 return LHSType;
12242}
12243
12244// C99 6.5.7
12245QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12246 SourceLocation Loc, BinaryOperatorKind Opc,
12247 bool IsCompAssign) {
12248 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12249
12250 // Vector shifts promote their scalar inputs to vector type.
12251 if (LHS.get()->getType()->isVectorType() ||
12252 RHS.get()->getType()->isVectorType()) {
12253 if (LangOpts.ZVector) {
12254 // The shift operators for the z vector extensions work basically
12255 // like general shifts, except that neither the LHS nor the RHS is
12256 // allowed to be a "vector bool".
12257 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12258 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12259 return InvalidOperands(Loc, LHS, RHS);
12260 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12261 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12262 return InvalidOperands(Loc, LHS, RHS);
12263 }
12264 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12265 }
12266
12267 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12268 RHS.get()->getType()->isSveVLSBuiltinType())
12269 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12270
12271 // Shifts don't perform usual arithmetic conversions, they just do integer
12272 // promotions on each operand. C99 6.5.7p3
12273
12274 // For the LHS, do usual unary conversions, but then reset them away
12275 // if this is a compound assignment.
12276 ExprResult OldLHS = LHS;
12277 LHS = UsualUnaryConversions(E: LHS.get());
12278 if (LHS.isInvalid())
12279 return QualType();
12280 QualType LHSType = LHS.get()->getType();
12281 if (IsCompAssign) LHS = OldLHS;
12282
12283 // The RHS is simpler.
12284 RHS = UsualUnaryConversions(E: RHS.get());
12285 if (RHS.isInvalid())
12286 return QualType();
12287 QualType RHSType = RHS.get()->getType();
12288
12289 // C99 6.5.7p2: Each of the operands shall have integer type.
12290 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12291 if ((!LHSType->isFixedPointOrIntegerType() &&
12292 !LHSType->hasIntegerRepresentation()) ||
12293 !RHSType->hasIntegerRepresentation()) {
12294 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12295 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12296 return ResultTy;
12297 }
12298
12299 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12300
12301 // "The type of the result is that of the promoted left operand."
12302 return LHSType;
12303}
12304
12305/// Diagnose bad pointer comparisons.
12306static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12307 ExprResult &LHS, ExprResult &RHS,
12308 bool IsError) {
12309 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12310 : diag::ext_typecheck_comparison_of_distinct_pointers)
12311 << LHS.get()->getType() << RHS.get()->getType()
12312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12313}
12314
12315/// Returns false if the pointers are converted to a composite type,
12316/// true otherwise.
12317static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12318 ExprResult &LHS, ExprResult &RHS) {
12319 // C++ [expr.rel]p2:
12320 // [...] Pointer conversions (4.10) and qualification
12321 // conversions (4.4) are performed on pointer operands (or on
12322 // a pointer operand and a null pointer constant) to bring
12323 // them to their composite pointer type. [...]
12324 //
12325 // C++ [expr.eq]p1 uses the same notion for (in)equality
12326 // comparisons of pointers.
12327
12328 QualType LHSType = LHS.get()->getType();
12329 QualType RHSType = RHS.get()->getType();
12330 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12331 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12332
12333 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12334 if (T.isNull()) {
12335 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12336 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12337 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12338 else
12339 S.InvalidOperands(Loc, LHS, RHS);
12340 return true;
12341 }
12342
12343 return false;
12344}
12345
12346static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12347 ExprResult &LHS,
12348 ExprResult &RHS,
12349 bool IsError) {
12350 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12351 : diag::ext_typecheck_comparison_of_fptr_to_void)
12352 << LHS.get()->getType() << RHS.get()->getType()
12353 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12354}
12355
12356static bool isObjCObjectLiteral(ExprResult &E) {
12357 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12358 case Stmt::ObjCArrayLiteralClass:
12359 case Stmt::ObjCDictionaryLiteralClass:
12360 case Stmt::ObjCStringLiteralClass:
12361 case Stmt::ObjCBoxedExprClass:
12362 return true;
12363 default:
12364 // Note that ObjCBoolLiteral is NOT an object literal!
12365 return false;
12366 }
12367}
12368
12369static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12370 const ObjCObjectPointerType *Type =
12371 LHS->getType()->getAs<ObjCObjectPointerType>();
12372
12373 // If this is not actually an Objective-C object, bail out.
12374 if (!Type)
12375 return false;
12376
12377 // Get the LHS object's interface type.
12378 QualType InterfaceType = Type->getPointeeType();
12379
12380 // If the RHS isn't an Objective-C object, bail out.
12381 if (!RHS->getType()->isObjCObjectPointerType())
12382 return false;
12383
12384 // Try to find the -isEqual: method.
12385 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12386 ObjCMethodDecl *Method =
12387 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12388 /*IsInstance=*/true);
12389 if (!Method) {
12390 if (Type->isObjCIdType()) {
12391 // For 'id', just check the global pool.
12392 Method =
12393 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12394 /*receiverId=*/receiverIdOrClass: true);
12395 } else {
12396 // Check protocols.
12397 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12398 /*IsInstance=*/true);
12399 }
12400 }
12401
12402 if (!Method)
12403 return false;
12404
12405 QualType T = Method->parameters()[0]->getType();
12406 if (!T->isObjCObjectPointerType())
12407 return false;
12408
12409 QualType R = Method->getReturnType();
12410 if (!R->isScalarType())
12411 return false;
12412
12413 return true;
12414}
12415
12416static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12417 ExprResult &LHS, ExprResult &RHS,
12418 BinaryOperator::Opcode Opc){
12419 Expr *Literal;
12420 Expr *Other;
12421 if (isObjCObjectLiteral(E&: LHS)) {
12422 Literal = LHS.get();
12423 Other = RHS.get();
12424 } else {
12425 Literal = RHS.get();
12426 Other = LHS.get();
12427 }
12428
12429 // Don't warn on comparisons against nil.
12430 Other = Other->IgnoreParenCasts();
12431 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12432 NPC: Expr::NPC_ValueDependentIsNotNull))
12433 return;
12434
12435 // This should be kept in sync with warn_objc_literal_comparison.
12436 // LK_String should always be after the other literals, since it has its own
12437 // warning flag.
12438 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12439 assert(LiteralKind != SemaObjC::LK_Block);
12440 if (LiteralKind == SemaObjC::LK_None) {
12441 llvm_unreachable("Unknown Objective-C object literal kind");
12442 }
12443
12444 if (LiteralKind == SemaObjC::LK_String)
12445 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12446 << Literal->getSourceRange();
12447 else
12448 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12449 << LiteralKind << Literal->getSourceRange();
12450
12451 if (BinaryOperator::isEqualityOp(Opc) &&
12452 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12453 SourceLocation Start = LHS.get()->getBeginLoc();
12454 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12455 CharSourceRange OpRange =
12456 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12457
12458 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12459 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12460 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12461 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12462 }
12463}
12464
12465/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12466static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12467 ExprResult &RHS, SourceLocation Loc,
12468 BinaryOperatorKind Opc) {
12469 // Check that left hand side is !something.
12470 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12471 if (!UO || UO->getOpcode() != UO_LNot) return;
12472
12473 // Only check if the right hand side is non-bool arithmetic type.
12474 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12475
12476 // Make sure that the something in !something is not bool.
12477 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12478 if (SubExpr->isKnownToHaveBooleanValue()) return;
12479
12480 // Emit warning.
12481 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12482 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12483 << Loc << IsBitwiseOp;
12484
12485 // First note suggest !(x < y)
12486 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12487 SourceLocation FirstClose = RHS.get()->getEndLoc();
12488 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12489 if (FirstClose.isInvalid())
12490 FirstOpen = SourceLocation();
12491 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12492 << IsBitwiseOp
12493 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12494 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12495
12496 // Second note suggests (!x) < y
12497 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12498 SourceLocation SecondClose = LHS.get()->getEndLoc();
12499 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12500 if (SecondClose.isInvalid())
12501 SecondOpen = SourceLocation();
12502 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12503 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12504 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12505}
12506
12507// Returns true if E refers to a non-weak array.
12508static bool checkForArray(const Expr *E) {
12509 const ValueDecl *D = nullptr;
12510 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12511 D = DR->getDecl();
12512 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12513 if (Mem->isImplicitAccess())
12514 D = Mem->getMemberDecl();
12515 }
12516 if (!D)
12517 return false;
12518 return D->getType()->isArrayType() && !D->isWeak();
12519}
12520
12521/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12522/// pointer and size is an unsigned integer. Return whether the result is
12523/// always true/false.
12524static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12525 const Expr *RHS,
12526 BinaryOperatorKind Opc) {
12527 if (!LHS->getType()->isPointerType() ||
12528 S.getLangOpts().PointerOverflowDefined)
12529 return std::nullopt;
12530
12531 // Canonicalize to >= or < predicate.
12532 switch (Opc) {
12533 case BO_GE:
12534 case BO_LT:
12535 break;
12536 case BO_GT:
12537 std::swap(a&: LHS, b&: RHS);
12538 Opc = BO_LT;
12539 break;
12540 case BO_LE:
12541 std::swap(a&: LHS, b&: RHS);
12542 Opc = BO_GE;
12543 break;
12544 default:
12545 return std::nullopt;
12546 }
12547
12548 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12549 if (!BO || BO->getOpcode() != BO_Add)
12550 return std::nullopt;
12551
12552 Expr *Other;
12553 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12554 Other = BO->getRHS();
12555 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12556 Other = BO->getLHS();
12557 else
12558 return std::nullopt;
12559
12560 if (!Other->getType()->isUnsignedIntegerType())
12561 return std::nullopt;
12562
12563 return Opc == BO_GE;
12564}
12565
12566/// Diagnose some forms of syntactically-obvious tautological comparison.
12567static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12568 Expr *LHS, Expr *RHS,
12569 BinaryOperatorKind Opc) {
12570 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12571 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12572
12573 QualType LHSType = LHS->getType();
12574 QualType RHSType = RHS->getType();
12575 if (LHSType->hasFloatingRepresentation() ||
12576 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12577 S.inTemplateInstantiation())
12578 return;
12579
12580 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12581 // Tautological diagnostics.
12582 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12583 return;
12584
12585 // Comparisons between two array types are ill-formed for operator<=>, so
12586 // we shouldn't emit any additional warnings about it.
12587 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12588 return;
12589
12590 // For non-floating point types, check for self-comparisons of the form
12591 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12592 // often indicate logic errors in the program.
12593 //
12594 // NOTE: Don't warn about comparison expressions resulting from macro
12595 // expansion. Also don't warn about comparisons which are only self
12596 // comparisons within a template instantiation. The warnings should catch
12597 // obvious cases in the definition of the template anyways. The idea is to
12598 // warn when the typed comparison operator will always evaluate to the same
12599 // result.
12600
12601 // Used for indexing into %select in warn_comparison_always
12602 enum {
12603 AlwaysConstant,
12604 AlwaysTrue,
12605 AlwaysFalse,
12606 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12607 };
12608
12609 // C++1a [array.comp]:
12610 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12611 // operands of array type.
12612 // C++2a [depr.array.comp]:
12613 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12614 // operands of array type are deprecated.
12615 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12616 RHSStripped->getType()->isArrayType()) {
12617 auto IsDeprArrayComparionIgnored =
12618 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12619 auto DiagID = S.getLangOpts().CPlusPlus26
12620 ? diag::warn_array_comparison_cxx26
12621 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12622 ? diag::warn_array_comparison
12623 : diag::warn_depr_array_comparison;
12624 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12625 << LHSStripped->getType() << RHSStripped->getType();
12626 // Carry on to produce the tautological comparison warning, if this
12627 // expression is potentially-evaluated, we can resolve the array to a
12628 // non-weak declaration, and so on.
12629 }
12630
12631 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12632 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12633 unsigned Result;
12634 switch (Opc) {
12635 case BO_EQ:
12636 case BO_LE:
12637 case BO_GE:
12638 Result = AlwaysTrue;
12639 break;
12640 case BO_NE:
12641 case BO_LT:
12642 case BO_GT:
12643 Result = AlwaysFalse;
12644 break;
12645 case BO_Cmp:
12646 Result = AlwaysEqual;
12647 break;
12648 default:
12649 Result = AlwaysConstant;
12650 break;
12651 }
12652 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12653 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12654 << 0 /*self-comparison*/
12655 << Result);
12656 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12657 // What is it always going to evaluate to?
12658 unsigned Result;
12659 switch (Opc) {
12660 case BO_EQ: // e.g. array1 == array2
12661 Result = AlwaysFalse;
12662 break;
12663 case BO_NE: // e.g. array1 != array2
12664 Result = AlwaysTrue;
12665 break;
12666 default: // e.g. array1 <= array2
12667 // The best we can say is 'a constant'
12668 Result = AlwaysConstant;
12669 break;
12670 }
12671 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12672 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12673 << 1 /*array comparison*/
12674 << Result);
12675 } else if (std::optional<bool> Res =
12676 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12677 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12678 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12679 << 2 /*pointer comparison*/
12680 << (*Res ? AlwaysTrue : AlwaysFalse));
12681 }
12682 }
12683
12684 if (isa<CastExpr>(Val: LHSStripped))
12685 LHSStripped = LHSStripped->IgnoreParenCasts();
12686 if (isa<CastExpr>(Val: RHSStripped))
12687 RHSStripped = RHSStripped->IgnoreParenCasts();
12688
12689 // Warn about comparisons against a string constant (unless the other
12690 // operand is null); the user probably wants string comparison function.
12691 Expr *LiteralString = nullptr;
12692 Expr *LiteralStringStripped = nullptr;
12693 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12694 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12695 NPC: Expr::NPC_ValueDependentIsNull)) {
12696 LiteralString = LHS;
12697 LiteralStringStripped = LHSStripped;
12698 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12699 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12700 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12701 NPC: Expr::NPC_ValueDependentIsNull)) {
12702 LiteralString = RHS;
12703 LiteralStringStripped = RHSStripped;
12704 }
12705
12706 if (LiteralString) {
12707 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12708 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12709 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12710 << LiteralString->getSourceRange());
12711 }
12712}
12713
12714static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12715 switch (CK) {
12716 default: {
12717#ifndef NDEBUG
12718 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12719 << "\n";
12720#endif
12721 llvm_unreachable("unhandled cast kind");
12722 }
12723 case CK_UserDefinedConversion:
12724 return ICK_Identity;
12725 case CK_LValueToRValue:
12726 return ICK_Lvalue_To_Rvalue;
12727 case CK_ArrayToPointerDecay:
12728 return ICK_Array_To_Pointer;
12729 case CK_FunctionToPointerDecay:
12730 return ICK_Function_To_Pointer;
12731 case CK_IntegralCast:
12732 return ICK_Integral_Conversion;
12733 case CK_FloatingCast:
12734 return ICK_Floating_Conversion;
12735 case CK_IntegralToFloating:
12736 case CK_FloatingToIntegral:
12737 return ICK_Floating_Integral;
12738 case CK_IntegralComplexCast:
12739 case CK_FloatingComplexCast:
12740 case CK_FloatingComplexToIntegralComplex:
12741 case CK_IntegralComplexToFloatingComplex:
12742 return ICK_Complex_Conversion;
12743 case CK_FloatingComplexToReal:
12744 case CK_FloatingRealToComplex:
12745 case CK_IntegralComplexToReal:
12746 case CK_IntegralRealToComplex:
12747 return ICK_Complex_Real;
12748 case CK_HLSLArrayRValue:
12749 return ICK_HLSL_Array_RValue;
12750 }
12751}
12752
12753static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12754 QualType FromType,
12755 SourceLocation Loc) {
12756 // Check for a narrowing implicit conversion.
12757 StandardConversionSequence SCS;
12758 SCS.setAsIdentityConversion();
12759 SCS.setToType(Idx: 0, T: FromType);
12760 SCS.setToType(Idx: 1, T: ToType);
12761 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12762 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12763
12764 APValue PreNarrowingValue;
12765 QualType PreNarrowingType;
12766 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12767 ConstantType&: PreNarrowingType,
12768 /*IgnoreFloatToIntegralConversion*/ true)) {
12769 case NK_Dependent_Narrowing:
12770 // Implicit conversion to a narrower type, but the expression is
12771 // value-dependent so we can't tell whether it's actually narrowing.
12772 case NK_Not_Narrowing:
12773 return false;
12774
12775 case NK_Constant_Narrowing:
12776 // Implicit conversion to a narrower type, and the value is not a constant
12777 // expression.
12778 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12779 << /*Constant*/ 1
12780 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12781 return true;
12782
12783 case NK_Variable_Narrowing:
12784 // Implicit conversion to a narrower type, and the value is not a constant
12785 // expression.
12786 case NK_Type_Narrowing:
12787 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12788 << /*Constant*/ 0 << FromType << ToType;
12789 // TODO: It's not a constant expression, but what if the user intended it
12790 // to be? Can we produce notes to help them figure out why it isn't?
12791 return true;
12792 }
12793 llvm_unreachable("unhandled case in switch");
12794}
12795
12796static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12797 ExprResult &LHS,
12798 ExprResult &RHS,
12799 SourceLocation Loc) {
12800 QualType LHSType = LHS.get()->getType();
12801 QualType RHSType = RHS.get()->getType();
12802 // Dig out the original argument type and expression before implicit casts
12803 // were applied. These are the types/expressions we need to check the
12804 // [expr.spaceship] requirements against.
12805 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12806 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12807 QualType LHSStrippedType = LHSStripped.get()->getType();
12808 QualType RHSStrippedType = RHSStripped.get()->getType();
12809
12810 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12811 // other is not, the program is ill-formed.
12812 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12813 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12814 return QualType();
12815 }
12816
12817 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12818 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12819 RHSStrippedType->isEnumeralType();
12820 if (NumEnumArgs == 1) {
12821 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12822 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12823 if (OtherTy->hasFloatingRepresentation()) {
12824 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12825 return QualType();
12826 }
12827 }
12828 if (NumEnumArgs == 2) {
12829 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12830 // type E, the operator yields the result of converting the operands
12831 // to the underlying type of E and applying <=> to the converted operands.
12832 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12833 S.InvalidOperands(Loc, LHS, RHS);
12834 return QualType();
12835 }
12836 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12837 assert(IntType->isArithmeticType());
12838
12839 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12840 // promote the boolean type, and all other promotable integer types, to
12841 // avoid this.
12842 if (S.Context.isPromotableIntegerType(T: IntType))
12843 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12844
12845 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12846 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12847 LHSType = RHSType = IntType;
12848 }
12849
12850 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12851 // usual arithmetic conversions are applied to the operands.
12852 QualType Type =
12853 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12854 if (LHS.isInvalid() || RHS.isInvalid())
12855 return QualType();
12856 if (Type.isNull()) {
12857 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12858 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12859 return ResultTy;
12860 }
12861
12862 std::optional<ComparisonCategoryType> CCT =
12863 getComparisonCategoryForBuiltinCmp(T: Type);
12864 if (!CCT)
12865 return S.InvalidOperands(Loc, LHS, RHS);
12866
12867 bool HasNarrowing = checkThreeWayNarrowingConversion(
12868 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12869 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12870 Loc: RHS.get()->getBeginLoc());
12871 if (HasNarrowing)
12872 return QualType();
12873
12874 assert(!Type.isNull() && "composite type for <=> has not been set");
12875
12876 return S.CheckComparisonCategoryType(
12877 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12878}
12879
12880static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12881 ExprResult &RHS,
12882 SourceLocation Loc,
12883 BinaryOperatorKind Opc) {
12884 if (Opc == BO_Cmp)
12885 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12886
12887 // C99 6.5.8p3 / C99 6.5.9p4
12888 QualType Type =
12889 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12890 if (LHS.isInvalid() || RHS.isInvalid())
12891 return QualType();
12892 if (Type.isNull()) {
12893 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12894 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12895 return ResultTy;
12896 }
12897 assert(Type->isArithmeticType() || Type->isEnumeralType());
12898
12899 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12900 return S.InvalidOperands(Loc, LHS, RHS);
12901
12902 // Check for comparisons of floating point operands using != and ==.
12903 if (Type->hasFloatingRepresentation())
12904 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12905
12906 // The result of comparisons is 'bool' in C++, 'int' in C.
12907 return S.Context.getLogicalOperationType();
12908}
12909
12910void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12911 if (!NullE.get()->getType()->isAnyPointerType())
12912 return;
12913 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12914 if (!E.get()->getType()->isAnyPointerType() &&
12915 E.get()->isNullPointerConstant(Ctx&: Context,
12916 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12917 Expr::NPCK_ZeroExpression) {
12918 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12919 if (CL->getValue() == 0)
12920 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12921 << NullValue
12922 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12923 Code: NullValue ? "NULL" : "(void *)0");
12924 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12925 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12926 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12927 if (T == Context.CharTy)
12928 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12929 << NullValue
12930 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12931 Code: NullValue ? "NULL" : "(void *)0");
12932 }
12933 }
12934}
12935
12936// C99 6.5.8, C++ [expr.rel]
12937QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12938 SourceLocation Loc,
12939 BinaryOperatorKind Opc) {
12940 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12941 bool IsThreeWay = Opc == BO_Cmp;
12942 bool IsOrdered = IsRelational || IsThreeWay;
12943 auto IsAnyPointerType = [](ExprResult E) {
12944 QualType Ty = E.get()->getType();
12945 return Ty->isPointerType() || Ty->isMemberPointerType();
12946 };
12947
12948 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12949 // type, array-to-pointer, ..., conversions are performed on both operands to
12950 // bring them to their composite type.
12951 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12952 // any type-related checks.
12953 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12954 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12955 if (LHS.isInvalid())
12956 return QualType();
12957 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12958 if (RHS.isInvalid())
12959 return QualType();
12960 } else {
12961 LHS = DefaultLvalueConversion(E: LHS.get());
12962 if (LHS.isInvalid())
12963 return QualType();
12964 RHS = DefaultLvalueConversion(E: RHS.get());
12965 if (RHS.isInvalid())
12966 return QualType();
12967 }
12968
12969 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12970 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12971 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12972 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12973 }
12974
12975 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
12976 RHS.get()->getType()->isConstantMatrixType()))
12977 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
12978
12979 // Handle vector comparisons separately.
12980 if (LHS.get()->getType()->isVectorType() ||
12981 RHS.get()->getType()->isVectorType())
12982 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12983
12984 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12985 RHS.get()->getType()->isSveVLSBuiltinType())
12986 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12987
12988 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12989 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12990
12991 QualType LHSType = LHS.get()->getType();
12992 QualType RHSType = RHS.get()->getType();
12993 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12994 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12995 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
12996
12997 if ((LHSType->isPointerType() &&
12998 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12999 (RHSType->isPointerType() &&
13000 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13001 return InvalidOperands(Loc, LHS, RHS);
13002
13003 const Expr::NullPointerConstantKind LHSNullKind =
13004 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13005 const Expr::NullPointerConstantKind RHSNullKind =
13006 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13007 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13008 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13009
13010 auto computeResultTy = [&]() {
13011 if (Opc != BO_Cmp)
13012 return QualType(Context.getLogicalOperationType());
13013 assert(getLangOpts().CPlusPlus);
13014 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13015
13016 QualType CompositeTy = LHS.get()->getType();
13017 assert(!CompositeTy->isReferenceType());
13018
13019 std::optional<ComparisonCategoryType> CCT =
13020 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13021 if (!CCT)
13022 return InvalidOperands(Loc, LHS, RHS);
13023
13024 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13025 // P0946R0: Comparisons between a null pointer constant and an object
13026 // pointer result in std::strong_equality, which is ill-formed under
13027 // P1959R0.
13028 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13029 << (LHSIsNull ? LHS.get()->getSourceRange()
13030 : RHS.get()->getSourceRange());
13031 return QualType();
13032 }
13033
13034 return CheckComparisonCategoryType(
13035 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13036 };
13037
13038 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13039 bool IsEquality = Opc == BO_EQ;
13040 if (RHSIsNull)
13041 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13042 Range: RHS.get()->getSourceRange());
13043 else
13044 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13045 Range: LHS.get()->getSourceRange());
13046 }
13047
13048 if (IsOrdered && LHSType->isFunctionPointerType() &&
13049 RHSType->isFunctionPointerType()) {
13050 // Valid unless a relational comparison of function pointers
13051 bool IsError = Opc == BO_Cmp;
13052 auto DiagID =
13053 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13054 : getLangOpts().CPlusPlus
13055 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13056 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13057 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13058 << RHS.get()->getSourceRange();
13059 if (IsError)
13060 return QualType();
13061 }
13062
13063 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13064 (RHSType->isIntegerType() && !RHSIsNull)) {
13065 // Skip normal pointer conversion checks in this case; we have better
13066 // diagnostics for this below.
13067 } else if (getLangOpts().CPlusPlus) {
13068 // Equality comparison of a function pointer to a void pointer is invalid,
13069 // but we allow it as an extension.
13070 // FIXME: If we really want to allow this, should it be part of composite
13071 // pointer type computation so it works in conditionals too?
13072 if (!IsOrdered &&
13073 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13074 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13075 // This is a gcc extension compatibility comparison.
13076 // In a SFINAE context, we treat this as a hard error to maintain
13077 // conformance with the C++ standard.
13078 bool IsError = isSFINAEContext();
13079 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13080
13081 if (IsError)
13082 return QualType();
13083
13084 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13085 return computeResultTy();
13086 }
13087
13088 // C++ [expr.eq]p2:
13089 // If at least one operand is a pointer [...] bring them to their
13090 // composite pointer type.
13091 // C++ [expr.spaceship]p6
13092 // If at least one of the operands is of pointer type, [...] bring them
13093 // to their composite pointer type.
13094 // C++ [expr.rel]p2:
13095 // If both operands are pointers, [...] bring them to their composite
13096 // pointer type.
13097 // For <=>, the only valid non-pointer types are arrays and functions, and
13098 // we already decayed those, so this is really the same as the relational
13099 // comparison rule.
13100 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13101 (IsOrdered ? 2 : 1) &&
13102 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13103 RHSType->isObjCObjectPointerType()))) {
13104 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13105 return QualType();
13106 return computeResultTy();
13107 }
13108 } else if (LHSType->isPointerType() &&
13109 RHSType->isPointerType()) { // C99 6.5.8p2
13110 // All of the following pointer-related warnings are GCC extensions, except
13111 // when handling null pointer constants.
13112 QualType LCanPointeeTy =
13113 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13114 QualType RCanPointeeTy =
13115 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13116
13117 // C99 6.5.9p2 and C99 6.5.8p2
13118 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13119 T2: RCanPointeeTy.getUnqualifiedType())) {
13120 if (IsRelational) {
13121 // Pointers both need to point to complete or incomplete types
13122 if ((LCanPointeeTy->isIncompleteType() !=
13123 RCanPointeeTy->isIncompleteType()) &&
13124 !getLangOpts().C11) {
13125 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13126 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13127 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13128 << RCanPointeeTy->isIncompleteType();
13129 }
13130 }
13131 } else if (!IsRelational &&
13132 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13133 // Valid unless comparison between non-null pointer and function pointer
13134 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13135 && !LHSIsNull && !RHSIsNull)
13136 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13137 /*isError*/IsError: false);
13138 } else {
13139 // Invalid
13140 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13141 }
13142 if (LCanPointeeTy != RCanPointeeTy) {
13143 // Treat NULL constant as a special case in OpenCL.
13144 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13145 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13146 Ctx: getASTContext())) {
13147 Diag(Loc,
13148 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13149 << LHSType << RHSType << 0 /* comparison */
13150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13151 }
13152 }
13153 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13154 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13155 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13156 : CK_BitCast;
13157
13158 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13159 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13160 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13161 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13162 bool ChangingCFIUncheckedCallee =
13163 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13164
13165 if (LHSIsNull && !RHSIsNull)
13166 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13167 else if (!ChangingCFIUncheckedCallee)
13168 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13169 }
13170 return computeResultTy();
13171 }
13172
13173
13174 // C++ [expr.eq]p4:
13175 // Two operands of type std::nullptr_t or one operand of type
13176 // std::nullptr_t and the other a null pointer constant compare
13177 // equal.
13178 // C23 6.5.9p5:
13179 // If both operands have type nullptr_t or one operand has type nullptr_t
13180 // and the other is a null pointer constant, they compare equal if the
13181 // former is a null pointer.
13182 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13183 if (LHSType->isNullPtrType()) {
13184 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13185 return computeResultTy();
13186 }
13187 if (RHSType->isNullPtrType()) {
13188 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13189 return computeResultTy();
13190 }
13191 }
13192
13193 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13194 // C23 6.5.9p6:
13195 // Otherwise, at least one operand is a pointer. If one is a pointer and
13196 // the other is a null pointer constant or has type nullptr_t, they
13197 // compare equal
13198 if (LHSIsNull && RHSType->isPointerType()) {
13199 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13200 return computeResultTy();
13201 }
13202 if (RHSIsNull && LHSType->isPointerType()) {
13203 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13204 return computeResultTy();
13205 }
13206 }
13207
13208 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13209 // These aren't covered by the composite pointer type rules.
13210 if (!IsOrdered && RHSType->isNullPtrType() &&
13211 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13212 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13213 return computeResultTy();
13214 }
13215 if (!IsOrdered && LHSType->isNullPtrType() &&
13216 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13217 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13218 return computeResultTy();
13219 }
13220
13221 if (getLangOpts().CPlusPlus) {
13222 if (IsRelational &&
13223 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13224 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13225 // HACK: Relational comparison of nullptr_t against a pointer type is
13226 // invalid per DR583, but we allow it within std::less<> and friends,
13227 // since otherwise common uses of it break.
13228 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13229 // friends to have std::nullptr_t overload candidates.
13230 DeclContext *DC = CurContext;
13231 if (isa<FunctionDecl>(Val: DC))
13232 DC = DC->getParent();
13233 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13234 if (CTSD->isInStdNamespace() &&
13235 llvm::StringSwitch<bool>(CTSD->getName())
13236 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13237 .Default(Value: false)) {
13238 if (RHSType->isNullPtrType())
13239 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13240 else
13241 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13242 return computeResultTy();
13243 }
13244 }
13245 }
13246
13247 // C++ [expr.eq]p2:
13248 // If at least one operand is a pointer to member, [...] bring them to
13249 // their composite pointer type.
13250 if (!IsOrdered &&
13251 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13252 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13253 return QualType();
13254 else
13255 return computeResultTy();
13256 }
13257 }
13258
13259 // Handle block pointer types.
13260 if (!IsOrdered && LHSType->isBlockPointerType() &&
13261 RHSType->isBlockPointerType()) {
13262 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13263 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13264
13265 if (!LHSIsNull && !RHSIsNull &&
13266 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13267 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13268 << LHSType << RHSType << LHS.get()->getSourceRange()
13269 << RHS.get()->getSourceRange();
13270 }
13271 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13272 return computeResultTy();
13273 }
13274
13275 // Allow block pointers to be compared with null pointer constants.
13276 if (!IsOrdered
13277 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13278 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13279 if (!LHSIsNull && !RHSIsNull) {
13280 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13281 ->getPointeeType()->isVoidType())
13282 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13283 ->getPointeeType()->isVoidType())))
13284 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13285 << LHSType << RHSType << LHS.get()->getSourceRange()
13286 << RHS.get()->getSourceRange();
13287 }
13288 if (LHSIsNull && !RHSIsNull)
13289 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13290 CK: RHSType->isPointerType() ? CK_BitCast
13291 : CK_AnyPointerToBlockPointerCast);
13292 else
13293 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13294 CK: LHSType->isPointerType() ? CK_BitCast
13295 : CK_AnyPointerToBlockPointerCast);
13296 return computeResultTy();
13297 }
13298
13299 if (LHSType->isObjCObjectPointerType() ||
13300 RHSType->isObjCObjectPointerType()) {
13301 const PointerType *LPT = LHSType->getAs<PointerType>();
13302 const PointerType *RPT = RHSType->getAs<PointerType>();
13303 if (LPT || RPT) {
13304 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13305 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13306
13307 if (!LPtrToVoid && !RPtrToVoid &&
13308 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13309 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13310 /*isError*/IsError: false);
13311 }
13312 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13313 // the RHS, but we have test coverage for this behavior.
13314 // FIXME: Consider using convertPointersToCompositeType in C++.
13315 if (LHSIsNull && !RHSIsNull) {
13316 Expr *E = LHS.get();
13317 if (getLangOpts().ObjCAutoRefCount)
13318 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13319 CCK: CheckedConversionKind::Implicit);
13320 LHS = ImpCastExprToType(E, Type: RHSType,
13321 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13322 }
13323 else {
13324 Expr *E = RHS.get();
13325 if (getLangOpts().ObjCAutoRefCount)
13326 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13327 CCK: CheckedConversionKind::Implicit,
13328 /*Diagnose=*/true,
13329 /*DiagnoseCFAudited=*/false, Opc);
13330 RHS = ImpCastExprToType(E, Type: LHSType,
13331 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13332 }
13333 return computeResultTy();
13334 }
13335 if (LHSType->isObjCObjectPointerType() &&
13336 RHSType->isObjCObjectPointerType()) {
13337 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13338 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13339 /*isError*/IsError: false);
13340 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13341 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13342
13343 if (LHSIsNull && !RHSIsNull)
13344 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13345 else
13346 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13347 return computeResultTy();
13348 }
13349
13350 if (!IsOrdered && LHSType->isBlockPointerType() &&
13351 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13352 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13353 CK: CK_BlockPointerToObjCPointerCast);
13354 return computeResultTy();
13355 } else if (!IsOrdered &&
13356 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13357 RHSType->isBlockPointerType()) {
13358 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13359 CK: CK_BlockPointerToObjCPointerCast);
13360 return computeResultTy();
13361 }
13362 }
13363 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13364 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13365 unsigned DiagID = 0;
13366 bool isError = false;
13367 if (LangOpts.DebuggerSupport) {
13368 // Under a debugger, allow the comparison of pointers to integers,
13369 // since users tend to want to compare addresses.
13370 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13371 (RHSIsNull && RHSType->isIntegerType())) {
13372 if (IsOrdered) {
13373 isError = getLangOpts().CPlusPlus;
13374 DiagID =
13375 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13376 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13377 }
13378 } else if (getLangOpts().CPlusPlus) {
13379 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13380 isError = true;
13381 } else if (IsOrdered)
13382 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13383 else
13384 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13385
13386 if (DiagID) {
13387 Diag(Loc, DiagID)
13388 << LHSType << RHSType << LHS.get()->getSourceRange()
13389 << RHS.get()->getSourceRange();
13390 if (isError)
13391 return QualType();
13392 }
13393
13394 if (LHSType->isIntegerType())
13395 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13396 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13397 else
13398 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13399 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13400 return computeResultTy();
13401 }
13402
13403 // Handle block pointers.
13404 if (!IsOrdered && RHSIsNull
13405 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13406 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13407 return computeResultTy();
13408 }
13409 if (!IsOrdered && LHSIsNull
13410 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13411 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13412 return computeResultTy();
13413 }
13414
13415 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13416 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13417 return computeResultTy();
13418 }
13419
13420 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13421 return computeResultTy();
13422 }
13423
13424 if (LHSIsNull && RHSType->isQueueT()) {
13425 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13426 return computeResultTy();
13427 }
13428
13429 if (LHSType->isQueueT() && RHSIsNull) {
13430 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13431 return computeResultTy();
13432 }
13433 }
13434
13435 return InvalidOperands(Loc, LHS, RHS);
13436}
13437
13438QualType Sema::GetSignedVectorType(QualType V) {
13439 const VectorType *VTy = V->castAs<VectorType>();
13440 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13441
13442 if (isa<ExtVectorType>(Val: VTy)) {
13443 if (VTy->isExtVectorBoolType())
13444 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13445 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13446 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13447 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13448 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13449 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13450 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13451 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13452 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13453 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13454 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13455 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13456 "Unhandled vector element size in vector compare");
13457 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13458 }
13459
13460 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13461 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13462 VecKind: VectorKind::Generic);
13463 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13464 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13465 VecKind: VectorKind::Generic);
13466 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13467 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13468 VecKind: VectorKind::Generic);
13469 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13470 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13471 VecKind: VectorKind::Generic);
13472 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13473 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13474 VecKind: VectorKind::Generic);
13475 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13476 "Unhandled vector element size in vector compare");
13477 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13478 VecKind: VectorKind::Generic);
13479}
13480
13481QualType Sema::GetSignedSizelessVectorType(QualType V) {
13482 const BuiltinType *VTy = V->castAs<BuiltinType>();
13483 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13484
13485 const QualType ETy = V->getSveEltType(Ctx: Context);
13486 const auto TypeSize = Context.getTypeSize(T: ETy);
13487
13488 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13489 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13490 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13491}
13492
13493QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13494 SourceLocation Loc,
13495 BinaryOperatorKind Opc) {
13496 if (Opc == BO_Cmp) {
13497 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13498 return QualType();
13499 }
13500
13501 // Check to make sure we're operating on vectors of the same type and width,
13502 // Allowing one side to be a scalar of element type.
13503 QualType vType =
13504 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13505 /*AllowBothBool*/ true,
13506 /*AllowBoolConversions*/ getLangOpts().ZVector,
13507 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13508 /*ReportInvalid*/ true);
13509 if (vType.isNull())
13510 return vType;
13511
13512 QualType LHSType = LHS.get()->getType();
13513
13514 // Determine the return type of a vector compare. By default clang will return
13515 // a scalar for all vector compares except vector bool and vector pixel.
13516 // With the gcc compiler we will always return a vector type and with the xl
13517 // compiler we will always return a scalar type. This switch allows choosing
13518 // which behavior is prefered.
13519 if (getLangOpts().AltiVec) {
13520 switch (getLangOpts().getAltivecSrcCompat()) {
13521 case LangOptions::AltivecSrcCompatKind::Mixed:
13522 // If AltiVec, the comparison results in a numeric type, i.e.
13523 // bool for C++, int for C
13524 if (vType->castAs<VectorType>()->getVectorKind() ==
13525 VectorKind::AltiVecVector)
13526 return Context.getLogicalOperationType();
13527 else
13528 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13529 break;
13530 case LangOptions::AltivecSrcCompatKind::GCC:
13531 // For GCC we always return the vector type.
13532 break;
13533 case LangOptions::AltivecSrcCompatKind::XL:
13534 return Context.getLogicalOperationType();
13535 break;
13536 }
13537 }
13538
13539 // For non-floating point types, check for self-comparisons of the form
13540 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13541 // often indicate logic errors in the program.
13542 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13543
13544 // Check for comparisons of floating point operands using != and ==.
13545 if (LHSType->hasFloatingRepresentation()) {
13546 assert(RHS.get()->getType()->hasFloatingRepresentation());
13547 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13548 }
13549
13550 // Return a signed type for the vector.
13551 return GetSignedVectorType(V: vType);
13552}
13553
13554QualType Sema::CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
13555 SourceLocation Loc,
13556 BinaryOperatorKind Opc) {
13557 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13558 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13559
13560 QualType MatrixTy =
13561 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13562 if (MatrixTy.isNull())
13563 return QualType();
13564
13565 if (!LHS.get()->getType()->isMatrixType()) {
13566 LHS = prepareMatrixSplat(MatrixTy, SplattedExpr: LHS.get());
13567 if (LHS.isInvalid())
13568 return QualType();
13569 LHS = ImpCastExprToType(E: LHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13570 }
13571 if (!RHS.get()->getType()->isMatrixType()) {
13572 RHS = prepareMatrixSplat(MatrixTy, SplattedExpr: RHS.get());
13573 if (RHS.isInvalid())
13574 return QualType();
13575 RHS = ImpCastExprToType(E: RHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13576 }
13577
13578 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13579 return Context.getConstantMatrixType(ElementType: Context.BoolTy, NumRows: MT->getNumRows(),
13580 NumColumns: MT->getNumColumns());
13581}
13582
13583QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13584 ExprResult &RHS,
13585 SourceLocation Loc,
13586 BinaryOperatorKind Opc) {
13587 if (Opc == BO_Cmp) {
13588 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13589 return QualType();
13590 }
13591
13592 // Check to make sure we're operating on vectors of the same type and width,
13593 // Allowing one side to be a scalar of element type.
13594 QualType vType = CheckSizelessVectorOperands(
13595 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13596
13597 if (vType.isNull())
13598 return vType;
13599
13600 QualType LHSType = LHS.get()->getType();
13601
13602 // For non-floating point types, check for self-comparisons of the form
13603 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13604 // often indicate logic errors in the program.
13605 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13606
13607 // Check for comparisons of floating point operands using != and ==.
13608 if (LHSType->hasFloatingRepresentation()) {
13609 assert(RHS.get()->getType()->hasFloatingRepresentation());
13610 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13611 }
13612
13613 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13614 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13615
13616 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13617 RHSBuiltinTy->isSVEBool())
13618 return LHSType;
13619
13620 // Return a signed type for the vector.
13621 return GetSignedSizelessVectorType(V: vType);
13622}
13623
13624static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13625 const ExprResult &XorRHS,
13626 const SourceLocation Loc) {
13627 // Do not diagnose macros.
13628 if (Loc.isMacroID())
13629 return;
13630
13631 // Do not diagnose if both LHS and RHS are macros.
13632 if (XorLHS.get()->getExprLoc().isMacroID() &&
13633 XorRHS.get()->getExprLoc().isMacroID())
13634 return;
13635
13636 bool Negative = false;
13637 bool ExplicitPlus = false;
13638 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13639 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13640
13641 if (!LHSInt)
13642 return;
13643 if (!RHSInt) {
13644 // Check negative literals.
13645 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13646 UnaryOperatorKind Opc = UO->getOpcode();
13647 if (Opc != UO_Minus && Opc != UO_Plus)
13648 return;
13649 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13650 if (!RHSInt)
13651 return;
13652 Negative = (Opc == UO_Minus);
13653 ExplicitPlus = !Negative;
13654 } else {
13655 return;
13656 }
13657 }
13658
13659 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13660 llvm::APInt RightSideValue = RHSInt->getValue();
13661 if (LeftSideValue != 2 && LeftSideValue != 10)
13662 return;
13663
13664 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13665 return;
13666
13667 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13668 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13669 llvm::StringRef ExprStr =
13670 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13671
13672 CharSourceRange XorRange =
13673 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13674 llvm::StringRef XorStr =
13675 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13676 // Do not diagnose if xor keyword/macro is used.
13677 if (XorStr == "xor")
13678 return;
13679
13680 std::string LHSStr = std::string(Lexer::getSourceText(
13681 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13682 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13683 std::string RHSStr = std::string(Lexer::getSourceText(
13684 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13685 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13686
13687 if (Negative) {
13688 RightSideValue = -RightSideValue;
13689 RHSStr = "-" + RHSStr;
13690 } else if (ExplicitPlus) {
13691 RHSStr = "+" + RHSStr;
13692 }
13693
13694 StringRef LHSStrRef = LHSStr;
13695 StringRef RHSStrRef = RHSStr;
13696 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13697 // literals.
13698 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13699 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13700 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13701 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13702 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13703 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13704 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13705 return;
13706
13707 bool SuggestXor =
13708 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13709 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13710 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13711 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13712 std::string SuggestedExpr = "1 << " + RHSStr;
13713 bool Overflow = false;
13714 llvm::APInt One = (LeftSideValue - 1);
13715 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13716 if (Overflow) {
13717 if (RightSideIntValue < 64)
13718 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13719 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13720 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13721 else if (RightSideIntValue == 64)
13722 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13723 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13724 else
13725 return;
13726 } else {
13727 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13728 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13729 << toString(I: PowValue, Radix: 10, Signed: true)
13730 << FixItHint::CreateReplacement(
13731 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13732 }
13733
13734 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13735 << ("0x2 ^ " + RHSStr) << SuggestXor;
13736 } else if (LeftSideValue == 10) {
13737 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13738 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13739 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13740 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13741 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13742 << ("0xA ^ " + RHSStr) << SuggestXor;
13743 }
13744}
13745
13746QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13747 SourceLocation Loc,
13748 BinaryOperatorKind Opc) {
13749 // Ensure that either both operands are of the same vector type, or
13750 // one operand is of a vector type and the other is of its element type.
13751 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13752 /*AllowBothBool*/ true,
13753 /*AllowBoolConversions*/ false,
13754 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13755 /*ReportInvalid*/ false);
13756 if (vType.isNull())
13757 return InvalidOperands(Loc, LHS, RHS);
13758 if (getLangOpts().OpenCL &&
13759 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13760 vType->hasFloatingRepresentation())
13761 return InvalidOperands(Loc, LHS, RHS);
13762 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13763 // usage of the logical operators && and || with vectors in C. This
13764 // check could be notionally dropped.
13765 if (!getLangOpts().CPlusPlus &&
13766 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13767 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13768 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13769 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13770 // `select` functions.
13771 if (getLangOpts().HLSL &&
13772 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13773 (void)InvalidOperands(Loc, LHS, RHS);
13774 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13775 return QualType();
13776 }
13777
13778 return GetSignedVectorType(V: LHS.get()->getType());
13779}
13780
13781QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13782 SourceLocation Loc,
13783 BinaryOperatorKind Opc) {
13784
13785 if (!getLangOpts().HLSL) {
13786 assert(false && "Logical operands are not supported in C\\C++");
13787 return QualType();
13788 }
13789
13790 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13791 (void)InvalidOperands(Loc, LHS, RHS);
13792 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13793 return QualType();
13794 }
13795 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13796 << getLangOpts().getHLSLVersion();
13797 return QualType();
13798}
13799
13800QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13801 SourceLocation Loc,
13802 bool IsCompAssign) {
13803 if (!IsCompAssign) {
13804 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13805 if (LHS.isInvalid())
13806 return QualType();
13807 }
13808 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13809 if (RHS.isInvalid())
13810 return QualType();
13811
13812 // For conversion purposes, we ignore any qualifiers.
13813 // For example, "const float" and "float" are equivalent.
13814 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13815 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13816
13817 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13818 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13819 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13820
13821 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13822 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13823
13824 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13825 // case we have to return InvalidOperands.
13826 ExprResult OriginalLHS = LHS;
13827 ExprResult OriginalRHS = RHS;
13828 if (LHSMatType && !RHSMatType) {
13829 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13830 if (!RHS.isInvalid())
13831 return LHSType;
13832
13833 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13834 }
13835
13836 if (!LHSMatType && RHSMatType) {
13837 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13838 if (!LHS.isInvalid())
13839 return RHSType;
13840 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13841 }
13842
13843 return InvalidOperands(Loc, LHS, RHS);
13844}
13845
13846QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13847 SourceLocation Loc,
13848 bool IsCompAssign) {
13849 if (!IsCompAssign) {
13850 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13851 if (LHS.isInvalid())
13852 return QualType();
13853 }
13854 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13855 if (RHS.isInvalid())
13856 return QualType();
13857
13858 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13859 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13860 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13861
13862 if (LHSMatType && RHSMatType) {
13863 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13864 return InvalidOperands(Loc, LHS, RHS);
13865
13866 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13867 return Context.getCommonSugaredType(
13868 X: LHS.get()->getType().getUnqualifiedType(),
13869 Y: RHS.get()->getType().getUnqualifiedType());
13870
13871 QualType LHSELTy = LHSMatType->getElementType(),
13872 RHSELTy = RHSMatType->getElementType();
13873 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13874 return InvalidOperands(Loc, LHS, RHS);
13875
13876 return Context.getConstantMatrixType(
13877 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13878 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13879 }
13880 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13881}
13882
13883static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13884 switch (Opc) {
13885 default:
13886 return false;
13887 case BO_And:
13888 case BO_AndAssign:
13889 case BO_Or:
13890 case BO_OrAssign:
13891 case BO_Xor:
13892 case BO_XorAssign:
13893 return true;
13894 }
13895}
13896
13897inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13898 SourceLocation Loc,
13899 BinaryOperatorKind Opc) {
13900 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13901
13902 bool IsCompAssign =
13903 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13904
13905 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13906
13907 if (LHS.get()->getType()->isVectorType() ||
13908 RHS.get()->getType()->isVectorType()) {
13909 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13910 RHS.get()->getType()->hasIntegerRepresentation())
13911 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13912 /*AllowBothBool*/ true,
13913 /*AllowBoolConversions*/ getLangOpts().ZVector,
13914 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13915 /*ReportInvalid*/ true);
13916 return InvalidOperands(Loc, LHS, RHS);
13917 }
13918
13919 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13920 RHS.get()->getType()->isSveVLSBuiltinType()) {
13921 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13922 RHS.get()->getType()->hasIntegerRepresentation())
13923 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13924 OperationKind: ArithConvKind::BitwiseOp);
13925 return InvalidOperands(Loc, LHS, RHS);
13926 }
13927
13928 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13929 RHS.get()->getType()->isSveVLSBuiltinType()) {
13930 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13931 RHS.get()->getType()->hasIntegerRepresentation())
13932 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13933 OperationKind: ArithConvKind::BitwiseOp);
13934 return InvalidOperands(Loc, LHS, RHS);
13935 }
13936
13937 if (Opc == BO_And)
13938 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13939
13940 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13941 RHS.get()->getType()->hasFloatingRepresentation())
13942 return InvalidOperands(Loc, LHS, RHS);
13943
13944 ExprResult LHSResult = LHS, RHSResult = RHS;
13945 QualType compType = UsualArithmeticConversions(
13946 LHS&: LHSResult, RHS&: RHSResult, Loc,
13947 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13948 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13949 return QualType();
13950 LHS = LHSResult.get();
13951 RHS = RHSResult.get();
13952
13953 if (Opc == BO_Xor)
13954 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13955
13956 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13957 return compType;
13958 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13959 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13960 return ResultTy;
13961}
13962
13963// C99 6.5.[13,14]
13964inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13965 SourceLocation Loc,
13966 BinaryOperatorKind Opc) {
13967 // Check vector operands differently.
13968 if (LHS.get()->getType()->isVectorType() ||
13969 RHS.get()->getType()->isVectorType())
13970 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13971
13972 if (LHS.get()->getType()->isConstantMatrixType() ||
13973 RHS.get()->getType()->isConstantMatrixType())
13974 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13975
13976 bool EnumConstantInBoolContext = false;
13977 for (const ExprResult &HS : {LHS, RHS}) {
13978 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13979 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13980 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13981 EnumConstantInBoolContext = true;
13982 }
13983 }
13984
13985 if (EnumConstantInBoolContext)
13986 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13987
13988 // WebAssembly tables can't be used with logical operators.
13989 QualType LHSTy = LHS.get()->getType();
13990 QualType RHSTy = RHS.get()->getType();
13991 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13992 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13993 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13994 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13995 return InvalidOperands(Loc, LHS, RHS);
13996 }
13997
13998 // Diagnose cases where the user write a logical and/or but probably meant a
13999 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14000 // is a constant.
14001 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14002 !LHS.get()->getType()->isBooleanType() &&
14003 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14004 // Don't warn in macros or template instantiations.
14005 !Loc.isMacroID() && !inTemplateInstantiation()) {
14006 // If the RHS can be constant folded, and if it constant folds to something
14007 // that isn't 0 or 1 (which indicate a potential logical operation that
14008 // happened to fold to true/false) then warn.
14009 // Parens on the RHS are ignored.
14010 Expr::EvalResult EVResult;
14011 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
14012 llvm::APSInt Result = EVResult.Val.getInt();
14013 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14014 !RHS.get()->getExprLoc().isMacroID()) ||
14015 (Result != 0 && Result != 1)) {
14016 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
14017 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14018 // Suggest replacing the logical operator with the bitwise version
14019 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
14020 << (Opc == BO_LAnd ? "&" : "|")
14021 << FixItHint::CreateReplacement(
14022 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
14023 Code: Opc == BO_LAnd ? "&" : "|");
14024 if (Opc == BO_LAnd)
14025 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14026 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
14027 << FixItHint::CreateRemoval(
14028 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
14029 RHS.get()->getEndLoc()));
14030 }
14031 }
14032 }
14033
14034 if (!Context.getLangOpts().CPlusPlus) {
14035 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14036 // not operate on the built-in scalar and vector float types.
14037 if (Context.getLangOpts().OpenCL &&
14038 Context.getLangOpts().OpenCLVersion < 120) {
14039 if (LHS.get()->getType()->isFloatingType() ||
14040 RHS.get()->getType()->isFloatingType())
14041 return InvalidOperands(Loc, LHS, RHS);
14042 }
14043
14044 LHS = UsualUnaryConversions(E: LHS.get());
14045 if (LHS.isInvalid())
14046 return QualType();
14047
14048 RHS = UsualUnaryConversions(E: RHS.get());
14049 if (RHS.isInvalid())
14050 return QualType();
14051
14052 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14053 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
14054 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14055 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
14056
14057 if (!LHS.get()->getType()->isScalarType() ||
14058 !RHS.get()->getType()->isScalarType())
14059 return InvalidOperands(Loc, LHS, RHS);
14060
14061 return Context.IntTy;
14062 }
14063
14064 // The following is safe because we only use this method for
14065 // non-overloadable operands.
14066
14067 // C++ [expr.log.and]p1
14068 // C++ [expr.log.or]p1
14069 // The operands are both contextually converted to type bool.
14070 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14071 if (LHSRes.isInvalid()) {
14072 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14073 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14074 return ResultTy;
14075 }
14076 LHS = LHSRes;
14077
14078 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14079 if (RHSRes.isInvalid()) {
14080 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14081 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14082 return ResultTy;
14083 }
14084 RHS = RHSRes;
14085
14086 // C++ [expr.log.and]p2
14087 // C++ [expr.log.or]p2
14088 // The result is a bool.
14089 return Context.BoolTy;
14090}
14091
14092static bool IsReadonlyMessage(Expr *E, Sema &S) {
14093 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14094 if (!ME) return false;
14095 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14096 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14097 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14098 if (!Base) return false;
14099 return Base->getMethodDecl() != nullptr;
14100}
14101
14102/// Is the given expression (which must be 'const') a reference to a
14103/// variable which was originally non-const, but which has become
14104/// 'const' due to being captured within a block?
14105enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14106static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14107 assert(E->isLValue() && E->getType().isConstQualified());
14108 E = E->IgnoreParens();
14109
14110 // Must be a reference to a declaration from an enclosing scope.
14111 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14112 if (!DRE) return NCCK_None;
14113 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14114
14115 ValueDecl *Value = DRE->getDecl();
14116
14117 // The declaration must be a value which is not declared 'const'.
14118 if (Value->getType().isConstQualified())
14119 return NCCK_None;
14120
14121 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14122 if (Binding) {
14123 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14124 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14125 return NCCK_Lambda;
14126 }
14127
14128 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14129 if (!Var)
14130 return NCCK_None;
14131 if (Var->getType()->isReferenceType())
14132 return NCCK_None;
14133
14134 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14135
14136 // Decide whether the first capture was for a block or a lambda.
14137 DeclContext *DC = S.CurContext, *Prev = nullptr;
14138 // Decide whether the first capture was for a block or a lambda.
14139 while (DC) {
14140 // For init-capture, it is possible that the variable belongs to the
14141 // template pattern of the current context.
14142 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14143 if (Var->isInitCapture() &&
14144 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14145 break;
14146 if (DC == Var->getDeclContext())
14147 break;
14148 Prev = DC;
14149 DC = DC->getParent();
14150 }
14151 // Unless we have an init-capture, we've gone one step too far.
14152 if (!Var->isInitCapture())
14153 DC = Prev;
14154 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14155}
14156
14157static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14158 Ty = Ty.getNonReferenceType();
14159 if (IsDereference && Ty->isPointerType())
14160 Ty = Ty->getPointeeType();
14161 return !Ty.isConstQualified();
14162}
14163
14164// Update err_typecheck_assign_const and note_typecheck_assign_const
14165// when this enum is changed.
14166enum {
14167 ConstFunction,
14168 ConstVariable,
14169 ConstMember,
14170 NestedConstMember,
14171 ConstUnknown, // Keep as last element
14172};
14173
14174/// Emit the "read-only variable not assignable" error and print notes to give
14175/// more information about why the variable is not assignable, such as pointing
14176/// to the declaration of a const variable, showing that a method is const, or
14177/// that the function is returning a const reference.
14178static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14179 SourceLocation Loc) {
14180 SourceRange ExprRange = E->getSourceRange();
14181
14182 // Only emit one error on the first const found. All other consts will emit
14183 // a note to the error.
14184 bool DiagnosticEmitted = false;
14185
14186 // Track if the current expression is the result of a dereference, and if the
14187 // next checked expression is the result of a dereference.
14188 bool IsDereference = false;
14189 bool NextIsDereference = false;
14190
14191 // Loop to process MemberExpr chains.
14192 while (true) {
14193 IsDereference = NextIsDereference;
14194
14195 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14196 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14197 NextIsDereference = ME->isArrow();
14198 const ValueDecl *VD = ME->getMemberDecl();
14199 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14200 // Mutable fields can be modified even if the class is const.
14201 if (Field->isMutable()) {
14202 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14203 break;
14204 }
14205
14206 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14207 if (!DiagnosticEmitted) {
14208 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14209 << ExprRange << ConstMember << false /*static*/ << Field
14210 << Field->getType();
14211 DiagnosticEmitted = true;
14212 }
14213 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14214 << ConstMember << false /*static*/ << Field << Field->getType()
14215 << Field->getSourceRange();
14216 }
14217 E = ME->getBase();
14218 continue;
14219 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14220 if (VDecl->getType().isConstQualified()) {
14221 if (!DiagnosticEmitted) {
14222 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14223 << ExprRange << ConstMember << true /*static*/ << VDecl
14224 << VDecl->getType();
14225 DiagnosticEmitted = true;
14226 }
14227 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14228 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14229 << VDecl->getSourceRange();
14230 }
14231 // Static fields do not inherit constness from parents.
14232 break;
14233 }
14234 break; // End MemberExpr
14235 } else if (const ArraySubscriptExpr *ASE =
14236 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14237 E = ASE->getBase()->IgnoreParenImpCasts();
14238 continue;
14239 } else if (const ExtVectorElementExpr *EVE =
14240 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14241 E = EVE->getBase()->IgnoreParenImpCasts();
14242 continue;
14243 }
14244 break;
14245 }
14246
14247 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14248 // Function calls
14249 const FunctionDecl *FD = CE->getDirectCallee();
14250 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14251 if (!DiagnosticEmitted) {
14252 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14253 << ConstFunction << FD;
14254 DiagnosticEmitted = true;
14255 }
14256 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14257 DiagID: diag::note_typecheck_assign_const)
14258 << ConstFunction << FD << FD->getReturnType()
14259 << FD->getReturnTypeSourceRange();
14260 }
14261 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14262 // Point to variable declaration.
14263 if (const ValueDecl *VD = DRE->getDecl()) {
14264 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14265 if (!DiagnosticEmitted) {
14266 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14267 << ExprRange << ConstVariable << VD << VD->getType();
14268 DiagnosticEmitted = true;
14269 }
14270 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14271 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14272 }
14273 }
14274 } else if (isa<CXXThisExpr>(Val: E)) {
14275 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14276 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14277 if (MD->isConst()) {
14278 if (!DiagnosticEmitted) {
14279 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14280 << ExprRange << MD;
14281 DiagnosticEmitted = true;
14282 }
14283 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14284 << MD << MD->getSourceRange();
14285 }
14286 }
14287 }
14288 }
14289
14290 if (DiagnosticEmitted)
14291 return;
14292
14293 // Can't determine a more specific message, so display the generic error.
14294 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14295}
14296
14297enum OriginalExprKind {
14298 OEK_Variable,
14299 OEK_Member,
14300 OEK_LValue
14301};
14302
14303static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14304 const RecordType *Ty,
14305 SourceLocation Loc, SourceRange Range,
14306 OriginalExprKind OEK,
14307 bool &DiagnosticEmitted) {
14308 std::vector<const RecordType *> RecordTypeList;
14309 RecordTypeList.push_back(x: Ty);
14310 unsigned NextToCheckIndex = 0;
14311 // We walk the record hierarchy breadth-first to ensure that we print
14312 // diagnostics in field nesting order.
14313 while (RecordTypeList.size() > NextToCheckIndex) {
14314 bool IsNested = NextToCheckIndex > 0;
14315 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14316 ->getDecl()
14317 ->getDefinitionOrSelf()
14318 ->fields()) {
14319 // First, check every field for constness.
14320 QualType FieldTy = Field->getType();
14321 if (FieldTy.isConstQualified()) {
14322 if (!DiagnosticEmitted) {
14323 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14324 << Range << NestedConstMember << OEK << VD
14325 << IsNested << Field;
14326 DiagnosticEmitted = true;
14327 }
14328 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14329 << NestedConstMember << IsNested << Field
14330 << FieldTy << Field->getSourceRange();
14331 }
14332
14333 // Then we append it to the list to check next in order.
14334 FieldTy = FieldTy.getCanonicalType();
14335 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14336 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14337 RecordTypeList.push_back(x: FieldRecTy);
14338 }
14339 }
14340 ++NextToCheckIndex;
14341 }
14342}
14343
14344/// Emit an error for the case where a record we are trying to assign to has a
14345/// const-qualified field somewhere in its hierarchy.
14346static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14347 SourceLocation Loc) {
14348 QualType Ty = E->getType();
14349 assert(Ty->isRecordType() && "lvalue was not record?");
14350 SourceRange Range = E->getSourceRange();
14351 const auto *RTy = Ty->getAsCanonical<RecordType>();
14352 bool DiagEmitted = false;
14353
14354 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14355 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14356 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14357 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14358 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14359 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14360 else
14361 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14362 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14363 if (!DiagEmitted)
14364 DiagnoseConstAssignment(S, E, Loc);
14365}
14366
14367/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14368/// emit an error and return true. If so, return false.
14369static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14370 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14371
14372 S.CheckShadowingDeclModification(E, Loc);
14373
14374 SourceLocation OrigLoc = Loc;
14375 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14376 Loc: &Loc);
14377 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14378 IsLV = Expr::MLV_InvalidMessageExpression;
14379 if (IsLV == Expr::MLV_Valid)
14380 return false;
14381
14382 unsigned DiagID = 0;
14383 bool NeedType = false;
14384 switch (IsLV) { // C99 6.5.16p2
14385 case Expr::MLV_ConstQualified:
14386 // Use a specialized diagnostic when we're assigning to an object
14387 // from an enclosing function or block.
14388 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14389 if (NCCK == NCCK_Block)
14390 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14391 else
14392 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14393 break;
14394 }
14395
14396 // In ARC, use some specialized diagnostics for occasions where we
14397 // infer 'const'. These are always pseudo-strong variables.
14398 if (S.getLangOpts().ObjCAutoRefCount) {
14399 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14400 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14401 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14402
14403 // Use the normal diagnostic if it's pseudo-__strong but the
14404 // user actually wrote 'const'.
14405 if (var->isARCPseudoStrong() &&
14406 (!var->getTypeSourceInfo() ||
14407 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14408 // There are three pseudo-strong cases:
14409 // - self
14410 ObjCMethodDecl *method = S.getCurMethodDecl();
14411 if (method && var == method->getSelfDecl()) {
14412 DiagID = method->isClassMethod()
14413 ? diag::err_typecheck_arc_assign_self_class_method
14414 : diag::err_typecheck_arc_assign_self;
14415
14416 // - Objective-C externally_retained attribute.
14417 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14418 isa<ParmVarDecl>(Val: var)) {
14419 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14420
14421 // - fast enumeration variables
14422 } else {
14423 DiagID = diag::err_typecheck_arr_assign_enumeration;
14424 }
14425
14426 SourceRange Assign;
14427 if (Loc != OrigLoc)
14428 Assign = SourceRange(OrigLoc, OrigLoc);
14429 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14430 // We need to preserve the AST regardless, so migration tool
14431 // can do its job.
14432 return false;
14433 }
14434 }
14435 }
14436
14437 // If none of the special cases above are triggered, then this is a
14438 // simple const assignment.
14439 if (DiagID == 0) {
14440 DiagnoseConstAssignment(S, E, Loc);
14441 return true;
14442 }
14443
14444 break;
14445 case Expr::MLV_ConstAddrSpace:
14446 DiagnoseConstAssignment(S, E, Loc);
14447 return true;
14448 case Expr::MLV_ConstQualifiedField:
14449 DiagnoseRecursiveConstFields(S, E, Loc);
14450 return true;
14451 case Expr::MLV_ArrayType:
14452 case Expr::MLV_ArrayTemporary:
14453 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14454 NeedType = true;
14455 break;
14456 case Expr::MLV_NotObjectType:
14457 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14458 NeedType = true;
14459 break;
14460 case Expr::MLV_LValueCast:
14461 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14462 break;
14463 case Expr::MLV_Valid:
14464 llvm_unreachable("did not take early return for MLV_Valid");
14465 case Expr::MLV_InvalidExpression:
14466 case Expr::MLV_MemberFunction:
14467 case Expr::MLV_ClassTemporary:
14468 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14469 break;
14470 case Expr::MLV_IncompleteType:
14471 case Expr::MLV_IncompleteVoidType:
14472 return S.RequireCompleteType(Loc, T: E->getType(),
14473 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14474 case Expr::MLV_DuplicateVectorComponents:
14475 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14476 break;
14477 case Expr::MLV_DuplicateMatrixComponents:
14478 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14479 break;
14480 case Expr::MLV_NoSetterProperty:
14481 llvm_unreachable("readonly properties should be processed differently");
14482 case Expr::MLV_InvalidMessageExpression:
14483 DiagID = diag::err_readonly_message_assignment;
14484 break;
14485 case Expr::MLV_SubObjCPropertySetting:
14486 DiagID = diag::err_no_subobject_property_setting;
14487 break;
14488 }
14489
14490 SourceRange Assign;
14491 if (Loc != OrigLoc)
14492 Assign = SourceRange(OrigLoc, OrigLoc);
14493 if (NeedType)
14494 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14495 else
14496 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14497 return true;
14498}
14499
14500static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14501 SourceLocation Loc,
14502 Sema &Sema) {
14503 if (Sema.inTemplateInstantiation())
14504 return;
14505 if (Sema.isUnevaluatedContext())
14506 return;
14507 if (Loc.isInvalid() || Loc.isMacroID())
14508 return;
14509 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14510 return;
14511
14512 // C / C++ fields
14513 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14514 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14515 if (ML && MR) {
14516 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14517 return;
14518 const ValueDecl *LHSDecl =
14519 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14520 const ValueDecl *RHSDecl =
14521 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14522 if (LHSDecl != RHSDecl)
14523 return;
14524 if (LHSDecl->getType().isVolatileQualified())
14525 return;
14526 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14527 if (RefTy->getPointeeType().isVolatileQualified())
14528 return;
14529
14530 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14531 }
14532
14533 // Objective-C instance variables
14534 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14535 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14536 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14537 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14538 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14539 if (RL && RR && RL->getDecl() == RR->getDecl())
14540 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14541 }
14542}
14543
14544// C99 6.5.16.1
14545QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14546 SourceLocation Loc,
14547 QualType CompoundType,
14548 BinaryOperatorKind Opc) {
14549 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14550
14551 // Verify that LHS is a modifiable lvalue, and emit error if not.
14552 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14553 return QualType();
14554
14555 QualType LHSType = LHSExpr->getType();
14556 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14557 CompoundType;
14558
14559 if (RHS.isUsable()) {
14560 // Even if this check fails don't return early to allow the best
14561 // possible error recovery and to allow any subsequent diagnostics to
14562 // work.
14563 const ValueDecl *Assignee = nullptr;
14564 bool ShowFullyQualifiedAssigneeName = false;
14565 // In simple cases describe what is being assigned to
14566 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14567 Assignee = DR->getDecl();
14568 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14569 Assignee = ME->getMemberDecl();
14570 ShowFullyQualifiedAssigneeName = true;
14571 }
14572
14573 BoundsSafetyCheckAssignmentToCountAttrPtr(
14574 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14575 ShowFullyQualifiedAssigneeName);
14576 }
14577
14578 // OpenCL v1.2 s6.1.1.1 p2:
14579 // The half data type can only be used to declare a pointer to a buffer that
14580 // contains half values
14581 if (getLangOpts().OpenCL &&
14582 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14583 LHSType->isHalfType()) {
14584 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14585 << LHSType.getUnqualifiedType();
14586 return QualType();
14587 }
14588
14589 // WebAssembly tables can't be used on RHS of an assignment expression.
14590 if (RHSType->isWebAssemblyTableType()) {
14591 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14592 return QualType();
14593 }
14594
14595 AssignConvertType ConvTy;
14596 if (CompoundType.isNull()) {
14597 Expr *RHSCheck = RHS.get();
14598
14599 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14600
14601 QualType LHSTy(LHSType);
14602 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14603 if (RHS.isInvalid())
14604 return QualType();
14605 // Special case of NSObject attributes on c-style pointer types.
14606 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14607 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14608 RHSType->isObjCObjectPointerType()) ||
14609 (Context.isObjCNSObjectType(Ty: RHSType) &&
14610 LHSType->isObjCObjectPointerType())))
14611 ConvTy = AssignConvertType::Compatible;
14612
14613 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14614 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14615
14616 // If the RHS is a unary plus or minus, check to see if they = and + are
14617 // right next to each other. If so, the user may have typo'd "x =+ 4"
14618 // instead of "x += 4".
14619 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14620 RHSCheck = ICE->getSubExpr();
14621 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14622 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14623 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14624 // Only if the two operators are exactly adjacent.
14625 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14626 // And there is a space or other character before the subexpr of the
14627 // unary +/-. We don't want to warn on "x=-1".
14628 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14629 UO->getSubExpr()->getBeginLoc().isFileID()) {
14630 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14631 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14632 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14633 }
14634 }
14635
14636 if (IsAssignConvertCompatible(ConvTy)) {
14637 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14638 // Warn about retain cycles where a block captures the LHS, but
14639 // not if the LHS is a simple variable into which the block is
14640 // being stored...unless that variable can be captured by reference!
14641 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14642 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14643 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14644 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14645 }
14646
14647 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14648 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14649 // It is safe to assign a weak reference into a strong variable.
14650 // Although this code can still have problems:
14651 // id x = self.weakProp;
14652 // id y = self.weakProp;
14653 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14654 // paths through the function. This should be revisited if
14655 // -Wrepeated-use-of-weak is made flow-sensitive.
14656 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14657 // variable, which will be valid for the current autorelease scope.
14658 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14659 Loc: RHS.get()->getBeginLoc()))
14660 getCurFunction()->markSafeWeakUse(E: RHS.get());
14661
14662 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14663 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14664 }
14665 }
14666 } else {
14667 // Compound assignment "x += y"
14668 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14669 }
14670
14671 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14672 Action: AssignmentAction::Assigning))
14673 return QualType();
14674
14675 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14676
14677 AssignedEntity AE{.LHS: LHSExpr};
14678 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14679
14680 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14681 if (CompoundType.isNull()) {
14682 // C++2a [expr.ass]p5:
14683 // A simple-assignment whose left operand is of a volatile-qualified
14684 // type is deprecated unless the assignment is either a discarded-value
14685 // expression or an unevaluated operand
14686 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14687 }
14688 }
14689
14690 // C11 6.5.16p3: The type of an assignment expression is the type of the
14691 // left operand would have after lvalue conversion.
14692 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14693 // qualified type, the value has the unqualified version of the type of the
14694 // lvalue; additionally, if the lvalue has atomic type, the value has the
14695 // non-atomic version of the type of the lvalue.
14696 // C++ 5.17p1: the type of the assignment expression is that of its left
14697 // operand.
14698 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14699}
14700
14701// Scenarios to ignore if expression E is:
14702// 1. an explicit cast expression into void
14703// 2. a function call expression that returns void
14704static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14705 E = E->IgnoreParens();
14706
14707 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14708 if (CE->getCastKind() == CK_ToVoid) {
14709 return true;
14710 }
14711
14712 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14713 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14714 CE->getSubExpr()->getType()->isDependentType()) {
14715 return true;
14716 }
14717 }
14718
14719 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14720 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14721 return false;
14722}
14723
14724void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14725 // No warnings in macros
14726 if (Loc.isMacroID())
14727 return;
14728
14729 // Don't warn in template instantiations.
14730 if (inTemplateInstantiation())
14731 return;
14732
14733 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14734 // instead, skip more than needed, then call back into here with the
14735 // CommaVisitor in SemaStmt.cpp.
14736 // The listed locations are the initialization and increment portions
14737 // of a for loop. The additional checks are on the condition of
14738 // if statements, do/while loops, and for loops.
14739 if (getCurScope()->isControlScope())
14740 return;
14741
14742 // If there are multiple comma operators used together, get the RHS of the
14743 // of the comma operator as the LHS.
14744 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14745 if (BO->getOpcode() != BO_Comma)
14746 break;
14747 LHS = BO->getRHS();
14748 }
14749
14750 // Only allow some expressions on LHS to not warn.
14751 if (IgnoreCommaOperand(E: LHS, Context))
14752 return;
14753
14754 Diag(Loc, DiagID: diag::warn_comma_operator);
14755 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14756 << LHS->getSourceRange()
14757 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14758 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14759 : "(void)(")
14760 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14761 Code: ")");
14762}
14763
14764// C99 6.5.17
14765static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14766 SourceLocation Loc) {
14767 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14768 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14769 if (LHS.isInvalid() || RHS.isInvalid())
14770 return QualType();
14771
14772 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14773 // operands, but not unary promotions.
14774 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14775
14776 // So we treat the LHS as a ignored value, and in C++ we allow the
14777 // containing site to determine what should be done with the RHS.
14778 LHS = S.IgnoredValueConversions(E: LHS.get());
14779 if (LHS.isInvalid())
14780 return QualType();
14781
14782 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14783
14784 if (!S.getLangOpts().CPlusPlus) {
14785 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14786 if (RHS.isInvalid())
14787 return QualType();
14788 if (!RHS.get()->getType()->isVoidType())
14789 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14790 DiagID: diag::err_incomplete_type);
14791 }
14792
14793 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14794 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14795
14796 return RHS.get()->getType();
14797}
14798
14799/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14800/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14801static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14802 ExprValueKind &VK,
14803 ExprObjectKind &OK,
14804 SourceLocation OpLoc, bool IsInc,
14805 bool IsPrefix) {
14806 QualType ResType = Op->getType();
14807 // Atomic types can be used for increment / decrement where the non-atomic
14808 // versions can, so ignore the _Atomic() specifier for the purpose of
14809 // checking.
14810 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14811 ResType = ResAtomicType->getValueType();
14812
14813 assert(!ResType.isNull() && "no type for increment/decrement expression");
14814
14815 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14816 // Decrement of bool is not allowed.
14817 if (!IsInc) {
14818 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14819 return QualType();
14820 }
14821 // Increment of bool sets it to true, but is deprecated.
14822 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14823 : diag::warn_increment_bool)
14824 << Op->getSourceRange();
14825 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14826 // Error on enum increments and decrements in C++ mode
14827 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14828 return QualType();
14829 } else if (ResType->isRealType()) {
14830 // OK!
14831 } else if (ResType->isPointerType()) {
14832 // C99 6.5.2.4p2, 6.5.6p2
14833 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14834 return QualType();
14835 } else if (ResType->isOverflowBehaviorType()) {
14836 // OK!
14837 } else if (ResType->isObjCObjectPointerType()) {
14838 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14839 // Otherwise, we just need a complete type.
14840 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14841 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14842 return QualType();
14843 } else if (ResType->isAnyComplexType()) {
14844 // C99 does not support ++/-- on complex types, we allow as an extension.
14845 S.DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::increment_complex)
14846 << IsInc << Op->getSourceRange();
14847 } else if (ResType->isPlaceholderType()) {
14848 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14849 if (PR.isInvalid()) return QualType();
14850 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14851 IsInc, IsPrefix);
14852 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14853 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14854 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14855 (ResType->castAs<VectorType>()->getVectorKind() !=
14856 VectorKind::AltiVecBool)) {
14857 // The z vector extensions allow ++ and -- for non-bool vectors.
14858 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14859 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14860 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14861 } else {
14862 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14863 << ResType << int(IsInc) << Op->getSourceRange();
14864 return QualType();
14865 }
14866 // At this point, we know we have a real, complex or pointer type.
14867 // Now make sure the operand is a modifiable lvalue.
14868 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14869 return QualType();
14870 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14871 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14872 // An operand with volatile-qualified type is deprecated
14873 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14874 << IsInc << ResType;
14875 }
14876 // In C++, a prefix increment is the same type as the operand. Otherwise
14877 // (in C or with postfix), the increment is the unqualified type of the
14878 // operand.
14879 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14880 VK = VK_LValue;
14881 OK = Op->getObjectKind();
14882 return ResType;
14883 } else {
14884 VK = VK_PRValue;
14885 return ResType.getUnqualifiedType();
14886 }
14887}
14888
14889/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14890/// This routine allows us to typecheck complex/recursive expressions
14891/// where the declaration is needed for type checking. We only need to
14892/// handle cases when the expression references a function designator
14893/// or is an lvalue. Here are some examples:
14894/// - &(x) => x
14895/// - &*****f => f for f a function designator.
14896/// - &s.xx => s
14897/// - &s.zz[1].yy -> s, if zz is an array
14898/// - *(x + 1) -> x, if x is an array
14899/// - &"123"[2] -> 0
14900/// - & __real__ x -> x
14901///
14902/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14903/// members.
14904static ValueDecl *getPrimaryDecl(Expr *E) {
14905 switch (E->getStmtClass()) {
14906 case Stmt::DeclRefExprClass:
14907 return cast<DeclRefExpr>(Val: E)->getDecl();
14908 case Stmt::MemberExprClass:
14909 // If this is an arrow operator, the address is an offset from
14910 // the base's value, so the object the base refers to is
14911 // irrelevant.
14912 if (cast<MemberExpr>(Val: E)->isArrow())
14913 return nullptr;
14914 // Otherwise, the expression refers to a part of the base
14915 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14916 case Stmt::ArraySubscriptExprClass: {
14917 // FIXME: This code shouldn't be necessary! We should catch the implicit
14918 // promotion of register arrays earlier.
14919 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14920 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14921 if (ICE->getSubExpr()->getType()->isArrayType())
14922 return getPrimaryDecl(E: ICE->getSubExpr());
14923 }
14924 return nullptr;
14925 }
14926 case Stmt::UnaryOperatorClass: {
14927 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14928
14929 switch(UO->getOpcode()) {
14930 case UO_Real:
14931 case UO_Imag:
14932 case UO_Extension:
14933 return getPrimaryDecl(E: UO->getSubExpr());
14934 default:
14935 return nullptr;
14936 }
14937 }
14938 case Stmt::ParenExprClass:
14939 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14940 case Stmt::ImplicitCastExprClass:
14941 // If the result of an implicit cast is an l-value, we care about
14942 // the sub-expression; otherwise, the result here doesn't matter.
14943 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14944 case Stmt::CXXUuidofExprClass:
14945 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14946 default:
14947 return nullptr;
14948 }
14949}
14950
14951namespace {
14952enum {
14953 AO_Bit_Field = 0,
14954 AO_Vector_Element = 1,
14955 AO_Property_Expansion = 2,
14956 AO_Register_Variable = 3,
14957 AO_Matrix_Element = 4,
14958 AO_No_Error = 5
14959};
14960}
14961/// Diagnose invalid operand for address of operations.
14962///
14963/// \param Type The type of operand which cannot have its address taken.
14964static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14965 Expr *E, unsigned Type) {
14966 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14967}
14968
14969bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14970 const Expr *Op,
14971 const CXXMethodDecl *MD) {
14972 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14973
14974 if (Op != DRE)
14975 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14976 << Op->getSourceRange();
14977
14978 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14979 if (isa<CXXDestructorDecl>(Val: MD))
14980 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14981 << DRE->getSourceRange();
14982
14983 if (DRE->getQualifier())
14984 return false;
14985
14986 if (MD->getParent()->getName().empty())
14987 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14988 << DRE->getSourceRange();
14989
14990 SmallString<32> Str;
14991 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14992 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14993 << DRE->getSourceRange()
14994 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14995}
14996
14997QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14998 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14999 if (PTy->getKind() == BuiltinType::Overload) {
15000 Expr *E = OrigOp.get()->IgnoreParens();
15001 if (!isa<OverloadExpr>(Val: E)) {
15002 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15003 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15004 << OrigOp.get()->getSourceRange();
15005 return QualType();
15006 }
15007
15008 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
15009 if (isa<UnresolvedMemberExpr>(Val: Ovl))
15010 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
15011 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15012 << OrigOp.get()->getSourceRange();
15013 return QualType();
15014 }
15015
15016 return Context.OverloadTy;
15017 }
15018
15019 if (PTy->getKind() == BuiltinType::UnknownAny)
15020 return Context.UnknownAnyTy;
15021
15022 if (PTy->getKind() == BuiltinType::BoundMember) {
15023 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15024 << OrigOp.get()->getSourceRange();
15025 return QualType();
15026 }
15027
15028 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15029 if (OrigOp.isInvalid()) return QualType();
15030 }
15031
15032 if (OrigOp.get()->isTypeDependent())
15033 return Context.DependentTy;
15034
15035 assert(!OrigOp.get()->hasPlaceholderType());
15036
15037 // Make sure to ignore parentheses in subsequent checks
15038 Expr *op = OrigOp.get()->IgnoreParens();
15039
15040 // In OpenCL captures for blocks called as lambda functions
15041 // are located in the private address space. Blocks used in
15042 // enqueue_kernel can be located in a different address space
15043 // depending on a vendor implementation. Thus preventing
15044 // taking an address of the capture to avoid invalid AS casts.
15045 if (LangOpts.OpenCL) {
15046 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15047 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15048 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
15049 return QualType();
15050 }
15051 }
15052
15053 if (getLangOpts().C99) {
15054 // Implement C99-only parts of addressof rules.
15055 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15056 if (uOp->getOpcode() == UO_Deref)
15057 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15058 // (assuming the deref expression is valid).
15059 return uOp->getSubExpr()->getType();
15060 }
15061 // Technically, there should be a check for array subscript
15062 // expressions here, but the result of one is always an lvalue anyway.
15063 }
15064 ValueDecl *dcl = getPrimaryDecl(E: op);
15065
15066 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15067 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15068 Loc: op->getBeginLoc()))
15069 return QualType();
15070
15071 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15072 unsigned AddressOfError = AO_No_Error;
15073
15074 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15075 bool IsError = isSFINAEContext();
15076 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15077 : diag::ext_typecheck_addrof_temporary)
15078 << op->getType() << op->getSourceRange();
15079 if (IsError)
15080 return QualType();
15081 // Materialize the temporary as an lvalue so that we can take its address.
15082 OrigOp = op =
15083 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15084 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15085 return Context.getPointerType(T: op->getType());
15086 } else if (lval == Expr::LV_MemberFunction) {
15087 // If it's an instance method, make a member pointer.
15088 // The expression must have exactly the form &A::foo.
15089
15090 // If the underlying expression isn't a decl ref, give up.
15091 if (!isa<DeclRefExpr>(Val: op)) {
15092 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15093 << OrigOp.get()->getSourceRange();
15094 return QualType();
15095 }
15096 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15097 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15098
15099 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15100 QualType MPTy = Context.getMemberPointerType(
15101 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15102
15103 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15104 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15105 // When pointer authentication is enabled, argument and return types of
15106 // vitual member functions must be complete. This is because vitrual
15107 // member function pointers are implemented using virtual dispatch
15108 // thunks and the thunks cannot be emitted if the argument or return
15109 // types are incomplete.
15110 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15111 SourceLocation DeclRefLoc,
15112 SourceLocation RetArgTypeLoc) {
15113 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15114 Diag(Loc: DeclRefLoc,
15115 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15116 Diag(Loc: RetArgTypeLoc,
15117 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15118 << T;
15119 return true;
15120 }
15121 return false;
15122 };
15123 QualType RetTy = MD->getReturnType();
15124 bool IsIncomplete =
15125 !RetTy->isVoidType() &&
15126 ReturnOrParamTypeIsIncomplete(
15127 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15128 for (auto *PVD : MD->parameters())
15129 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15130 PVD->getBeginLoc());
15131 if (IsIncomplete)
15132 return QualType();
15133 }
15134
15135 // Under the MS ABI, lock down the inheritance model now.
15136 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15137 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15138 return MPTy;
15139 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15140 // C99 6.5.3.2p1
15141 // The operand must be either an l-value or a function designator
15142 if (!op->getType()->isFunctionType()) {
15143 // Use a special diagnostic for loads from property references.
15144 if (isa<PseudoObjectExpr>(Val: op)) {
15145 AddressOfError = AO_Property_Expansion;
15146 } else {
15147 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15148 << op->getType() << op->getSourceRange();
15149 return QualType();
15150 }
15151 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15152 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15153 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15154 }
15155
15156 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15157 // The operand cannot be a bit-field
15158 AddressOfError = AO_Bit_Field;
15159 } else if (op->getObjectKind() == OK_VectorComponent) {
15160 // The operand cannot be an element of a vector
15161 AddressOfError = AO_Vector_Element;
15162 } else if (op->getObjectKind() == OK_MatrixComponent) {
15163 // The operand cannot be an element of a matrix.
15164 AddressOfError = AO_Matrix_Element;
15165 } else if (dcl) { // C99 6.5.3.2p1
15166 // We have an lvalue with a decl. Make sure the decl is not declared
15167 // with the register storage-class specifier.
15168 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15169 // in C++ it is not error to take address of a register
15170 // variable (c++03 7.1.1P3)
15171 if (vd->getStorageClass() == SC_Register &&
15172 !getLangOpts().CPlusPlus) {
15173 AddressOfError = AO_Register_Variable;
15174 }
15175 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15176 AddressOfError = AO_Property_Expansion;
15177 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15178 return Context.OverloadTy;
15179 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15180 // Okay: we can take the address of a field.
15181 // Could be a pointer to member, though, if there is an explicit
15182 // scope qualifier for the class.
15183
15184 // [C++26] [expr.prim.id.general]
15185 // If an id-expression E denotes a non-static non-type member
15186 // of some class C [...] and if E is a qualified-id, E is
15187 // not the un-parenthesized operand of the unary & operator [...]
15188 // the id-expression is transformed into a class member access expression.
15189 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15190 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15191 DeclContext *Ctx = dcl->getDeclContext();
15192 if (Ctx && Ctx->isRecord()) {
15193 if (dcl->getType()->isReferenceType()) {
15194 Diag(Loc: OpLoc,
15195 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15196 << dcl->getDeclName() << dcl->getType();
15197 return QualType();
15198 }
15199
15200 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15201 Ctx = Ctx->getParent();
15202
15203 QualType MPTy = Context.getMemberPointerType(
15204 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15205 // Under the MS ABI, lock down the inheritance model now.
15206 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15207 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15208 return MPTy;
15209 }
15210 }
15211 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15212 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15213 UnnamedGlobalConstantDecl>(Val: dcl))
15214 llvm_unreachable("Unknown/unexpected decl type");
15215 }
15216
15217 if (AddressOfError != AO_No_Error) {
15218 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15219 return QualType();
15220 }
15221
15222 if (lval == Expr::LV_IncompleteVoidType) {
15223 // Taking the address of a void variable is technically illegal, but we
15224 // allow it in cases which are otherwise valid.
15225 // Example: "extern void x; void* y = &x;".
15226 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15227 }
15228
15229 // If the operand has type "type", the result has type "pointer to type".
15230 if (op->getType()->isObjCObjectType())
15231 return Context.getObjCObjectPointerType(OIT: op->getType());
15232
15233 // Cannot take the address of WebAssembly references or tables.
15234 if (Context.getTargetInfo().getTriple().isWasm()) {
15235 QualType OpTy = op->getType();
15236 if (OpTy.isWebAssemblyReferenceType()) {
15237 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15238 << 1 << OrigOp.get()->getSourceRange();
15239 return QualType();
15240 }
15241 if (OpTy->isWebAssemblyTableType()) {
15242 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15243 << 1 << OrigOp.get()->getSourceRange();
15244 return QualType();
15245 }
15246 }
15247
15248 CheckAddressOfPackedMember(rhs: op);
15249
15250 return Context.getPointerType(T: op->getType());
15251}
15252
15253static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15254 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15255 if (!DRE)
15256 return;
15257 const Decl *D = DRE->getDecl();
15258 if (!D)
15259 return;
15260 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15261 if (!Param)
15262 return;
15263 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15264 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15265 return;
15266 if (FunctionScopeInfo *FD = S.getCurFunction())
15267 FD->ModifiedNonNullParams.insert(Ptr: Param);
15268}
15269
15270/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15271static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15272 SourceLocation OpLoc,
15273 bool IsAfterAmp = false) {
15274 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15275 if (ConvResult.isInvalid())
15276 return QualType();
15277 Op = ConvResult.get();
15278 QualType OpTy = Op->getType();
15279 QualType Result;
15280
15281 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15282 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15283 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15284 Range: Op->getSourceRange());
15285 }
15286
15287 if (const PointerType *PT = OpTy->getAs<PointerType>())
15288 {
15289 Result = PT->getPointeeType();
15290 }
15291 else if (const ObjCObjectPointerType *OPT =
15292 OpTy->getAs<ObjCObjectPointerType>())
15293 Result = OPT->getPointeeType();
15294 else {
15295 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15296 if (PR.isInvalid()) return QualType();
15297 if (PR.get() != Op)
15298 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15299 }
15300
15301 if (Result.isNull()) {
15302 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15303 << OpTy << Op->getSourceRange();
15304 return QualType();
15305 }
15306
15307 if (Result->isVoidType()) {
15308 // C++ [expr.unary.op]p1:
15309 // [...] the expression to which [the unary * operator] is applied shall
15310 // be a pointer to an object type, or a pointer to a function type
15311 LangOptions LO = S.getLangOpts();
15312 if (LO.CPlusPlus)
15313 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15314 << OpTy << Op->getSourceRange();
15315 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15316 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15317 << OpTy << Op->getSourceRange();
15318 }
15319
15320 // Dereferences are usually l-values...
15321 VK = VK_LValue;
15322
15323 // ...except that certain expressions are never l-values in C.
15324 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15325 VK = VK_PRValue;
15326
15327 return Result;
15328}
15329
15330BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15331 BinaryOperatorKind Opc;
15332 switch (Kind) {
15333 default: llvm_unreachable("Unknown binop!");
15334 case tok::periodstar: Opc = BO_PtrMemD; break;
15335 case tok::arrowstar: Opc = BO_PtrMemI; break;
15336 case tok::star: Opc = BO_Mul; break;
15337 case tok::slash: Opc = BO_Div; break;
15338 case tok::percent: Opc = BO_Rem; break;
15339 case tok::plus: Opc = BO_Add; break;
15340 case tok::minus: Opc = BO_Sub; break;
15341 case tok::lessless: Opc = BO_Shl; break;
15342 case tok::greatergreater: Opc = BO_Shr; break;
15343 case tok::lessequal: Opc = BO_LE; break;
15344 case tok::less: Opc = BO_LT; break;
15345 case tok::greaterequal: Opc = BO_GE; break;
15346 case tok::greater: Opc = BO_GT; break;
15347 case tok::exclaimequal: Opc = BO_NE; break;
15348 case tok::equalequal: Opc = BO_EQ; break;
15349 case tok::spaceship: Opc = BO_Cmp; break;
15350 case tok::amp: Opc = BO_And; break;
15351 case tok::caret: Opc = BO_Xor; break;
15352 case tok::pipe: Opc = BO_Or; break;
15353 case tok::ampamp: Opc = BO_LAnd; break;
15354 case tok::pipepipe: Opc = BO_LOr; break;
15355 case tok::equal: Opc = BO_Assign; break;
15356 case tok::starequal: Opc = BO_MulAssign; break;
15357 case tok::slashequal: Opc = BO_DivAssign; break;
15358 case tok::percentequal: Opc = BO_RemAssign; break;
15359 case tok::plusequal: Opc = BO_AddAssign; break;
15360 case tok::minusequal: Opc = BO_SubAssign; break;
15361 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15362 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15363 case tok::ampequal: Opc = BO_AndAssign; break;
15364 case tok::caretequal: Opc = BO_XorAssign; break;
15365 case tok::pipeequal: Opc = BO_OrAssign; break;
15366 case tok::comma: Opc = BO_Comma; break;
15367 }
15368 return Opc;
15369}
15370
15371static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15372 tok::TokenKind Kind) {
15373 UnaryOperatorKind Opc;
15374 switch (Kind) {
15375 default: llvm_unreachable("Unknown unary op!");
15376 case tok::plusplus: Opc = UO_PreInc; break;
15377 case tok::minusminus: Opc = UO_PreDec; break;
15378 case tok::amp: Opc = UO_AddrOf; break;
15379 case tok::star: Opc = UO_Deref; break;
15380 case tok::plus: Opc = UO_Plus; break;
15381 case tok::minus: Opc = UO_Minus; break;
15382 case tok::tilde: Opc = UO_Not; break;
15383 case tok::exclaim: Opc = UO_LNot; break;
15384 case tok::kw___real: Opc = UO_Real; break;
15385 case tok::kw___imag: Opc = UO_Imag; break;
15386 case tok::kw___extension__: Opc = UO_Extension; break;
15387 }
15388 return Opc;
15389}
15390
15391const FieldDecl *
15392Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15393 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15394 // common for setters.
15395 // struct A {
15396 // int X;
15397 // -void setX(int X) { X = X; }
15398 // +void setX(int X) { this->X = X; }
15399 // };
15400
15401 // Only consider parameters for self assignment fixes.
15402 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15403 return nullptr;
15404 const auto *Method =
15405 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15406 if (!Method)
15407 return nullptr;
15408
15409 const CXXRecordDecl *Parent = Method->getParent();
15410 // In theory this is fixable if the lambda explicitly captures this, but
15411 // that's added complexity that's rarely going to be used.
15412 if (Parent->isLambda())
15413 return nullptr;
15414
15415 // FIXME: Use an actual Lookup operation instead of just traversing fields
15416 // in order to get base class fields.
15417 auto Field =
15418 llvm::find_if(Range: Parent->fields(),
15419 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15420 return F->getDeclName() == Name;
15421 });
15422 return (Field != Parent->field_end()) ? *Field : nullptr;
15423}
15424
15425/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15426/// This warning suppressed in the event of macro expansions.
15427static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15428 SourceLocation OpLoc, bool IsBuiltin) {
15429 if (S.inTemplateInstantiation())
15430 return;
15431 if (S.isUnevaluatedContext())
15432 return;
15433 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15434 return;
15435 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15436 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15437 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15438 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15439 if (!LHSDeclRef || !RHSDeclRef ||
15440 LHSDeclRef->getLocation().isMacroID() ||
15441 RHSDeclRef->getLocation().isMacroID())
15442 return;
15443 const ValueDecl *LHSDecl =
15444 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15445 const ValueDecl *RHSDecl =
15446 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15447 if (LHSDecl != RHSDecl)
15448 return;
15449 if (LHSDecl->getType().isVolatileQualified())
15450 return;
15451 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15452 if (RefTy->getPointeeType().isVolatileQualified())
15453 return;
15454
15455 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15456 : diag::warn_self_assignment_overloaded)
15457 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15458 << RHSExpr->getSourceRange();
15459 if (const FieldDecl *SelfAssignField =
15460 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15461 Diag << 1 << SelfAssignField
15462 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15463 else
15464 Diag << 0;
15465}
15466
15467/// Check if a bitwise-& is performed on an Objective-C pointer. This
15468/// is usually indicative of introspection within the Objective-C pointer.
15469static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15470 SourceLocation OpLoc) {
15471 if (!S.getLangOpts().ObjC)
15472 return;
15473
15474 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15475 const Expr *LHS = L.get();
15476 const Expr *RHS = R.get();
15477
15478 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15479 ObjCPointerExpr = LHS;
15480 OtherExpr = RHS;
15481 }
15482 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15483 ObjCPointerExpr = RHS;
15484 OtherExpr = LHS;
15485 }
15486
15487 // This warning is deliberately made very specific to reduce false
15488 // positives with logic that uses '&' for hashing. This logic mainly
15489 // looks for code trying to introspect into tagged pointers, which
15490 // code should generally never do.
15491 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15492 unsigned Diag = diag::warn_objc_pointer_masking;
15493 // Determine if we are introspecting the result of performSelectorXXX.
15494 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15495 // Special case messages to -performSelector and friends, which
15496 // can return non-pointer values boxed in a pointer value.
15497 // Some clients may wish to silence warnings in this subcase.
15498 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15499 Selector S = ME->getSelector();
15500 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15501 if (SelArg0.starts_with(Prefix: "performSelector"))
15502 Diag = diag::warn_objc_pointer_masking_performSelector;
15503 }
15504
15505 S.Diag(Loc: OpLoc, DiagID: Diag)
15506 << ObjCPointerExpr->getSourceRange();
15507 }
15508}
15509
15510// This helper function promotes a binary operator's operands (which are of a
15511// half vector type) to a vector of floats and then truncates the result to
15512// a vector of either half or short.
15513static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15514 BinaryOperatorKind Opc, QualType ResultTy,
15515 ExprValueKind VK, ExprObjectKind OK,
15516 bool IsCompAssign, SourceLocation OpLoc,
15517 FPOptionsOverride FPFeatures) {
15518 auto &Context = S.getASTContext();
15519 assert((isVector(ResultTy, Context.HalfTy) ||
15520 isVector(ResultTy, Context.ShortTy)) &&
15521 "Result must be a vector of half or short");
15522 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15523 isVector(RHS.get()->getType(), Context.HalfTy) &&
15524 "both operands expected to be a half vector");
15525
15526 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15527 QualType BinOpResTy = RHS.get()->getType();
15528
15529 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15530 // change BinOpResTy to a vector of ints.
15531 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15532 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15533
15534 if (IsCompAssign)
15535 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15536 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15537 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15538
15539 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15540 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15541 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15542 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15543}
15544
15545/// Returns true if conversion between vectors of halfs and vectors of floats
15546/// is needed.
15547static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15548 QualType ResultTy, Expr *E0,
15549 Expr *E1 = nullptr) {
15550 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15551 return false;
15552
15553 // The conversion truncates the result to a half/short vector, so it shouldn't
15554 // apply when the result is not that type (e.g. HLSL comparisons).
15555 if (ResultTy->isVectorType() && !isVector(QT: ResultTy, ElementType: Ctx.HalfTy) &&
15556 !isVector(QT: ResultTy, ElementType: Ctx.ShortTy))
15557 return false;
15558
15559 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15560 QualType Ty = E->IgnoreImplicit()->getType();
15561
15562 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15563 // to vectors of floats. Although the element type of the vectors is __fp16,
15564 // the vectors shouldn't be treated as storage-only types. See the
15565 // discussion here: https://reviews.llvm.org/rG825235c140e7
15566 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15567 if (VT->getVectorKind() == VectorKind::Neon)
15568 return false;
15569 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15570 }
15571 return false;
15572 };
15573
15574 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15575}
15576
15577ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15578 BinaryOperatorKind Opc, Expr *LHSExpr,
15579 Expr *RHSExpr, bool ForFoldExpression) {
15580 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15581 // The syntax only allows initializer lists on the RHS of assignment,
15582 // so we don't need to worry about accepting invalid code for
15583 // non-assignment operators.
15584 // C++11 5.17p9:
15585 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15586 // of x = {} is x = T().
15587 InitializationKind Kind = InitializationKind::CreateDirectList(
15588 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15589 InitializedEntity Entity =
15590 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15591 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15592 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15593 if (Init.isInvalid())
15594 return Init;
15595 RHSExpr = Init.get();
15596 }
15597
15598 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15599 QualType ResultTy; // Result type of the binary operator.
15600 // The following two variables are used for compound assignment operators
15601 QualType CompLHSTy; // Type of LHS after promotions for computation
15602 QualType CompResultTy; // Type of computation result
15603 ExprValueKind VK = VK_PRValue;
15604 ExprObjectKind OK = OK_Ordinary;
15605 bool ConvertHalfVec = false;
15606
15607 if (!LHS.isUsable() || !RHS.isUsable())
15608 return ExprError();
15609
15610 if (getLangOpts().OpenCL) {
15611 QualType LHSTy = LHSExpr->getType();
15612 QualType RHSTy = RHSExpr->getType();
15613 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15614 // the ATOMIC_VAR_INIT macro.
15615 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15616 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15617 if (BO_Assign == Opc)
15618 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15619 else
15620 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15621 return ExprError();
15622 }
15623
15624 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15625 // only with a builtin functions and therefore should be disallowed here.
15626 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15627 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15628 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15629 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15630 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15631 return ExprError();
15632 }
15633 }
15634
15635 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15636 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15637
15638 switch (Opc) {
15639 case BO_Assign:
15640 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15641 if (getLangOpts().CPlusPlus &&
15642 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15643 VK = LHS.get()->getValueKind();
15644 OK = LHS.get()->getObjectKind();
15645 }
15646 if (!ResultTy.isNull()) {
15647 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15648 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15649
15650 // Avoid copying a block to the heap if the block is assigned to a local
15651 // auto variable that is declared in the same scope as the block. This
15652 // optimization is unsafe if the local variable is declared in an outer
15653 // scope. For example:
15654 //
15655 // BlockTy b;
15656 // {
15657 // b = ^{...};
15658 // }
15659 // // It is unsafe to invoke the block here if it wasn't copied to the
15660 // // heap.
15661 // b();
15662
15663 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15664 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15665 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15666 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15667 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15668
15669 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15670 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15671 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15672 }
15673 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15674 break;
15675 case BO_PtrMemD:
15676 case BO_PtrMemI:
15677 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15678 isIndirect: Opc == BO_PtrMemI);
15679 break;
15680 case BO_Mul:
15681 case BO_Div:
15682 ConvertHalfVec = true;
15683 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15684 break;
15685 case BO_Rem:
15686 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15687 break;
15688 case BO_Add:
15689 ConvertHalfVec = true;
15690 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15691 break;
15692 case BO_Sub:
15693 ConvertHalfVec = true;
15694 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15695 break;
15696 case BO_Shl:
15697 case BO_Shr:
15698 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15699 break;
15700 case BO_LE:
15701 case BO_LT:
15702 case BO_GE:
15703 case BO_GT:
15704 ConvertHalfVec = true;
15705 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15706
15707 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15708 !ForFoldExpression && BI && BI->isComparisonOp())
15709 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15710 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15711
15712 break;
15713 case BO_EQ:
15714 case BO_NE:
15715 ConvertHalfVec = true;
15716 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15717 break;
15718 case BO_Cmp:
15719 ConvertHalfVec = true;
15720 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15721 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15722 break;
15723 case BO_And:
15724 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15725 [[fallthrough]];
15726 case BO_Xor:
15727 case BO_Or:
15728 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15729 break;
15730 case BO_LAnd:
15731 case BO_LOr:
15732 ConvertHalfVec = true;
15733 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15734 break;
15735 case BO_MulAssign:
15736 case BO_DivAssign:
15737 ConvertHalfVec = true;
15738 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15739 CompLHSTy = CompResultTy;
15740 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15741 ResultTy =
15742 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15743 break;
15744 case BO_RemAssign:
15745 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15746 CompLHSTy = CompResultTy;
15747 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15748 ResultTy =
15749 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15750 break;
15751 case BO_AddAssign:
15752 ConvertHalfVec = true;
15753 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15754 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15755 ResultTy =
15756 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15757 break;
15758 case BO_SubAssign:
15759 ConvertHalfVec = true;
15760 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15761 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15762 ResultTy =
15763 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15764 break;
15765 case BO_ShlAssign:
15766 case BO_ShrAssign:
15767 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15768 CompLHSTy = CompResultTy;
15769 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15770 ResultTy =
15771 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15772 break;
15773 case BO_AndAssign:
15774 case BO_OrAssign: // fallthrough
15775 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15776 [[fallthrough]];
15777 case BO_XorAssign:
15778 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15779 CompLHSTy = CompResultTy;
15780 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15781 ResultTy =
15782 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15783 break;
15784 case BO_Comma:
15785 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15786 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15787 VK = RHS.get()->getValueKind();
15788 OK = RHS.get()->getObjectKind();
15789 }
15790 break;
15791 }
15792 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15793 return ExprError();
15794
15795 // Some of the binary operations require promoting operands of half vector to
15796 // float vectors and truncating the result back to half vector. For now, we do
15797 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15798 // arm64).
15799 assert(
15800 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15801 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15802 "both sides are half vectors or neither sides are");
15803 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, ResultTy,
15804 E0: LHS.get(), E1: RHS.get());
15805
15806 // Check for array bounds violations for both sides of the BinaryOperator
15807 CheckArrayAccess(E: LHS.get());
15808 CheckArrayAccess(E: RHS.get());
15809
15810 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15811 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15812 Name: &Context.Idents.get(Name: "object_setClass"),
15813 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15814 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15815 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15816 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15817 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15818 Code: "object_setClass(")
15819 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15820 Code: ",")
15821 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15822 }
15823 else
15824 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15825 }
15826 else if (const ObjCIvarRefExpr *OIRE =
15827 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15828 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15829
15830 // Opc is not a compound assignment if CompResultTy is null.
15831 if (CompResultTy.isNull()) {
15832 if (ConvertHalfVec)
15833 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15834 OpLoc, FPFeatures: CurFPFeatureOverrides());
15835 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15836 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15837 }
15838
15839 // Handle compound assignments.
15840 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15841 OK_ObjCProperty) {
15842 VK = VK_LValue;
15843 OK = LHS.get()->getObjectKind();
15844 }
15845
15846 // The LHS is not converted to the result type for fixed-point compound
15847 // assignment as the common type is computed on demand. Reset the CompLHSTy
15848 // to the LHS type we would have gotten after unary conversions.
15849 if (CompResultTy->isFixedPointType())
15850 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15851
15852 if (ConvertHalfVec)
15853 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15854 OpLoc, FPFeatures: CurFPFeatureOverrides());
15855
15856 return CompoundAssignOperator::Create(
15857 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15858 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15859}
15860
15861/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15862/// operators are mixed in a way that suggests that the programmer forgot that
15863/// comparison operators have higher precedence. The most typical example of
15864/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15865static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15866 SourceLocation OpLoc, Expr *LHSExpr,
15867 Expr *RHSExpr) {
15868 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15869 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15870
15871 // Check that one of the sides is a comparison operator and the other isn't.
15872 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15873 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15874 if (isLeftComp == isRightComp)
15875 return;
15876
15877 // Bitwise operations are sometimes used as eager logical ops.
15878 // Don't diagnose this.
15879 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15880 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15881 if (isLeftBitwise || isRightBitwise)
15882 return;
15883
15884 SourceRange DiagRange = isLeftComp
15885 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15886 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15887 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15888 SourceRange ParensRange =
15889 isLeftComp
15890 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15891 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15892
15893 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15894 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15895 SuggestParentheses(Self, Loc: OpLoc,
15896 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15897 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15898 SuggestParentheses(Self, Loc: OpLoc,
15899 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15900 << BinaryOperator::getOpcodeStr(Op: Opc),
15901 ParenRange: ParensRange);
15902}
15903
15904/// It accepts a '&&' expr that is inside a '||' one.
15905/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15906/// in parentheses.
15907static void
15908EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15909 BinaryOperator *Bop) {
15910 assert(Bop->getOpcode() == BO_LAnd);
15911 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15912 << Bop->getSourceRange() << OpLoc;
15913 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15914 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15915 << Bop->getOpcodeStr(),
15916 ParenRange: Bop->getSourceRange());
15917}
15918
15919/// Look for '&&' in the left hand of a '||' expr.
15920static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15921 Expr *LHSExpr, Expr *RHSExpr) {
15922 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15923 if (Bop->getOpcode() == BO_LAnd) {
15924 // If it's "string_literal && a || b" don't warn since the precedence
15925 // doesn't matter.
15926 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15927 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15928 } else if (Bop->getOpcode() == BO_LOr) {
15929 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15930 // If it's "a || b && string_literal || c" we didn't warn earlier for
15931 // "a || b && string_literal", but warn now.
15932 if (RBop->getOpcode() == BO_LAnd &&
15933 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15934 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15935 }
15936 }
15937 }
15938}
15939
15940/// Look for '&&' in the right hand of a '||' expr.
15941static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15942 Expr *LHSExpr, Expr *RHSExpr) {
15943 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15944 if (Bop->getOpcode() == BO_LAnd) {
15945 // If it's "a || b && string_literal" don't warn since the precedence
15946 // doesn't matter.
15947 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15948 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15949 }
15950 }
15951}
15952
15953/// Look for bitwise op in the left or right hand of a bitwise op with
15954/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15955/// the '&' expression in parentheses.
15956static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15957 SourceLocation OpLoc, Expr *SubExpr) {
15958 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15959 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15960 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15961 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15962 << Bop->getSourceRange() << OpLoc;
15963 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15964 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15965 << Bop->getOpcodeStr(),
15966 ParenRange: Bop->getSourceRange());
15967 }
15968 }
15969}
15970
15971static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15972 Expr *SubExpr, StringRef Shift) {
15973 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15974 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15975 StringRef Op = Bop->getOpcodeStr();
15976 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15977 << Bop->getSourceRange() << OpLoc << Shift << Op;
15978 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15979 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15980 ParenRange: Bop->getSourceRange());
15981 }
15982 }
15983}
15984
15985static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15986 Expr *LHSExpr, Expr *RHSExpr) {
15987 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15988 if (!OCE)
15989 return;
15990
15991 FunctionDecl *FD = OCE->getDirectCallee();
15992 if (!FD || !FD->isOverloadedOperator())
15993 return;
15994
15995 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15996 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15997 return;
15998
15999 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
16000 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16001 << (Kind == OO_LessLess);
16002 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
16003 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16004 << (Kind == OO_LessLess ? "<<" : ">>"),
16005 ParenRange: OCE->getSourceRange());
16006 SuggestParentheses(
16007 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
16008 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
16009}
16010
16011/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16012/// precedence.
16013static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16014 SourceLocation OpLoc, Expr *LHSExpr,
16015 Expr *RHSExpr){
16016 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16017 if (BinaryOperator::isBitwiseOp(Opc))
16018 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16019
16020 // Diagnose "arg1 & arg2 | arg3"
16021 if ((Opc == BO_Or || Opc == BO_Xor) &&
16022 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16023 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
16024 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
16025 }
16026
16027 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16028 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16029 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16030 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16031 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16032 }
16033
16034 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16035 || Opc == BO_Shr) {
16036 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16037 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16038 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16039 }
16040
16041 // Warn on overloaded shift operators and comparisons, such as:
16042 // cout << 5 == 4;
16043 if (BinaryOperator::isComparisonOp(Opc))
16044 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16045}
16046
16047ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16048 tok::TokenKind Kind,
16049 Expr *LHSExpr, Expr *RHSExpr) {
16050 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16051 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16052 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16053
16054 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16055 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16056
16057 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
16058 ? BuiltinCountedByRefKind::Assignment
16059 : BuiltinCountedByRefKind::BinaryExpr;
16060
16061 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
16062 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
16063
16064 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16065}
16066
16067void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16068 UnresolvedSetImpl &Functions) {
16069 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16070 if (OverOp != OO_None && OverOp != OO_Equal)
16071 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16072
16073 // In C++20 onwards, we may have a second operator to look up.
16074 if (getLangOpts().CPlusPlus20) {
16075 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16076 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16077 }
16078}
16079
16080/// Build an overloaded binary operator expression in the given scope.
16081static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16082 BinaryOperatorKind Opc,
16083 Expr *LHS, Expr *RHS) {
16084 switch (Opc) {
16085 case BO_Assign:
16086 // In the non-overloaded case, we warn about self-assignment (x = x) for
16087 // both simple assignment and certain compound assignments where algebra
16088 // tells us the operation yields a constant result. When the operator is
16089 // overloaded, we can't do the latter because we don't want to assume that
16090 // those algebraic identities still apply; for example, a path-building
16091 // library might use operator/= to append paths. But it's still reasonable
16092 // to assume that simple assignment is just moving/copying values around
16093 // and so self-assignment is likely a bug.
16094 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16095 [[fallthrough]];
16096 case BO_DivAssign:
16097 case BO_RemAssign:
16098 case BO_SubAssign:
16099 case BO_AndAssign:
16100 case BO_OrAssign:
16101 case BO_XorAssign:
16102 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16103 break;
16104 default:
16105 break;
16106 }
16107
16108 // Find all of the overloaded operators visible from this point.
16109 UnresolvedSet<16> Functions;
16110 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16111
16112 // Build the (potentially-overloaded, potentially-dependent)
16113 // binary operation.
16114 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16115}
16116
16117ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16118 BinaryOperatorKind Opc, Expr *LHSExpr,
16119 Expr *RHSExpr, bool ForFoldExpression) {
16120 if (!LHSExpr || !RHSExpr)
16121 return ExprError();
16122
16123 // We want to end up calling one of SemaPseudoObject::checkAssignment
16124 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16125 // both expressions are overloadable or either is type-dependent),
16126 // or CreateBuiltinBinOp (in any other case). We also want to get
16127 // any placeholder types out of the way.
16128
16129 // Handle pseudo-objects in the LHS.
16130 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16131 // Assignments with a pseudo-object l-value need special analysis.
16132 if (pty->getKind() == BuiltinType::PseudoObject &&
16133 BinaryOperator::isAssignmentOp(Opc))
16134 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16135
16136 // Don't resolve overloads if the other type is overloadable.
16137 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16138 // We can't actually test that if we still have a placeholder,
16139 // though. Fortunately, none of the exceptions we see in that
16140 // code below are valid when the LHS is an overload set. Note
16141 // that an overload set can be dependently-typed, but it never
16142 // instantiates to having an overloadable type.
16143 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16144 if (resolvedRHS.isInvalid()) return ExprError();
16145 RHSExpr = resolvedRHS.get();
16146
16147 if (RHSExpr->isTypeDependent() ||
16148 RHSExpr->getType()->isOverloadableType())
16149 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16150 }
16151
16152 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16153 // template, diagnose the missing 'template' keyword instead of diagnosing
16154 // an invalid use of a bound member function.
16155 //
16156 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16157 // to C++1z [over.over]/1.4, but we already checked for that case above.
16158 if (Opc == BO_LT && inTemplateInstantiation() &&
16159 (pty->getKind() == BuiltinType::BoundMember ||
16160 pty->getKind() == BuiltinType::Overload)) {
16161 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16162 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16163 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16164 return isa<FunctionTemplateDecl>(Val: ND);
16165 })) {
16166 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16167 : OE->getNameLoc(),
16168 DiagID: diag::err_template_kw_missing)
16169 << OE->getName().getAsIdentifierInfo();
16170 return ExprError();
16171 }
16172 }
16173
16174 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16175 if (LHS.isInvalid()) return ExprError();
16176 LHSExpr = LHS.get();
16177 }
16178
16179 // Handle pseudo-objects in the RHS.
16180 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16181 // An overload in the RHS can potentially be resolved by the type
16182 // being assigned to.
16183 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16184 if (getLangOpts().CPlusPlus &&
16185 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16186 LHSExpr->getType()->isOverloadableType()))
16187 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16188
16189 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16190 ForFoldExpression);
16191 }
16192
16193 // Don't resolve overloads if the other type is overloadable.
16194 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16195 LHSExpr->getType()->isOverloadableType())
16196 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16197
16198 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16199 if (!resolvedRHS.isUsable()) return ExprError();
16200 RHSExpr = resolvedRHS.get();
16201 }
16202
16203 if (getLangOpts().HLSL) {
16204 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16205 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16206 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16207 return ExprError();
16208 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16209 std::optional<ExprResult> ConvRHS =
16210 HLSL().tryPerformConstantBufferConversion(BaseExpr: RHSExpr);
16211 if (ConvRHS && Context.hasSameUnqualifiedType(
16212 T1: LHSExpr->getType(), T2: ConvRHS->get()->getType())) {
16213 assert(!ConvRHS->isInvalid());
16214 RHSExpr = ConvRHS->get();
16215 }
16216 }
16217 }
16218
16219 if (getLangOpts().CPlusPlus) {
16220 bool CanOverloadBinOp =
16221 !getLangOpts().HLSL ||
16222 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16223 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16224 bool TypeDependent =
16225 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16226 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16227 RHSExpr->getType()->isOverloadableType();
16228 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16229 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16230 }
16231
16232 if (getLangOpts().RecoveryAST &&
16233 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16234 assert(!getLangOpts().CPlusPlus);
16235 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16236 "Should only occur in error-recovery path.");
16237 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16238 // C [6.15.16] p3:
16239 // An assignment expression has the value of the left operand after the
16240 // assignment, but is not an lvalue.
16241 return CompoundAssignOperator::Create(
16242 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16243 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16244 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16245 QualType ResultType;
16246 switch (Opc) {
16247 case BO_Assign:
16248 ResultType = LHSExpr->getType().getUnqualifiedType();
16249 break;
16250 case BO_LT:
16251 case BO_GT:
16252 case BO_LE:
16253 case BO_GE:
16254 case BO_EQ:
16255 case BO_NE:
16256 case BO_LAnd:
16257 case BO_LOr:
16258 // These operators have a fixed result type regardless of operands.
16259 ResultType = Context.IntTy;
16260 break;
16261 case BO_Comma:
16262 ResultType = RHSExpr->getType();
16263 break;
16264 default:
16265 ResultType = Context.DependentTy;
16266 break;
16267 }
16268 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16269 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16270 FPFeatures: CurFPFeatureOverrides());
16271 }
16272
16273 // Build a built-in binary operation.
16274 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16275}
16276
16277static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16278 if (T.isNull() || T->isDependentType())
16279 return false;
16280
16281 if (!Ctx.isPromotableIntegerType(T))
16282 return true;
16283
16284 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16285}
16286
16287ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16288 UnaryOperatorKind Opc, Expr *InputExpr,
16289 bool IsAfterAmp) {
16290 ExprResult Input = InputExpr;
16291 ExprValueKind VK = VK_PRValue;
16292 ExprObjectKind OK = OK_Ordinary;
16293 QualType resultType;
16294 bool CanOverflow = false;
16295
16296 bool ConvertHalfVec = false;
16297 if (getLangOpts().OpenCL) {
16298 QualType Ty = InputExpr->getType();
16299 // The only legal unary operation for atomics is '&'.
16300 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16301 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16302 // only with a builtin functions and therefore should be disallowed here.
16303 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16304 || Ty->isBlockPointerType())) {
16305 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16306 << InputExpr->getType()
16307 << Input.get()->getSourceRange());
16308 }
16309 }
16310
16311 if (getLangOpts().HLSL && OpLoc.isValid()) {
16312 if (Opc == UO_AddrOf)
16313 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16314 if (Opc == UO_Deref)
16315 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16316 }
16317
16318 if (InputExpr->isTypeDependent() &&
16319 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16320 resultType = Context.DependentTy;
16321 } else {
16322 switch (Opc) {
16323 case UO_PreInc:
16324 case UO_PreDec:
16325 case UO_PostInc:
16326 case UO_PostDec:
16327 resultType =
16328 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16329 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16330 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16331 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16332 break;
16333 case UO_AddrOf:
16334 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16335 CheckAddressOfNoDeref(E: InputExpr);
16336 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16337 break;
16338 case UO_Deref: {
16339 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16340 if (Input.isInvalid())
16341 return ExprError();
16342 resultType =
16343 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16344 break;
16345 }
16346 case UO_Plus:
16347 case UO_Minus:
16348 CanOverflow = Opc == UO_Minus &&
16349 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16350 Input = UsualUnaryConversions(E: Input.get());
16351 if (Input.isInvalid())
16352 return ExprError();
16353 // Unary plus and minus require promoting an operand of half vector to a
16354 // float vector and truncating the result back to a half vector. For now,
16355 // we do this only when HalfArgsAndReturns is set (that is, when the
16356 // target is arm or arm64).
16357 ConvertHalfVec = needsConversionOfHalfVec(
16358 OpRequiresConversion: true, Ctx&: Context, ResultTy: Input.get()->getType(), E0: Input.get());
16359
16360 // If the operand is a half vector, promote it to a float vector.
16361 if (ConvertHalfVec)
16362 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16363 resultType = Input.get()->getType();
16364 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16365 break;
16366 else if (resultType->isVectorType() &&
16367 // The z vector extensions don't allow + or - with bool vectors.
16368 (!Context.getLangOpts().ZVector ||
16369 resultType->castAs<VectorType>()->getVectorKind() !=
16370 VectorKind::AltiVecBool))
16371 break;
16372 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16373 break;
16374 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16375 Opc == UO_Plus && resultType->isPointerType())
16376 break;
16377
16378 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16379 << resultType << Input.get()->getSourceRange());
16380
16381 case UO_Not: // bitwise complement
16382 Input = UsualUnaryConversions(E: Input.get());
16383 if (Input.isInvalid())
16384 return ExprError();
16385 resultType = Input.get()->getType();
16386 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16387 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16388 // C99 does not support '~' for complex conjugation.
16389 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16390 << resultType << Input.get()->getSourceRange();
16391 else if (resultType->hasIntegerRepresentation())
16392 break;
16393 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16394 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16395 // on vector float types.
16396 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16397 if (!T->isIntegerType())
16398 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16399 << resultType << Input.get()->getSourceRange());
16400 } else {
16401 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16402 << resultType << Input.get()->getSourceRange());
16403 }
16404 break;
16405
16406 case UO_LNot: // logical negation
16407 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16408 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16409 if (Input.isInvalid())
16410 return ExprError();
16411 resultType = Input.get()->getType();
16412
16413 // Though we still have to promote half FP to float...
16414 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16415 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16416 .get();
16417 resultType = Context.FloatTy;
16418 }
16419
16420 // WebAsembly tables can't be used in unary expressions.
16421 if (resultType->isPointerType() &&
16422 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16423 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16424 << resultType << Input.get()->getSourceRange());
16425 }
16426
16427 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16428 // C99 6.5.3.3p1: ok, fallthrough;
16429 if (Context.getLangOpts().CPlusPlus) {
16430 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16431 // operand contextually converted to bool.
16432 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16433 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16434 } else if (Context.getLangOpts().OpenCL &&
16435 Context.getLangOpts().OpenCLVersion < 120) {
16436 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16437 // operate on scalar float types.
16438 if (!resultType->isIntegerType() && !resultType->isPointerType())
16439 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16440 << resultType << Input.get()->getSourceRange());
16441 }
16442 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16443 !resultType->hasBooleanRepresentation()) {
16444 // HLSL unary logical 'not' behaves like C++, which states that the
16445 // operand is converted to bool and the result is bool, however HLSL
16446 // extends this property to vectors.
16447 const VectorType *VTy = resultType->castAs<VectorType>();
16448 resultType =
16449 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16450
16451 Input = ImpCastExprToType(
16452 E: Input.get(), Type: resultType,
16453 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16454 .get();
16455 break;
16456 } else if (resultType->isExtVectorType()) {
16457 if (Context.getLangOpts().OpenCL &&
16458 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16459 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16460 // operate on vector float types.
16461 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16462 if (!T->isIntegerType())
16463 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16464 << resultType << Input.get()->getSourceRange());
16465 }
16466 // Vector logical not returns the signed variant of the operand type.
16467 resultType = GetSignedVectorType(V: resultType);
16468 break;
16469 } else if (Context.getLangOpts().CPlusPlus &&
16470 resultType->isVectorType()) {
16471 const VectorType *VTy = resultType->castAs<VectorType>();
16472 if (VTy->getVectorKind() != VectorKind::Generic)
16473 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16474 << resultType << Input.get()->getSourceRange());
16475
16476 // Vector logical not returns the signed variant of the operand type.
16477 resultType = GetSignedVectorType(V: resultType);
16478 break;
16479 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16480 resultType = Context.getLogicalOperationType();
16481 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16482 break;
16483 } else {
16484 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16485 << resultType << Input.get()->getSourceRange());
16486 }
16487
16488 // LNot always has type int. C99 6.5.3.3p5.
16489 // In C++, it's bool. C++ 5.3.1p8
16490 resultType = Context.getLogicalOperationType();
16491 break;
16492 case UO_Real:
16493 case UO_Imag:
16494 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16495 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16496 // ordinary complex l-values to ordinary l-values and all other values to
16497 // r-values.
16498 if (Input.isInvalid())
16499 return ExprError();
16500 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16501 if (Input.get()->isGLValue() &&
16502 Input.get()->getObjectKind() == OK_Ordinary)
16503 VK = Input.get()->getValueKind();
16504 } else if (!getLangOpts().CPlusPlus) {
16505 // In C, a volatile scalar is read by __imag. In C++, it is not.
16506 Input = DefaultLvalueConversion(E: Input.get());
16507 }
16508 break;
16509 case UO_Extension:
16510 resultType = Input.get()->getType();
16511 VK = Input.get()->getValueKind();
16512 OK = Input.get()->getObjectKind();
16513 break;
16514 case UO_Coawait:
16515 // It's unnecessary to represent the pass-through operator co_await in the
16516 // AST; just return the input expression instead.
16517 assert(!Input.get()->getType()->isDependentType() &&
16518 "the co_await expression must be non-dependant before "
16519 "building operator co_await");
16520 return Input;
16521 }
16522 }
16523 if (resultType.isNull() || Input.isInvalid())
16524 return ExprError();
16525
16526 // Check for array bounds violations in the operand of the UnaryOperator,
16527 // except for the '*' and '&' operators that have to be handled specially
16528 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16529 // that are explicitly defined as valid by the standard).
16530 if (Opc != UO_AddrOf && Opc != UO_Deref)
16531 CheckArrayAccess(E: Input.get());
16532
16533 auto *UO =
16534 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16535 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16536
16537 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16538 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16539 !isUnevaluatedContext())
16540 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16541
16542 // Convert the result back to a half vector.
16543 if (ConvertHalfVec)
16544 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16545 return UO;
16546}
16547
16548bool Sema::isQualifiedMemberAccess(Expr *E) {
16549 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16550 if (!DRE->getQualifier())
16551 return false;
16552
16553 ValueDecl *VD = DRE->getDecl();
16554 if (!VD->isCXXClassMember())
16555 return false;
16556
16557 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16558 return true;
16559 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16560 return Method->isImplicitObjectMemberFunction();
16561
16562 return false;
16563 }
16564
16565 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16566 if (!ULE->getQualifier())
16567 return false;
16568
16569 for (NamedDecl *D : ULE->decls()) {
16570 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16571 if (Method->isImplicitObjectMemberFunction())
16572 return true;
16573 } else {
16574 // Overload set does not contain methods.
16575 break;
16576 }
16577 }
16578
16579 return false;
16580 }
16581
16582 return false;
16583}
16584
16585ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16586 UnaryOperatorKind Opc, Expr *Input,
16587 bool IsAfterAmp) {
16588 // First things first: handle placeholders so that the
16589 // overloaded-operator check considers the right type.
16590 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16591 // Increment and decrement of pseudo-object references.
16592 if (pty->getKind() == BuiltinType::PseudoObject &&
16593 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16594 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16595
16596 // extension is always a builtin operator.
16597 if (Opc == UO_Extension)
16598 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16599
16600 // & gets special logic for several kinds of placeholder.
16601 // The builtin code knows what to do.
16602 if (Opc == UO_AddrOf &&
16603 (pty->getKind() == BuiltinType::Overload ||
16604 pty->getKind() == BuiltinType::UnknownAny ||
16605 pty->getKind() == BuiltinType::BoundMember))
16606 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16607
16608 // Anything else needs to be handled now.
16609 ExprResult Result = CheckPlaceholderExpr(E: Input);
16610 if (Result.isInvalid()) return ExprError();
16611 Input = Result.get();
16612 }
16613
16614 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16615 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16616 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16617 // Find all of the overloaded operators visible from this point.
16618 UnresolvedSet<16> Functions;
16619 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16620 if (S && OverOp != OO_None)
16621 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16622
16623 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16624 }
16625
16626 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16627}
16628
16629ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16630 Expr *Input, bool IsAfterAmp) {
16631 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16632 IsAfterAmp);
16633}
16634
16635ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16636 LabelDecl *TheDecl) {
16637 TheDecl->markUsed(C&: Context);
16638 // Create the AST node. The address of a label always has type 'void*'.
16639 auto *Res = new (Context) AddrLabelExpr(
16640 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16641
16642 if (getCurFunction())
16643 getCurFunction()->AddrLabels.push_back(Elt: Res);
16644
16645 return Res;
16646}
16647
16648void Sema::ActOnStartStmtExpr() {
16649 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16650 // Make sure we diagnose jumping into a statement expression.
16651 setFunctionHasBranchProtectedScope();
16652}
16653
16654void Sema::ActOnStmtExprError() {
16655 // Note that function is also called by TreeTransform when leaving a
16656 // StmtExpr scope without rebuilding anything.
16657
16658 DiscardCleanupsInEvaluationContext();
16659 PopExpressionEvaluationContext();
16660}
16661
16662ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16663 SourceLocation RPLoc) {
16664 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16665}
16666
16667ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16668 SourceLocation RPLoc, unsigned TemplateDepth) {
16669 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16670 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16671
16672 if (hasAnyUnrecoverableErrorsInThisFunction())
16673 DiscardCleanupsInEvaluationContext();
16674 assert(!Cleanup.exprNeedsCleanups() &&
16675 "cleanups within StmtExpr not correctly bound!");
16676 PopExpressionEvaluationContext();
16677
16678 // FIXME: there are a variety of strange constraints to enforce here, for
16679 // example, it is not possible to goto into a stmt expression apparently.
16680 // More semantic analysis is needed.
16681
16682 // If there are sub-stmts in the compound stmt, take the type of the last one
16683 // as the type of the stmtexpr.
16684 QualType Ty = Context.VoidTy;
16685 bool StmtExprMayBindToTemp = false;
16686 if (!Compound->body_empty()) {
16687 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16688 if (const Expr *Value = LastStmt->getExprStmt()) {
16689 StmtExprMayBindToTemp = true;
16690 Ty = Value->getType();
16691 }
16692 }
16693 }
16694
16695 // FIXME: Check that expression type is complete/non-abstract; statement
16696 // expressions are not lvalues.
16697 Expr *ResStmtExpr =
16698 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16699 if (StmtExprMayBindToTemp)
16700 return MaybeBindToTemporary(E: ResStmtExpr);
16701 return ResStmtExpr;
16702}
16703
16704ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16705 if (ER.isInvalid())
16706 return ExprError();
16707
16708 // Do function/array conversion on the last expression, but not
16709 // lvalue-to-rvalue. However, initialize an unqualified type.
16710 ER = DefaultFunctionArrayConversion(E: ER.get());
16711 if (ER.isInvalid())
16712 return ExprError();
16713 Expr *E = ER.get();
16714
16715 if (E->isTypeDependent())
16716 return E;
16717
16718 // In ARC, if the final expression ends in a consume, splice
16719 // the consume out and bind it later. In the alternate case
16720 // (when dealing with a retainable type), the result
16721 // initialization will create a produce. In both cases the
16722 // result will be +1, and we'll need to balance that out with
16723 // a bind.
16724 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16725 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16726 return Cast->getSubExpr();
16727
16728 // FIXME: Provide a better location for the initialization.
16729 return PerformCopyInitialization(
16730 Entity: InitializedEntity::InitializeStmtExprResult(
16731 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16732 EqualLoc: SourceLocation(), Init: E);
16733}
16734
16735ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16736 TypeSourceInfo *TInfo,
16737 const Designation &Desig,
16738 SourceLocation RParenLoc) {
16739 QualType ArgTy = TInfo->getType();
16740 bool Dependent = ArgTy->isDependentType();
16741 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16742
16743 // We must have at least one component that refers to the type, and the first
16744 // one is known to be a field designator. Verify that the ArgTy represents
16745 // a struct/union/class.
16746 if (!Dependent && !ArgTy->isRecordType())
16747 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16748 << ArgTy << TypeRange);
16749
16750 // Type must be complete per C99 7.17p3 because a declaring a variable
16751 // with an incomplete type would be ill-formed.
16752 if (!Dependent
16753 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16754 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16755 return ExprError();
16756
16757 bool DidWarnAboutNonPOD = false;
16758 QualType CurrentType = ArgTy;
16759 SmallVector<OffsetOfNode, 4> Comps;
16760 SmallVector<Expr *, 4> Exprs;
16761 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16762 const Designator &D = Desig.getDesignator(Idx: I);
16763 assert(!D.isArrayRangeDesignator());
16764 if (D.isArrayDesignator()) {
16765 // Offset of an array sub-field. TODO: Should we allow vector elements?
16766 if (!CurrentType->isDependentType()) {
16767 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16768 if(!AT)
16769 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
16770 << CurrentType);
16771 CurrentType = AT->getElementType();
16772 } else
16773 CurrentType = Context.DependentTy;
16774
16775 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
16776 if (IdxRval.isInvalid())
16777 return ExprError();
16778 Expr *Idx = IdxRval.get();
16779
16780 // The expression must be an integral expression.
16781 // FIXME: An integral constant expression?
16782 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16783 !Idx->getType()->isIntegerType())
16784 return ExprError(
16785 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16786 << Idx->getSourceRange());
16787
16788 // Record this array index.
16789 Comps.push_back(
16790 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16791 Exprs.push_back(Elt: Idx);
16792 continue;
16793 }
16794
16795 assert(D.isFieldDesignator());
16796 const IdentifierInfo *Name = D.getFieldDecl();
16797
16798 // Offset of a field.
16799 if (CurrentType->isDependentType()) {
16800 // We have the offset of a field, but we can't look into the dependent
16801 // type. Just record the identifier of the field.
16802 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16803 CurrentType = Context.DependentTy;
16804 continue;
16805 }
16806
16807 // We need to have a complete type to look into.
16808 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
16809 DiagID: diag::err_offsetof_incomplete_type))
16810 return ExprError();
16811
16812 // Look for the designated field.
16813 auto *RD = CurrentType->getAsRecordDecl();
16814 if (!RD)
16815 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
16816 << CurrentType);
16817
16818 // C++ [lib.support.types]p5:
16819 // The macro offsetof accepts a restricted set of type arguments in this
16820 // International Standard. type shall be a POD structure or a POD union
16821 // (clause 9).
16822 // C++11 [support.types]p4:
16823 // If type is not a standard-layout class (Clause 9), the results are
16824 // undefined.
16825 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16826 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16827 unsigned DiagID =
16828 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16829 : diag::ext_offsetof_non_pod_type;
16830
16831 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16832 Diag(Loc: BuiltinLoc, DiagID)
16833 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
16834 << CurrentType;
16835 DidWarnAboutNonPOD = true;
16836 }
16837 }
16838
16839 // Look for the field.
16840 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
16841 LookupQualifiedName(R, LookupCtx: RD);
16842 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16843 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16844 if (!MemberDecl) {
16845 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16846 MemberDecl = IndirectMemberDecl->getAnonField();
16847 }
16848
16849 if (!MemberDecl) {
16850 // Lookup could be ambiguous when looking up a placeholder variable
16851 // __builtin_offsetof(S, _).
16852 // In that case we would already have emitted a diagnostic
16853 if (!R.isAmbiguous())
16854 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16855 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
16856 return ExprError();
16857 }
16858
16859 // C99 7.17p3:
16860 // (If the specified member is a bit-field, the behavior is undefined.)
16861 //
16862 // We diagnose this as an error.
16863 if (MemberDecl->isBitField()) {
16864 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
16865 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16866 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16867 return ExprError();
16868 }
16869
16870 RecordDecl *Parent = MemberDecl->getParent();
16871 if (IndirectMemberDecl)
16872 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16873
16874 // If the member was found in a base class, introduce OffsetOfNodes for
16875 // the base class indirections.
16876 CXXBasePaths Paths;
16877 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
16878 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16879 if (Paths.getDetectedVirtual()) {
16880 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
16881 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16882 return ExprError();
16883 }
16884
16885 CXXBasePath &Path = Paths.front();
16886 for (const CXXBasePathElement &B : Path)
16887 Comps.push_back(Elt: OffsetOfNode(B.Base));
16888 }
16889
16890 if (IndirectMemberDecl) {
16891 for (auto *FI : IndirectMemberDecl->chain()) {
16892 assert(isa<FieldDecl>(FI));
16893 Comps.push_back(
16894 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
16895 }
16896 } else
16897 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
16898
16899 CurrentType = MemberDecl->getType().getNonReferenceType();
16900 }
16901
16902 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16903 comps: Comps, exprs: Exprs, RParenLoc);
16904}
16905
16906ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
16907 SourceLocation TypeLoc,
16908 ParsedType ParsedArgTy,
16909 const Designation &Desig,
16910 SourceLocation RParenLoc) {
16911
16912 TypeSourceInfo *ArgTInfo;
16913 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16914 if (ArgTy.isNull())
16915 return ExprError();
16916
16917 if (!ArgTInfo)
16918 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16919
16920 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
16921}
16922
16923ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16924 Expr *CondExpr,
16925 Expr *LHSExpr, Expr *RHSExpr,
16926 SourceLocation RPLoc) {
16927 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16928
16929 ExprValueKind VK = VK_PRValue;
16930 ExprObjectKind OK = OK_Ordinary;
16931 QualType resType;
16932 bool CondIsTrue = false;
16933 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16934 resType = Context.DependentTy;
16935 } else {
16936 // The conditional expression is required to be a constant expression.
16937 llvm::APSInt condEval(32);
16938 ExprResult CondICE = VerifyIntegerConstantExpression(
16939 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16940 if (CondICE.isInvalid())
16941 return ExprError();
16942 CondExpr = CondICE.get();
16943 CondIsTrue = condEval.getZExtValue();
16944
16945 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16946 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16947
16948 resType = ActiveExpr->getType();
16949 VK = ActiveExpr->getValueKind();
16950 OK = ActiveExpr->getObjectKind();
16951 }
16952
16953 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16954 resType, VK, OK, RPLoc, CondIsTrue);
16955}
16956
16957//===----------------------------------------------------------------------===//
16958// Clang Extensions.
16959//===----------------------------------------------------------------------===//
16960
16961void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16962 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16963
16964 if (LangOpts.CPlusPlus) {
16965 MangleNumberingContext *MCtx;
16966 Decl *ManglingContextDecl;
16967 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16968 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16969 if (MCtx) {
16970 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16971 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16972 }
16973 }
16974
16975 PushBlockScope(BlockScope: CurScope, Block);
16976 CurContext->addDecl(D: Block);
16977 if (CurScope)
16978 PushDeclContext(S: CurScope, DC: Block);
16979 else
16980 CurContext = Block;
16981
16982 getCurBlock()->HasImplicitReturnType = true;
16983
16984 // Enter a new evaluation context to insulate the block from any
16985 // cleanups from the enclosing full-expression.
16986 PushExpressionEvaluationContext(
16987 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16988}
16989
16990void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16991 Scope *CurScope) {
16992 assert(ParamInfo.getIdentifier() == nullptr &&
16993 "block-id should have no identifier!");
16994 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16995 BlockScopeInfo *CurBlock = getCurBlock();
16996
16997 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16998 QualType T = Sig->getType();
16999 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
17000
17001 // GetTypeForDeclarator always produces a function type for a block
17002 // literal signature. Furthermore, it is always a FunctionProtoType
17003 // unless the function was written with a typedef.
17004 assert(T->isFunctionType() &&
17005 "GetTypeForDeclarator made a non-function block signature");
17006
17007 // Look for an explicit signature in that function type.
17008 FunctionProtoTypeLoc ExplicitSignature;
17009
17010 if ((ExplicitSignature = Sig->getTypeLoc()
17011 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17012
17013 // Check whether that explicit signature was synthesized by
17014 // GetTypeForDeclarator. If so, don't save that as part of the
17015 // written signature.
17016 if (ExplicitSignature.getLocalRangeBegin() ==
17017 ExplicitSignature.getLocalRangeEnd()) {
17018 // This would be much cheaper if we stored TypeLocs instead of
17019 // TypeSourceInfos.
17020 TypeLoc Result = ExplicitSignature.getReturnLoc();
17021 unsigned Size = Result.getFullDataSize();
17022 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
17023 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
17024
17025 ExplicitSignature = FunctionProtoTypeLoc();
17026 }
17027 }
17028
17029 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17030 CurBlock->FunctionType = T;
17031
17032 const auto *Fn = T->castAs<FunctionType>();
17033 QualType RetTy = Fn->getReturnType();
17034 bool isVariadic =
17035 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17036
17037 CurBlock->TheDecl->setIsVariadic(isVariadic);
17038
17039 // Context.DependentTy is used as a placeholder for a missing block
17040 // return type. TODO: what should we do with declarators like:
17041 // ^ * { ... }
17042 // If the answer is "apply template argument deduction"....
17043 if (RetTy != Context.DependentTy) {
17044 CurBlock->ReturnType = RetTy;
17045 CurBlock->TheDecl->setBlockMissingReturnType(false);
17046 CurBlock->HasImplicitReturnType = false;
17047 }
17048
17049 // Push block parameters from the declarator if we had them.
17050 SmallVector<ParmVarDecl*, 8> Params;
17051 if (ExplicitSignature) {
17052 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17053 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
17054 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17055 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17056 // Diagnose this as an extension in C17 and earlier.
17057 if (!getLangOpts().C23)
17058 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
17059 }
17060 Params.push_back(Elt: Param);
17061 }
17062
17063 // Fake up parameter variables if we have a typedef, like
17064 // ^ fntype { ... }
17065 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17066 for (const auto &I : Fn->param_types()) {
17067 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17068 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
17069 Params.push_back(Elt: Param);
17070 }
17071 }
17072
17073 // Set the parameters on the block decl.
17074 if (!Params.empty()) {
17075 CurBlock->TheDecl->setParams(Params);
17076 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17077 /*CheckParameterNames=*/false);
17078 }
17079
17080 // Finally we can process decl attributes.
17081 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17082
17083 // Put the parameter variables in scope.
17084 for (auto *AI : CurBlock->TheDecl->parameters()) {
17085 AI->setOwningFunction(CurBlock->TheDecl);
17086
17087 // If this has an identifier, add it to the scope stack.
17088 if (AI->getIdentifier()) {
17089 CheckShadow(S: CurBlock->TheScope, D: AI);
17090
17091 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17092 }
17093
17094 if (AI->isInvalidDecl())
17095 CurBlock->TheDecl->setInvalidDecl();
17096 }
17097}
17098
17099void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17100 // Leave the expression-evaluation context.
17101 DiscardCleanupsInEvaluationContext();
17102 PopExpressionEvaluationContext();
17103
17104 // Pop off CurBlock, handle nested blocks.
17105 PopDeclContext();
17106 PopFunctionScopeInfo();
17107}
17108
17109ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17110 Stmt *Body, Scope *CurScope) {
17111 // If blocks are disabled, emit an error.
17112 if (!LangOpts.Blocks)
17113 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17114
17115 // Leave the expression-evaluation context.
17116 if (hasAnyUnrecoverableErrorsInThisFunction())
17117 DiscardCleanupsInEvaluationContext();
17118 assert(!Cleanup.exprNeedsCleanups() &&
17119 "cleanups within block not correctly bound!");
17120 PopExpressionEvaluationContext();
17121
17122 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17123 BlockDecl *BD = BSI->TheDecl;
17124
17125 maybeAddDeclWithEffects(D: BD);
17126
17127 if (BSI->HasImplicitReturnType)
17128 deduceClosureReturnType(CSI&: *BSI);
17129
17130 QualType RetTy = Context.VoidTy;
17131 if (!BSI->ReturnType.isNull())
17132 RetTy = BSI->ReturnType;
17133
17134 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17135 QualType BlockTy;
17136
17137 // If the user wrote a function type in some form, try to use that.
17138 if (!BSI->FunctionType.isNull()) {
17139 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17140
17141 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17142 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17143
17144 // Turn protoless block types into nullary block types.
17145 if (isa<FunctionNoProtoType>(Val: FTy)) {
17146 FunctionProtoType::ExtProtoInfo EPI;
17147 EPI.ExtInfo = Ext;
17148 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17149
17150 // Otherwise, if we don't need to change anything about the function type,
17151 // preserve its sugar structure.
17152 } else if (FTy->getReturnType() == RetTy &&
17153 (!NoReturn || FTy->getNoReturnAttr())) {
17154 BlockTy = BSI->FunctionType;
17155
17156 // Otherwise, make the minimal modifications to the function type.
17157 } else {
17158 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17159 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17160 EPI.TypeQuals = Qualifiers();
17161 EPI.ExtInfo = Ext;
17162 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17163 }
17164
17165 // If we don't have a function type, just build one from nothing.
17166 } else {
17167 FunctionProtoType::ExtProtoInfo EPI;
17168 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17169 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17170 }
17171
17172 DiagnoseUnusedParameters(Parameters: BD->parameters());
17173 BlockTy = Context.getBlockPointerType(T: BlockTy);
17174
17175 // If needed, diagnose invalid gotos and switches in the block.
17176 if (getCurFunction()->NeedsScopeChecking() &&
17177 !PP.isCodeCompletionEnabled())
17178 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17179
17180 BD->setBody(cast<CompoundStmt>(Val: Body));
17181
17182 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17183 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17184
17185 // Try to apply the named return value optimization. We have to check again
17186 // if we can do this, though, because blocks keep return statements around
17187 // to deduce an implicit return type.
17188 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17189 !BD->isDependentContext())
17190 computeNRVO(Body, Scope: BSI);
17191
17192 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17193 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17194 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17195 UseContext: NonTrivialCUnionContext::FunctionReturn,
17196 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17197
17198 PopDeclContext();
17199
17200 // Set the captured variables on the block.
17201 SmallVector<BlockDecl::Capture, 4> Captures;
17202 for (Capture &Cap : BSI->Captures) {
17203 if (Cap.isInvalid() || Cap.isThisCapture())
17204 continue;
17205 // Cap.getVariable() is always a VarDecl because
17206 // blocks cannot capture structured bindings or other ValueDecl kinds.
17207 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17208 Expr *CopyExpr = nullptr;
17209 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17210 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17211 // The capture logic needs the destructor, so make sure we mark it.
17212 // Usually this is unnecessary because most local variables have
17213 // their destructors marked at declaration time, but parameters are
17214 // an exception because it's technically only the call site that
17215 // actually requires the destructor.
17216 if (isa<ParmVarDecl>(Val: Var))
17217 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17218
17219 // Enter a separate potentially-evaluated context while building block
17220 // initializers to isolate their cleanups from those of the block
17221 // itself.
17222 // FIXME: Is this appropriate even when the block itself occurs in an
17223 // unevaluated operand?
17224 EnterExpressionEvaluationContext EvalContext(
17225 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17226
17227 SourceLocation Loc = Cap.getLocation();
17228
17229 ExprResult Result = BuildDeclarationNameExpr(
17230 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17231
17232 // According to the blocks spec, the capture of a variable from
17233 // the stack requires a const copy constructor. This is not true
17234 // of the copy/move done to move a __block variable to the heap.
17235 if (!Result.isInvalid() &&
17236 !Result.get()->getType().isConstQualified()) {
17237 Result = ImpCastExprToType(E: Result.get(),
17238 Type: Result.get()->getType().withConst(),
17239 CK: CK_NoOp, VK: VK_LValue);
17240 }
17241
17242 if (!Result.isInvalid()) {
17243 Result = PerformCopyInitialization(
17244 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17245 Type: Cap.getCaptureType()),
17246 EqualLoc: Loc, Init: Result.get());
17247 }
17248
17249 // Build a full-expression copy expression if initialization
17250 // succeeded and used a non-trivial constructor. Recover from
17251 // errors by pretending that the copy isn't necessary.
17252 if (!Result.isInvalid() &&
17253 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17254 ->isTrivial()) {
17255 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17256 CopyExpr = Result.get();
17257 }
17258 }
17259 }
17260
17261 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17262 CopyExpr);
17263 Captures.push_back(Elt: NewCap);
17264 }
17265 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17266
17267 // Pop the block scope now but keep it alive to the end of this function.
17268 AnalysisBasedWarnings::Policy WP =
17269 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17270 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17271
17272 BlockExpr *Result = new (Context)
17273 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17274
17275 // If the block isn't obviously global, i.e. it captures anything at
17276 // all, then we need to do a few things in the surrounding context:
17277 if (Result->getBlockDecl()->hasCaptures()) {
17278 // First, this expression has a new cleanup object.
17279 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17280 Cleanup.setExprNeedsCleanups(true);
17281
17282 // It also gets a branch-protected scope if any of the captured
17283 // variables needs destruction.
17284 for (const auto &CI : Result->getBlockDecl()->captures()) {
17285 const VarDecl *var = CI.getVariable();
17286 if (var->getType().isDestructedType() != QualType::DK_none) {
17287 setFunctionHasBranchProtectedScope();
17288 break;
17289 }
17290 }
17291 }
17292
17293 if (getCurFunction())
17294 getCurFunction()->addBlock(BD);
17295
17296 // This can happen if the block's return type is deduced, but
17297 // the return expression is invalid.
17298 if (BD->isInvalidDecl())
17299 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17300 SubExprs: {Result}, T: Result->getType());
17301 return Result;
17302}
17303
17304ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17305 SourceLocation RPLoc) {
17306 TypeSourceInfo *TInfo;
17307 GetTypeFromParser(Ty, TInfo: &TInfo);
17308 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17309}
17310
17311ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17312 Expr *E, TypeSourceInfo *TInfo,
17313 SourceLocation RPLoc) {
17314 Expr *OrigExpr = E;
17315 VAArgExpr::VarArgKind VAKind = VAArgExpr::VA_Std;
17316
17317 // CUDA device global function does not support varargs.
17318 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17319 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17320 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17321 if (T == CUDAFunctionTarget::Global)
17322 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17323 }
17324 }
17325
17326 // NVPTX does not support va_arg expression.
17327 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17328 Context.getTargetInfo().getTriple().isNVPTX())
17329 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17330
17331 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17332 // as Microsoft ABI on an actual Microsoft platform, where
17333 // __builtin_ms_va_list and __builtin_va_list are the same.)
17334 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17335 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17336 QualType MSVaListType = Context.getBuiltinMSVaListType();
17337 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17338 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17339 return ExprError();
17340 VAKind = VAArgExpr::VA_MS;
17341 }
17342 }
17343
17344 // Get the va_list type
17345 QualType VaListType = Context.getBuiltinVaListType();
17346
17347 // It might be a __builtin_zos_va_list!
17348 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17349 // E->getType() can be:
17350 // - va_list: equal to array (char*)[2] (inside function)
17351 // - char **: decayed array (va_list passed as parameter)
17352 // We need to check for both cases.
17353 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17354 assert(ZOSVaListType->isArrayType() &&
17355 "__builtin_zos_va_list must be an array type");
17356 QualType DecayedType = Context.getArrayDecayedType(T: ZOSVaListType);
17357 if (Context.hasSameType(T1: ZOSVaListType, T2: E->getType()) ||
17358 Context.hasSameType(T1: DecayedType, T2: E->getType())) {
17359 VAKind = VAArgExpr::VA_ZOS;
17360 VaListType = ZOSVaListType;
17361 }
17362 }
17363
17364 if (VAKind != VAArgExpr::VA_MS) {
17365 if (VaListType->isArrayType()) {
17366 // Deal with implicit array decay; for example, on x86-64,
17367 // va_list is an array, but it's supposed to decay to
17368 // a pointer for va_arg.
17369 VaListType = Context.getArrayDecayedType(T: VaListType);
17370 // Make sure the input expression also decays appropriately.
17371 ExprResult Result = UsualUnaryConversions(E);
17372 if (Result.isInvalid())
17373 return ExprError();
17374 E = Result.get();
17375 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17376 // If va_list is a record type and we are compiling in C++ mode,
17377 // check the argument using reference binding.
17378 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17379 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17380 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17381 if (Init.isInvalid())
17382 return ExprError();
17383 E = Init.getAs<Expr>();
17384 } else {
17385 // Otherwise, the va_list argument must be an l-value because
17386 // it is modified by va_arg.
17387 if (!E->isTypeDependent() &&
17388 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17389 return ExprError();
17390 }
17391 }
17392
17393 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17394 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17395 return ExprError(
17396 Diag(Loc: E->getBeginLoc(),
17397 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17398 << OrigExpr->getType() << E->getSourceRange());
17399
17400 if (!TInfo->getType()->isDependentType()) {
17401 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17402 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17403 Args: TInfo->getTypeLoc()))
17404 return ExprError();
17405
17406 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17407 T: TInfo->getType(),
17408 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17409 Args: TInfo->getTypeLoc()))
17410 return ExprError();
17411
17412 if (!TInfo->getType().isPODType(Context)) {
17413 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17414 DiagID: TInfo->getType()->isObjCLifetimeType()
17415 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17416 : diag::warn_second_parameter_to_va_arg_not_pod)
17417 << TInfo->getType()
17418 << TInfo->getTypeLoc().getSourceRange();
17419 }
17420
17421 if (TInfo->getType()->isArrayType()) {
17422 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17423 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17424 << TInfo->getType()
17425 << TInfo->getTypeLoc().getSourceRange());
17426 }
17427
17428 // Check for va_arg where arguments of the given type will be promoted
17429 // (i.e. this va_arg is guaranteed to have undefined behavior).
17430 QualType PromoteType;
17431 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17432 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17433 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17434 // and C23 7.16.1.1p2 says, in part:
17435 // If type is not compatible with the type of the actual next argument
17436 // (as promoted according to the default argument promotions), the
17437 // behavior is undefined, except for the following cases:
17438 // - both types are pointers to qualified or unqualified versions of
17439 // compatible types;
17440 // - one type is compatible with a signed integer type, the other
17441 // type is compatible with the corresponding unsigned integer type,
17442 // and the value is representable in both types;
17443 // - one type is pointer to qualified or unqualified void and the
17444 // other is a pointer to a qualified or unqualified character type;
17445 // - or, the type of the next argument is nullptr_t and type is a
17446 // pointer type that has the same representation and alignment
17447 // requirements as a pointer to a character type.
17448 // Given that type compatibility is the primary requirement (ignoring
17449 // qualifications), you would think we could call typesAreCompatible()
17450 // directly to test this. However, in C++, that checks for *same type*,
17451 // which causes false positives when passing an enumeration type to
17452 // va_arg. Instead, get the underlying type of the enumeration and pass
17453 // that.
17454 QualType UnderlyingType = TInfo->getType();
17455 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17456 UnderlyingType = ED->getIntegerType();
17457 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17458 /*CompareUnqualified*/ true))
17459 PromoteType = QualType();
17460
17461 // If the types are still not compatible, we need to test whether the
17462 // promoted type and the underlying type are the same except for
17463 // signedness. Ask the AST for the correctly corresponding type and see
17464 // if that's compatible.
17465 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17466 PromoteType->isUnsignedIntegerType() !=
17467 UnderlyingType->isUnsignedIntegerType()) {
17468 UnderlyingType =
17469 UnderlyingType->isUnsignedIntegerType()
17470 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17471 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17472 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17473 /*CompareUnqualified*/ true))
17474 PromoteType = QualType();
17475 }
17476 }
17477 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17478 PromoteType = Context.DoubleTy;
17479 if (!PromoteType.isNull())
17480 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17481 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17482 << TInfo->getType()
17483 << PromoteType
17484 << TInfo->getTypeLoc().getSourceRange());
17485 }
17486
17487 QualType T = TInfo->getType().getNonLValueExprType(Context);
17488 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17489}
17490
17491ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17492 // The type of __null will be int or long, depending on the size of
17493 // pointers on the target.
17494 QualType Ty;
17495 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17496 if (pw == Context.getTargetInfo().getIntWidth())
17497 Ty = Context.IntTy;
17498 else if (pw == Context.getTargetInfo().getLongWidth())
17499 Ty = Context.LongTy;
17500 else if (pw == Context.getTargetInfo().getLongLongWidth())
17501 Ty = Context.LongLongTy;
17502 else {
17503 llvm_unreachable("I don't know size of pointer!");
17504 }
17505
17506 return new (Context) GNUNullExpr(Ty, TokenLoc);
17507}
17508
17509static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17510 CXXRecordDecl *ImplDecl = nullptr;
17511
17512 // Fetch the std::source_location::__impl decl.
17513 if (NamespaceDecl *Std = S.getStdNamespace()) {
17514 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17515 Loc, Sema::LookupOrdinaryName);
17516 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17517 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17518 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17519 Loc, Sema::LookupOrdinaryName);
17520 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17521 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17522 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17523 }
17524 }
17525 }
17526 }
17527
17528 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17529 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17530 return nullptr;
17531 }
17532
17533 // Verify that __impl is a trivial struct type, with no base classes, and with
17534 // only the four expected fields.
17535 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17536 ImplDecl->getNumBases() != 0) {
17537 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17538 return nullptr;
17539 }
17540
17541 unsigned Count = 0;
17542 for (FieldDecl *F : ImplDecl->fields()) {
17543 StringRef Name = F->getName();
17544
17545 if (Name == "_M_file_name") {
17546 if (F->getType() !=
17547 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17548 break;
17549 Count++;
17550 } else if (Name == "_M_function_name") {
17551 if (F->getType() !=
17552 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17553 break;
17554 Count++;
17555 } else if (Name == "_M_line") {
17556 if (!F->getType()->isIntegerType())
17557 break;
17558 Count++;
17559 } else if (Name == "_M_column") {
17560 if (!F->getType()->isIntegerType())
17561 break;
17562 Count++;
17563 } else {
17564 Count = 100; // invalid
17565 break;
17566 }
17567 }
17568 if (Count != 4) {
17569 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17570 return nullptr;
17571 }
17572
17573 return ImplDecl;
17574}
17575
17576ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17577 SourceLocation BuiltinLoc,
17578 SourceLocation RPLoc) {
17579 QualType ResultTy;
17580 switch (Kind) {
17581 case SourceLocIdentKind::File:
17582 case SourceLocIdentKind::FileName:
17583 case SourceLocIdentKind::Function:
17584 case SourceLocIdentKind::FuncSig: {
17585 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17586 ResultTy =
17587 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17588 break;
17589 }
17590 case SourceLocIdentKind::Line:
17591 case SourceLocIdentKind::Column:
17592 ResultTy = Context.UnsignedIntTy;
17593 break;
17594 case SourceLocIdentKind::SourceLocStruct:
17595 if (!StdSourceLocationImplDecl) {
17596 StdSourceLocationImplDecl =
17597 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17598 if (!StdSourceLocationImplDecl)
17599 return ExprError();
17600 }
17601 ResultTy = Context.getPointerType(
17602 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17603 break;
17604 }
17605
17606 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17607}
17608
17609ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17610 SourceLocation BuiltinLoc,
17611 SourceLocation RPLoc,
17612 DeclContext *ParentContext) {
17613 return new (Context)
17614 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17615}
17616
17617ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17618 StringLiteral *BinaryData, StringRef FileName) {
17619 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17620 Data->BinaryData = BinaryData;
17621 Data->FileName = FileName;
17622 return new (Context)
17623 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17624 Data->getDataElementCount());
17625}
17626
17627static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17628 const Expr *SrcExpr) {
17629 if (!DstType->isFunctionPointerType() ||
17630 !SrcExpr->getType()->isFunctionType())
17631 return false;
17632
17633 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17634 if (!DRE)
17635 return false;
17636
17637 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17638 if (!FD)
17639 return false;
17640
17641 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17642 /*Complain=*/true,
17643 Loc: SrcExpr->getBeginLoc());
17644}
17645
17646bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17647 SourceLocation Loc,
17648 QualType DstType, QualType SrcType,
17649 Expr *SrcExpr, AssignmentAction Action,
17650 bool *Complained) {
17651 if (Complained)
17652 *Complained = false;
17653
17654 // Decode the result (notice that AST's are still created for extensions).
17655 bool CheckInferredResultType = false;
17656 bool isInvalid = false;
17657 unsigned DiagKind = 0;
17658 ConversionFixItGenerator ConvHints;
17659 bool MayHaveConvFixit = false;
17660 bool MayHaveFunctionDiff = false;
17661 const ObjCInterfaceDecl *IFace = nullptr;
17662 const ObjCProtocolDecl *PDecl = nullptr;
17663
17664 switch (ConvTy) {
17665 case AssignConvertType::Compatible:
17666 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17667 return false;
17668 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17669 // Still a valid conversion, but we may want to diagnose for C++
17670 // compatibility reasons.
17671 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17672 break;
17673 case AssignConvertType::PointerToInt:
17674 if (getLangOpts().CPlusPlus) {
17675 DiagKind = diag::err_typecheck_convert_pointer_int;
17676 isInvalid = true;
17677 } else {
17678 DiagKind = diag::ext_typecheck_convert_pointer_int;
17679 }
17680 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17681 MayHaveConvFixit = true;
17682 break;
17683 case AssignConvertType::IntToPointer:
17684 if (getLangOpts().CPlusPlus) {
17685 DiagKind = diag::err_typecheck_convert_int_pointer;
17686 isInvalid = true;
17687 } else {
17688 DiagKind = diag::ext_typecheck_convert_int_pointer;
17689 }
17690 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17691 MayHaveConvFixit = true;
17692 break;
17693 case AssignConvertType::IncompatibleFunctionPointerStrict:
17694 DiagKind =
17695 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17696 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17697 MayHaveConvFixit = true;
17698 break;
17699 case AssignConvertType::IncompatibleFunctionPointer:
17700 if (getLangOpts().CPlusPlus) {
17701 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17702 isInvalid = true;
17703 } else {
17704 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17705 }
17706 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17707 MayHaveConvFixit = true;
17708 break;
17709 case AssignConvertType::IncompatiblePointer:
17710 if (Action == AssignmentAction::Passing_CFAudited) {
17711 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17712 } else if (getLangOpts().CPlusPlus) {
17713 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17714 isInvalid = true;
17715 } else {
17716 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17717 }
17718 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17719 SrcType->isObjCObjectPointerType();
17720 if (CheckInferredResultType) {
17721 SrcType = SrcType.getUnqualifiedType();
17722 DstType = DstType.getUnqualifiedType();
17723 } else {
17724 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17725 }
17726 MayHaveConvFixit = true;
17727 break;
17728 case AssignConvertType::IncompatiblePointerSign:
17729 if (getLangOpts().CPlusPlus) {
17730 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17731 isInvalid = true;
17732 } else {
17733 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17734 }
17735 break;
17736 case AssignConvertType::FunctionVoidPointer:
17737 if (getLangOpts().CPlusPlus) {
17738 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17739 isInvalid = true;
17740 } else {
17741 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17742 }
17743 break;
17744 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17745 // Perform decay if necessary.
17746 if (SrcType->canDecayToPointerType())
17747 SrcType = Context.getDecayedType(T: SrcType);
17748
17749 isInvalid = true;
17750
17751 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17752 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17753 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17754 DiagKind = diag::err_typecheck_incompatible_address_space;
17755 break;
17756 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17757 DiagKind = diag::err_typecheck_incompatible_ownership;
17758 break;
17759 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17760 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17761 break;
17762 }
17763
17764 llvm_unreachable("unknown error case for discarding qualifiers!");
17765 // fallthrough
17766 }
17767 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17768 if (SrcType->isArrayType())
17769 SrcType = Context.getArrayDecayedType(T: SrcType);
17770
17771 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17772 break;
17773 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17774 // If the qualifiers lost were because we were applying the
17775 // (deprecated) C++ conversion from a string literal to a char*
17776 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17777 // Ideally, this check would be performed in
17778 // checkPointerTypesForAssignment. However, that would require a
17779 // bit of refactoring (so that the second argument is an
17780 // expression, rather than a type), which should be done as part
17781 // of a larger effort to fix checkPointerTypesForAssignment for
17782 // C++ semantics.
17783 if (getLangOpts().CPlusPlus &&
17784 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17785 return false;
17786 if (getLangOpts().CPlusPlus) {
17787 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17788 isInvalid = true;
17789 } else {
17790 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17791 }
17792
17793 break;
17794 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17795 if (getLangOpts().CPlusPlus) {
17796 isInvalid = true;
17797 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17798 } else {
17799 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17800 }
17801 break;
17802 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17803 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17804 isInvalid = true;
17805 break;
17806 case AssignConvertType::IntToBlockPointer:
17807 DiagKind = diag::err_int_to_block_pointer;
17808 isInvalid = true;
17809 break;
17810 case AssignConvertType::IncompatibleBlockPointer:
17811 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17812 isInvalid = true;
17813 break;
17814 case AssignConvertType::IncompatibleObjCQualifiedId: {
17815 if (SrcType->isObjCQualifiedIdType()) {
17816 const ObjCObjectPointerType *srcOPT =
17817 SrcType->castAs<ObjCObjectPointerType>();
17818 for (auto *srcProto : srcOPT->quals()) {
17819 PDecl = srcProto;
17820 break;
17821 }
17822 if (const ObjCInterfaceType *IFaceT =
17823 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17824 IFace = IFaceT->getDecl();
17825 }
17826 else if (DstType->isObjCQualifiedIdType()) {
17827 const ObjCObjectPointerType *dstOPT =
17828 DstType->castAs<ObjCObjectPointerType>();
17829 for (auto *dstProto : dstOPT->quals()) {
17830 PDecl = dstProto;
17831 break;
17832 }
17833 if (const ObjCInterfaceType *IFaceT =
17834 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17835 IFace = IFaceT->getDecl();
17836 }
17837 if (getLangOpts().CPlusPlus) {
17838 DiagKind = diag::err_incompatible_qualified_id;
17839 isInvalid = true;
17840 } else {
17841 DiagKind = diag::warn_incompatible_qualified_id;
17842 }
17843 break;
17844 }
17845 case AssignConvertType::IncompatibleVectors:
17846 if (getLangOpts().CPlusPlus) {
17847 DiagKind = diag::err_incompatible_vectors;
17848 isInvalid = true;
17849 } else {
17850 DiagKind = diag::warn_incompatible_vectors;
17851 }
17852 break;
17853 case AssignConvertType::IncompatibleObjCWeakRef:
17854 DiagKind = diag::err_arc_weak_unavailable_assign;
17855 isInvalid = true;
17856 break;
17857 case AssignConvertType::CompatibleOBTDiscards:
17858 return false;
17859 case AssignConvertType::IncompatibleOBTKinds: {
17860 assert(!SrcType->isFunctionType() &&
17861 "Unexpected function type found in IncompatibleOBTKinds assignment");
17862 if (SrcType->canDecayToPointerType())
17863 SrcType = Context.getDecayedType(T: SrcType);
17864
17865 auto getOBTKindName = [](QualType Ty) -> StringRef {
17866 if (Ty->isPointerType())
17867 Ty = Ty->getPointeeType();
17868 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17869 return OBT->getBehaviorKind() ==
17870 OverflowBehaviorType::OverflowBehaviorKind::Trap
17871 ? "__ob_trap"
17872 : "__ob_wrap";
17873 }
17874 llvm_unreachable("OBT kind unhandled");
17875 };
17876
17877 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
17878 << DstType << SrcType << getOBTKindName(DstType)
17879 << getOBTKindName(SrcType);
17880 isInvalid = true;
17881 return true;
17882 }
17883 case AssignConvertType::Incompatible:
17884 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17885 if (Complained)
17886 *Complained = true;
17887 return true;
17888 }
17889
17890 DiagKind = diag::err_typecheck_convert_incompatible;
17891 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17892 MayHaveConvFixit = true;
17893 isInvalid = true;
17894 MayHaveFunctionDiff = true;
17895 break;
17896 }
17897
17898 QualType FirstType, SecondType;
17899 switch (Action) {
17900 case AssignmentAction::Assigning:
17901 case AssignmentAction::Initializing:
17902 // The destination type comes first.
17903 FirstType = DstType;
17904 SecondType = SrcType;
17905 break;
17906
17907 case AssignmentAction::Returning:
17908 case AssignmentAction::Passing:
17909 case AssignmentAction::Passing_CFAudited:
17910 case AssignmentAction::Converting:
17911 case AssignmentAction::Sending:
17912 case AssignmentAction::Casting:
17913 // The source type comes first.
17914 FirstType = SrcType;
17915 SecondType = DstType;
17916 break;
17917 }
17918
17919 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17920 AssignmentAction ActionForDiag = Action;
17921 if (Action == AssignmentAction::Passing_CFAudited)
17922 ActionForDiag = AssignmentAction::Passing;
17923
17924 FDiag << FirstType << SecondType << ActionForDiag
17925 << SrcExpr->getSourceRange();
17926
17927 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17928 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17929 auto isPlainChar = [](const clang::Type *Type) {
17930 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17931 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17932 };
17933 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17934 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17935 }
17936
17937 // If we can fix the conversion, suggest the FixIts.
17938 if (!ConvHints.isNull()) {
17939 for (FixItHint &H : ConvHints.Hints)
17940 FDiag << H;
17941 }
17942
17943 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17944
17945 if (MayHaveFunctionDiff)
17946 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17947
17948 Diag(Loc, PD: FDiag);
17949 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17950 DiagKind == diag::err_incompatible_qualified_id) &&
17951 PDecl && IFace && !IFace->hasDefinition())
17952 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17953 << IFace << PDecl;
17954
17955 if (SecondType == Context.OverloadTy)
17956 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17957 DestType: FirstType, /*TakingAddress=*/true);
17958
17959 if (CheckInferredResultType)
17960 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17961
17962 if (Action == AssignmentAction::Returning &&
17963 ConvTy == AssignConvertType::IncompatiblePointer)
17964 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17965
17966 if (Complained)
17967 *Complained = true;
17968 return isInvalid;
17969}
17970
17971ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17972 llvm::APSInt *Result,
17973 AllowFoldKind CanFold) {
17974 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17975 public:
17976 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17977 QualType T) override {
17978 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17979 << T << S.LangOpts.CPlusPlus;
17980 }
17981 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17982 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17983 }
17984 } Diagnoser;
17985
17986 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17987}
17988
17989ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17990 llvm::APSInt *Result,
17991 unsigned DiagID,
17992 AllowFoldKind CanFold) {
17993 class IDDiagnoser : public VerifyICEDiagnoser {
17994 unsigned DiagID;
17995
17996 public:
17997 IDDiagnoser(unsigned DiagID)
17998 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17999
18000 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18001 return S.Diag(Loc, DiagID);
18002 }
18003 } Diagnoser(DiagID);
18004
18005 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18006}
18007
18008Sema::SemaDiagnosticBuilder
18009Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
18010 QualType T) {
18011 return diagnoseNotICE(S, Loc);
18012}
18013
18014Sema::SemaDiagnosticBuilder
18015Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
18016 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18017}
18018
18019ExprResult
18020Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
18021 VerifyICEDiagnoser &Diagnoser,
18022 AllowFoldKind CanFold) {
18023 SourceLocation DiagLoc = E->getBeginLoc();
18024
18025 if (getLangOpts().CPlusPlus11) {
18026 // C++11 [expr.const]p5:
18027 // If an expression of literal class type is used in a context where an
18028 // integral constant expression is required, then that class type shall
18029 // have a single non-explicit conversion function to an integral or
18030 // unscoped enumeration type
18031 ExprResult Converted;
18032 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18033 VerifyICEDiagnoser &BaseDiagnoser;
18034 public:
18035 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18036 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18037 BaseDiagnoser.Suppress, true),
18038 BaseDiagnoser(BaseDiagnoser) {}
18039
18040 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18041 QualType T) override {
18042 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18043 }
18044
18045 SemaDiagnosticBuilder diagnoseIncomplete(
18046 Sema &S, SourceLocation Loc, QualType T) override {
18047 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
18048 }
18049
18050 SemaDiagnosticBuilder diagnoseExplicitConv(
18051 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18052 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
18053 }
18054
18055 SemaDiagnosticBuilder noteExplicitConv(
18056 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18057 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18058 << ConvTy->isEnumeralType() << ConvTy;
18059 }
18060
18061 SemaDiagnosticBuilder diagnoseAmbiguous(
18062 Sema &S, SourceLocation Loc, QualType T) override {
18063 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
18064 }
18065
18066 SemaDiagnosticBuilder noteAmbiguous(
18067 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18068 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18069 << ConvTy->isEnumeralType() << ConvTy;
18070 }
18071
18072 SemaDiagnosticBuilder diagnoseConversion(
18073 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18074 llvm_unreachable("conversion functions are permitted");
18075 }
18076 } ConvertDiagnoser(Diagnoser);
18077
18078 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18079 Converter&: ConvertDiagnoser);
18080 if (Converted.isInvalid())
18081 return Converted;
18082 E = Converted.get();
18083 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18084 // don't try to evaluate it later. We also don't want to return the
18085 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18086 // this function will attempt to use 'Value'.
18087 if (isa<RecoveryExpr>(Val: E))
18088 return ExprError();
18089 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18090 return ExprError();
18091 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18092 // An ICE must be of integral or unscoped enumeration type.
18093 if (!Diagnoser.Suppress)
18094 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18095 << E->getSourceRange();
18096 return ExprError();
18097 }
18098
18099 ExprResult RValueExpr = DefaultLvalueConversion(E);
18100 if (RValueExpr.isInvalid())
18101 return ExprError();
18102
18103 E = RValueExpr.get();
18104
18105 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18106 // in the non-ICE case.
18107 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18108 SmallVector<PartialDiagnosticAt, 8> Notes;
18109 if (Result)
18110 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18111 if (!isa<ConstantExpr>(Val: E))
18112 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18113 : ConstantExpr::Create(Context, E);
18114
18115 if (Notes.empty())
18116 return E;
18117
18118 // If our only note is the usual "invalid subexpression" note, just point
18119 // the caret at its location rather than producing an essentially
18120 // redundant note.
18121 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18122 diag::note_invalid_subexpr_in_const_expr) {
18123 DiagLoc = Notes[0].first;
18124 Notes.clear();
18125 }
18126
18127 if (getLangOpts().CPlusPlus) {
18128 if (!Diagnoser.Suppress) {
18129 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18130 for (const PartialDiagnosticAt &Note : Notes)
18131 Diag(Loc: Note.first, PD: Note.second);
18132 }
18133 return ExprError();
18134 }
18135
18136 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18137 for (const PartialDiagnosticAt &Note : Notes)
18138 Diag(Loc: Note.first, PD: Note.second);
18139
18140 return E;
18141 }
18142
18143 Expr::EvalResult EvalResult;
18144 SmallVector<PartialDiagnosticAt, 8> Notes;
18145 SmallVector<PartialDiagnosticAt> MSWarning;
18146 EvalResult.Diag = &Notes;
18147 EvalResult.ExtendedDiag = &MSWarning;
18148
18149 // Try to evaluate the expression, and produce diagnostics explaining why it's
18150 // not a constant expression as a side-effect.
18151 bool Folded =
18152 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18153 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18154 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18155
18156 if (!isa<ConstantExpr>(Val: E))
18157 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18158
18159 // For -fms-compatibility mode we relax some requirements
18160 // for constant folding in non-SFINAE contexts
18161 if (!MSWarning.empty()) {
18162 if (isSFINAEContext()) {
18163 Folded = false;
18164 } else {
18165 for (auto &Info : MSWarning)
18166 Diag(Loc: Info.first, PD: Info.second);
18167 }
18168 }
18169
18170 // In C++11, we can rely on diagnostics being produced for any expression
18171 // which is not a constant expression. If no diagnostics were produced, then
18172 // this is a constant expression.
18173 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18174 if (Result)
18175 *Result = EvalResult.Val.getInt();
18176 return E;
18177 }
18178
18179 // If our only note is the usual "invalid subexpression" note, just point
18180 // the caret at its location rather than producing an essentially
18181 // redundant note.
18182 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18183 diag::note_invalid_subexpr_in_const_expr) {
18184 DiagLoc = Notes[0].first;
18185 Notes.clear();
18186 }
18187
18188 if (!Folded || CanFold == AllowFoldKind::No) {
18189 if (!Diagnoser.Suppress) {
18190 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18191 for (const PartialDiagnosticAt &Note : Notes)
18192 Diag(Loc: Note.first, PD: Note.second);
18193 }
18194
18195 return ExprError();
18196 }
18197
18198 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18199 for (const PartialDiagnosticAt &Note : Notes)
18200 Diag(Loc: Note.first, PD: Note.second);
18201
18202 if (Result)
18203 *Result = EvalResult.Val.getInt();
18204 return E;
18205}
18206
18207namespace {
18208 // Handle the case where we conclude a expression which we speculatively
18209 // considered to be unevaluated is actually evaluated.
18210 class TransformToPE : public TreeTransform<TransformToPE> {
18211 typedef TreeTransform<TransformToPE> BaseTransform;
18212
18213 public:
18214 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18215
18216 // Make sure we redo semantic analysis
18217 bool AlwaysRebuild() { return true; }
18218 bool ReplacingOriginal() { return true; }
18219
18220 // We need to special-case DeclRefExprs referring to FieldDecls which
18221 // are not part of a member pointer formation; normal TreeTransforming
18222 // doesn't catch this case because of the way we represent them in the AST.
18223 // FIXME: This is a bit ugly; is it really the best way to handle this
18224 // case?
18225 //
18226 // Error on DeclRefExprs referring to FieldDecls.
18227 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18228 if (isa<FieldDecl>(Val: E->getDecl()) &&
18229 !SemaRef.isUnevaluatedContext())
18230 return SemaRef.Diag(Loc: E->getLocation(),
18231 DiagID: diag::err_invalid_non_static_member_use)
18232 << E->getDecl() << E->getSourceRange();
18233
18234 return BaseTransform::TransformDeclRefExpr(E);
18235 }
18236
18237 // Exception: filter out member pointer formation
18238 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18239 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18240 return E;
18241
18242 return BaseTransform::TransformUnaryOperator(E);
18243 }
18244
18245 // The body of a lambda-expression is in a separate expression evaluation
18246 // context so never needs to be transformed.
18247 // FIXME: Ideally we wouldn't transform the closure type either, and would
18248 // just recreate the capture expressions and lambda expression.
18249 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18250 return SkipLambdaBody(E, S: Body);
18251 }
18252 };
18253}
18254
18255ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18256 assert(isUnevaluatedContext() &&
18257 "Should only transform unevaluated expressions");
18258 ExprEvalContexts.back().Context =
18259 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18260 if (isUnevaluatedContext())
18261 return E;
18262 return TransformToPE(*this).TransformExpr(E);
18263}
18264
18265TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18266 assert(isUnevaluatedContext() &&
18267 "Should only transform unevaluated expressions");
18268 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18269 if (isUnevaluatedContext())
18270 return TInfo;
18271 return TransformToPE(*this).TransformType(TSI: TInfo);
18272}
18273
18274void
18275Sema::PushExpressionEvaluationContext(
18276 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18277 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18278 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18279 Args&: LambdaContextDecl, Args&: ExprContext);
18280
18281 // Discarded statements and immediate contexts nested in other
18282 // discarded statements or immediate context are themselves
18283 // a discarded statement or an immediate context, respectively.
18284 ExprEvalContexts.back().InDiscardedStatement =
18285 parentEvaluationContext().isDiscardedStatementContext();
18286
18287 // C++23 [expr.const]/p15
18288 // An expression or conversion is in an immediate function context if [...]
18289 // it is a subexpression of a manifestly constant-evaluated expression or
18290 // conversion.
18291 const auto &Prev = parentEvaluationContext();
18292 ExprEvalContexts.back().InImmediateFunctionContext =
18293 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18294
18295 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18296 Prev.InImmediateEscalatingFunctionContext;
18297
18298 Cleanup.reset();
18299 if (!MaybeODRUseExprs.empty())
18300 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18301}
18302
18303void
18304Sema::PushExpressionEvaluationContext(
18305 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18306 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18307 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18308 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18309}
18310
18311void Sema::PushExpressionEvaluationContextForFunction(
18312 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18313 // [expr.const]/p14.1
18314 // An expression or conversion is in an immediate function context if it is
18315 // potentially evaluated and either: its innermost enclosing non-block scope
18316 // is a function parameter scope of an immediate function.
18317 PushExpressionEvaluationContext(
18318 NewContext: FD && FD->isConsteval()
18319 ? ExpressionEvaluationContext::ImmediateFunctionContext
18320 : NewContext);
18321 const Sema::ExpressionEvaluationContextRecord &Parent =
18322 parentEvaluationContext();
18323 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18324
18325 Current.InDiscardedStatement = false;
18326
18327 if (FD) {
18328
18329 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18330 // context is nested in an immediate function context, so smaller contexts
18331 // that appear inside immediate functions (like variable initializers) are
18332 // considered to be inside an immediate function context even though by
18333 // themselves they are not immediate function contexts. But when a new
18334 // function is entered, we need to reset this tracking, since the entered
18335 // function might be not an immediate function.
18336
18337 Current.InImmediateEscalatingFunctionContext =
18338 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18339
18340 if (isLambdaMethod(DC: FD))
18341 Current.InImmediateFunctionContext =
18342 FD->isConsteval() ||
18343 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18344 Parent.isImmediateFunctionContext()));
18345 else
18346 Current.InImmediateFunctionContext = FD->isConsteval();
18347 }
18348}
18349
18350ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18351 TypeSourceInfo *TSI) {
18352 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18353}
18354
18355ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18356 TypeSourceInfo *TSI) {
18357 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18358}
18359
18360namespace {
18361
18362const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18363 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18364 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18365 if (E->getOpcode() == UO_Deref)
18366 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18367 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18368 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18369 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18370 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18371 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18372 QualType Inner;
18373 QualType Ty = E->getType();
18374 if (const auto *Ptr = Ty->getAs<PointerType>())
18375 Inner = Ptr->getPointeeType();
18376 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18377 Inner = Arr->getElementType();
18378 else
18379 return nullptr;
18380
18381 if (Inner->hasAttr(AK: attr::NoDeref))
18382 return E;
18383 }
18384 return nullptr;
18385}
18386
18387} // namespace
18388
18389void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18390 for (const Expr *E : Rec.PossibleDerefs) {
18391 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18392 if (DeclRef) {
18393 const ValueDecl *Decl = DeclRef->getDecl();
18394 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18395 << Decl->getName() << E->getSourceRange();
18396 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18397 } else {
18398 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18399 << E->getSourceRange();
18400 }
18401 }
18402 Rec.PossibleDerefs.clear();
18403}
18404
18405void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18406 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18407 return;
18408
18409 // Note: ignoring parens here is not justified by the standard rules, but
18410 // ignoring parentheses seems like a more reasonable approach, and this only
18411 // drives a deprecation warning so doesn't affect conformance.
18412 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18413 if (BO->getOpcode() == BO_Assign) {
18414 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18415 llvm::erase(C&: LHSs, V: BO->getLHS());
18416 }
18417 }
18418}
18419
18420void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18421 assert(getLangOpts().CPlusPlus20 &&
18422 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18423 "Cannot mark an immediate escalating expression outside of an "
18424 "immediate escalating context");
18425 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18426 Call && Call->getCallee()) {
18427 if (auto *DeclRef =
18428 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18429 DeclRef->setIsImmediateEscalating(true);
18430 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18431 Ctr->setIsImmediateEscalating(true);
18432 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18433 DeclRef->setIsImmediateEscalating(true);
18434 } else {
18435 assert(false && "expected an immediately escalating expression");
18436 }
18437 if (FunctionScopeInfo *FI = getCurFunction())
18438 FI->FoundImmediateEscalatingExpression = true;
18439}
18440
18441ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18442 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18443 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18444 isCheckingDefaultArgumentOrInitializer() ||
18445 RebuildingImmediateInvocation || isImmediateFunctionContext())
18446 return E;
18447
18448 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18449 /// It's OK if this fails; we'll also remove this in
18450 /// HandleImmediateInvocations, but catching it here allows us to avoid
18451 /// walking the AST looking for it in simple cases.
18452 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18453 if (auto *DeclRef =
18454 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18455 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18456
18457 // C++23 [expr.const]/p16
18458 // An expression or conversion is immediate-escalating if it is not initially
18459 // in an immediate function context and it is [...] an immediate invocation
18460 // that is not a constant expression and is not a subexpression of an
18461 // immediate invocation.
18462 APValue Cached;
18463 auto CheckConstantExpressionAndKeepResult = [&]() {
18464 Expr::EvalResult Eval;
18465 bool Res = E.get()->EvaluateAsConstantExpr(
18466 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18467 if (Res && !Eval.DiagEmitted) {
18468 Cached = std::move(Eval.Val);
18469 return true;
18470 }
18471 return false;
18472 };
18473
18474 if (!E.get()->isValueDependent() &&
18475 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18476 !CheckConstantExpressionAndKeepResult()) {
18477 MarkExpressionAsImmediateEscalating(E: E.get());
18478 return E;
18479 }
18480
18481 if (Cleanup.exprNeedsCleanups()) {
18482 // Since an immediate invocation is a full expression itself - it requires
18483 // an additional ExprWithCleanups node, but it can participate to a bigger
18484 // full expression which actually requires cleanups to be run after so
18485 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18486 // may discard cleanups for outer expression too early.
18487
18488 // Note that ExprWithCleanups created here must always have empty cleanup
18489 // objects:
18490 // - compound literals do not create cleanup objects in C++ and immediate
18491 // invocations are C++-only.
18492 // - blocks are not allowed inside constant expressions and compiler will
18493 // issue an error if they appear there.
18494 //
18495 // Hence, in correct code any cleanup objects created inside current
18496 // evaluation context must be outside the immediate invocation.
18497 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18498 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18499 }
18500
18501 ConstantExpr *Res = ConstantExpr::Create(
18502 Context: getASTContext(), E: E.get(),
18503 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18504 Context: getASTContext()),
18505 /*IsImmediateInvocation*/ true);
18506 if (Cached.hasValue())
18507 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18508 /// Value-dependent constant expressions should not be immediately
18509 /// evaluated until they are instantiated.
18510 if (!Res->isValueDependent())
18511 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18512 return Res;
18513}
18514
18515static void EvaluateAndDiagnoseImmediateInvocation(
18516 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18517 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18518 Expr::EvalResult Eval;
18519 Eval.Diag = &Notes;
18520 ConstantExpr *CE = Candidate.getPointer();
18521 bool Result = CE->EvaluateAsConstantExpr(
18522 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18523 if (!Result || !Notes.empty()) {
18524 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18525 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18526 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18527 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18528 FunctionDecl *FD = nullptr;
18529 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18530 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18531 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18532 FD = Call->getConstructor();
18533 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18534 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18535
18536 assert(FD && FD->isImmediateFunction() &&
18537 "could not find an immediate function in this expression");
18538 if (FD->isInvalidDecl())
18539 return;
18540 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18541 << FD << FD->isConsteval();
18542 if (auto Context =
18543 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18544 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18545 << Context->Decl;
18546 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18547 }
18548 if (!FD->isConsteval())
18549 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18550 for (auto &Note : Notes)
18551 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18552 return;
18553 }
18554 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18555}
18556
18557static void RemoveNestedImmediateInvocation(
18558 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18559 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18560 struct ComplexRemove : TreeTransform<ComplexRemove> {
18561 using Base = TreeTransform<ComplexRemove>;
18562 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18563 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18564 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18565 CurrentII;
18566 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18567 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18568 SmallVector<Sema::ImmediateInvocationCandidate,
18569 4>::reverse_iterator Current)
18570 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18571 void RemoveImmediateInvocation(ConstantExpr* E) {
18572 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18573 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18574 return Elem.getPointer() == E;
18575 });
18576 // It is possible that some subexpression of the current immediate
18577 // invocation was handled from another expression evaluation context. Do
18578 // not handle the current immediate invocation if some of its
18579 // subexpressions failed before.
18580 if (It == IISet.rend()) {
18581 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18582 CurrentII->setInt(1);
18583 } else {
18584 It->setInt(1); // Mark as deleted
18585 }
18586 }
18587 ExprResult TransformConstantExpr(ConstantExpr *E) {
18588 if (!E->isImmediateInvocation())
18589 return Base::TransformConstantExpr(E);
18590 RemoveImmediateInvocation(E);
18591 return Base::TransformExpr(E: E->getSubExpr());
18592 }
18593 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18594 /// we need to remove its DeclRefExpr from the DRSet.
18595 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18596 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18597 return Base::TransformCXXOperatorCallExpr(E);
18598 }
18599 /// Base::TransformUserDefinedLiteral doesn't preserve the
18600 /// UserDefinedLiteral node.
18601 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18602 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18603 /// here.
18604 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18605 if (!Init)
18606 return Init;
18607
18608 // We cannot use IgnoreImpCasts because we need to preserve
18609 // full expressions.
18610 while (true) {
18611 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18612 Init = ICE->getSubExpr();
18613 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18614 Init = ICE->getSubExpr();
18615 else
18616 break;
18617 }
18618 /// ConstantExprs are the first layer of implicit node to be removed so if
18619 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18620 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18621 CE && CE->isImmediateInvocation())
18622 RemoveImmediateInvocation(E: CE);
18623 return Base::TransformInitializer(Init, NotCopyInit);
18624 }
18625 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18626 DRSet.erase(Ptr: E);
18627 return E;
18628 }
18629 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18630 // Do not rebuild lambdas to avoid creating a new type.
18631 // Lambdas have already been processed inside their eval contexts.
18632 return E;
18633 }
18634
18635 // We do not have enough information to transform opaque expressions and
18636 // assume they do not contain immediate subexpressions.
18637 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18638
18639 bool AlwaysRebuild() { return false; }
18640 bool ReplacingOriginal() { return true; }
18641 bool AllowSkippingCXXConstructExpr() {
18642 bool Res = AllowSkippingFirstCXXConstructExpr;
18643 AllowSkippingFirstCXXConstructExpr = true;
18644 return Res;
18645 }
18646 bool AllowSkippingFirstCXXConstructExpr = true;
18647 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18648 Rec.ImmediateInvocationCandidates, It);
18649
18650 /// CXXConstructExpr with a single argument are getting skipped by
18651 /// TreeTransform in some situtation because they could be implicit. This
18652 /// can only occur for the top-level CXXConstructExpr because it is used
18653 /// nowhere in the expression being transformed therefore will not be rebuilt.
18654 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18655 /// skipping the first CXXConstructExpr.
18656 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18657 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18658
18659 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18660 // The result may not be usable in case of previous compilation errors.
18661 // In this case evaluation of the expression may result in crash so just
18662 // don't do anything further with the result.
18663 if (Res.isUsable()) {
18664 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18665 It->getPointer()->setSubExpr(Res.get());
18666 }
18667}
18668
18669static void
18670HandleImmediateInvocations(Sema &SemaRef,
18671 Sema::ExpressionEvaluationContextRecord &Rec) {
18672 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18673 Rec.ReferenceToConsteval.size() == 0) ||
18674 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18675 return;
18676
18677 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18678 // [...]
18679 // - the initializer of a variable that is usable in constant expressions or
18680 // has constant initialization.
18681 if (SemaRef.getLangOpts().CPlusPlus23 &&
18682 Rec.ExprContext ==
18683 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18684 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18685 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18686 VD->hasConstantInitialization())) {
18687 // An expression or conversion is in an 'immediate function context' if it
18688 // is potentially evaluated and either:
18689 // [...]
18690 // - it is a subexpression of a manifestly constant-evaluated expression
18691 // or conversion.
18692 return;
18693 }
18694 }
18695
18696 /// When we have more than 1 ImmediateInvocationCandidates or previously
18697 /// failed immediate invocations, we need to check for nested
18698 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18699 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18700 /// invocation.
18701 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18702 !SemaRef.FailedImmediateInvocations.empty()) {
18703
18704 /// Prevent sema calls during the tree transform from adding pointers that
18705 /// are already in the sets.
18706 llvm::SaveAndRestore DisableIITracking(
18707 SemaRef.RebuildingImmediateInvocation, true);
18708
18709 /// Prevent diagnostic during tree transfrom as they are duplicates
18710 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18711
18712 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18713 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18714 if (!It->getInt())
18715 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18716 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18717 Rec.ReferenceToConsteval.size()) {
18718 struct SimpleRemove : DynamicRecursiveASTVisitor {
18719 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18720 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18721 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18722 DRSet.erase(Ptr: E);
18723 return DRSet.size();
18724 }
18725 } Visitor(Rec.ReferenceToConsteval);
18726 Visitor.TraverseStmt(
18727 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18728 }
18729 for (auto CE : Rec.ImmediateInvocationCandidates)
18730 if (!CE.getInt())
18731 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18732 for (auto *DR : Rec.ReferenceToConsteval) {
18733 // If the expression is immediate escalating, it is not an error;
18734 // The outer context itself becomes immediate and further errors,
18735 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18736 if (DR->isImmediateEscalating())
18737 continue;
18738 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18739 const NamedDecl *ND = FD;
18740 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18741 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18742 ND = MD->getParent();
18743
18744 // C++23 [expr.const]/p16
18745 // An expression or conversion is immediate-escalating if it is not
18746 // initially in an immediate function context and it is [...] a
18747 // potentially-evaluated id-expression that denotes an immediate function
18748 // that is not a subexpression of an immediate invocation.
18749 bool ImmediateEscalating = false;
18750 bool IsPotentiallyEvaluated =
18751 Rec.Context ==
18752 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18753 Rec.Context ==
18754 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18755 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18756 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18757
18758 if (!Rec.InImmediateEscalatingFunctionContext ||
18759 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18760 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18761 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18762 if (!FD->getBuiltinID())
18763 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18764 if (auto Context =
18765 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18766 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18767 << Context->Decl;
18768 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18769 }
18770 if (FD->isImmediateEscalating() && !FD->isConsteval())
18771 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18772
18773 } else {
18774 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18775 }
18776 }
18777}
18778
18779void Sema::PopExpressionEvaluationContext() {
18780 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18781 if (!Rec.Lambdas.empty()) {
18782 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18783 if (!getLangOpts().CPlusPlus20 &&
18784 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18785 Rec.isUnevaluated() ||
18786 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18787 unsigned D;
18788 if (Rec.isUnevaluated()) {
18789 // C++11 [expr.prim.lambda]p2:
18790 // A lambda-expression shall not appear in an unevaluated operand
18791 // (Clause 5).
18792 D = diag::err_lambda_unevaluated_operand;
18793 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18794 // C++1y [expr.const]p2:
18795 // A conditional-expression e is a core constant expression unless the
18796 // evaluation of e, following the rules of the abstract machine, would
18797 // evaluate [...] a lambda-expression.
18798 D = diag::err_lambda_in_constant_expression;
18799 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18800 // C++17 [expr.prim.lamda]p2:
18801 // A lambda-expression shall not appear [...] in a template-argument.
18802 D = diag::err_lambda_in_invalid_context;
18803 } else
18804 llvm_unreachable("Couldn't infer lambda error message.");
18805
18806 for (const auto *L : Rec.Lambdas)
18807 Diag(Loc: L->getBeginLoc(), DiagID: D);
18808 }
18809 }
18810
18811 // Append the collected materialized temporaries into previous context before
18812 // exit if the previous also is a lifetime extending context.
18813 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18814 parentEvaluationContext().InLifetimeExtendingContext &&
18815 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18816 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18817 RHS: Rec.ForRangeLifetimeExtendTemps);
18818 }
18819
18820 WarnOnPendingNoDerefs(Rec);
18821 HandleImmediateInvocations(SemaRef&: *this, Rec);
18822
18823 // Warn on any volatile-qualified simple-assignments that are not discarded-
18824 // value expressions nor unevaluated operands (those cases get removed from
18825 // this list by CheckUnusedVolatileAssignment).
18826 for (auto *BO : Rec.VolatileAssignmentLHSs)
18827 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18828 << BO->getType();
18829
18830 // When are coming out of an unevaluated context, clear out any
18831 // temporaries that we may have created as part of the evaluation of
18832 // the expression in that context: they aren't relevant because they
18833 // will never be constructed.
18834 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18835 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18836 CE: ExprCleanupObjects.end());
18837 Cleanup = Rec.ParentCleanup;
18838 CleanupVarDeclMarking();
18839 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18840 // Otherwise, merge the contexts together.
18841 } else {
18842 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18843 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18844 }
18845
18846 DiagnoseMisalignedMembers();
18847
18848 // Pop the current expression evaluation context off the stack.
18849 ExprEvalContexts.pop_back();
18850}
18851
18852void Sema::DiscardCleanupsInEvaluationContext() {
18853 ExprCleanupObjects.erase(
18854 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18855 CE: ExprCleanupObjects.end());
18856 Cleanup.reset();
18857 MaybeODRUseExprs.clear();
18858}
18859
18860ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18861 ExprResult Result = CheckPlaceholderExpr(E);
18862 if (Result.isInvalid())
18863 return ExprError();
18864 E = Result.get();
18865 if (!E->getType()->isVariablyModifiedType())
18866 return E;
18867 return TransformToPotentiallyEvaluated(E);
18868}
18869
18870/// Are we in a context that is potentially constant evaluated per C++20
18871/// [expr.const]p12?
18872static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18873 /// C++2a [expr.const]p12:
18874 // An expression or conversion is potentially constant evaluated if it is
18875 switch (SemaRef.ExprEvalContexts.back().Context) {
18876 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18877 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18878
18879 // -- a manifestly constant-evaluated expression,
18880 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18881 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18882 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18883 // -- a potentially-evaluated expression,
18884 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18885 // -- an immediate subexpression of a braced-init-list,
18886
18887 // -- [FIXME] an expression of the form & cast-expression that occurs
18888 // within a templated entity
18889 // -- a subexpression of one of the above that is not a subexpression of
18890 // a nested unevaluated operand.
18891 return true;
18892
18893 case Sema::ExpressionEvaluationContext::Unevaluated:
18894 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18895 // Expressions in this context are never evaluated.
18896 return false;
18897 }
18898 llvm_unreachable("Invalid context");
18899}
18900
18901/// Return true if this function has a calling convention that requires mangling
18902/// in the size of the parameter pack.
18903static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18904 // These manglings are only applicable for targets whcih use Microsoft
18905 // mangling scheme for C.
18906 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18907 return false;
18908
18909 // If this is C++ and this isn't an extern "C" function, parameters do not
18910 // need to be complete. In this case, C++ mangling will apply, which doesn't
18911 // use the size of the parameters.
18912 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18913 return false;
18914
18915 // Stdcall, fastcall, and vectorcall need this special treatment.
18916 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18917 switch (CC) {
18918 case CC_X86StdCall:
18919 case CC_X86FastCall:
18920 case CC_X86VectorCall:
18921 return true;
18922 default:
18923 break;
18924 }
18925 return false;
18926}
18927
18928/// Require that all of the parameter types of function be complete. Normally,
18929/// parameter types are only required to be complete when a function is called
18930/// or defined, but to mangle functions with certain calling conventions, the
18931/// mangler needs to know the size of the parameter list. In this situation,
18932/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18933/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18934/// result in a linker error. Clang doesn't implement this behavior, and instead
18935/// attempts to error at compile time.
18936static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18937 SourceLocation Loc) {
18938 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18939 FunctionDecl *FD;
18940 ParmVarDecl *Param;
18941
18942 public:
18943 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18944 : FD(FD), Param(Param) {}
18945
18946 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18947 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18948 StringRef CCName;
18949 switch (CC) {
18950 case CC_X86StdCall:
18951 CCName = "stdcall";
18952 break;
18953 case CC_X86FastCall:
18954 CCName = "fastcall";
18955 break;
18956 case CC_X86VectorCall:
18957 CCName = "vectorcall";
18958 break;
18959 default:
18960 llvm_unreachable("CC does not need mangling");
18961 }
18962
18963 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18964 << Param->getDeclName() << FD->getDeclName() << CCName;
18965 }
18966 };
18967
18968 for (ParmVarDecl *Param : FD->parameters()) {
18969 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18970 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18971 }
18972}
18973
18974namespace {
18975enum class OdrUseContext {
18976 /// Declarations in this context are not odr-used.
18977 None,
18978 /// Declarations in this context are formally odr-used, but this is a
18979 /// dependent context.
18980 Dependent,
18981 /// Declarations in this context are odr-used but not actually used (yet).
18982 FormallyOdrUsed,
18983 /// Declarations in this context are used.
18984 Used
18985};
18986}
18987
18988/// Are we within a context in which references to resolved functions or to
18989/// variables result in odr-use?
18990static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18991 const Sema::ExpressionEvaluationContextRecord &Context =
18992 SemaRef.currentEvaluationContext();
18993
18994 if (Context.isUnevaluated())
18995 return OdrUseContext::None;
18996
18997 if (SemaRef.CurContext->isDependentContext())
18998 return OdrUseContext::Dependent;
18999
19000 if (Context.isDiscardedStatementContext())
19001 return OdrUseContext::FormallyOdrUsed;
19002
19003 else if (Context.Context ==
19004 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
19005 return OdrUseContext::FormallyOdrUsed;
19006
19007 return OdrUseContext::Used;
19008}
19009
19010static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
19011 if (!Func->isConstexpr())
19012 return false;
19013
19014 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19015 return true;
19016
19017 // Lambda conversion operators are never user provided.
19018 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
19019 return isLambdaConversionOperator(C: Conv);
19020
19021 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
19022 return CCD && CCD->getInheritedConstructor();
19023}
19024
19025void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
19026 bool MightBeOdrUse) {
19027 assert(Func && "No function?");
19028
19029 Func->setReferenced();
19030
19031 // Recursive functions aren't really used until they're used from some other
19032 // context.
19033 bool IsRecursiveCall = CurContext == Func;
19034
19035 // C++11 [basic.def.odr]p3:
19036 // A function whose name appears as a potentially-evaluated expression is
19037 // odr-used if it is the unique lookup result or the selected member of a
19038 // set of overloaded functions [...].
19039 //
19040 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19041 // can just check that here.
19042 OdrUseContext OdrUse =
19043 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
19044 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19045 OdrUse = OdrUseContext::FormallyOdrUsed;
19046
19047 // Trivial default constructors and destructors are never actually used.
19048 // FIXME: What about other special members?
19049 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19050 OdrUse == OdrUseContext::Used) {
19051 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
19052 if (Constructor->isDefaultConstructor())
19053 OdrUse = OdrUseContext::FormallyOdrUsed;
19054 if (isa<CXXDestructorDecl>(Val: Func))
19055 OdrUse = OdrUseContext::FormallyOdrUsed;
19056 }
19057
19058 // C++20 [expr.const]p12:
19059 // A function [...] is needed for constant evaluation if it is [...] a
19060 // constexpr function that is named by an expression that is potentially
19061 // constant evaluated
19062 bool NeededForConstantEvaluation =
19063 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
19064 isImplicitlyDefinableConstexprFunction(Func);
19065
19066 // Determine whether we require a function definition to exist, per
19067 // C++11 [temp.inst]p3:
19068 // Unless a function template specialization has been explicitly
19069 // instantiated or explicitly specialized, the function template
19070 // specialization is implicitly instantiated when the specialization is
19071 // referenced in a context that requires a function definition to exist.
19072 // C++20 [temp.inst]p7:
19073 // The existence of a definition of a [...] function is considered to
19074 // affect the semantics of the program if the [...] function is needed for
19075 // constant evaluation by an expression
19076 // C++20 [basic.def.odr]p10:
19077 // Every program shall contain exactly one definition of every non-inline
19078 // function or variable that is odr-used in that program outside of a
19079 // discarded statement
19080 // C++20 [special]p1:
19081 // The implementation will implicitly define [defaulted special members]
19082 // if they are odr-used or needed for constant evaluation.
19083 //
19084 // Note that we skip the implicit instantiation of templates that are only
19085 // used in unused default arguments or by recursive calls to themselves.
19086 // This is formally non-conforming, but seems reasonable in practice.
19087 bool NeedDefinition =
19088 !IsRecursiveCall &&
19089 (OdrUse == OdrUseContext::Used ||
19090 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19091
19092 // C++14 [temp.expl.spec]p6:
19093 // If a template [...] is explicitly specialized then that specialization
19094 // shall be declared before the first use of that specialization that would
19095 // cause an implicit instantiation to take place, in every translation unit
19096 // in which such a use occurs
19097 if (NeedDefinition &&
19098 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19099 Func->getMemberSpecializationInfo()))
19100 checkSpecializationReachability(Loc, Spec: Func);
19101
19102 if (getLangOpts().CUDA)
19103 CUDA().CheckCall(Loc, Callee: Func);
19104
19105 // If we need a definition, try to create one.
19106 if (NeedDefinition && !Func->getBody()) {
19107 runWithSufficientStackSpace(Loc, Fn: [&] {
19108 if (CXXConstructorDecl *Constructor =
19109 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19110 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19111 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19112 if (Constructor->isDefaultConstructor()) {
19113 if (Constructor->isTrivial() &&
19114 !Constructor->hasAttr<DLLExportAttr>())
19115 return;
19116 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19117 } else if (Constructor->isCopyConstructor()) {
19118 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19119 } else if (Constructor->isMoveConstructor()) {
19120 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19121 }
19122 } else if (Constructor->getInheritedConstructor()) {
19123 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19124 }
19125 } else if (CXXDestructorDecl *Destructor =
19126 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19127 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19128 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19129 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19130 return;
19131 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19132 }
19133 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19134 MarkVTableUsed(Loc, Class: Destructor->getParent());
19135 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19136 if (MethodDecl->isOverloadedOperator() &&
19137 MethodDecl->getOverloadedOperator() == OO_Equal) {
19138 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19139 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19140 if (MethodDecl->isCopyAssignmentOperator())
19141 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19142 else if (MethodDecl->isMoveAssignmentOperator())
19143 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19144 }
19145 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19146 MethodDecl->getParent()->isLambda()) {
19147 CXXConversionDecl *Conversion =
19148 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19149 if (Conversion->isLambdaToBlockPointerConversion())
19150 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19151 else
19152 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19153 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19154 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19155 }
19156
19157 if (Func->isDefaulted() && !Func->isDeleted()) {
19158 DefaultedComparisonKind DCK = Func->getDefaultedComparisonKind();
19159 if (DCK != DefaultedComparisonKind::None)
19160 DefineDefaultedComparison(Loc, FD: Func, DCK);
19161 }
19162
19163 // Implicit instantiation of function templates and member functions of
19164 // class templates.
19165 if (Func->isImplicitlyInstantiable()) {
19166 TemplateSpecializationKind TSK =
19167 Func->getTemplateSpecializationKindForInstantiation();
19168 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19169 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19170 if (FirstInstantiation) {
19171 PointOfInstantiation = Loc;
19172 if (auto *MSI = Func->getMemberSpecializationInfo())
19173 MSI->setPointOfInstantiation(Loc);
19174 // FIXME: Notify listener.
19175 else
19176 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19177 } else if (TSK != TSK_ImplicitInstantiation) {
19178 // Use the point of use as the point of instantiation, instead of the
19179 // point of explicit instantiation (which we track as the actual point
19180 // of instantiation). This gives better backtraces in diagnostics.
19181 PointOfInstantiation = Loc;
19182 }
19183
19184 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19185 Func->isConstexpr()) {
19186 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19187 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19188 CodeSynthesisContexts.size())
19189 PendingLocalImplicitInstantiations.push_back(
19190 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19191 else if (Func->isConstexpr())
19192 // Do not defer instantiations of constexpr functions, to avoid the
19193 // expression evaluator needing to call back into Sema if it sees a
19194 // call to such a function.
19195 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19196 else {
19197 Func->setInstantiationIsPending(true);
19198 PendingInstantiations.push_back(
19199 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19200 if (llvm::isTimeTraceVerbose()) {
19201 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19202 std::string Name;
19203 llvm::raw_string_ostream OS(Name);
19204 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19205 /*Qualified=*/true);
19206 return Name;
19207 });
19208 }
19209 // Notify the consumer that a function was implicitly instantiated.
19210 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19211 }
19212 }
19213 } else {
19214 // Walk redefinitions, as some of them may be instantiable.
19215 for (auto *i : Func->redecls()) {
19216 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19217 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19218 }
19219 }
19220 });
19221 }
19222
19223 // If a constructor was defined in the context of a default parameter
19224 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19225 // context), its initializers may not be referenced yet.
19226 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19227 EnterExpressionEvaluationContext EvalContext(
19228 *this,
19229 Constructor->isImmediateFunction()
19230 ? ExpressionEvaluationContext::ImmediateFunctionContext
19231 : ExpressionEvaluationContext::PotentiallyEvaluated,
19232 Constructor);
19233 for (CXXCtorInitializer *Init : Constructor->inits()) {
19234 if (Init->isInClassMemberInitializer())
19235 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19236 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19237 });
19238 }
19239 }
19240
19241 // C++14 [except.spec]p17:
19242 // An exception-specification is considered to be needed when:
19243 // - the function is odr-used or, if it appears in an unevaluated operand,
19244 // would be odr-used if the expression were potentially-evaluated;
19245 //
19246 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19247 // function is a pure virtual function we're calling, and in that case the
19248 // function was selected by overload resolution and we need to resolve its
19249 // exception specification for a different reason.
19250 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19251 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19252 ResolveExceptionSpec(Loc, FPT);
19253
19254 // A callee could be called by a host function then by a device function.
19255 // If we only try recording once, we will miss recording the use on device
19256 // side. Therefore keep trying until it is recorded.
19257 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19258 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19259 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19260
19261 // If this is the first "real" use, act on that.
19262 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19263 // Keep track of used but undefined functions.
19264 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19265 if (mightHaveNonExternalLinkage(FD: Func))
19266 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19267 else if (Func->getMostRecentDecl()->isInlined() &&
19268 !LangOpts.GNUInline &&
19269 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19270 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19271 else if (isExternalWithNoLinkageType(VD: Func))
19272 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19273 }
19274
19275 // Some x86 Windows calling conventions mangle the size of the parameter
19276 // pack into the name. Computing the size of the parameters requires the
19277 // parameter types to be complete. Check that now.
19278 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19279 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19280
19281 // In the MS C++ ABI, the compiler emits destructor variants where they are
19282 // used. If the destructor is used here but defined elsewhere, mark the
19283 // virtual base destructors referenced. If those virtual base destructors
19284 // are inline, this will ensure they are defined when emitting the complete
19285 // destructor variant. This checking may be redundant if the destructor is
19286 // provided later in this TU.
19287 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19288 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19289 CXXRecordDecl *Parent = Dtor->getParent();
19290 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19291 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19292 }
19293 }
19294
19295 Func->markUsed(C&: Context);
19296 }
19297}
19298
19299/// Directly mark a variable odr-used. Given a choice, prefer to use
19300/// MarkVariableReferenced since it does additional checks and then
19301/// calls MarkVarDeclODRUsed.
19302/// If the variable must be captured:
19303/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19304/// - else capture it in the DeclContext that maps to the
19305/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19306static void
19307MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19308 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19309 // Keep track of used but undefined variables.
19310 // FIXME: We shouldn't suppress this warning for static data members.
19311 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19312 assert(Var && "expected a capturable variable");
19313
19314 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19315 (!Var->isExternallyVisible() || Var->isInline() ||
19316 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19317 !(Var->isStaticDataMember() && Var->hasInit())) {
19318 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19319 if (old.isInvalid())
19320 old = Loc;
19321 }
19322 QualType CaptureType, DeclRefType;
19323 if (SemaRef.LangOpts.OpenMP)
19324 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19325 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19326 /*EllipsisLoc*/ SourceLocation(),
19327 /*BuildAndDiagnose*/ true, CaptureType,
19328 DeclRefType, FunctionScopeIndexToStopAt);
19329
19330 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19331 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19332 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19333 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19334 if (VarTarget == SemaCUDA::CVT_Host &&
19335 (UserTarget == CUDAFunctionTarget::Device ||
19336 UserTarget == CUDAFunctionTarget::HostDevice ||
19337 UserTarget == CUDAFunctionTarget::Global)) {
19338 // Diagnose ODR-use of host global variables in device functions.
19339 // Reference of device global variables in host functions is allowed
19340 // through shadow variables therefore it is not diagnosed.
19341 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19342 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19343 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19344 SemaRef.targetDiag(Loc: Var->getLocation(),
19345 DiagID: Var->getType().isConstQualified()
19346 ? diag::note_cuda_const_var_unpromoted
19347 : diag::note_cuda_host_var);
19348 }
19349 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19350 // Also capture __device__ const variables, which are classified
19351 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19352 // an explicit CUDADeviceAttr to distinguish them from plain
19353 // const variables (no __device__), which also get CVT_Both but
19354 // only have an implicit CUDADeviceAttr.
19355 (VarTarget == SemaCUDA::CVT_Both &&
19356 Var->hasAttr<CUDADeviceAttr>() &&
19357 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19358 !Var->hasAttr<CUDASharedAttr>() &&
19359 (UserTarget == CUDAFunctionTarget::Host ||
19360 UserTarget == CUDAFunctionTarget::HostDevice)) {
19361 // Record a CUDA/HIP device side variable if it is ODR-used
19362 // by host code. This is done conservatively, when the variable is
19363 // referenced in any of the following contexts:
19364 // - a non-function context
19365 // - a host function
19366 // - a host device function
19367 // This makes the ODR-use of the device side variable by host code to
19368 // be visible in the device compilation for the compiler to be able to
19369 // emit template variables instantiated by host code only and to
19370 // externalize the static device side variable ODR-used by host code.
19371 if (!Var->hasExternalStorage())
19372 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19373 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19374 (!FD || (!FD->getDescribedFunctionTemplate() &&
19375 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19376 GVA_StrongExternal)))
19377 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19378 }
19379 }
19380
19381 V->markUsed(C&: SemaRef.Context);
19382}
19383
19384void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19385 SourceLocation Loc,
19386 unsigned CapturingScopeIndex) {
19387 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19388}
19389
19390static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19391 SourceLocation loc,
19392 ValueDecl *var) {
19393 DeclContext *VarDC = var->getDeclContext();
19394
19395 // If the parameter still belongs to the translation unit, then
19396 // we're actually just using one parameter in the declaration of
19397 // the next.
19398 if (isa<ParmVarDecl>(Val: var) &&
19399 isa<TranslationUnitDecl>(Val: VarDC))
19400 return;
19401
19402 // For C code, don't diagnose about capture if we're not actually in code
19403 // right now; it's impossible to write a non-constant expression outside of
19404 // function context, so we'll get other (more useful) diagnostics later.
19405 //
19406 // For C++, things get a bit more nasty... it would be nice to suppress this
19407 // diagnostic for certain cases like using a local variable in an array bound
19408 // for a member of a local class, but the correct predicate is not obvious.
19409 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19410 return;
19411
19412 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19413 unsigned ContextKind = 3; // unknown
19414 if (isa<CXXMethodDecl>(Val: VarDC) &&
19415 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19416 ContextKind = 2;
19417 } else if (isa<FunctionDecl>(Val: VarDC)) {
19418 ContextKind = 0;
19419 } else if (isa<BlockDecl>(Val: VarDC)) {
19420 ContextKind = 1;
19421 }
19422
19423 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19424 << var << ValueKind << ContextKind << VarDC;
19425 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19426 << var;
19427
19428 // FIXME: Add additional diagnostic info about class etc. which prevents
19429 // capture.
19430}
19431
19432static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19433 ValueDecl *Var,
19434 bool &SubCapturesAreNested,
19435 QualType &CaptureType,
19436 QualType &DeclRefType) {
19437 // Check whether we've already captured it.
19438 if (CSI->CaptureMap.count(Val: Var)) {
19439 // If we found a capture, any subcaptures are nested.
19440 SubCapturesAreNested = true;
19441
19442 // Retrieve the capture type for this variable.
19443 CaptureType = CSI->getCapture(Var).getCaptureType();
19444
19445 // Compute the type of an expression that refers to this variable.
19446 DeclRefType = CaptureType.getNonReferenceType();
19447
19448 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19449 // are mutable in the sense that user can change their value - they are
19450 // private instances of the captured declarations.
19451 const Capture &Cap = CSI->getCapture(Var);
19452 // C++ [expr.prim.lambda]p10:
19453 // The type of such a data member is [...] an lvalue reference to the
19454 // referenced function type if the entity is a reference to a function.
19455 // [...]
19456 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19457 !(isa<LambdaScopeInfo>(Val: CSI) &&
19458 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19459 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19460 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19461 DeclRefType.addConst();
19462 return true;
19463 }
19464 return false;
19465}
19466
19467// Only block literals, captured statements, and lambda expressions can
19468// capture; other scopes don't work.
19469static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19470 ValueDecl *Var,
19471 SourceLocation Loc,
19472 const bool Diagnose,
19473 Sema &S) {
19474 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19475 return getLambdaAwareParentOfDeclContext(DC);
19476
19477 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19478 if (Underlying) {
19479 if (Underlying->hasLocalStorage() && Diagnose)
19480 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19481 }
19482 return nullptr;
19483}
19484
19485// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19486// certain types of variables (unnamed, variably modified types etc.)
19487// so check for eligibility.
19488static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19489 SourceLocation Loc, const bool Diagnose,
19490 Sema &S) {
19491
19492 assert((isa<VarDecl, BindingDecl>(Var)) &&
19493 "Only variables and structured bindings can be captured");
19494
19495 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19496 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19497
19498 // Lambdas are not allowed to capture unnamed variables
19499 // (e.g. anonymous unions).
19500 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19501 // assuming that's the intent.
19502 if (IsLambda && !Var->getDeclName()) {
19503 if (Diagnose) {
19504 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19505 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19506 }
19507 return false;
19508 }
19509
19510 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19511 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19512 if (Diagnose) {
19513 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19514 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19515 }
19516 return false;
19517 }
19518 // Prohibit structs with flexible array members too.
19519 // We cannot capture what is in the tail end of the struct.
19520 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19521 VTD && VTD->hasFlexibleArrayMember()) {
19522 if (Diagnose) {
19523 if (IsBlock)
19524 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19525 else
19526 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19527 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19528 }
19529 return false;
19530 }
19531 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19532 // Lambdas and captured statements are not allowed to capture __block
19533 // variables; they don't support the expected semantics.
19534 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19535 if (Diagnose) {
19536 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19537 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19538 }
19539 return false;
19540 }
19541 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19542 if (S.getLangOpts().OpenCL && IsBlock &&
19543 Var->getType()->isBlockPointerType()) {
19544 if (Diagnose)
19545 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19546 return false;
19547 }
19548
19549 if (isa<BindingDecl>(Val: Var)) {
19550 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19551 if (Diagnose)
19552 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19553 return false;
19554 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19555 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19556 ? diag::warn_cxx17_compat_capture_binding
19557 : diag::ext_capture_binding)
19558 << Var;
19559 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19560 }
19561 }
19562
19563 return true;
19564}
19565
19566// Returns true if the capture by block was successful.
19567static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19568 SourceLocation Loc, const bool BuildAndDiagnose,
19569 QualType &CaptureType, QualType &DeclRefType,
19570 const bool Nested, Sema &S, bool Invalid) {
19571 bool ByRef = false;
19572
19573 // Blocks are not allowed to capture arrays, excepting OpenCL.
19574 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19575 // (decayed to pointers).
19576 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19577 if (BuildAndDiagnose) {
19578 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19579 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19580 Invalid = true;
19581 } else {
19582 return false;
19583 }
19584 }
19585
19586 // Forbid the block-capture of autoreleasing variables.
19587 if (!Invalid &&
19588 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19589 if (BuildAndDiagnose) {
19590 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19591 << /*block*/ 0;
19592 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19593 Invalid = true;
19594 } else {
19595 return false;
19596 }
19597 }
19598
19599 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19600 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19601 QualType PointeeTy = PT->getPointeeType();
19602
19603 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19604 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19605 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19606 if (BuildAndDiagnose) {
19607 SourceLocation VarLoc = Var->getLocation();
19608 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19609 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19610 }
19611 }
19612 }
19613
19614 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19615 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19616 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19617 // Block capture by reference does not change the capture or
19618 // declaration reference types.
19619 ByRef = true;
19620 } else {
19621 // Block capture by copy introduces 'const'.
19622 CaptureType = CaptureType.getNonReferenceType().withConst();
19623 DeclRefType = CaptureType;
19624 }
19625
19626 // Actually capture the variable.
19627 if (BuildAndDiagnose)
19628 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19629 CaptureType, Invalid);
19630
19631 return !Invalid;
19632}
19633
19634/// Capture the given variable in the captured region.
19635static bool captureInCapturedRegion(
19636 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19637 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19638 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19639 Sema &S, bool Invalid) {
19640 // By default, capture variables by reference.
19641 bool ByRef = true;
19642 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19643 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19644 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19645 // Using an LValue reference type is consistent with Lambdas (see below).
19646 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19647 bool HasConst = DeclRefType.isConstQualified();
19648 DeclRefType = DeclRefType.getUnqualifiedType();
19649 // Don't lose diagnostics about assignments to const.
19650 if (HasConst)
19651 DeclRefType.addConst();
19652 }
19653 // Do not capture firstprivates in tasks.
19654 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19655 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19656 return true;
19657 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19658 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19659 }
19660
19661 if (ByRef)
19662 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19663 else
19664 CaptureType = DeclRefType;
19665
19666 // Actually capture the variable.
19667 if (BuildAndDiagnose)
19668 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19669 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19670
19671 return !Invalid;
19672}
19673
19674/// Capture the given variable in the lambda.
19675static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19676 SourceLocation Loc, const bool BuildAndDiagnose,
19677 QualType &CaptureType, QualType &DeclRefType,
19678 const bool RefersToCapturedVariable,
19679 const TryCaptureKind Kind,
19680 SourceLocation EllipsisLoc, const bool IsTopScope,
19681 Sema &S, bool Invalid) {
19682 // Determine whether we are capturing by reference or by value.
19683 bool ByRef = false;
19684 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19685 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19686 } else {
19687 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19688 }
19689
19690 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19691 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19692 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19693 Invalid = true;
19694 }
19695
19696 // Compute the type of the field that will capture this variable.
19697 if (ByRef) {
19698 // C++11 [expr.prim.lambda]p15:
19699 // An entity is captured by reference if it is implicitly or
19700 // explicitly captured but not captured by copy. It is
19701 // unspecified whether additional unnamed non-static data
19702 // members are declared in the closure type for entities
19703 // captured by reference.
19704 //
19705 // FIXME: It is not clear whether we want to build an lvalue reference
19706 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19707 // to do the former, while EDG does the latter. Core issue 1249 will
19708 // clarify, but for now we follow GCC because it's a more permissive and
19709 // easily defensible position.
19710 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19711 } else {
19712 // C++11 [expr.prim.lambda]p14:
19713 // For each entity captured by copy, an unnamed non-static
19714 // data member is declared in the closure type. The
19715 // declaration order of these members is unspecified. The type
19716 // of such a data member is the type of the corresponding
19717 // captured entity if the entity is not a reference to an
19718 // object, or the referenced type otherwise. [Note: If the
19719 // captured entity is a reference to a function, the
19720 // corresponding data member is also a reference to a
19721 // function. - end note ]
19722 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19723 if (!RefType->getPointeeType()->isFunctionType())
19724 CaptureType = RefType->getPointeeType();
19725 }
19726
19727 // Forbid the lambda copy-capture of autoreleasing variables.
19728 if (!Invalid &&
19729 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19730 if (BuildAndDiagnose) {
19731 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19732 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19733 << Var->getDeclName();
19734 Invalid = true;
19735 } else {
19736 return false;
19737 }
19738 }
19739
19740 // Make sure that by-copy captures are of a complete and non-abstract type.
19741 if (!Invalid && BuildAndDiagnose) {
19742 if (!CaptureType->isDependentType() &&
19743 S.RequireCompleteSizedType(
19744 Loc, T: CaptureType,
19745 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19746 Args: Var->getDeclName()))
19747 Invalid = true;
19748 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19749 DiagID: diag::err_capture_of_abstract_type))
19750 Invalid = true;
19751 }
19752 }
19753
19754 // Compute the type of a reference to this captured variable.
19755 if (ByRef)
19756 DeclRefType = CaptureType.getNonReferenceType();
19757 else {
19758 // C++ [expr.prim.lambda]p5:
19759 // The closure type for a lambda-expression has a public inline
19760 // function call operator [...]. This function call operator is
19761 // declared const (9.3.1) if and only if the lambda-expression's
19762 // parameter-declaration-clause is not followed by mutable.
19763 DeclRefType = CaptureType.getNonReferenceType();
19764 bool Const = LSI->lambdaCaptureShouldBeConst();
19765 // C++ [expr.prim.lambda]p10:
19766 // The type of such a data member is [...] an lvalue reference to the
19767 // referenced function type if the entity is a reference to a function.
19768 // [...]
19769 if (Const && !CaptureType->isReferenceType() &&
19770 !DeclRefType->isFunctionType())
19771 DeclRefType.addConst();
19772 }
19773
19774 // Add the capture.
19775 if (BuildAndDiagnose)
19776 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19777 Loc, EllipsisLoc, CaptureType, Invalid);
19778
19779 return !Invalid;
19780}
19781
19782static bool canCaptureVariableByCopy(ValueDecl *Var,
19783 const ASTContext &Context) {
19784 // Offer a Copy fix even if the type is dependent.
19785 if (Var->getType()->isDependentType())
19786 return true;
19787 QualType T = Var->getType().getNonReferenceType();
19788 if (T.isTriviallyCopyableType(Context))
19789 return true;
19790 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19791
19792 if (!(RD = RD->getDefinition()))
19793 return false;
19794 if (RD->hasSimpleCopyConstructor())
19795 return true;
19796 if (RD->hasUserDeclaredCopyConstructor())
19797 for (CXXConstructorDecl *Ctor : RD->ctors())
19798 if (Ctor->isCopyConstructor())
19799 return !Ctor->isDeleted();
19800 }
19801 return false;
19802}
19803
19804/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19805/// default capture. Fixes may be omitted if they aren't allowed by the
19806/// standard, for example we can't emit a default copy capture fix-it if we
19807/// already explicitly copy capture capture another variable.
19808static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19809 ValueDecl *Var) {
19810 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19811 // Don't offer Capture by copy of default capture by copy fixes if Var is
19812 // known not to be copy constructible.
19813 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19814
19815 SmallString<32> FixBuffer;
19816 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19817 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19818 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19819 if (ShouldOfferCopyFix) {
19820 // Offer fixes to insert an explicit capture for the variable.
19821 // [] -> [VarName]
19822 // [OtherCapture] -> [OtherCapture, VarName]
19823 FixBuffer.assign(Refs: {Separator, Var->getName()});
19824 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19825 << Var << /*value*/ 0
19826 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19827 }
19828 // As above but capture by reference.
19829 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19830 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19831 << Var << /*reference*/ 1
19832 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19833 }
19834
19835 // Only try to offer default capture if there are no captures excluding this
19836 // and init captures.
19837 // [this]: OK.
19838 // [X = Y]: OK.
19839 // [&A, &B]: Don't offer.
19840 // [A, B]: Don't offer.
19841 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19842 return !C.isThisCapture() && !C.isInitCapture();
19843 }))
19844 return;
19845
19846 // The default capture specifiers, '=' or '&', must appear first in the
19847 // capture body.
19848 SourceLocation DefaultInsertLoc =
19849 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19850
19851 if (ShouldOfferCopyFix) {
19852 bool CanDefaultCopyCapture = true;
19853 // [=, *this] OK since c++17
19854 // [=, this] OK since c++20
19855 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19856 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19857 ? LSI->getCXXThisCapture().isCopyCapture()
19858 : false;
19859 // We can't use default capture by copy if any captures already specified
19860 // capture by copy.
19861 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19862 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19863 })) {
19864 FixBuffer.assign(Refs: {"=", Separator});
19865 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19866 << /*value*/ 0
19867 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19868 }
19869 }
19870
19871 // We can't use default capture by reference if any captures already specified
19872 // capture by reference.
19873 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19874 return !C.isInitCapture() && C.isReferenceCapture() &&
19875 !C.isThisCapture();
19876 })) {
19877 FixBuffer.assign(Refs: {"&", Separator});
19878 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19879 << /*reference*/ 1
19880 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19881 }
19882}
19883
19884bool Sema::tryCaptureVariable(
19885 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19886 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19887 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19888 // An init-capture is notionally from the context surrounding its
19889 // declaration, but its parent DC is the lambda class.
19890 DeclContext *VarDC =
19891 Var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19892 DeclContext *DC = CurContext;
19893
19894 // Skip past RequiresExprBodys because they don't constitute function scopes.
19895 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
19896 DC = DC->getParent();
19897
19898 // tryCaptureVariable is called every time a DeclRef is formed,
19899 // it can therefore have non-negigible impact on performances.
19900 // For local variables and when there is no capturing scope,
19901 // we can bailout early.
19902 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19903 return true;
19904
19905 // Exception: Function parameters are not tied to the function's DeclContext
19906 // until we enter the function definition. Capturing them anyway would result
19907 // in an out-of-bounds error while traversing DC and its parents.
19908 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19909 return true;
19910
19911 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19912 if (VD) {
19913 if (VD->isInitCapture())
19914 VarDC = VarDC->getParent();
19915 } else {
19916 VD = Var->getPotentiallyDecomposedVarDecl();
19917 }
19918 assert(VD && "Cannot capture a null variable");
19919
19920 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19921 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19922 // We need to sync up the Declaration Context with the
19923 // FunctionScopeIndexToStopAt
19924 if (FunctionScopeIndexToStopAt) {
19925 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19926 unsigned FSIndex = FunctionScopes.size() - 1;
19927 // When we're parsing the lambda parameter list, the current DeclContext is
19928 // NOT the lambda but its parent. So move away the current LSI before
19929 // aligning DC and FunctionScopeIndexToStopAt.
19930 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19931 FSIndex && LSI && !LSI->AfterParameterList)
19932 --FSIndex;
19933 assert(MaxFunctionScopesIndex <= FSIndex &&
19934 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19935 "FunctionScopes.");
19936 while (FSIndex != MaxFunctionScopesIndex) {
19937 DC = getLambdaAwareParentOfDeclContext(DC);
19938 --FSIndex;
19939 }
19940 }
19941
19942 // Capture global variables if it is required to use private copy of this
19943 // variable.
19944 bool IsGlobal = !VD->hasLocalStorage();
19945 if (IsGlobal && !(LangOpts.OpenMP &&
19946 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19947 StopAt: MaxFunctionScopesIndex)))
19948 return true;
19949
19950 if (isa<VarDecl>(Val: Var))
19951 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19952
19953 // Walk up the stack to determine whether we can capture the variable,
19954 // performing the "simple" checks that don't depend on type. We stop when
19955 // we've either hit the declared scope of the variable or find an existing
19956 // capture of that variable. We start from the innermost capturing-entity
19957 // (the DC) and ensure that all intervening capturing-entities
19958 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19959 // declcontext can either capture the variable or have already captured
19960 // the variable.
19961 CaptureType = Var->getType();
19962 DeclRefType = CaptureType.getNonReferenceType();
19963 bool Nested = false;
19964 bool Explicit = (Kind != TryCaptureKind::Implicit);
19965 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19966 do {
19967
19968 LambdaScopeInfo *LSI = nullptr;
19969 if (!FunctionScopes.empty())
19970 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19971 Val: FunctionScopes[FunctionScopesIndex]);
19972
19973 bool IsInScopeDeclarationContext =
19974 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19975
19976 if (LSI && !LSI->AfterParameterList) {
19977 // This allows capturing parameters from a default value which does not
19978 // seems correct
19979 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19980 return true;
19981 }
19982 // If the variable is declared in the current context, there is no need to
19983 // capture it.
19984 if (IsInScopeDeclarationContext &&
19985 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19986 return true;
19987
19988 // Only block literals, captured statements, and lambda expressions can
19989 // capture; other scopes don't work.
19990 DeclContext *ParentDC =
19991 !IsInScopeDeclarationContext
19992 ? DC->getParent()
19993 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19994 Diagnose: BuildAndDiagnose, S&: *this);
19995 // We need to check for the parent *first* because, if we *have*
19996 // private-captured a global variable, we need to recursively capture it in
19997 // intermediate blocks, lambdas, etc.
19998 if (!ParentDC) {
19999 if (IsGlobal) {
20000 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20001 break;
20002 }
20003 return true;
20004 }
20005
20006 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20007 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
20008
20009 // Check whether we've already captured it.
20010 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
20011 DeclRefType)) {
20012 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
20013 break;
20014 }
20015
20016 // When evaluating some attributes (like enable_if) we might refer to a
20017 // function parameter appertaining to the same declaration as that
20018 // attribute.
20019 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
20020 Parm && Parm->getDeclContext() == DC)
20021 return true;
20022
20023 // If we are instantiating a generic lambda call operator body,
20024 // we do not want to capture new variables. What was captured
20025 // during either a lambdas transformation or initial parsing
20026 // should be used.
20027 if (isGenericLambdaCallOperatorSpecialization(DC)) {
20028 if (BuildAndDiagnose) {
20029 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20030 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
20031 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20032 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20033 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20034 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20035 } else
20036 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
20037 }
20038 return true;
20039 }
20040
20041 // Try to capture variable-length arrays types.
20042 if (Var->getType()->isVariablyModifiedType()) {
20043 // We're going to walk down into the type and look for VLA
20044 // expressions.
20045 QualType QTy = Var->getType();
20046 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20047 QTy = PVD->getOriginalType();
20048 captureVariablyModifiedType(Context, T: QTy, CSI);
20049 }
20050
20051 if (getLangOpts().OpenMP) {
20052 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20053 // OpenMP private variables should not be captured in outer scope, so
20054 // just break here. Similarly, global variables that are captured in a
20055 // target region should not be captured outside the scope of the region.
20056 if (RSI->CapRegionKind == CR_OpenMP) {
20057 // FIXME: We should support capturing structured bindings in OpenMP.
20058 if (isa<BindingDecl>(Val: Var)) {
20059 if (BuildAndDiagnose) {
20060 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
20061 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
20062 }
20063 return true;
20064 }
20065 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20066 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
20067 // If the variable is private (i.e. not captured) and has variably
20068 // modified type, we still need to capture the type for correct
20069 // codegen in all regions, associated with the construct. Currently,
20070 // it is captured in the innermost captured region only.
20071 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20072 Var->getType()->isVariablyModifiedType()) {
20073 QualType QTy = Var->getType();
20074 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20075 QTy = PVD->getOriginalType();
20076 for (int I = 1,
20077 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
20078 I < E; ++I) {
20079 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20080 Val: FunctionScopes[FunctionScopesIndex - I]);
20081 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20082 "Wrong number of captured regions associated with the "
20083 "OpenMP construct.");
20084 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
20085 }
20086 }
20087 bool IsTargetCap =
20088 IsOpenMPPrivateDecl != OMPC_private &&
20089 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
20090 CaptureLevel: RSI->OpenMPCaptureLevel);
20091 // Do not capture global if it is not privatized in outer regions.
20092 bool IsGlobalCap =
20093 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20094 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
20095
20096 // When we detect target captures we are looking from inside the
20097 // target region, therefore we need to propagate the capture from the
20098 // enclosing region. Therefore, the capture is not initially nested.
20099 if (IsTargetCap)
20100 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20101 Level: RSI->OpenMPLevel);
20102
20103 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20104 (IsGlobal && !IsGlobalCap)) {
20105 Nested = !IsTargetCap;
20106 bool HasConst = DeclRefType.isConstQualified();
20107 DeclRefType = DeclRefType.getUnqualifiedType();
20108 // Don't lose diagnostics about assignments to const.
20109 if (HasConst)
20110 DeclRefType.addConst();
20111 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20112 break;
20113 }
20114 }
20115 }
20116 }
20117 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20118 // No capture-default, and this is not an explicit capture
20119 // so cannot capture this variable.
20120 if (BuildAndDiagnose) {
20121 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20122 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20123 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20124 if (LSI->Lambda) {
20125 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20126 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20127 }
20128 // FIXME: If we error out because an outer lambda can not implicitly
20129 // capture a variable that an inner lambda explicitly captures, we
20130 // should have the inner lambda do the explicit capture - because
20131 // it makes for cleaner diagnostics later. This would purely be done
20132 // so that the diagnostic does not misleadingly claim that a variable
20133 // can not be captured by a lambda implicitly even though it is captured
20134 // explicitly. Suggestion:
20135 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20136 // at the function head
20137 // - cache the StartingDeclContext - this must be a lambda
20138 // - captureInLambda in the innermost lambda the variable.
20139 }
20140 return true;
20141 }
20142 Explicit = false;
20143 FunctionScopesIndex--;
20144 if (IsInScopeDeclarationContext)
20145 DC = ParentDC;
20146 } while (!VarDC->Equals(DC));
20147
20148 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20149 // computing the type of the capture at each step, checking type-specific
20150 // requirements, and adding captures if requested.
20151 // If the variable had already been captured previously, we start capturing
20152 // at the lambda nested within that one.
20153 bool Invalid = false;
20154 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20155 ++I) {
20156 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20157
20158 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20159 // certain types of variables (unnamed, variably modified types etc.)
20160 // so check for eligibility.
20161 if (!Invalid)
20162 Invalid =
20163 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20164
20165 // After encountering an error, if we're actually supposed to capture, keep
20166 // capturing in nested contexts to suppress any follow-on diagnostics.
20167 if (Invalid && !BuildAndDiagnose)
20168 return true;
20169
20170 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20171 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20172 DeclRefType, Nested, S&: *this, Invalid);
20173 Nested = true;
20174 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20175 Invalid = !captureInCapturedRegion(
20176 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20177 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20178 Nested = true;
20179 } else {
20180 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20181 Invalid =
20182 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20183 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20184 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20185 Nested = true;
20186 }
20187
20188 if (Invalid && !BuildAndDiagnose)
20189 return true;
20190 }
20191 return Invalid;
20192}
20193
20194bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20195 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20196 QualType CaptureType;
20197 QualType DeclRefType;
20198 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20199 /*BuildAndDiagnose=*/true, CaptureType,
20200 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20201}
20202
20203bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20204 QualType CaptureType;
20205 QualType DeclRefType;
20206 return !tryCaptureVariable(
20207 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20208 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20209}
20210
20211QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20212 assert(Var && "Null value cannot be captured");
20213
20214 QualType CaptureType;
20215 QualType DeclRefType;
20216
20217 // Determine whether we can capture this variable.
20218 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20219 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20220 FunctionScopeIndexToStopAt: nullptr))
20221 return QualType();
20222
20223 return DeclRefType;
20224}
20225
20226namespace {
20227// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20228// The produced TemplateArgumentListInfo* points to data stored within this
20229// object, so should only be used in contexts where the pointer will not be
20230// used after the CopiedTemplateArgs object is destroyed.
20231class CopiedTemplateArgs {
20232 bool HasArgs;
20233 TemplateArgumentListInfo TemplateArgStorage;
20234public:
20235 template<typename RefExpr>
20236 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20237 if (HasArgs)
20238 E->copyTemplateArgumentsInto(TemplateArgStorage);
20239 }
20240 operator TemplateArgumentListInfo*()
20241#ifdef __has_cpp_attribute
20242#if __has_cpp_attribute(clang::lifetimebound)
20243 [[clang::lifetimebound]]
20244#endif
20245#endif
20246 {
20247 return HasArgs ? &TemplateArgStorage : nullptr;
20248 }
20249};
20250}
20251
20252/// Walk the set of potential results of an expression and mark them all as
20253/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20254///
20255/// \return A new expression if we found any potential results, ExprEmpty() if
20256/// not, and ExprError() if we diagnosed an error.
20257static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20258 NonOdrUseReason NOUR) {
20259 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20260 // an object that satisfies the requirements for appearing in a
20261 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20262 // is immediately applied." This function handles the lvalue-to-rvalue
20263 // conversion part.
20264 //
20265 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20266 // transform it into the relevant kind of non-odr-use node and rebuild the
20267 // tree of nodes leading to it.
20268 //
20269 // This is a mini-TreeTransform that only transforms a restricted subset of
20270 // nodes (and only certain operands of them).
20271
20272 // Rebuild a subexpression.
20273 auto Rebuild = [&](Expr *Sub) {
20274 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20275 };
20276
20277 // Check whether a potential result satisfies the requirements of NOUR.
20278 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20279 // Any entity other than a VarDecl is always odr-used whenever it's named
20280 // in a potentially-evaluated expression.
20281 auto *VD = dyn_cast<VarDecl>(Val: D);
20282 if (!VD)
20283 return true;
20284
20285 // C++2a [basic.def.odr]p4:
20286 // A variable x whose name appears as a potentially-evalauted expression
20287 // e is odr-used by e unless
20288 // -- x is a reference that is usable in constant expressions, or
20289 // -- x is a variable of non-reference type that is usable in constant
20290 // expressions and has no mutable subobjects, and e is an element of
20291 // the set of potential results of an expression of
20292 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20293 // conversion is applied, or
20294 // -- x is a variable of non-reference type, and e is an element of the
20295 // set of potential results of a discarded-value expression to which
20296 // the lvalue-to-rvalue conversion is not applied
20297 //
20298 // We check the first bullet and the "potentially-evaluated" condition in
20299 // BuildDeclRefExpr. We check the type requirements in the second bullet
20300 // in CheckLValueToRValueConversionOperand below.
20301 switch (NOUR) {
20302 case NOUR_None:
20303 case NOUR_Unevaluated:
20304 llvm_unreachable("unexpected non-odr-use-reason");
20305
20306 case NOUR_Constant:
20307 // Constant references were handled when they were built.
20308 if (VD->getType()->isReferenceType())
20309 return true;
20310 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20311 if (RD->hasDefinition() && RD->hasMutableFields())
20312 return true;
20313 if (!VD->isUsableInConstantExpressions(C: S.Context))
20314 return true;
20315 break;
20316
20317 case NOUR_Discarded:
20318 if (VD->getType()->isReferenceType())
20319 return true;
20320 break;
20321 }
20322 return false;
20323 };
20324
20325 // Check whether this expression may be odr-used in CUDA/HIP.
20326 auto MaybeCUDAODRUsed = [&]() -> bool {
20327 if (!S.LangOpts.CUDA)
20328 return false;
20329 LambdaScopeInfo *LSI = S.getCurLambda();
20330 if (!LSI)
20331 return false;
20332 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20333 if (!DRE)
20334 return false;
20335 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20336 if (!VD)
20337 return false;
20338 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20339 };
20340
20341 // Mark that this expression does not constitute an odr-use.
20342 auto MarkNotOdrUsed = [&] {
20343 if (!MaybeCUDAODRUsed()) {
20344 S.MaybeODRUseExprs.remove(X: E);
20345 if (LambdaScopeInfo *LSI = S.getCurLambda())
20346 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20347 }
20348 };
20349
20350 // C++2a [basic.def.odr]p2:
20351 // The set of potential results of an expression e is defined as follows:
20352 switch (E->getStmtClass()) {
20353 // -- If e is an id-expression, ...
20354 case Expr::DeclRefExprClass: {
20355 auto *DRE = cast<DeclRefExpr>(Val: E);
20356 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20357 break;
20358
20359 // Rebuild as a non-odr-use DeclRefExpr.
20360 MarkNotOdrUsed();
20361 return DeclRefExpr::Create(
20362 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20363 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20364 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20365 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20366 }
20367
20368 case Expr::FunctionParmPackExprClass: {
20369 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20370 // If any of the declarations in the pack is odr-used, then the expression
20371 // as a whole constitutes an odr-use.
20372 for (ValueDecl *D : *FPPE)
20373 if (IsPotentialResultOdrUsed(D))
20374 return ExprEmpty();
20375
20376 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20377 // nothing cares about whether we marked this as an odr-use, but it might
20378 // be useful for non-compiler tools.
20379 MarkNotOdrUsed();
20380 break;
20381 }
20382
20383 // -- If e is a subscripting operation with an array operand...
20384 case Expr::ArraySubscriptExprClass: {
20385 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20386 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20387 if (!OldBase->getType()->isArrayType())
20388 break;
20389 ExprResult Base = Rebuild(OldBase);
20390 if (!Base.isUsable())
20391 return Base;
20392 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20393 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20394 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20395 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20396 rbLoc: ASE->getRBracketLoc());
20397 }
20398
20399 case Expr::MemberExprClass: {
20400 auto *ME = cast<MemberExpr>(Val: E);
20401 // -- If e is a class member access expression [...] naming a non-static
20402 // data member...
20403 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20404 ExprResult Base = Rebuild(ME->getBase());
20405 if (!Base.isUsable())
20406 return Base;
20407 return MemberExpr::Create(
20408 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20409 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20410 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20411 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20412 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20413 }
20414
20415 if (ME->getMemberDecl()->isCXXInstanceMember())
20416 break;
20417
20418 // -- If e is a class member access expression naming a static data member,
20419 // ...
20420 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20421 break;
20422
20423 // Rebuild as a non-odr-use MemberExpr.
20424 MarkNotOdrUsed();
20425 return MemberExpr::Create(
20426 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20427 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20428 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20429 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20430 }
20431
20432 case Expr::BinaryOperatorClass: {
20433 auto *BO = cast<BinaryOperator>(Val: E);
20434 Expr *LHS = BO->getLHS();
20435 Expr *RHS = BO->getRHS();
20436 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20437 if (BO->getOpcode() == BO_PtrMemD) {
20438 ExprResult Sub = Rebuild(LHS);
20439 if (!Sub.isUsable())
20440 return Sub;
20441 BO->setLHS(Sub.get());
20442 // -- If e is a comma expression, ...
20443 } else if (BO->getOpcode() == BO_Comma) {
20444 ExprResult Sub = Rebuild(RHS);
20445 if (!Sub.isUsable())
20446 return Sub;
20447 BO->setRHS(Sub.get());
20448 } else {
20449 break;
20450 }
20451 return ExprResult(BO);
20452 }
20453
20454 // -- If e has the form (e1)...
20455 case Expr::ParenExprClass: {
20456 auto *PE = cast<ParenExpr>(Val: E);
20457 ExprResult Sub = Rebuild(PE->getSubExpr());
20458 if (!Sub.isUsable())
20459 return Sub;
20460 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20461 }
20462
20463 // -- If e is a glvalue conditional expression, ...
20464 // We don't apply this to a binary conditional operator. FIXME: Should we?
20465 case Expr::ConditionalOperatorClass: {
20466 auto *CO = cast<ConditionalOperator>(Val: E);
20467 ExprResult LHS = Rebuild(CO->getLHS());
20468 if (LHS.isInvalid())
20469 return ExprError();
20470 ExprResult RHS = Rebuild(CO->getRHS());
20471 if (RHS.isInvalid())
20472 return ExprError();
20473 if (!LHS.isUsable() && !RHS.isUsable())
20474 return ExprEmpty();
20475 if (!LHS.isUsable())
20476 LHS = CO->getLHS();
20477 if (!RHS.isUsable())
20478 RHS = CO->getRHS();
20479 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20480 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20481 }
20482
20483 // [Clang extension]
20484 // -- If e has the form __extension__ e1...
20485 case Expr::UnaryOperatorClass: {
20486 auto *UO = cast<UnaryOperator>(Val: E);
20487 if (UO->getOpcode() != UO_Extension)
20488 break;
20489 ExprResult Sub = Rebuild(UO->getSubExpr());
20490 if (!Sub.isUsable())
20491 return Sub;
20492 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20493 Input: Sub.get());
20494 }
20495
20496 // [Clang extension]
20497 // -- If e has the form _Generic(...), the set of potential results is the
20498 // union of the sets of potential results of the associated expressions.
20499 case Expr::GenericSelectionExprClass: {
20500 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20501
20502 SmallVector<Expr *, 4> AssocExprs;
20503 bool AnyChanged = false;
20504 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20505 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20506 if (AssocExpr.isInvalid())
20507 return ExprError();
20508 if (AssocExpr.isUsable()) {
20509 AssocExprs.push_back(Elt: AssocExpr.get());
20510 AnyChanged = true;
20511 } else {
20512 AssocExprs.push_back(Elt: OrigAssocExpr);
20513 }
20514 }
20515
20516 void *ExOrTy = nullptr;
20517 bool IsExpr = GSE->isExprPredicate();
20518 if (IsExpr)
20519 ExOrTy = GSE->getControllingExpr();
20520 else
20521 ExOrTy = GSE->getControllingType();
20522 return AnyChanged ? S.CreateGenericSelectionExpr(
20523 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20524 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20525 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20526 : ExprEmpty();
20527 }
20528
20529 // [Clang extension]
20530 // -- If e has the form __builtin_choose_expr(...), the set of potential
20531 // results is the union of the sets of potential results of the
20532 // second and third subexpressions.
20533 case Expr::ChooseExprClass: {
20534 auto *CE = cast<ChooseExpr>(Val: E);
20535
20536 ExprResult LHS = Rebuild(CE->getLHS());
20537 if (LHS.isInvalid())
20538 return ExprError();
20539
20540 ExprResult RHS = Rebuild(CE->getLHS());
20541 if (RHS.isInvalid())
20542 return ExprError();
20543
20544 if (!LHS.get() && !RHS.get())
20545 return ExprEmpty();
20546 if (!LHS.isUsable())
20547 LHS = CE->getLHS();
20548 if (!RHS.isUsable())
20549 RHS = CE->getRHS();
20550
20551 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20552 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20553 }
20554
20555 // Step through non-syntactic nodes.
20556 case Expr::ConstantExprClass: {
20557 auto *CE = cast<ConstantExpr>(Val: E);
20558 ExprResult Sub = Rebuild(CE->getSubExpr());
20559 if (!Sub.isUsable())
20560 return Sub;
20561 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20562 }
20563
20564 // We could mostly rely on the recursive rebuilding to rebuild implicit
20565 // casts, but not at the top level, so rebuild them here.
20566 case Expr::ImplicitCastExprClass: {
20567 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20568 // Only step through the narrow set of cast kinds we expect to encounter.
20569 // Anything else suggests we've left the region in which potential results
20570 // can be found.
20571 switch (ICE->getCastKind()) {
20572 case CK_NoOp:
20573 case CK_DerivedToBase:
20574 case CK_UncheckedDerivedToBase: {
20575 ExprResult Sub = Rebuild(ICE->getSubExpr());
20576 if (!Sub.isUsable())
20577 return Sub;
20578 CXXCastPath Path(ICE->path());
20579 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20580 VK: ICE->getValueKind(), BasePath: &Path);
20581 }
20582
20583 default:
20584 break;
20585 }
20586 break;
20587 }
20588
20589 default:
20590 break;
20591 }
20592
20593 // Can't traverse through this node. Nothing to do.
20594 return ExprEmpty();
20595}
20596
20597ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20598 // Check whether the operand is or contains an object of non-trivial C union
20599 // type.
20600 if (E->getType().isVolatileQualified() &&
20601 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20602 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20603 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20604 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20605 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20606
20607 // C++2a [basic.def.odr]p4:
20608 // [...] an expression of non-volatile-qualified non-class type to which
20609 // the lvalue-to-rvalue conversion is applied [...]
20610 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20611 return E;
20612
20613 ExprResult Result =
20614 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20615 if (Result.isInvalid())
20616 return ExprError();
20617 return Result.get() ? Result : E;
20618}
20619
20620ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20621 if (!Res.isUsable())
20622 return Res;
20623
20624 // If a constant-expression is a reference to a variable where we delay
20625 // deciding whether it is an odr-use, just assume we will apply the
20626 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20627 // (a non-type template argument), we have special handling anyway.
20628 return CheckLValueToRValueConversionOperand(E: Res.get());
20629}
20630
20631void Sema::CleanupVarDeclMarking() {
20632 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20633 // call.
20634 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20635 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20636
20637 for (Expr *E : LocalMaybeODRUseExprs) {
20638 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20639 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20640 Loc: DRE->getLocation(), SemaRef&: *this);
20641 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20642 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20643 SemaRef&: *this);
20644 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20645 for (ValueDecl *VD : *FP)
20646 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20647 } else {
20648 llvm_unreachable("Unexpected expression");
20649 }
20650 }
20651
20652 assert(MaybeODRUseExprs.empty() &&
20653 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20654}
20655
20656static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20657 ValueDecl *Var, Expr *E) {
20658 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20659 if (!VD)
20660 return;
20661
20662 const bool RefersToEnclosingScope =
20663 (SemaRef.CurContext != VD->getDeclContext() &&
20664 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20665 if (RefersToEnclosingScope) {
20666 LambdaScopeInfo *const LSI =
20667 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20668 if (LSI && (!LSI->CallOperator ||
20669 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20670 // If a variable could potentially be odr-used, defer marking it so
20671 // until we finish analyzing the full expression for any
20672 // lvalue-to-rvalue
20673 // or discarded value conversions that would obviate odr-use.
20674 // Add it to the list of potential captures that will be analyzed
20675 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20676 // unless the variable is a reference that was initialized by a constant
20677 // expression (this will never need to be captured or odr-used).
20678 //
20679 // FIXME: We can simplify this a lot after implementing P0588R1.
20680 assert(E && "Capture variable should be used in an expression.");
20681 if (!Var->getType()->isReferenceType() ||
20682 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20683 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20684 }
20685 }
20686}
20687
20688static void DoMarkVarDeclReferenced(
20689 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20690 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20691 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20692 isa<FunctionParmPackExpr>(E)) &&
20693 "Invalid Expr argument to DoMarkVarDeclReferenced");
20694 Var->setReferenced();
20695
20696 if (Var->isInvalidDecl())
20697 return;
20698
20699 auto *MSI = Var->getMemberSpecializationInfo();
20700 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20701 : Var->getTemplateSpecializationKind();
20702
20703 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20704 bool UsableInConstantExpr =
20705 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20706
20707 // Only track variables with internal linkage or local scope.
20708 // Use canonical decl so in-class declarations and out-of-class definitions
20709 // of static data members in anonymous namespaces are tracked as a single
20710 // entry.
20711 const VarDecl *CanonVar = Var->getCanonicalDecl();
20712 if ((CanonVar->isLocalVarDeclOrParm() ||
20713 CanonVar->isInternalLinkageFileVar()) &&
20714 !CanonVar->hasExternalStorage()) {
20715 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20716 }
20717
20718 // C++20 [expr.const]p12:
20719 // A variable [...] is needed for constant evaluation if it is [...] a
20720 // variable whose name appears as a potentially constant evaluated
20721 // expression that is either a contexpr variable or is of non-volatile
20722 // const-qualified integral type or of reference type
20723 bool NeededForConstantEvaluation =
20724 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20725
20726 bool NeedDefinition =
20727 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20728 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20729 Var->getType()->isUndeducedType());
20730
20731 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20732 "Can't instantiate a partial template specialization.");
20733
20734 // If this might be a member specialization of a static data member, check
20735 // the specialization is visible. We already did the checks for variable
20736 // template specializations when we created them.
20737 if (NeedDefinition && TSK != TSK_Undeclared &&
20738 !isa<VarTemplateSpecializationDecl>(Val: Var))
20739 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20740
20741 // Perform implicit instantiation of static data members, static data member
20742 // templates of class templates, and variable template specializations. Delay
20743 // instantiations of variable templates, except for those that could be used
20744 // in a constant expression.
20745 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20746 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20747 // instantiation declaration if a variable is usable in a constant
20748 // expression (among other cases).
20749 bool TryInstantiating =
20750 TSK == TSK_ImplicitInstantiation ||
20751 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20752
20753 if (TryInstantiating) {
20754 SourceLocation PointOfInstantiation =
20755 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20756 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20757 if (FirstInstantiation) {
20758 PointOfInstantiation = Loc;
20759 if (MSI)
20760 MSI->setPointOfInstantiation(PointOfInstantiation);
20761 // FIXME: Notify listener.
20762 else
20763 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20764 }
20765
20766 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20767 // Do not defer instantiations of variables that could be used in a
20768 // constant expression.
20769 // The type deduction also needs a complete initializer.
20770 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20771 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20772 });
20773
20774 // The size of an incomplete array type can be updated by
20775 // instantiating the initializer. The DeclRefExpr's type should be
20776 // updated accordingly too, or users of it would be confused!
20777 if (E)
20778 SemaRef.getCompletedType(E);
20779
20780 // Re-set the member to trigger a recomputation of the dependence bits
20781 // for the expression.
20782 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20783 DRE->setDecl(DRE->getDecl());
20784 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20785 ME->setMemberDecl(ME->getMemberDecl());
20786 } else if (FirstInstantiation) {
20787 SemaRef.PendingInstantiations
20788 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20789 } else {
20790 bool Inserted = false;
20791 for (auto &I : SemaRef.SavedPendingInstantiations) {
20792 auto Iter = llvm::find_if(
20793 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20794 return P.first == Var;
20795 });
20796 if (Iter != I.end()) {
20797 SemaRef.PendingInstantiations.push_back(x: *Iter);
20798 I.erase(position: Iter);
20799 Inserted = true;
20800 break;
20801 }
20802 }
20803
20804 // FIXME: For a specialization of a variable template, we don't
20805 // distinguish between "declaration and type implicitly instantiated"
20806 // and "implicit instantiation of definition requested", so we have
20807 // no direct way to avoid enqueueing the pending instantiation
20808 // multiple times.
20809 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20810 SemaRef.PendingInstantiations
20811 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20812 }
20813 }
20814 }
20815
20816 // C++2a [basic.def.odr]p4:
20817 // A variable x whose name appears as a potentially-evaluated expression e
20818 // is odr-used by e unless
20819 // -- x is a reference that is usable in constant expressions
20820 // -- x is a variable of non-reference type that is usable in constant
20821 // expressions and has no mutable subobjects [FIXME], and e is an
20822 // element of the set of potential results of an expression of
20823 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20824 // conversion is applied
20825 // -- x is a variable of non-reference type, and e is an element of the set
20826 // of potential results of a discarded-value expression to which the
20827 // lvalue-to-rvalue conversion is not applied [FIXME]
20828 //
20829 // We check the first part of the second bullet here, and
20830 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20831 // FIXME: To get the third bullet right, we need to delay this even for
20832 // variables that are not usable in constant expressions.
20833
20834 // If we already know this isn't an odr-use, there's nothing more to do.
20835 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20836 if (DRE->isNonOdrUse())
20837 return;
20838 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20839 if (ME->isNonOdrUse())
20840 return;
20841
20842 switch (OdrUse) {
20843 case OdrUseContext::None:
20844 // In some cases, a variable may not have been marked unevaluated, if it
20845 // appears in a defaukt initializer.
20846 assert((!E || isa<FunctionParmPackExpr>(E) ||
20847 SemaRef.isUnevaluatedContext()) &&
20848 "missing non-odr-use marking for unevaluated decl ref");
20849 break;
20850
20851 case OdrUseContext::FormallyOdrUsed:
20852 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20853 // behavior.
20854 break;
20855
20856 case OdrUseContext::Used:
20857 // If we might later find that this expression isn't actually an odr-use,
20858 // delay the marking.
20859 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20860 SemaRef.MaybeODRUseExprs.insert(X: E);
20861 else
20862 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20863 break;
20864
20865 case OdrUseContext::Dependent:
20866 // If this is a dependent context, we don't need to mark variables as
20867 // odr-used, but we may still need to track them for lambda capture.
20868 // FIXME: Do we also need to do this inside dependent typeid expressions
20869 // (which are modeled as unevaluated at this point)?
20870 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20871 break;
20872 }
20873}
20874
20875static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20876 BindingDecl *BD, Expr *E) {
20877 BD->setReferenced();
20878
20879 if (BD->isInvalidDecl())
20880 return;
20881
20882 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20883 if (OdrUse == OdrUseContext::Used) {
20884 QualType CaptureType, DeclRefType;
20885 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20886 /*EllipsisLoc*/ SourceLocation(),
20887 /*BuildAndDiagnose*/ true, CaptureType,
20888 DeclRefType,
20889 /*FunctionScopeIndexToStopAt*/ nullptr);
20890 } else if (OdrUse == OdrUseContext::Dependent) {
20891 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20892 }
20893}
20894
20895void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20896 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20897}
20898
20899// C++ [temp.dep.expr]p3:
20900// An id-expression is type-dependent if it contains:
20901// - an identifier associated by name lookup with an entity captured by copy
20902// in a lambda-expression that has an explicit object parameter whose type
20903// is dependent ([dcl.fct]),
20904static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20905 Sema &SemaRef, ValueDecl *D, Expr *E) {
20906 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20907 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20908 return;
20909
20910 // If any enclosing lambda with a dependent explicit object parameter either
20911 // explicitly captures the variable by value, or has a capture default of '='
20912 // and does not capture the variable by reference, then the type of the DRE
20913 // is dependent on the type of that lambda's explicit object parameter.
20914 auto IsDependent = [&]() {
20915 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20916 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20917 if (!LSI)
20918 continue;
20919
20920 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20921 LSI->AfterParameterList)
20922 return false;
20923
20924 const auto *MD = LSI->CallOperator;
20925 if (MD->getType().isNull())
20926 continue;
20927
20928 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20929 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20930 !Ty->getParamType(i: 0)->isDependentType())
20931 continue;
20932
20933 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20934 if (C->isCopyCapture())
20935 return true;
20936 continue;
20937 }
20938
20939 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20940 return true;
20941 }
20942 return false;
20943 }();
20944
20945 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20946 Set: IsDependent, Context: SemaRef.getASTContext());
20947}
20948
20949static void
20950MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20951 bool MightBeOdrUse,
20952 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20953 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20954 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20955
20956 if (SemaRef.getLangOpts().OpenACC)
20957 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20958
20959 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20960 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20961 if (SemaRef.getLangOpts().CPlusPlus)
20962 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20963 D: Var, E);
20964 return;
20965 }
20966
20967 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20968 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20969 if (SemaRef.getLangOpts().CPlusPlus)
20970 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20971 D: Decl, E);
20972 return;
20973 }
20974 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20975
20976 // If this is a call to a method via a cast, also mark the method in the
20977 // derived class used in case codegen can devirtualize the call.
20978 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20979 if (!ME)
20980 return;
20981 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20982 if (!MD)
20983 return;
20984 // Only attempt to devirtualize if this is truly a virtual call.
20985 bool IsVirtualCall = MD->isVirtual() &&
20986 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20987 if (!IsVirtualCall)
20988 return;
20989
20990 // If it's possible to devirtualize the call, mark the called function
20991 // referenced.
20992 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20993 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20994 if (DM)
20995 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20996}
20997
20998void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20999 // [basic.def.odr] (CWG 1614)
21000 // A function is named by an expression or conversion [...]
21001 // unless it is a pure virtual function and either the expression is not an
21002 // id-expression naming the function with an explicitly qualified name or
21003 // the expression forms a pointer to member
21004 bool OdrUse = true;
21005 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
21006 if (Method->isVirtual() &&
21007 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
21008 OdrUse = false;
21009
21010 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
21011 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
21012 !isImmediateFunctionContext() &&
21013 !isCheckingDefaultArgumentOrInitializer() &&
21014 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21015 !FD->isDependentContext())
21016 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
21017 }
21018 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
21019 RefsMinusAssignments);
21020}
21021
21022void Sema::MarkMemberReferenced(MemberExpr *E) {
21023 // C++11 [basic.def.odr]p2:
21024 // A non-overloaded function whose name appears as a potentially-evaluated
21025 // expression or a member of a set of candidate functions, if selected by
21026 // overload resolution when referred to from a potentially-evaluated
21027 // expression, is odr-used, unless it is a pure virtual function and its
21028 // name is not explicitly qualified.
21029 bool MightBeOdrUse = true;
21030 if (E->performsVirtualDispatch(LO: getLangOpts())) {
21031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
21032 if (Method->isPureVirtual())
21033 MightBeOdrUse = false;
21034 }
21035 SourceLocation Loc =
21036 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21037 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
21038 RefsMinusAssignments);
21039}
21040
21041void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
21042 for (ValueDecl *VD : *E)
21043 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
21044 RefsMinusAssignments);
21045}
21046
21047/// Perform marking for a reference to an arbitrary declaration. It
21048/// marks the declaration referenced, and performs odr-use checking for
21049/// functions and variables. This method should not be used when building a
21050/// normal expression which refers to a variable.
21051void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
21052 bool MightBeOdrUse) {
21053 if (MightBeOdrUse) {
21054 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
21055 MarkVariableReferenced(Loc, Var: VD);
21056 return;
21057 }
21058 }
21059 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
21060 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
21061 return;
21062 }
21063 D->setReferenced();
21064}
21065
21066namespace {
21067 // Mark all of the declarations used by a type as referenced.
21068 // FIXME: Not fully implemented yet! We need to have a better understanding
21069 // of when we're entering a context we should not recurse into.
21070 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21071 // TreeTransforms rebuilding the type in a new context. Rather than
21072 // duplicating the TreeTransform logic, we should consider reusing it here.
21073 // Currently that causes problems when rebuilding LambdaExprs.
21074class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21075 Sema &S;
21076 SourceLocation Loc;
21077
21078public:
21079 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21080
21081 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21082};
21083}
21084
21085bool MarkReferencedDecls::TraverseTemplateArgument(
21086 const TemplateArgument &Arg) {
21087 {
21088 // A non-type template argument is a constant-evaluated context.
21089 EnterExpressionEvaluationContext Evaluated(
21090 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
21091 if (Arg.getKind() == TemplateArgument::Declaration) {
21092 if (Decl *D = Arg.getAsDecl())
21093 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
21094 } else if (Arg.getKind() == TemplateArgument::Expression) {
21095 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
21096 }
21097 }
21098
21099 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
21100}
21101
21102void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
21103 MarkReferencedDecls Marker(*this, Loc);
21104 Marker.TraverseType(T);
21105}
21106
21107namespace {
21108/// Helper class that marks all of the declarations referenced by
21109/// potentially-evaluated subexpressions as "referenced".
21110class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21111public:
21112 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21113 bool SkipLocalVariables;
21114 ArrayRef<const Expr *> StopAt;
21115
21116 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21117 ArrayRef<const Expr *> StopAt)
21118 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21119
21120 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21121 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21122 }
21123
21124 void Visit(Expr *E) {
21125 if (llvm::is_contained(Range&: StopAt, Element: E))
21126 return;
21127 Inherited::Visit(S: E);
21128 }
21129
21130 void VisitConstantExpr(ConstantExpr *E) {
21131 // Don't mark declarations within a ConstantExpression, as this expression
21132 // will be evaluated and folded to a value.
21133 }
21134
21135 void VisitDeclRefExpr(DeclRefExpr *E) {
21136 // If we were asked not to visit local variables, don't.
21137 if (SkipLocalVariables) {
21138 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21139 if (VD->hasLocalStorage())
21140 return;
21141 }
21142
21143 // FIXME: This can trigger the instantiation of the initializer of a
21144 // variable, which can cause the expression to become value-dependent
21145 // or error-dependent. Do we need to propagate the new dependence bits?
21146 S.MarkDeclRefReferenced(E);
21147 }
21148
21149 void VisitMemberExpr(MemberExpr *E) {
21150 S.MarkMemberReferenced(E);
21151 Visit(E: E->getBase());
21152 }
21153};
21154} // namespace
21155
21156void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21157 bool SkipLocalVariables,
21158 ArrayRef<const Expr*> StopAt) {
21159 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21160}
21161
21162/// Emit a diagnostic when statements are reachable.
21163bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21164 const PartialDiagnostic &PD) {
21165 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21166 // The initializer of a constexpr variable or of the first declaration of a
21167 // static data member is not syntactically a constant evaluated constant,
21168 // but nonetheless is always required to be a constant expression, so we
21169 // can skip diagnosing.
21170 if (Decl &&
21171 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21172 Decl->isFirstDecl() && !Decl->isInline())))
21173 return false;
21174
21175 if (Stmts.empty()) {
21176 Diag(Loc, PD);
21177 return true;
21178 }
21179
21180 if (getCurFunction()) {
21181 // This queue flushes after the function is analyzed, by which time an
21182 // ignore-all-warnings region live here is gone, so sample it now. A note
21183 // is not error-class either, so this also drops the notes that accompany a
21184 // skipped warning. They arrive on their own call, out of reach of the
21185 // engine's rule that drops a note whose warning was ignored.
21186 if (Diags.getIgnoreAllWarnings() &&
21187 Diags.getDiagnosticIDs()->isWarningOrExtension(DiagID: PD.getDiagID()))
21188 return false;
21189 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21190 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21191 return true;
21192 }
21193
21194 // For non-constexpr file-scope variables with reachability context (non-empty
21195 // Stmts), build a CFG for the initializer and check whether the context in
21196 // question is reachable.
21197 if (Decl && Decl->isFileVarDecl()) {
21198 AnalysisWarnings.registerVarDeclWarning(
21199 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21200 return true;
21201 }
21202
21203 Diag(Loc, PD);
21204 return true;
21205}
21206
21207/// Emit a diagnostic that describes an effect on the run-time behavior
21208/// of the program being compiled.
21209///
21210/// This routine emits the given diagnostic when the code currently being
21211/// type-checked is "potentially evaluated", meaning that there is a
21212/// possibility that the code will actually be executable. Code in sizeof()
21213/// expressions, code used only during overload resolution, etc., are not
21214/// potentially evaluated. This routine will suppress such diagnostics or,
21215/// in the absolutely nutty case of potentially potentially evaluated
21216/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21217/// later.
21218///
21219/// This routine should be used for all diagnostics that describe the run-time
21220/// behavior of a program, such as passing a non-POD value through an ellipsis.
21221/// Failure to do so will likely result in spurious diagnostics or failures
21222/// during overload resolution or within sizeof/alignof/typeof/typeid.
21223bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21224 const PartialDiagnostic &PD) {
21225
21226 if (ExprEvalContexts.back().isDiscardedStatementContext())
21227 return false;
21228
21229 switch (ExprEvalContexts.back().Context) {
21230 case ExpressionEvaluationContext::Unevaluated:
21231 case ExpressionEvaluationContext::UnevaluatedList:
21232 case ExpressionEvaluationContext::UnevaluatedAbstract:
21233 case ExpressionEvaluationContext::DiscardedStatement:
21234 // The argument will never be evaluated, so don't complain.
21235 break;
21236
21237 case ExpressionEvaluationContext::ConstantEvaluated:
21238 case ExpressionEvaluationContext::ImmediateFunctionContext:
21239 // Relevant diagnostics should be produced by constant evaluation.
21240 break;
21241
21242 case ExpressionEvaluationContext::PotentiallyEvaluated:
21243 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21244 return DiagIfReachable(Loc, Stmts, PD);
21245 }
21246
21247 return false;
21248}
21249
21250bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21251 const PartialDiagnostic &PD) {
21252 return DiagRuntimeBehavior(
21253 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21254 PD);
21255}
21256
21257bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21258 CallExpr *CE, FunctionDecl *FD) {
21259 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21260 return false;
21261
21262 // If we're inside a decltype's expression, don't check for a valid return
21263 // type or construct temporaries until we know whether this is the last call.
21264 if (ExprEvalContexts.back().ExprContext ==
21265 ExpressionEvaluationContextRecord::EK_Decltype) {
21266 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21267 return false;
21268 }
21269
21270 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21271 FunctionDecl *FD;
21272 CallExpr *CE;
21273
21274 public:
21275 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21276 : FD(FD), CE(CE) { }
21277
21278 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21279 if (!FD) {
21280 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21281 << T << CE->getSourceRange();
21282 return;
21283 }
21284
21285 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21286 << CE->getSourceRange() << FD << T;
21287 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21288 << FD->getDeclName();
21289 }
21290 } Diagnoser(FD, CE);
21291
21292 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21293 return true;
21294
21295 return false;
21296}
21297
21298// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21299// will prevent this condition from triggering, which is what we want.
21300void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21301 SourceLocation Loc;
21302
21303 unsigned diagnostic = diag::warn_condition_is_assignment;
21304 bool IsOrAssign = false;
21305
21306 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21307 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21308 return;
21309
21310 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21311
21312 // Greylist some idioms by putting them into a warning subcategory.
21313 if (ObjCMessageExpr *ME
21314 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21315 Selector Sel = ME->getSelector();
21316
21317 // self = [<foo> init...]
21318 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21319 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21320
21321 // <foo> = [<bar> nextObject]
21322 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21323 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21324 }
21325
21326 Loc = Op->getOperatorLoc();
21327 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21328 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21329 return;
21330
21331 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21332 Loc = Op->getOperatorLoc();
21333 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21334 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21335 else {
21336 // Not an assignment.
21337 return;
21338 }
21339
21340 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21341
21342 SourceLocation Open = E->getBeginLoc();
21343 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21344 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21345 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21346 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21347
21348 if (IsOrAssign)
21349 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21350 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21351 else
21352 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21353 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21354}
21355
21356void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21357 // Don't warn if the parens came from a macro.
21358 SourceLocation parenLoc = ParenE->getBeginLoc();
21359 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21360 return;
21361 // Don't warn for dependent expressions.
21362 if (ParenE->isTypeDependent())
21363 return;
21364
21365 Expr *E = ParenE->IgnoreParens();
21366 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21367 return;
21368
21369 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21370 if (opE->getOpcode() == BO_EQ &&
21371 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21372 == Expr::MLV_Valid) {
21373 SourceLocation Loc = opE->getOperatorLoc();
21374
21375 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21376 SourceRange ParenERange = ParenE->getSourceRange();
21377 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21378 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21379 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21380 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21381 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21382 }
21383}
21384
21385ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21386 bool IsConstexpr) {
21387 DiagnoseAssignmentAsCondition(E);
21388 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21389 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21390
21391 ExprResult result = CheckPlaceholderExpr(E);
21392 if (result.isInvalid()) return ExprError();
21393 E = result.get();
21394
21395 if (!E->isTypeDependent()) {
21396 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21397 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21398
21399 if (getLangOpts().CPlusPlus)
21400 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21401
21402 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21403 if (ERes.isInvalid())
21404 return ExprError();
21405 E = ERes.get();
21406
21407 QualType T = E->getType();
21408 if (!T->isScalarType()) { // C99 6.8.4.1p1
21409 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21410 << T << E->getSourceRange();
21411 return ExprError();
21412 }
21413 CheckBoolLikeConversion(E, CC: Loc);
21414 }
21415
21416 return E;
21417}
21418
21419Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21420 Expr *SubExpr, ConditionKind CK,
21421 bool MissingOK) {
21422 // MissingOK indicates whether having no condition expression is valid
21423 // (for loop) or invalid (e.g. while loop).
21424 if (!SubExpr)
21425 return MissingOK ? ConditionResult() : ConditionError();
21426
21427 ExprResult Cond;
21428 switch (CK) {
21429 case ConditionKind::Boolean:
21430 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21431 break;
21432
21433 case ConditionKind::ConstexprIf:
21434 // Note: this might produce a FullExpr
21435 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21436 break;
21437
21438 case ConditionKind::Switch:
21439 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21440 break;
21441 }
21442 if (Cond.isInvalid()) {
21443 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21444 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21445 if (!Cond.get())
21446 return ConditionError();
21447 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21448 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21449
21450 if (!Cond.isUsable())
21451 return ConditionError();
21452
21453 return ConditionResult(*this, nullptr, Cond,
21454 CK == ConditionKind::ConstexprIf);
21455}
21456
21457namespace {
21458 /// A visitor for rebuilding a call to an __unknown_any expression
21459 /// to have an appropriate type.
21460 struct RebuildUnknownAnyFunction
21461 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21462
21463 Sema &S;
21464
21465 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21466
21467 ExprResult VisitStmt(Stmt *S) {
21468 llvm_unreachable("unexpected statement!");
21469 }
21470
21471 ExprResult VisitExpr(Expr *E) {
21472 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21473 << E->getSourceRange();
21474 return ExprError();
21475 }
21476
21477 /// Rebuild an expression which simply semantically wraps another
21478 /// expression which it shares the type and value kind of.
21479 template <class T> ExprResult rebuildSugarExpr(T *E) {
21480 ExprResult SubResult = Visit(S: E->getSubExpr());
21481 if (SubResult.isInvalid()) return ExprError();
21482
21483 Expr *SubExpr = SubResult.get();
21484 E->setSubExpr(SubExpr);
21485 E->setType(SubExpr->getType());
21486 E->setValueKind(SubExpr->getValueKind());
21487 assert(E->getObjectKind() == OK_Ordinary);
21488 return E;
21489 }
21490
21491 ExprResult VisitParenExpr(ParenExpr *E) {
21492 return rebuildSugarExpr(E);
21493 }
21494
21495 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21496 return rebuildSugarExpr(E);
21497 }
21498
21499 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21500 ExprResult SubResult = Visit(S: E->getSubExpr());
21501 if (SubResult.isInvalid()) return ExprError();
21502
21503 Expr *SubExpr = SubResult.get();
21504 E->setSubExpr(SubExpr);
21505 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21506 assert(E->isPRValue());
21507 assert(E->getObjectKind() == OK_Ordinary);
21508 return E;
21509 }
21510
21511 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21512 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21513
21514 E->setType(VD->getType());
21515
21516 assert(E->isPRValue());
21517 if (S.getLangOpts().CPlusPlus &&
21518 !(isa<CXXMethodDecl>(Val: VD) &&
21519 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21520 E->setValueKind(VK_LValue);
21521
21522 return E;
21523 }
21524
21525 ExprResult VisitMemberExpr(MemberExpr *E) {
21526 return resolveDecl(E, VD: E->getMemberDecl());
21527 }
21528
21529 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21530 return resolveDecl(E, VD: E->getDecl());
21531 }
21532 };
21533}
21534
21535/// Given a function expression of unknown-any type, try to rebuild it
21536/// to have a function type.
21537static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21538 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21539 if (Result.isInvalid()) return ExprError();
21540 return S.DefaultFunctionArrayConversion(E: Result.get());
21541}
21542
21543namespace {
21544 /// A visitor for rebuilding an expression of type __unknown_anytype
21545 /// into one which resolves the type directly on the referring
21546 /// expression. Strict preservation of the original source
21547 /// structure is not a goal.
21548 struct RebuildUnknownAnyExpr
21549 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21550
21551 Sema &S;
21552
21553 /// The current destination type.
21554 QualType DestType;
21555
21556 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21557 : S(S), DestType(CastType) {}
21558
21559 ExprResult VisitStmt(Stmt *S) {
21560 llvm_unreachable("unexpected statement!");
21561 }
21562
21563 ExprResult VisitExpr(Expr *E) {
21564 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21565 << E->getSourceRange();
21566 return ExprError();
21567 }
21568
21569 ExprResult VisitCallExpr(CallExpr *E);
21570 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21571
21572 /// Rebuild an expression which simply semantically wraps another
21573 /// expression which it shares the type and value kind of.
21574 template <class T> ExprResult rebuildSugarExpr(T *E) {
21575 ExprResult SubResult = Visit(S: E->getSubExpr());
21576 if (SubResult.isInvalid()) return ExprError();
21577 Expr *SubExpr = SubResult.get();
21578 E->setSubExpr(SubExpr);
21579 E->setType(SubExpr->getType());
21580 E->setValueKind(SubExpr->getValueKind());
21581 assert(E->getObjectKind() == OK_Ordinary);
21582 return E;
21583 }
21584
21585 ExprResult VisitParenExpr(ParenExpr *E) {
21586 return rebuildSugarExpr(E);
21587 }
21588
21589 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21590 return rebuildSugarExpr(E);
21591 }
21592
21593 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21594 const PointerType *Ptr = DestType->getAs<PointerType>();
21595 if (!Ptr) {
21596 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21597 << E->getSourceRange();
21598 return ExprError();
21599 }
21600
21601 if (isa<CallExpr>(Val: E->getSubExpr())) {
21602 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21603 << E->getSourceRange();
21604 return ExprError();
21605 }
21606
21607 assert(E->isPRValue());
21608 assert(E->getObjectKind() == OK_Ordinary);
21609 E->setType(DestType);
21610
21611 // Build the sub-expression as if it were an object of the pointee type.
21612 DestType = Ptr->getPointeeType();
21613 ExprResult SubResult = Visit(S: E->getSubExpr());
21614 if (SubResult.isInvalid()) return ExprError();
21615 E->setSubExpr(SubResult.get());
21616 return E;
21617 }
21618
21619 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21620
21621 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21622
21623 ExprResult VisitMemberExpr(MemberExpr *E) {
21624 return resolveDecl(E, VD: E->getMemberDecl());
21625 }
21626
21627 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21628 return resolveDecl(E, VD: E->getDecl());
21629 }
21630 };
21631}
21632
21633/// Rebuilds a call expression which yielded __unknown_anytype.
21634ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21635 Expr *CalleeExpr = E->getCallee();
21636
21637 enum FnKind {
21638 FK_MemberFunction,
21639 FK_FunctionPointer,
21640 FK_BlockPointer
21641 };
21642
21643 FnKind Kind;
21644 QualType CalleeType = CalleeExpr->getType();
21645 if (CalleeType == S.Context.BoundMemberTy) {
21646 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21647 Kind = FK_MemberFunction;
21648 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21649 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21650 CalleeType = Ptr->getPointeeType();
21651 Kind = FK_FunctionPointer;
21652 } else {
21653 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21654 Kind = FK_BlockPointer;
21655 }
21656 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21657
21658 // Verify that this is a legal result type of a function.
21659 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21660 DestType->isFunctionType()) {
21661 unsigned diagID = diag::err_func_returning_array_function;
21662 if (Kind == FK_BlockPointer)
21663 diagID = diag::err_block_returning_array_function;
21664
21665 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21666 << DestType->isFunctionType() << DestType;
21667 return ExprError();
21668 }
21669
21670 // Otherwise, go ahead and set DestType as the call's result.
21671 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21672 E->setValueKind(Expr::getValueKindForType(T: DestType));
21673 assert(E->getObjectKind() == OK_Ordinary);
21674
21675 // Rebuild the function type, replacing the result type with DestType.
21676 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21677 if (Proto) {
21678 // __unknown_anytype(...) is a special case used by the debugger when
21679 // it has no idea what a function's signature is.
21680 //
21681 // We want to build this call essentially under the K&R
21682 // unprototyped rules, but making a FunctionNoProtoType in C++
21683 // would foul up all sorts of assumptions. However, we cannot
21684 // simply pass all arguments as variadic arguments, nor can we
21685 // portably just call the function under a non-variadic type; see
21686 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21687 // However, it turns out that in practice it is generally safe to
21688 // call a function declared as "A foo(B,C,D);" under the prototype
21689 // "A foo(B,C,D,...);". The only known exception is with the
21690 // Windows ABI, where any variadic function is implicitly cdecl
21691 // regardless of its normal CC. Therefore we change the parameter
21692 // types to match the types of the arguments.
21693 //
21694 // This is a hack, but it is far superior to moving the
21695 // corresponding target-specific code from IR-gen to Sema/AST.
21696
21697 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21698 SmallVector<QualType, 8> ArgTypes;
21699 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21700 ArgTypes.reserve(N: E->getNumArgs());
21701 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21702 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21703 }
21704 ParamTypes = ArgTypes;
21705 }
21706 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21707 EPI: Proto->getExtProtoInfo());
21708 } else {
21709 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21710 Info: FnType->getExtInfo());
21711 }
21712
21713 // Rebuild the appropriate pointer-to-function type.
21714 switch (Kind) {
21715 case FK_MemberFunction:
21716 // Nothing to do.
21717 break;
21718
21719 case FK_FunctionPointer:
21720 DestType = S.Context.getPointerType(T: DestType);
21721 break;
21722
21723 case FK_BlockPointer:
21724 DestType = S.Context.getBlockPointerType(T: DestType);
21725 break;
21726 }
21727
21728 // Finally, we can recurse.
21729 ExprResult CalleeResult = Visit(S: CalleeExpr);
21730 if (!CalleeResult.isUsable()) return ExprError();
21731 E->setCallee(CalleeResult.get());
21732
21733 // Bind a temporary if necessary.
21734 return S.MaybeBindToTemporary(E);
21735}
21736
21737ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21738 // Verify that this is a legal result type of a call.
21739 if (DestType->isArrayType() || DestType->isFunctionType()) {
21740 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21741 << DestType->isFunctionType() << DestType;
21742 return ExprError();
21743 }
21744
21745 // Rewrite the method result type if available.
21746 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21747 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21748 Method->setReturnType(DestType);
21749 }
21750
21751 // Change the type of the message.
21752 E->setType(DestType.getNonReferenceType());
21753 E->setValueKind(Expr::getValueKindForType(T: DestType));
21754
21755 return S.MaybeBindToTemporary(E);
21756}
21757
21758ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21759 // The only case we should ever see here is a function-to-pointer decay.
21760 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21761 assert(E->isPRValue());
21762 assert(E->getObjectKind() == OK_Ordinary);
21763
21764 E->setType(DestType);
21765
21766 // Rebuild the sub-expression as the pointee (function) type.
21767 DestType = DestType->castAs<PointerType>()->getPointeeType();
21768
21769 ExprResult Result = Visit(S: E->getSubExpr());
21770 if (!Result.isUsable()) return ExprError();
21771
21772 E->setSubExpr(Result.get());
21773 return E;
21774 } else if (E->getCastKind() == CK_LValueToRValue) {
21775 assert(E->isPRValue());
21776 assert(E->getObjectKind() == OK_Ordinary);
21777
21778 assert(isa<BlockPointerType>(E->getType()));
21779
21780 E->setType(DestType);
21781
21782 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21783 DestType = S.Context.getLValueReferenceType(T: DestType);
21784
21785 ExprResult Result = Visit(S: E->getSubExpr());
21786 if (!Result.isUsable()) return ExprError();
21787
21788 E->setSubExpr(Result.get());
21789 return E;
21790 } else {
21791 llvm_unreachable("Unhandled cast type!");
21792 }
21793}
21794
21795ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21796 ExprValueKind ValueKind = VK_LValue;
21797 QualType Type = DestType;
21798
21799 // We know how to make this work for certain kinds of decls:
21800
21801 // - functions
21802 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21803 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21804 DestType = Ptr->getPointeeType();
21805 ExprResult Result = resolveDecl(E, VD);
21806 if (Result.isInvalid()) return ExprError();
21807 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21808 VK: VK_PRValue);
21809 }
21810
21811 if (!Type->isFunctionType()) {
21812 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21813 << VD << E->getSourceRange();
21814 return ExprError();
21815 }
21816 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21817 // We must match the FunctionDecl's type to the hack introduced in
21818 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21819 // type. See the lengthy commentary in that routine.
21820 QualType FDT = FD->getType();
21821 const FunctionType *FnType = FDT->castAs<FunctionType>();
21822 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21823 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21824 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21825 SourceLocation Loc = FD->getLocation();
21826 FunctionDecl *NewFD = FunctionDecl::Create(
21827 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21828 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21829 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21830 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21831 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21832
21833 if (FD->getQualifier())
21834 NewFD->setQualifierInfo(FD->getQualifierLoc());
21835
21836 SmallVector<ParmVarDecl*, 16> Params;
21837 for (const auto &AI : FT->param_types()) {
21838 ParmVarDecl *Param =
21839 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21840 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21841 Params.push_back(Elt: Param);
21842 }
21843 NewFD->setParams(Params);
21844 DRE->setDecl(NewFD);
21845 VD = DRE->getDecl();
21846 }
21847 }
21848
21849 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21850 if (MD->isInstance()) {
21851 ValueKind = VK_PRValue;
21852 Type = S.Context.BoundMemberTy;
21853 }
21854
21855 // Function references aren't l-values in C.
21856 if (!S.getLangOpts().CPlusPlus)
21857 ValueKind = VK_PRValue;
21858
21859 // - variables
21860 } else if (isa<VarDecl>(Val: VD)) {
21861 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21862 Type = RefTy->getPointeeType();
21863 } else if (Type->isFunctionType()) {
21864 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21865 << VD << E->getSourceRange();
21866 return ExprError();
21867 }
21868
21869 // - nothing else
21870 } else {
21871 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21872 << VD << E->getSourceRange();
21873 return ExprError();
21874 }
21875
21876 // Modifying the declaration like this is friendly to IR-gen but
21877 // also really dangerous.
21878 VD->setType(DestType);
21879 E->setType(Type);
21880 E->setValueKind(ValueKind);
21881 return E;
21882}
21883
21884ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21885 Expr *CastExpr, CastKind &CastKind,
21886 ExprValueKind &VK, CXXCastPath &Path) {
21887 // The type we're casting to must be either void or complete.
21888 if (!CastType->isVoidType() &&
21889 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21890 DiagID: diag::err_typecheck_cast_to_incomplete))
21891 return ExprError();
21892
21893 // Rewrite the casted expression from scratch.
21894 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21895 if (!result.isUsable()) return ExprError();
21896
21897 CastExpr = result.get();
21898 VK = CastExpr->getValueKind();
21899 CastKind = CK_NoOp;
21900
21901 return CastExpr;
21902}
21903
21904ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21905 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21906}
21907
21908ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21909 Expr *arg, QualType &paramType) {
21910 // If the syntactic form of the argument is not an explicit cast of
21911 // any sort, just do default argument promotion.
21912 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21913 if (!castArg) {
21914 ExprResult result = DefaultArgumentPromotion(E: arg);
21915 if (result.isInvalid()) return ExprError();
21916 paramType = result.get()->getType();
21917 return result;
21918 }
21919
21920 // Otherwise, use the type that was written in the explicit cast.
21921 assert(!arg->hasPlaceholderType());
21922 paramType = castArg->getTypeAsWritten();
21923
21924 // Copy-initialize a parameter of that type.
21925 InitializedEntity entity =
21926 InitializedEntity::InitializeParameter(Context, Type: paramType,
21927 /*consumed*/ Consumed: false);
21928 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21929}
21930
21931static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21932 Expr *orig = E;
21933 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21934 while (true) {
21935 E = E->IgnoreParenImpCasts();
21936 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21937 E = call->getCallee();
21938 diagID = diag::err_uncasted_call_of_unknown_any;
21939 } else {
21940 break;
21941 }
21942 }
21943
21944 SourceLocation loc;
21945 NamedDecl *d;
21946 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21947 loc = ref->getLocation();
21948 d = ref->getDecl();
21949 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21950 loc = mem->getMemberLoc();
21951 d = mem->getMemberDecl();
21952 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21953 diagID = diag::err_uncasted_call_of_unknown_any;
21954 loc = msg->getSelectorStartLoc();
21955 d = msg->getMethodDecl();
21956 if (!d) {
21957 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21958 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21959 << orig->getSourceRange();
21960 return ExprError();
21961 }
21962 } else {
21963 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21964 << E->getSourceRange();
21965 return ExprError();
21966 }
21967
21968 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21969
21970 // Never recoverable.
21971 return ExprError();
21972}
21973
21974ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21975 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21976 if (!placeholderType) return E;
21977
21978 switch (placeholderType->getKind()) {
21979 case BuiltinType::UnresolvedTemplate: {
21980 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
21981 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21982 // There's only one FoundDecl for UnresolvedTemplate type. See
21983 // BuildTemplateIdExpr.
21984 NamedDecl *Temp = *ULE->decls_begin();
21985 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21986
21987 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21988 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21989 // as it models only the unqualified-id case, where this case can clearly be
21990 // qualified. Thus we can't just qualify an assumed template.
21991 TemplateName TN;
21992 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21993 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21994 Template: TemplateName(TD));
21995 else
21996 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21997
21998 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21999 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22000 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
22001 << IsTypeAliasTemplateDecl;
22002
22003 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22004 bool HasAnyDependentTA = false;
22005 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22006 HasAnyDependentTA |= Arg.getArgument().isDependent();
22007 TAL.addArgument(Loc: Arg);
22008 }
22009
22010 QualType TST;
22011 {
22012 SFINAETrap Trap(*this);
22013 TST = CheckTemplateIdType(
22014 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
22015 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22016 }
22017 if (TST.isNull())
22018 TST = Context.getTemplateSpecializationType(
22019 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
22020 /*CanonicalArgs=*/{},
22021 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22022 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
22023 T: TST);
22024 }
22025
22026 // Overloaded expressions.
22027 case BuiltinType::Overload: {
22028 // Try to resolve a single function template specialization.
22029 // This is obligatory.
22030 ExprResult Result = E;
22031 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
22032 return Result;
22033
22034 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22035 // leaves Result unchanged on failure.
22036 Result = E;
22037 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
22038 return Result;
22039
22040 // If that failed, try to recover with a call.
22041 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
22042 /*complain*/ ForceComplain: true);
22043 return Result;
22044 }
22045
22046 // Bound member functions.
22047 case BuiltinType::BoundMember: {
22048 ExprResult result = E;
22049 const Expr *BME = E->IgnoreParens();
22050 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
22051 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22052 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
22053 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22054 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
22055 if (ME->getMemberNameInfo().getName().getNameKind() ==
22056 DeclarationName::CXXDestructorName)
22057 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22058 }
22059 tryToRecoverWithCall(E&: result, PD,
22060 /*complain*/ ForceComplain: true);
22061 return result;
22062 }
22063
22064 // ARC unbridged casts.
22065 case BuiltinType::ARCUnbridgedCast: {
22066 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
22067 ObjC().diagnoseARCUnbridgedCast(e: realCast);
22068 return realCast;
22069 }
22070
22071 // Expressions of unknown type.
22072 case BuiltinType::UnknownAny:
22073 return diagnoseUnknownAnyExpr(S&: *this, E);
22074
22075 // Pseudo-objects.
22076 case BuiltinType::PseudoObject:
22077 return PseudoObject().checkRValue(E);
22078
22079 case BuiltinType::BuiltinFn: {
22080 // Accept __noop without parens by implicitly converting it to a call expr.
22081 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
22082 if (DRE) {
22083 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
22084 unsigned BuiltinID = FD->getBuiltinID();
22085 if (BuiltinID == Builtin::BI__noop) {
22086 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
22087 CK: CK_BuiltinFnToFnPtr)
22088 .get();
22089 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
22090 VK: VK_PRValue, RParenLoc: SourceLocation(),
22091 FPFeatures: FPOptionsOverride());
22092 }
22093
22094 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
22095 // Any use of these other than a direct call is ill-formed as of C++20,
22096 // because they are not addressable functions. In earlier language
22097 // modes, warn and force an instantiation of the real body.
22098 Diag(Loc: E->getBeginLoc(),
22099 DiagID: getLangOpts().CPlusPlus20
22100 ? diag::err_use_of_unaddressable_function
22101 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22102 if (FD->isImplicitlyInstantiable()) {
22103 // Require a definition here because a normal attempt at
22104 // instantiation for a builtin will be ignored, and we won't try
22105 // again later. We assume that the definition of the template
22106 // precedes this use.
22107 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
22108 /*Recursive=*/false,
22109 /*DefinitionRequired=*/true,
22110 /*AtEndOfTU=*/false);
22111 }
22112 // Produce a properly-typed reference to the function.
22113 CXXScopeSpec SS;
22114 SS.Adopt(Other: DRE->getQualifierLoc());
22115 TemplateArgumentListInfo TemplateArgs;
22116 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22117 return BuildDeclRefExpr(
22118 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22119 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22120 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22121 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22122 }
22123 }
22124
22125 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22126 return ExprError();
22127 }
22128
22129 case BuiltinType::IncompleteMatrixIdx: {
22130 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22131 // At this point, we know there was no second [] to complete the operator.
22132 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22133 if (getLangOpts().HLSL) {
22134 return CreateBuiltinMatrixSingleSubscriptExpr(
22135 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22136 }
22137 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22138 return ExprError();
22139 }
22140
22141 // Expressions of unknown type.
22142 case BuiltinType::ArraySection:
22143 // If we've already diagnosed something on the array section type, we
22144 // shouldn't need to do any further diagnostic here.
22145 if (!E->containsErrors())
22146 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22147 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22148 return ExprError();
22149
22150 // Expressions of unknown type.
22151 case BuiltinType::OMPArrayShaping:
22152 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22153
22154 case BuiltinType::OMPIterator:
22155 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22156
22157 // Everything else should be impossible.
22158#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22159 case BuiltinType::Id:
22160#include "clang/Basic/OpenCLImageTypes.def"
22161#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22162 case BuiltinType::Id:
22163#include "clang/Basic/OpenCLExtensionTypes.def"
22164#define SVE_TYPE(Name, Id, SingletonId) \
22165 case BuiltinType::Id:
22166#include "clang/Basic/AArch64ACLETypes.def"
22167#define PPC_VECTOR_TYPE(Name, Id, Size) \
22168 case BuiltinType::Id:
22169#include "clang/Basic/PPCTypes.def"
22170#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22171#include "clang/Basic/RISCVVTypes.def"
22172#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22173#include "clang/Basic/WebAssemblyReferenceTypes.def"
22174#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22175#include "clang/Basic/AMDGPUTypes.def"
22176#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22177#include "clang/Basic/HLSLIntangibleTypes.def"
22178#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22179#include "clang/Basic/SPIRVTypes.def"
22180#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22181#define PLACEHOLDER_TYPE(Id, SingletonId)
22182#include "clang/AST/BuiltinTypes.def"
22183 break;
22184 }
22185
22186 llvm_unreachable("invalid placeholder type!");
22187}
22188
22189bool Sema::CheckCaseExpression(Expr *E) {
22190 if (E->isTypeDependent())
22191 return true;
22192 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22193 return E->getType()->isIntegralOrEnumerationType();
22194 return false;
22195}
22196
22197ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22198 ArrayRef<Expr *> SubExprs, QualType T) {
22199 if (!Context.getLangOpts().RecoveryAST)
22200 return ExprError();
22201
22202 if (isSFINAEContext())
22203 return ExprError();
22204
22205 if (T.isNull() || T->isUndeducedType() ||
22206 !Context.getLangOpts().RecoveryASTType)
22207 // We don't know the concrete type, fallback to dependent type.
22208 T = Context.DependentTy;
22209
22210 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22211}
22212