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
2551// Diagnose when a macro cannot be expanded because it's a function-like macro
2552// being used as a function-like macro. Returns true if a diagnostic is emitted.
2553static bool diagnoseFunctionLikeMacro(Sema &SemaRef, DeclarationName Name,
2554 SourceLocation TypoLoc) {
2555
2556 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2557 if (II->hasMacroDefinition()) {
2558 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2559 if (MI && MI->isFunctionLike()) {
2560 // If the identifier is immediately followed by '(', the user did
2561 // attempt to invoke it as a function-like macro; the failure is
2562 // for some other reason (e.g. wrong argument count), which the
2563 // preprocessor already diagnosed separately. Don't suggest adding
2564 // parens in that case, since they're already there.
2565 SourceManager &SM = SemaRef.getSourceManager();
2566 const LangOptions &LangOpts = SemaRef.getLangOpts();
2567 std::optional<Token> NextTok =
2568 Lexer::findNextToken(Loc: TypoLoc, SM, LangOpts);
2569 if (NextTok && NextTok->is(K: tok::l_paren))
2570 return false;
2571 SemaRef.Diag(Loc: TypoLoc,
2572 DiagID: diag::err_undeclared_var_use_suggest_func_like_macro)
2573 << II->getName();
2574 SemaRef.Diag(Loc: MI->getDefinitionLoc(),
2575 DiagID: diag::note_function_like_macro_requires_parens)
2576 << II->getName();
2577 return true;
2578 }
2579 }
2580 }
2581 return false;
2582}
2583
2584void
2585Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2586 TemplateArgumentListInfo &Buffer,
2587 DeclarationNameInfo &NameInfo,
2588 const TemplateArgumentListInfo *&TemplateArgs) {
2589 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2590 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2591 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2592
2593 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2594 Id.TemplateId->NumArgs);
2595 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2596
2597 TemplateName TName = Id.TemplateId->Template.get();
2598 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2599 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2600 TemplateArgs = &Buffer;
2601 } else {
2602 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2603 TemplateArgs = nullptr;
2604 }
2605}
2606
2607bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2608 // During a default argument instantiation the CurContext points
2609 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2610 // function parameter list, hence add an explicit check.
2611 bool isDefaultArgument =
2612 !CodeSynthesisContexts.empty() &&
2613 CodeSynthesisContexts.back().Kind ==
2614 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2615 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2616 bool isInstance = CurMethod && CurMethod->isInstance() &&
2617 R.getNamingClass() == CurMethod->getParent() &&
2618 !isDefaultArgument;
2619
2620 // There are two ways we can find a class-scope declaration during template
2621 // instantiation that we did not find in the template definition: if it is a
2622 // member of a dependent base class, or if it is declared after the point of
2623 // use in the same class. Distinguish these by comparing the class in which
2624 // the member was found to the naming class of the lookup.
2625 unsigned DiagID = diag::err_found_in_dependent_base;
2626 unsigned NoteID = diag::note_member_declared_at;
2627 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2628 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2629 : diag::err_found_later_in_class;
2630 } else if (getLangOpts().MSVCCompat) {
2631 DiagID = diag::ext_found_in_dependent_base;
2632 NoteID = diag::note_dependent_member_use;
2633 }
2634
2635 if (isInstance) {
2636 // Give a code modification hint to insert 'this->'.
2637 Diag(Loc: R.getNameLoc(), DiagID)
2638 << R.getLookupName()
2639 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2640 CheckCXXThisCapture(Loc: R.getNameLoc());
2641 } else {
2642 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2643 // they're not shadowed).
2644 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2645 }
2646
2647 for (const NamedDecl *D : R)
2648 Diag(Loc: D->getLocation(), DiagID: NoteID);
2649
2650 // Return true if we are inside a default argument instantiation
2651 // and the found name refers to an instance member function, otherwise
2652 // the caller will try to create an implicit member call and this is wrong
2653 // for default arguments.
2654 //
2655 // FIXME: Is this special case necessary? We could allow the caller to
2656 // diagnose this.
2657 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2658 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2659 return true;
2660 }
2661
2662 // Tell the callee to try to recover.
2663 return false;
2664}
2665
2666bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2667 CorrectionCandidateCallback &CCC,
2668 TemplateArgumentListInfo *ExplicitTemplateArgs,
2669 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2670 DeclarationName Name = R.getLookupName();
2671 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2672
2673 unsigned diagnostic = diag::err_undeclared_var_use;
2674 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2675 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2676 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2677 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2678 diagnostic = diag::err_undeclared_use;
2679 diagnostic_suggest = diag::err_undeclared_use_suggest;
2680 }
2681
2682 // If the original lookup was an unqualified lookup, fake an
2683 // unqualified lookup. This is useful when (for example) the
2684 // original lookup would not have found something because it was a
2685 // dependent name.
2686 DeclContext *DC =
2687 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2688 while (DC) {
2689 if (isa<CXXRecordDecl>(Val: DC)) {
2690 if (ExplicitTemplateArgs) {
2691 if (LookupTemplateName(
2692 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2693 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2694 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2695 return true;
2696 } else {
2697 LookupQualifiedName(R, LookupCtx: DC);
2698 }
2699
2700 if (!R.empty()) {
2701 // Don't give errors about ambiguities in this lookup.
2702 R.suppressDiagnostics();
2703
2704 // If there's a best viable function among the results, only mention
2705 // that one in the notes.
2706 OverloadCandidateSet Candidates(R.getNameLoc(),
2707 OverloadCandidateSet::CSK_Normal);
2708 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2709 OverloadCandidateSet::iterator Best;
2710 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2711 OR_Success) {
2712 R.clear();
2713 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2714 R.resolveKind();
2715 }
2716
2717 return DiagnoseDependentMemberLookup(R);
2718 }
2719
2720 R.clear();
2721 }
2722
2723 DC = DC->getLookupParent();
2724 }
2725
2726 // We didn't find anything, so try to correct for a typo.
2727 TypoCorrection Corrected;
2728 if (S && (Corrected =
2729 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2730 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2731 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2732 bool DroppedSpecifier =
2733 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2734 R.setLookupName(Corrected.getCorrection());
2735
2736 bool AcceptableWithRecovery = false;
2737 bool AcceptableWithoutRecovery = false;
2738 NamedDecl *ND = Corrected.getFoundDecl();
2739 if (ND) {
2740 if (Corrected.isOverloaded()) {
2741 OverloadCandidateSet OCS(R.getNameLoc(),
2742 OverloadCandidateSet::CSK_Normal);
2743 OverloadCandidateSet::iterator Best;
2744 for (NamedDecl *CD : Corrected) {
2745 if (FunctionTemplateDecl *FTD =
2746 dyn_cast<FunctionTemplateDecl>(Val: CD))
2747 AddTemplateOverloadCandidate(
2748 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2749 Args, CandidateSet&: OCS);
2750 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2751 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2752 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2753 Args, CandidateSet&: OCS);
2754 }
2755 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2756 case OR_Success:
2757 ND = Best->FoundDecl;
2758 Corrected.setCorrectionDecl(ND);
2759 break;
2760 default:
2761 // FIXME: Arbitrarily pick the first declaration for the note.
2762 Corrected.setCorrectionDecl(ND);
2763 break;
2764 }
2765 }
2766 R.addDecl(D: ND);
2767 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2768 CXXRecordDecl *Record =
2769 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2770 if (!Record)
2771 Record = cast<CXXRecordDecl>(
2772 Val: ND->getDeclContext()->getRedeclContext());
2773 R.setNamingClass(Record);
2774 }
2775
2776 auto *UnderlyingND = ND->getUnderlyingDecl();
2777 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2778 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2779 // FIXME: If we ended up with a typo for a type name or
2780 // Objective-C class name, we're in trouble because the parser
2781 // is in the wrong place to recover. Suggest the typo
2782 // correction, but don't make it a fix-it since we're not going
2783 // to recover well anyway.
2784 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2785 getAsTypeTemplateDecl(D: UnderlyingND) ||
2786 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2787 } else {
2788 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2789 // because we aren't able to recover.
2790 AcceptableWithoutRecovery = true;
2791 }
2792
2793 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2794 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2795 ? diag::note_implicit_param_decl
2796 : diag::note_previous_decl;
2797 if (SS.isEmpty())
2798 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2799 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2800 else
2801 diagnoseTypo(Correction: Corrected,
2802 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2803 << Name << computeDeclContext(SS, EnteringContext: false)
2804 << DroppedSpecifier << NameRange,
2805 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2806
2807 if (Corrected.WillReplaceSpecifier()) {
2808 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2809 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2810 SS.MakeTrivial(Context, Qualifier: NNS,
2811 R: NNS ? NameRange.getBegin() : SourceRange());
2812 }
2813
2814 // Tell the callee whether to try to recover.
2815 return !AcceptableWithRecovery;
2816 }
2817 }
2818 R.clear();
2819
2820 if (diagnoseFunctionLikeMacro(SemaRef, Name, TypoLoc: R.getNameLoc()))
2821 return true;
2822
2823 // Emit a special diagnostic for failed member lookups.
2824 // FIXME: computing the declaration context might fail here (?)
2825 if (!SS.isEmpty()) {
2826 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2827 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2828 return true;
2829 }
2830
2831 // Give up, we can't recover.
2832 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2833 return true;
2834}
2835
2836/// In Microsoft mode, if we are inside a template class whose parent class has
2837/// dependent base classes, and we can't resolve an unqualified identifier, then
2838/// assume the identifier is a member of a dependent base class. We can only
2839/// recover successfully in static methods, instance methods, and other contexts
2840/// where 'this' is available. This doesn't precisely match MSVC's
2841/// instantiation model, but it's close enough.
2842static Expr *
2843recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2844 DeclarationNameInfo &NameInfo,
2845 SourceLocation TemplateKWLoc,
2846 const TemplateArgumentListInfo *TemplateArgs) {
2847 // Only try to recover from lookup into dependent bases in static methods or
2848 // contexts where 'this' is available.
2849 QualType ThisType = S.getCurrentThisType();
2850 const CXXRecordDecl *RD = nullptr;
2851 if (!ThisType.isNull())
2852 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2853 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2854 RD = MD->getParent();
2855 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2856 return nullptr;
2857
2858 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2859 // is available, suggest inserting 'this->' as a fixit.
2860 SourceLocation Loc = NameInfo.getLoc();
2861 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2862 DB << NameInfo.getName() << RD;
2863
2864 if (!ThisType.isNull()) {
2865 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2866 return CXXDependentScopeMemberExpr::Create(
2867 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2868 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2869 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2870 }
2871
2872 // Synthesize a fake NNS that points to the derived class. This will
2873 // perform name lookup during template instantiation.
2874 CXXScopeSpec SS;
2875 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2876 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2877 return DependentScopeDeclRefExpr::Create(
2878 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2879 TemplateArgs);
2880}
2881
2882ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2883 SourceLocation TemplateKWLoc,
2884 UnqualifiedId &Id, bool HasTrailingLParen,
2885 bool IsAddressOfOperand,
2886 CorrectionCandidateCallback *CCC,
2887 bool IsInlineAsmIdentifier) {
2888 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2889 "cannot be direct & operand and have a trailing lparen");
2890 if (SS.isInvalid())
2891 return ExprError();
2892
2893 TemplateArgumentListInfo TemplateArgsBuffer;
2894
2895 // Decompose the UnqualifiedId into the following data.
2896 DeclarationNameInfo NameInfo;
2897 const TemplateArgumentListInfo *TemplateArgs;
2898 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2899
2900 DeclarationName Name = NameInfo.getName();
2901 IdentifierInfo *II = Name.getAsIdentifierInfo();
2902 SourceLocation NameLoc = NameInfo.getLoc();
2903
2904 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId &&
2905 Id.TemplateId->Template)
2906 if (TemplateName TN = Id.TemplateId->Template.get();
2907 TN.getAsPackIndexingTemplate())
2908 return CheckVarOrConceptTemplateTemplateId(NameInfo, Template: TN, TemplateArgs);
2909
2910 if (II && II->isEditorPlaceholder()) {
2911 // FIXME: When typed placeholders are supported we can create a typed
2912 // placeholder expression node.
2913 return ExprError();
2914 }
2915
2916 // This specially handles arguments of attributes appertains to a type of C
2917 // struct field such that the name lookup within a struct finds the member
2918 // name, which is not the case for other contexts in C.
2919 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2920 // See if this is reference to a field of struct.
2921 LookupResult R(*this, NameInfo, LookupMemberName);
2922 // LookupName handles a name lookup from within anonymous struct.
2923 if (LookupName(R, S)) {
2924 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2925 QualType type = VD->getType().getNonReferenceType();
2926 // This will eventually be translated into MemberExpr upon
2927 // the use of instantiated struct fields.
2928 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2929 }
2930 }
2931 }
2932
2933 // Perform the required lookup.
2934 LookupResult R(*this, NameInfo,
2935 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2936 ? LookupObjCImplicitSelfParam
2937 : LookupOrdinaryName);
2938 if (TemplateKWLoc.isValid() || TemplateArgs) {
2939 // Lookup the template name again to correctly establish the context in
2940 // which it was found. This is really unfortunate as we already did the
2941 // lookup to determine that it was a template name in the first place. If
2942 // this becomes a performance hit, we can work harder to preserve those
2943 // results until we get here but it's likely not worth it.
2944 AssumedTemplateKind AssumedTemplate;
2945 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2946 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2947 ATK: &AssumedTemplate))
2948 return ExprError();
2949
2950 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2951 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2952 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2953 } else {
2954 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2955 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2956 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2957
2958 // If the result might be in a dependent base class, this is a dependent
2959 // id-expression.
2960 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2961 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2962 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2963
2964 // If this reference is in an Objective-C method, then we need to do
2965 // some special Objective-C lookup, too.
2966 if (IvarLookupFollowUp) {
2967 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2968 if (E.isInvalid())
2969 return ExprError();
2970
2971 if (Expr *Ex = E.getAs<Expr>())
2972 return Ex;
2973 }
2974 }
2975
2976 if (R.isAmbiguous())
2977 return ExprError();
2978
2979 // This could be an implicitly declared function reference if the language
2980 // mode allows it as a feature.
2981 if (R.empty() && HasTrailingLParen && II &&
2982 getLangOpts().implicitFunctionsAllowed()) {
2983 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2984 if (D) R.addDecl(D);
2985 }
2986
2987 // Determine whether this name might be a candidate for
2988 // argument-dependent lookup.
2989 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2990
2991 if (R.empty() && !ADL) {
2992 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2993 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2994 TemplateKWLoc, TemplateArgs))
2995 return E;
2996 }
2997
2998 // Don't diagnose an empty lookup for inline assembly.
2999 if (IsInlineAsmIdentifier)
3000 return ExprError();
3001
3002 // If this name wasn't predeclared and if this is not a function
3003 // call, diagnose the problem.
3004 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3005 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3006 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3007 "Typo correction callback misconfigured");
3008 if (CCC) {
3009 // Make sure the callback knows what the typo being diagnosed is.
3010 CCC->setTypoName(II);
3011 if (SS.isValid())
3012 CCC->setTypoNNS(SS.getScopeRep());
3013 }
3014 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3015 // a template name, but we happen to have always already looked up the name
3016 // before we get here if it must be a template name.
3017 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
3018 Args: {}, LookupCtx: nullptr))
3019 return ExprError();
3020
3021 assert(!R.empty() &&
3022 "DiagnoseEmptyLookup returned false but added no results");
3023
3024 // If we found an Objective-C instance variable, let
3025 // LookupInObjCMethod build the appropriate expression to
3026 // reference the ivar.
3027 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3028 R.clear();
3029 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
3030 // In a hopelessly buggy code, Objective-C instance variable
3031 // lookup fails and no expression will be built to reference it.
3032 if (!E.isInvalid() && !E.get())
3033 return ExprError();
3034 return E;
3035 }
3036 }
3037
3038 // This is guaranteed from this point on.
3039 assert(!R.empty() || ADL);
3040
3041 // Check whether this might be a C++ implicit instance member access.
3042 // C++ [class.mfct.non-static]p3:
3043 // When an id-expression that is not part of a class member access
3044 // syntax and not used to form a pointer to member is used in the
3045 // body of a non-static member function of class X, if name lookup
3046 // resolves the name in the id-expression to a non-static non-type
3047 // member of some class C, the id-expression is transformed into a
3048 // class member access expression using (*this) as the
3049 // postfix-expression to the left of the . operator.
3050 //
3051 // But we don't actually need to do this for '&' operands if R
3052 // resolved to a function or overloaded function set, because the
3053 // expression is ill-formed if it actually works out to be a
3054 // non-static member function:
3055 //
3056 // C++ [expr.ref]p4:
3057 // Otherwise, if E1.E2 refers to a non-static member function. . .
3058 // [t]he expression can be used only as the left-hand operand of a
3059 // member function call.
3060 //
3061 // There are other safeguards against such uses, but it's important
3062 // to get this right here so that we don't end up making a
3063 // spuriously dependent expression if we're inside a dependent
3064 // instance method.
3065 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3066 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3067 S);
3068
3069 if (TemplateArgs || TemplateKWLoc.isValid()) {
3070
3071 // In C++1y, if this is a variable template id, then check it
3072 // in BuildTemplateIdExpr().
3073 // The single lookup result must be a variable template declaration.
3074 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3075 (Id.TemplateId->Kind == TNK_Var_template ||
3076 Id.TemplateId->Kind == TNK_Concept_template)) {
3077 assert(R.getAsSingle<TemplateDecl>() &&
3078 "There should only be one declaration found.");
3079 }
3080
3081 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3082 }
3083
3084 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3085}
3086
3087ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3088 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3089 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3090 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3091 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3092
3093 if (R.isAmbiguous())
3094 return ExprError();
3095
3096 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3097 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3098 NameInfo, /*TemplateArgs=*/nullptr);
3099
3100 if (R.empty()) {
3101 // Don't diagnose problems with invalid record decl, the secondary no_member
3102 // diagnostic during template instantiation is likely bogus, e.g. if a class
3103 // is invalid because it's derived from an invalid base class, then missing
3104 // members were likely supposed to be inherited.
3105 DeclContext *DC = computeDeclContext(SS);
3106 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3107 if (CD->isInvalidDecl() || CD->isBeingDefined())
3108 return ExprError();
3109 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3110 << NameInfo.getName() << DC << SS.getRange();
3111 return ExprError();
3112 }
3113
3114 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3115 QualType ET;
3116 TypeLocBuilder TLB;
3117 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3118 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3119 Qualifier: SS.getScopeRep(), TD: TagD,
3120 /*OwnsTag=*/false);
3121 auto TL = TLB.push<TagTypeLoc>(T: ET);
3122 TL.setElaboratedKeywordLoc(SourceLocation());
3123 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3124 TL.setNameLoc(NameInfo.getLoc());
3125 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3126 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3127 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3128 TLB.push<TypedefTypeLoc>(T: ET).set(
3129 /*ElaboratedKeywordLoc=*/SourceLocation(),
3130 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3131 } else {
3132 // FIXME: What else can appear here?
3133 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3134 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3135 assert(SS.isEmpty());
3136 }
3137
3138 // Diagnose a missing typename if this resolved unambiguously to a type in
3139 // a dependent context. If we can recover with a type, downgrade this to
3140 // a warning in Microsoft compatibility mode.
3141 unsigned DiagID = diag::err_typename_missing;
3142 if (RecoveryTSI && getLangOpts().MSVCCompat)
3143 DiagID = diag::ext_typename_missing;
3144 SourceLocation Loc = SS.getBeginLoc();
3145 auto D = Diag(Loc, DiagID);
3146 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3147
3148 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3149 // context.
3150 if (!RecoveryTSI)
3151 return ExprError();
3152
3153 // Only issue the fixit if we're prepared to recover.
3154 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3155
3156 // Recover by pretending this was an elaborated type.
3157 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3158
3159 return ExprEmpty();
3160 }
3161
3162 // If necessary, build an implicit class member access.
3163 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3164 return BuildPossibleImplicitMemberExpr(SS,
3165 /*TemplateKWLoc=*/SourceLocation(),
3166 R, /*TemplateArgs=*/nullptr,
3167 /*S=*/nullptr);
3168
3169 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3170}
3171
3172ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3173 NestedNameSpecifier Qualifier,
3174 NamedDecl *FoundDecl,
3175 NamedDecl *Member) {
3176 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3177 if (!RD)
3178 return From;
3179
3180 QualType DestRecordType;
3181 QualType DestType;
3182 QualType FromRecordType;
3183 QualType FromType = From->getType();
3184 bool PointerConversions = false;
3185 if (isa<FieldDecl>(Val: Member)) {
3186 DestRecordType = Context.getCanonicalTagType(TD: RD);
3187 auto FromPtrType = FromType->getAs<PointerType>();
3188 DestRecordType = Context.getAddrSpaceQualType(
3189 T: DestRecordType, AddressSpace: FromPtrType
3190 ? FromType->getPointeeType().getAddressSpace()
3191 : FromType.getAddressSpace());
3192
3193 if (FromPtrType) {
3194 DestType = Context.getPointerType(T: DestRecordType);
3195 FromRecordType = FromPtrType->getPointeeType();
3196 PointerConversions = true;
3197 } else {
3198 DestType = DestRecordType;
3199 FromRecordType = FromType;
3200 }
3201 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3202 if (!Method->isImplicitObjectMemberFunction())
3203 return From;
3204
3205 DestType = Method->getThisType().getNonReferenceType();
3206 DestRecordType = Method->getFunctionObjectParameterType();
3207
3208 if (FromType->getAs<PointerType>()) {
3209 FromRecordType = FromType->getPointeeType();
3210 PointerConversions = true;
3211 } else {
3212 FromRecordType = FromType;
3213 DestType = DestRecordType;
3214 }
3215
3216 LangAS FromAS = FromRecordType.getAddressSpace();
3217 LangAS DestAS = DestRecordType.getAddressSpace();
3218 if (FromAS != DestAS) {
3219 QualType FromRecordTypeWithoutAS =
3220 Context.removeAddrSpaceQualType(T: FromRecordType);
3221 QualType FromTypeWithDestAS =
3222 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3223 if (PointerConversions)
3224 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3225 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3226 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3227 .get();
3228 }
3229 } else {
3230 // No conversion necessary.
3231 return From;
3232 }
3233
3234 if (DestType->isDependentType() || FromType->isDependentType())
3235 return From;
3236
3237 // If the unqualified types are the same, no conversion is necessary.
3238 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3239 return From;
3240
3241 SourceRange FromRange = From->getSourceRange();
3242 SourceLocation FromLoc = FromRange.getBegin();
3243
3244 ExprValueKind VK = From->getValueKind();
3245
3246 // C++ [class.member.lookup]p8:
3247 // [...] Ambiguities can often be resolved by qualifying a name with its
3248 // class name.
3249 //
3250 // If the member was a qualified name and the qualified referred to a
3251 // specific base subobject type, we'll cast to that intermediate type
3252 // first and then to the object in which the member is declared. That allows
3253 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3254 //
3255 // class Base { public: int x; };
3256 // class Derived1 : public Base { };
3257 // class Derived2 : public Base { };
3258 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3259 //
3260 // void VeryDerived::f() {
3261 // x = 17; // error: ambiguous base subobjects
3262 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3263 // }
3264 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3265 QualType QType = QualType(Qualifier.getAsType(), 0);
3266 assert(QType->isRecordType() && "lookup done with non-record type");
3267
3268 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3269
3270 // In C++98, the qualifier type doesn't actually have to be a base
3271 // type of the object type, in which case we just ignore it.
3272 // Otherwise build the appropriate casts.
3273 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3274 CXXCastPath BasePath;
3275 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3276 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3277 return ExprError();
3278
3279 if (PointerConversions)
3280 QType = Context.getPointerType(T: QType);
3281 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3282 VK, BasePath: &BasePath).get();
3283
3284 FromType = QType;
3285 FromRecordType = QRecordType;
3286
3287 // If the qualifier type was the same as the destination type,
3288 // we're done.
3289 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3290 return From;
3291 }
3292 }
3293
3294 CXXCastPath BasePath;
3295 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3296 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3297 /*IgnoreAccess=*/true))
3298 return ExprError();
3299
3300 // Propagate qualifiers to base subobjects as per:
3301 // C++ [basic.type.qualifier]p1.2:
3302 // A volatile object is [...] a subobject of a volatile object.
3303 Qualifiers FromTypeQuals = FromType.getQualifiers();
3304 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3305 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3306
3307 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3308 BasePath: &BasePath);
3309}
3310
3311bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3312 const LookupResult &R,
3313 bool HasTrailingLParen) {
3314 // Only when used directly as the postfix-expression of a call.
3315 if (!HasTrailingLParen)
3316 return false;
3317
3318 // Never if a scope specifier was provided.
3319 if (SS.isNotEmpty())
3320 return false;
3321
3322 // Only in C++ or ObjC++.
3323 if (!getLangOpts().CPlusPlus)
3324 return false;
3325
3326 // Turn off ADL when we find certain kinds of declarations during
3327 // normal lookup:
3328 for (const NamedDecl *D : R) {
3329 // C++0x [basic.lookup.argdep]p3:
3330 // -- a declaration of a class member
3331 // Since using decls preserve this property, we check this on the
3332 // original decl.
3333 if (D->isCXXClassMember())
3334 return false;
3335
3336 // C++0x [basic.lookup.argdep]p3:
3337 // -- a block-scope function declaration that is not a
3338 // using-declaration
3339 // NOTE: we also trigger this for function templates (in fact, we
3340 // don't check the decl type at all, since all other decl types
3341 // turn off ADL anyway).
3342 if (isa<UsingShadowDecl>(Val: D))
3343 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3344 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3345 return false;
3346
3347 // C++0x [basic.lookup.argdep]p3:
3348 // -- a declaration that is neither a function or a function
3349 // template
3350 // And also for builtin functions.
3351 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3352 // But also builtin functions.
3353 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3354 return false;
3355 } else if (!isa<FunctionTemplateDecl>(Val: D))
3356 return false;
3357 }
3358
3359 return true;
3360}
3361
3362
3363/// Diagnoses obvious problems with the use of the given declaration
3364/// as an expression. This is only actually called for lookups that
3365/// were not overloaded, and it doesn't promise that the declaration
3366/// will in fact be used.
3367static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3368 bool AcceptInvalid) {
3369 if (D->isInvalidDecl() && !AcceptInvalid)
3370 return true;
3371
3372 if (isa<TypedefNameDecl>(Val: D)) {
3373 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3374 return true;
3375 }
3376
3377 if (isa<ObjCInterfaceDecl>(Val: D)) {
3378 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3379 return true;
3380 }
3381
3382 if (isa<NamespaceDecl>(Val: D)) {
3383 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3384 return true;
3385 }
3386
3387 return false;
3388}
3389
3390// Certain multiversion types should be treated as overloaded even when there is
3391// only one result.
3392static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3393 assert(R.isSingleResult() && "Expected only a single result");
3394 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3395 return FD &&
3396 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3397}
3398
3399ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3400 LookupResult &R, bool NeedsADL,
3401 bool AcceptInvalidDecl) {
3402 // If this is a single, fully-resolved result and we don't need ADL,
3403 // just build an ordinary singleton decl ref.
3404 if (!NeedsADL && R.isSingleResult() &&
3405 !R.getAsSingle<FunctionTemplateDecl>() &&
3406 !ShouldLookupResultBeMultiVersionOverload(R))
3407 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3408 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3409 AcceptInvalidDecl);
3410
3411 // We only need to check the declaration if there's exactly one
3412 // result, because in the overloaded case the results can only be
3413 // functions and function templates.
3414 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3415 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3416 AcceptInvalid: AcceptInvalidDecl))
3417 return ExprError();
3418
3419 // Otherwise, just build an unresolved lookup expression. Suppress
3420 // any lookup-related diagnostics; we'll hash these out later, when
3421 // we've picked a target.
3422 R.suppressDiagnostics();
3423
3424 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3425 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3426 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3427 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3428
3429 return ULE;
3430}
3431
3432ExprResult Sema::BuildDeclarationNameExpr(
3433 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3434 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3435 bool AcceptInvalidDecl) {
3436 assert(D && "Cannot refer to a NULL declaration");
3437 assert(!isa<FunctionTemplateDecl>(D) &&
3438 "Cannot refer unambiguously to a function template");
3439
3440 SourceLocation Loc = NameInfo.getLoc();
3441 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3442 // Recovery from invalid cases (e.g. D is an invalid Decl).
3443 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3444 // diagnostics, as invalid decls use int as a fallback type.
3445 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3446 }
3447
3448 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3449 // Specifically diagnose references to class templates that are missing
3450 // a template argument list.
3451 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3452 return ExprError();
3453 }
3454
3455 // Make sure that we're referring to a value.
3456 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3457 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3458 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3459 return ExprError();
3460 }
3461
3462 // Check whether this declaration can be used. Note that we suppress
3463 // this check when we're going to perform argument-dependent lookup
3464 // on this function name, because this might not be the function
3465 // that overload resolution actually selects.
3466 if (DiagnoseUseOfDecl(D, Locs: Loc))
3467 return ExprError();
3468
3469 auto *VD = cast<ValueDecl>(Val: D);
3470
3471 // Only create DeclRefExpr's for valid Decl's.
3472 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3473 return ExprError();
3474
3475 // Handle members of anonymous structs and unions. If we got here,
3476 // and the reference is to a class member indirect field, then this
3477 // must be the subject of a pointer-to-member expression.
3478 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3479 IndirectField && !IndirectField->isCXXClassMember())
3480 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3481 indirectField: IndirectField);
3482
3483 QualType type = VD->getType();
3484 if (type.isNull())
3485 return ExprError();
3486 ExprValueKind valueKind = VK_PRValue;
3487
3488 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3489 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3490 // is expanded by some outer '...' in the context of the use.
3491 type = type.getNonPackExpansionType();
3492
3493 switch (D->getKind()) {
3494 // Ignore all the non-ValueDecl kinds.
3495#define ABSTRACT_DECL(kind)
3496#define VALUE(type, base)
3497#define DECL(type, base) case Decl::type:
3498#include "clang/AST/DeclNodes.inc"
3499 llvm_unreachable("invalid value decl kind");
3500
3501 // These shouldn't make it here.
3502 case Decl::ObjCAtDefsField:
3503 llvm_unreachable("forming non-member reference to ivar?");
3504
3505 // Enum constants are always r-values and never references.
3506 // Unresolved using declarations are dependent.
3507 case Decl::EnumConstant:
3508 case Decl::UnresolvedUsingValue:
3509 case Decl::OMPDeclareReduction:
3510 case Decl::OMPDeclareMapper:
3511 valueKind = VK_PRValue;
3512 break;
3513
3514 // Fields and indirect fields that got here must be for
3515 // pointer-to-member expressions; we just call them l-values for
3516 // internal consistency, because this subexpression doesn't really
3517 // exist in the high-level semantics.
3518 case Decl::Field:
3519 case Decl::IndirectField:
3520 case Decl::ObjCIvar:
3521 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3522 "building reference to field in C?");
3523
3524 // These can't have reference type in well-formed programs, but
3525 // for internal consistency we do this anyway.
3526 type = type.getNonReferenceType();
3527 valueKind = VK_LValue;
3528 break;
3529
3530 // Non-type template parameters are either l-values or r-values
3531 // depending on the type.
3532 case Decl::NonTypeTemplateParm: {
3533 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3534 type = reftype->getPointeeType();
3535 valueKind = VK_LValue; // even if the parameter is an r-value reference
3536 break;
3537 }
3538
3539 // [expr.prim.id.unqual]p2:
3540 // If the entity is a template parameter object for a template
3541 // parameter of type T, the type of the expression is const T.
3542 // [...] The expression is an lvalue if the entity is a [...] template
3543 // parameter object.
3544 if (type->isRecordType()) {
3545 type = type.getUnqualifiedType().withConst();
3546 valueKind = VK_LValue;
3547 break;
3548 }
3549
3550 // For non-references, we need to strip qualifiers just in case
3551 // the template parameter was declared as 'const int' or whatever.
3552 valueKind = VK_PRValue;
3553 type = type.getUnqualifiedType();
3554 break;
3555 }
3556
3557 case Decl::Var:
3558 case Decl::VarTemplateSpecialization:
3559 case Decl::VarTemplatePartialSpecialization:
3560 case Decl::Decomposition:
3561 case Decl::Binding:
3562 case Decl::OMPCapturedExpr:
3563 // In C, "extern void blah;" is valid and is an r-value.
3564 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3565 type->isVoidType()) {
3566 valueKind = VK_PRValue;
3567 break;
3568 }
3569 [[fallthrough]];
3570
3571 case Decl::ImplicitParam:
3572 case Decl::ParmVar: {
3573 // These are always l-values.
3574 valueKind = VK_LValue;
3575 type = type.getNonReferenceType();
3576
3577 // FIXME: Does the addition of const really only apply in
3578 // potentially-evaluated contexts? Since the variable isn't actually
3579 // captured in an unevaluated context, it seems that the answer is no.
3580 if (!isUnevaluatedContext()) {
3581 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3582 if (!CapturedType.isNull())
3583 type = CapturedType;
3584 }
3585 break;
3586 }
3587
3588 case Decl::Function: {
3589 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3590 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3591 type = Context.BuiltinFnTy;
3592 valueKind = VK_PRValue;
3593 break;
3594 }
3595 }
3596
3597 const FunctionType *fty = type->castAs<FunctionType>();
3598
3599 // If we're referring to a function with an __unknown_anytype
3600 // result type, make the entire expression __unknown_anytype.
3601 if (fty->getReturnType() == Context.UnknownAnyTy) {
3602 type = Context.UnknownAnyTy;
3603 valueKind = VK_PRValue;
3604 break;
3605 }
3606
3607 // Functions are l-values in C++.
3608 if (getLangOpts().CPlusPlus) {
3609 valueKind = VK_LValue;
3610 break;
3611 }
3612
3613 // C99 DR 316 says that, if a function type comes from a
3614 // function definition (without a prototype), that type is only
3615 // used for checking compatibility. Therefore, when referencing
3616 // the function, we pretend that we don't have the full function
3617 // type.
3618 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3619 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3620 Info: fty->getExtInfo());
3621
3622 // Functions are r-values in C.
3623 valueKind = VK_PRValue;
3624 break;
3625 }
3626
3627 case Decl::CXXDeductionGuide:
3628 llvm_unreachable("building reference to deduction guide");
3629
3630 case Decl::MSProperty:
3631 case Decl::MSGuid:
3632 case Decl::TemplateParamObject:
3633 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3634 // capture in OpenMP, or duplicated between host and device?
3635 valueKind = VK_LValue;
3636 break;
3637
3638 case Decl::UnnamedGlobalConstant:
3639 valueKind = VK_LValue;
3640 break;
3641
3642 case Decl::CXXMethod:
3643 // If we're referring to a method with an __unknown_anytype
3644 // result type, make the entire expression __unknown_anytype.
3645 // This should only be possible with a type written directly.
3646 if (const FunctionProtoType *proto =
3647 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3648 if (proto->getReturnType() == Context.UnknownAnyTy) {
3649 type = Context.UnknownAnyTy;
3650 valueKind = VK_PRValue;
3651 break;
3652 }
3653
3654 // C++ methods are l-values if static, r-values if non-static.
3655 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3656 valueKind = VK_LValue;
3657 break;
3658 }
3659 [[fallthrough]];
3660
3661 case Decl::CXXConversion:
3662 case Decl::CXXDestructor:
3663 case Decl::CXXConstructor:
3664 valueKind = VK_PRValue;
3665 break;
3666 }
3667
3668 auto *E =
3669 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3670 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3671 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3672 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3673 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3674 // diagnostics).
3675 if (VD->isInvalidDecl() && E)
3676 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3677 return E;
3678}
3679
3680static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3681 SmallString<32> &Target) {
3682 Target.resize(N: CharByteWidth * (Source.size() + 1));
3683 char *ResultPtr = &Target[0];
3684 const llvm::UTF8 *ErrorPtr;
3685 bool success =
3686 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3687 (void)success;
3688 assert(success);
3689 Target.resize(N: ResultPtr - &Target[0]);
3690}
3691
3692ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3693 PredefinedIdentKind IK) {
3694 Decl *currentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
3695 if (!currentDecl) {
3696 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3697 currentDecl = Context.getTranslationUnitDecl();
3698 }
3699
3700 QualType ResTy;
3701 StringLiteral *SL = nullptr;
3702 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3703 ResTy = Context.DependentTy;
3704 else {
3705 // Pre-defined identifiers are of type char[x], where x is the length of
3706 // the string.
3707 bool ForceElaboratedPrinting =
3708 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3709 auto Str =
3710 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3711 unsigned Length = Str.length();
3712
3713 llvm::APInt LengthI(32, Length + 1);
3714 if (IK == PredefinedIdentKind::LFunction ||
3715 IK == PredefinedIdentKind::LFuncSig) {
3716 ResTy =
3717 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3718 SmallString<32> RawChars;
3719 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3720 Source: Str, Target&: RawChars);
3721 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3722 ASM: ArraySizeModifier::Normal,
3723 /*IndexTypeQuals*/ 0);
3724 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3725 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3726 } else {
3727 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3728 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3729 ASM: ArraySizeModifier::Normal,
3730 /*IndexTypeQuals*/ 0);
3731 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3732 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3733 }
3734 }
3735
3736 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3737 SL);
3738}
3739
3740ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3741 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3742}
3743
3744ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3745 SmallString<16> CharBuffer;
3746 bool Invalid = false;
3747 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3748 if (Invalid)
3749 return ExprError();
3750
3751 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3752 PP, Tok.getKind());
3753 if (Literal.hadError())
3754 return ExprError();
3755
3756 QualType Ty;
3757 if (Literal.isWide())
3758 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3759 else if (Literal.isUTF8() && getLangOpts().C23)
3760 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3761 else if (Literal.isUTF8() && getLangOpts().Char8)
3762 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3763 else if (Literal.isUTF16())
3764 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3765 else if (Literal.isUTF32())
3766 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3767 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3768 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3769 else
3770 Ty = Context.CharTy; // 'x' -> char in C++;
3771 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3772
3773 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3774 if (Literal.isWide())
3775 Kind = CharacterLiteralKind::Wide;
3776 else if (Literal.isUTF16())
3777 Kind = CharacterLiteralKind::UTF16;
3778 else if (Literal.isUTF32())
3779 Kind = CharacterLiteralKind::UTF32;
3780 else if (Literal.isUTF8())
3781 Kind = CharacterLiteralKind::UTF8;
3782
3783 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3784 Tok.getLocation());
3785
3786 if (Literal.getUDSuffix().empty())
3787 return Lit;
3788
3789 // We're building a user-defined literal.
3790 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3791 SourceLocation UDSuffixLoc =
3792 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3793
3794 // Make sure we're allowed user-defined literals here.
3795 if (!UDLScope)
3796 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3797
3798 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3799 // operator "" X (ch)
3800 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3801 Args: Lit, LitEndLoc: Tok.getLocation());
3802}
3803
3804ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3805 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3806 return IntegerLiteral::Create(C: Context,
3807 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3808 type: Context.IntTy, l: Loc);
3809}
3810
3811ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3812 ExprResult Inner;
3813 if (getLangOpts().CPlusPlus) {
3814 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3815 } else {
3816 // C doesn't actually have a way to represent literal values of type
3817 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3818 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3819 Inner =
3820 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3821 }
3822 return Inner;
3823}
3824
3825static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3826 QualType Ty, SourceLocation Loc) {
3827 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3828
3829 using llvm::APFloat;
3830 APFloat Val(Format);
3831
3832 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3833 if (RM == llvm::RoundingMode::Dynamic)
3834 RM = llvm::RoundingMode::NearestTiesToEven;
3835 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3836
3837 // Overflow is always an error, but underflow is only an error if
3838 // we underflowed to zero (APFloat reports denormals as underflow).
3839 if ((result & APFloat::opOverflow) ||
3840 ((result & APFloat::opUnderflow) && Val.isZero())) {
3841 unsigned diagnostic;
3842 SmallString<20> buffer;
3843 if (result & APFloat::opOverflow) {
3844 diagnostic = diag::warn_float_overflow;
3845 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3846 } else {
3847 diagnostic = diag::warn_float_underflow;
3848 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3849 }
3850
3851 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3852 }
3853
3854 bool isExact = (result == APFloat::opOK);
3855 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3856}
3857
3858bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3859 assert(E && "Invalid expression");
3860
3861 if (E->isValueDependent())
3862 return false;
3863
3864 QualType QT = E->getType();
3865 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3866 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3867 return true;
3868 }
3869
3870 llvm::APSInt ValueAPS;
3871 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3872
3873 if (R.isInvalid())
3874 return true;
3875
3876 // GCC allows the value of unroll count to be 0.
3877 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3878 // "The values of 0 and 1 block any unrolling of the loop."
3879 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3880 // '#pragma unroll' cases.
3881 bool ValueIsPositive =
3882 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3883 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3884 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3885 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3886 return true;
3887 }
3888
3889 return false;
3890}
3891
3892ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3893 // Fast path for a single digit (which is quite common). A single digit
3894 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3895 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3896 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3897 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3898 }
3899
3900 SmallString<128> SpellingBuffer;
3901 // NumericLiteralParser wants to overread by one character. Add padding to
3902 // the buffer in case the token is copied to the buffer. If getSpelling()
3903 // returns a StringRef to the memory buffer, it should have a null char at
3904 // the EOF, so it is also safe.
3905 SpellingBuffer.resize(N: Tok.getLength() + 1);
3906
3907 // Get the spelling of the token, which eliminates trigraphs, etc.
3908 bool Invalid = false;
3909 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3910 if (Invalid)
3911 return ExprError();
3912
3913 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3914 PP.getSourceManager(), PP.getLangOpts(),
3915 PP.getTargetInfo(), PP.getDiagnostics());
3916 if (Literal.hadError)
3917 return ExprError();
3918
3919 if (Literal.hasUDSuffix()) {
3920 // We're building a user-defined literal.
3921 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3922 SourceLocation UDSuffixLoc =
3923 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3924
3925 // Make sure we're allowed user-defined literals here.
3926 if (!UDLScope)
3927 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3928
3929 QualType CookedTy;
3930 if (Literal.isFloatingLiteral()) {
3931 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3932 // long double, the literal is treated as a call of the form
3933 // operator "" X (f L)
3934 CookedTy = Context.LongDoubleTy;
3935 } else {
3936 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3937 // unsigned long long, the literal is treated as a call of the form
3938 // operator "" X (n ULL)
3939 CookedTy = Context.UnsignedLongLongTy;
3940 }
3941
3942 DeclarationName OpName =
3943 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3944 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3945 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3946
3947 SourceLocation TokLoc = Tok.getLocation();
3948
3949 // Perform literal operator lookup to determine if we're building a raw
3950 // literal or a cooked one.
3951 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3952 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3953 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3954 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3955 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3956 case LOLR_ErrorNoDiagnostic:
3957 // Lookup failure for imaginary constants isn't fatal, there's still the
3958 // GNU extension producing _Complex types.
3959 break;
3960 case LOLR_Error:
3961 return ExprError();
3962 case LOLR_Cooked: {
3963 Expr *Lit;
3964 if (Literal.isFloatingLiteral()) {
3965 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3966 } else {
3967 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3968 if (Literal.GetIntegerValue(Val&: ResultVal))
3969 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3970 << /* Unsigned */ 1;
3971 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3972 l: Tok.getLocation());
3973 }
3974 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3975 }
3976
3977 case LOLR_Raw: {
3978 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3979 // literal is treated as a call of the form
3980 // operator "" X ("n")
3981 unsigned Length = Literal.getUDSuffixOffset();
3982 QualType StrTy = Context.getConstantArrayType(
3983 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3984 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3985 Expr *Lit =
3986 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3987 Kind: StringLiteralKind::Ordinary,
3988 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3989 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3990 }
3991
3992 case LOLR_Template: {
3993 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3994 // template), L is treated as a call fo the form
3995 // operator "" X <'c1', 'c2', ... 'ck'>()
3996 // where n is the source character sequence c1 c2 ... ck.
3997 TemplateArgumentListInfo ExplicitArgs;
3998 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3999 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4000 llvm::APSInt Value(CharBits, CharIsUnsigned);
4001 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4002 Value = TokSpelling[I];
4003 TemplateArgument Arg(Context, Value, Context.CharTy);
4004 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
4005 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
4006 }
4007 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
4008 }
4009 case LOLR_StringTemplatePack:
4010 llvm_unreachable("unexpected literal operator lookup result");
4011 }
4012 }
4013
4014 Expr *Res;
4015
4016 if (Literal.isFixedPointLiteral()) {
4017 QualType Ty;
4018
4019 if (Literal.isAccum) {
4020 if (Literal.isHalf) {
4021 Ty = Context.ShortAccumTy;
4022 } else if (Literal.isLong) {
4023 Ty = Context.LongAccumTy;
4024 } else {
4025 Ty = Context.AccumTy;
4026 }
4027 } else if (Literal.isFract) {
4028 if (Literal.isHalf) {
4029 Ty = Context.ShortFractTy;
4030 } else if (Literal.isLong) {
4031 Ty = Context.LongFractTy;
4032 } else {
4033 Ty = Context.FractTy;
4034 }
4035 }
4036
4037 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
4038
4039 bool isSigned = !Literal.isUnsigned;
4040 unsigned scale = Context.getFixedPointScale(Ty);
4041 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4042
4043 llvm::APInt Val(bit_width, 0, isSigned);
4044 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
4045 bool ValIsZero = Val.isZero() && !Overflowed;
4046
4047 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4048 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4049 // Clause 6.4.4 - The value of a constant shall be in the range of
4050 // representable values for its type, with exception for constants of a
4051 // fract type with a value of exactly 1; such a constant shall denote
4052 // the maximal value for the type.
4053 --Val;
4054 else if (Val.ugt(RHS: MaxVal) || Overflowed)
4055 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
4056
4057 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4058 l: Tok.getLocation(), Scale: scale);
4059 } else if (Literal.isFloatingLiteral()) {
4060 QualType Ty;
4061 if (Literal.isHalf){
4062 if (getLangOpts().HLSL ||
4063 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4064 Ty = Context.HalfTy;
4065 else {
4066 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4067 return ExprError();
4068 }
4069 } else if (Literal.isFloat)
4070 Ty = Context.FloatTy;
4071 else if (Literal.isLong)
4072 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4073 else if (Literal.isFloat16)
4074 Ty = Context.Float16Ty;
4075 else if (Literal.isFloat128)
4076 Ty = Context.Float128Ty;
4077 else if (getLangOpts().HLSL)
4078 Ty = Context.FloatTy;
4079 else
4080 Ty = Context.DoubleTy;
4081
4082 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4083
4084 if (Ty == Context.DoubleTy) {
4085 if (getLangOpts().SinglePrecisionConstants) {
4086 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4087 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4088 }
4089 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4090 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4091 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4092 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4093 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4094 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4095 }
4096 }
4097 } else if (!Literal.isIntegerLiteral()) {
4098 return ExprError();
4099 } else {
4100 QualType Ty;
4101
4102 // 'z/uz' literals are a C++23 feature.
4103 if (Literal.isSizeT) {
4104 if (getLangOpts().CPlusPlus)
4105 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::size_t_suffix);
4106 else
4107 Diag(Loc: Tok.getLocation(), DiagID: diag::err_cxx23_size_t_suffix);
4108 }
4109
4110 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4111 // but we do not currently support the suffix in C++ mode because it's not
4112 // entirely clear whether WG21 will prefer this suffix to return a library
4113 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4114 // literals are a C++ extension.
4115 if (Literal.isBitInt)
4116 PP.Diag(Loc: Tok.getLocation(),
4117 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4118 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4119 : diag::ext_c23_bitint_suffix);
4120
4121 // Get the value in the widest-possible width. What is "widest" depends on
4122 // whether the literal is a bit-precise integer or not. For a bit-precise
4123 // integer type, try to scan the source to determine how many bits are
4124 // needed to represent the value. This may seem a bit expensive, but trying
4125 // to get the integer value from an overly-wide APInt is *extremely*
4126 // expensive, so the naive approach of assuming
4127 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4128 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4129 if (Literal.isBitInt)
4130 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4131 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4132 if (Literal.MicrosoftInteger) {
4133 if (Literal.MicrosoftInteger == 128 &&
4134 !Context.getTargetInfo().hasInt128Type())
4135 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4136 << Literal.isUnsigned;
4137 BitsNeeded = std::max<unsigned>(a: BitsNeeded, b: Literal.MicrosoftInteger);
4138 }
4139
4140 llvm::APInt ResultVal(BitsNeeded, 0);
4141
4142 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4143 // If this value didn't fit into uintmax_t, error and force to ull.
4144 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4145 << /* Unsigned */ 1;
4146 Ty = Context.UnsignedLongLongTy;
4147 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4148 "long long is not intmax_t?");
4149 } else {
4150 // If this value fits into a ULL, try to figure out what else it fits into
4151 // according to the rules of C99 6.4.4.1p5.
4152
4153 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4154 // be an unsigned int.
4155 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4156
4157 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4158 // suffix for portability of code with C++, but both `l` and `ll` are
4159 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4160 // same.
4161 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4162 Literal.isLong = true;
4163 Literal.isLongLong = false;
4164 }
4165
4166 // Check from smallest to largest, picking the smallest type we can.
4167 unsigned Width = 0;
4168
4169 // Microsoft specific integer suffixes are explicitly sized.
4170 if (Literal.MicrosoftInteger) {
4171 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4172 Width = 8;
4173 Ty = Context.CharTy;
4174 } else {
4175 Width = Literal.MicrosoftInteger;
4176 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4177 /*Signed=*/!Literal.isUnsigned);
4178 }
4179 // To maintain consistency with MSVC, we chose to truncate directly
4180 // without issuing any warnings.
4181 ResultVal = ResultVal.zextOrTrunc(width: Width);
4182 }
4183
4184 // Bit-precise integer literals are automagically-sized based on the
4185 // width required by the literal.
4186 if (Literal.isBitInt) {
4187 // The signed version has one more bit for the sign value. There are no
4188 // zero-width bit-precise integers, even if the literal value is 0.
4189 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4190 (Literal.isUnsigned ? 0u : 1u);
4191
4192 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4193 // and reset the type to the largest supported width.
4194 unsigned int MaxBitIntWidth =
4195 Context.getTargetInfo().getMaxBitIntWidth();
4196 if (Width > MaxBitIntWidth) {
4197 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4198 << Literal.isUnsigned;
4199 Width = MaxBitIntWidth;
4200 }
4201
4202 // Reset the result value to the smaller APInt and select the correct
4203 // type to be used. Note, we zext even for signed values because the
4204 // literal itself is always an unsigned value (a preceeding - is a
4205 // unary operator, not part of the literal).
4206 ResultVal = ResultVal.zextOrTrunc(width: Width);
4207 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4208 }
4209
4210 // Check C++23 size_t literals.
4211 if (Literal.isSizeT) {
4212 assert(!Literal.MicrosoftInteger &&
4213 "size_t literals can't be Microsoft literals");
4214 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4215 T: Context.getTargetInfo().getSizeType());
4216
4217 // Does it fit in size_t?
4218 if (ResultVal.isIntN(N: SizeTSize)) {
4219 // Does it fit in ssize_t?
4220 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4221 Ty = Context.getSignedSizeType();
4222 else if (AllowUnsigned)
4223 Ty = Context.getSizeType();
4224 Width = SizeTSize;
4225 }
4226 }
4227
4228 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4229 !Literal.isSizeT) {
4230 // Are int/unsigned possibilities?
4231 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4232
4233 // Does it fit in a unsigned int?
4234 if (ResultVal.isIntN(N: IntSize)) {
4235 // Does it fit in a signed int?
4236 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4237 Ty = Context.IntTy;
4238 else if (AllowUnsigned)
4239 Ty = Context.UnsignedIntTy;
4240 Width = IntSize;
4241 }
4242 }
4243
4244 // Are long/unsigned long possibilities?
4245 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4246 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4247
4248 // Does it fit in a unsigned long?
4249 if (ResultVal.isIntN(N: LongSize)) {
4250 // Does it fit in a signed long?
4251 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4252 Ty = Context.LongTy;
4253 else if (AllowUnsigned)
4254 Ty = Context.UnsignedLongTy;
4255 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4256 // is compatible.
4257 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4258 const unsigned LongLongSize =
4259 Context.getTargetInfo().getLongLongWidth();
4260 Diag(Loc: Tok.getLocation(),
4261 DiagID: getLangOpts().CPlusPlus
4262 ? Literal.isLong
4263 ? diag::warn_old_implicitly_unsigned_long_cxx
4264 : /*C++98 UB*/ diag::
4265 ext_old_implicitly_unsigned_long_cxx
4266 : diag::warn_old_implicitly_unsigned_long)
4267 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4268 : /*will be ill-formed*/ 1);
4269 Ty = Context.UnsignedLongTy;
4270 }
4271 Width = LongSize;
4272 }
4273 }
4274
4275 // Check long long if needed.
4276 if (Ty.isNull() && !Literal.isSizeT) {
4277 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4278
4279 // Does it fit in a unsigned long long?
4280 if (ResultVal.isIntN(N: LongLongSize)) {
4281 // Does it fit in a signed long long?
4282 // To be compatible with MSVC, hex integer literals ending with the
4283 // LL or i64 suffix are always signed in Microsoft mode.
4284 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4285 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4286 Ty = Context.LongLongTy;
4287 else if (AllowUnsigned)
4288 Ty = Context.UnsignedLongLongTy;
4289 Width = LongLongSize;
4290
4291 // 'long long' is a C99 or C++11 feature, whether the literal
4292 // explicitly specified 'long long' or we needed the extra width.
4293 if (getLangOpts().CPlusPlus)
4294 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4295 ? diag::warn_cxx98_compat_longlong
4296 : diag::ext_cxx11_longlong);
4297 else if (!getLangOpts().C99)
4298 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4299 }
4300 }
4301
4302 // If we still couldn't decide a type, we either have 'size_t' literal
4303 // that is out of range, or a decimal literal that does not fit in a
4304 // signed long long and has no U suffix.
4305 if (Ty.isNull()) {
4306 if (Literal.isSizeT)
4307 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4308 << Literal.isUnsigned;
4309 else
4310 Diag(Loc: Tok.getLocation(),
4311 DiagID: diag::ext_integer_literal_too_large_for_signed);
4312 Ty = Context.UnsignedLongLongTy;
4313 Width = Context.getTargetInfo().getLongLongWidth();
4314 }
4315
4316 if (ResultVal.getBitWidth() != Width)
4317 ResultVal = ResultVal.trunc(width: Width);
4318 }
4319 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4320 }
4321
4322 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4323 if (Literal.isImaginary) {
4324 Res = new (Context) ImaginaryLiteral(Res,
4325 Context.getComplexType(T: Res->getType()));
4326
4327 // In C++, this is a GNU extension. In C, it's a C2y extension.
4328 if (getLangOpts().CPlusPlus)
4329 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_gnu_imaginary_constant);
4330 else
4331 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::imaginary_constant);
4332 }
4333 return Res;
4334}
4335
4336ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4337 assert(E && "ActOnParenExpr() missing expr");
4338 QualType ExprTy = E->getType();
4339 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4340 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4341 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4342 return new (Context) ParenExpr(L, R, E);
4343}
4344
4345static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4346 SourceLocation Loc,
4347 SourceRange ArgRange) {
4348 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4349 // scalar or vector data type argument..."
4350 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4351 // type (C99 6.2.5p18) or void.
4352 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4353 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4354 << T << ArgRange;
4355 return true;
4356 }
4357
4358 assert((T->isVoidType() || !T->isIncompleteType()) &&
4359 "Scalar types should always be complete");
4360 return false;
4361}
4362
4363static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4364 SourceLocation Loc,
4365 SourceRange ArgRange) {
4366 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4367 if (!T->isVectorType() && !T->isSizelessVectorType())
4368 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4369 << ""
4370 << "__builtin_vectorelements" << T << ArgRange;
4371
4372 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4373 if (T->isSVESizelessBuiltinType()) {
4374 llvm::StringMap<bool> CallerFeatureMap;
4375 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4376 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4377 }
4378 }
4379
4380 return false;
4381}
4382
4383static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4384 SourceLocation Loc,
4385 SourceRange ArgRange) {
4386 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4387 return true;
4388
4389 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4390 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4391 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4392 return true;
4393 }
4394
4395 return false;
4396}
4397
4398static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4399 SourceLocation Loc,
4400 SourceRange ArgRange,
4401 UnaryExprOrTypeTrait TraitKind) {
4402 // Invalid types must be hard errors for SFINAE in C++.
4403 if (S.LangOpts.CPlusPlus)
4404 return true;
4405
4406 // C99 6.5.3.4p1:
4407 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4408 TraitKind == UETT_PreferredAlignOf) {
4409
4410 // sizeof(function)/alignof(function) is allowed as an extension.
4411 if (T->isFunctionType()) {
4412 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4413 << getTraitSpelling(T: TraitKind) << ArgRange;
4414 return false;
4415 }
4416
4417 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4418 // this is an error (OpenCL v1.1 s6.3.k)
4419 if (T->isVoidType()) {
4420 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4421 : diag::ext_sizeof_alignof_void_type;
4422 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4423 return false;
4424 }
4425 }
4426 return true;
4427}
4428
4429static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4430 SourceLocation Loc,
4431 SourceRange ArgRange,
4432 UnaryExprOrTypeTrait TraitKind) {
4433 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4434 // runtime doesn't allow it.
4435 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4436 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4437 << T << (TraitKind == UETT_SizeOf)
4438 << ArgRange;
4439 return true;
4440 }
4441
4442 return false;
4443}
4444
4445/// Check whether E is a pointer from a decayed array type (the decayed
4446/// pointer type is equal to T) and emit a warning if it is.
4447static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4448 const Expr *E) {
4449 // Don't warn if the operation changed the type.
4450 if (T != E->getType())
4451 return;
4452
4453 // Now look for array decays.
4454 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4455 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4456 return;
4457
4458 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4459 << ICE->getType()
4460 << ICE->getSubExpr()->getType();
4461}
4462
4463bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4464 UnaryExprOrTypeTrait ExprKind) {
4465 QualType ExprTy = E->getType();
4466 assert(!ExprTy->isReferenceType());
4467
4468 bool IsUnevaluatedOperand =
4469 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4470 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4471 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4472 if (IsUnevaluatedOperand) {
4473 ExprResult Result = CheckUnevaluatedOperand(E);
4474 if (Result.isInvalid())
4475 return true;
4476 E = Result.get();
4477 }
4478
4479 // The operand for sizeof and alignof is in an unevaluated expression context,
4480 // so side effects could result in unintended consequences.
4481 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4482 // used to build SFINAE gadgets.
4483 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4484 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4485 !E->isInstantiationDependent() &&
4486 !E->getType()->isVariableArrayType() &&
4487 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4488 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4489
4490 if (ExprKind == UETT_VecStep)
4491 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4492 ArgRange: E->getSourceRange());
4493
4494 if (ExprKind == UETT_VectorElements)
4495 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4496 ArgRange: E->getSourceRange());
4497
4498 // Explicitly list some types as extensions.
4499 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4500 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4501 return false;
4502
4503 // WebAssembly tables are always illegal operands to unary expressions and
4504 // type traits.
4505 if (Context.getTargetInfo().getTriple().isWasm() &&
4506 E->getType()->isWebAssemblyTableType()) {
4507 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4508 << getTraitSpelling(T: ExprKind);
4509 return true;
4510 }
4511
4512 // 'alignof' applied to an expression only requires the base element type of
4513 // the expression to be complete. 'sizeof' requires the expression's type to
4514 // be complete (and will attempt to complete it if it's an array of unknown
4515 // bound).
4516 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4517 if (RequireCompleteSizedType(
4518 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4519 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4520 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4521 return true;
4522 } else {
4523 if (RequireCompleteSizedExprType(
4524 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4525 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4526 return true;
4527 }
4528
4529 // Completing the expression's type may have changed it.
4530 ExprTy = E->getType();
4531 assert(!ExprTy->isReferenceType());
4532
4533 if (ExprTy->isFunctionType()) {
4534 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4535 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4536 return true;
4537 }
4538
4539 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4540 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4541 return true;
4542
4543 if (ExprKind == UETT_CountOf) {
4544 // The type has to be an array type. We already checked for incomplete
4545 // types above.
4546 QualType ExprType = E->IgnoreParens()->getType();
4547 if (!ExprType->isArrayType()) {
4548 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4549 return true;
4550 }
4551 // FIXME: warn on _Countof on an array parameter. Not warning on it
4552 // currently because there are papers in WG14 about array types which do
4553 // not decay that could impact this behavior, so we want to see if anything
4554 // changes here before coming up with a warning group for _Countof-related
4555 // diagnostics.
4556 }
4557
4558 if (ExprKind == UETT_SizeOf) {
4559 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4560 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4561 QualType OType = PVD->getOriginalType();
4562 QualType Type = PVD->getType();
4563 if (Type->isPointerType() && OType->isArrayType()) {
4564 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4565 << Type << OType;
4566 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4567 }
4568 }
4569 }
4570
4571 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4572 // decays into a pointer and returns an unintended result. This is most
4573 // likely a typo for "sizeof(array) op x".
4574 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4575 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4576 E: BO->getLHS());
4577 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4578 E: BO->getRHS());
4579 }
4580 }
4581
4582 return false;
4583}
4584
4585static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4586 // Cannot know anything else if the expression is dependent.
4587 if (E->isTypeDependent())
4588 return false;
4589
4590 if (E->getObjectKind() == OK_BitField) {
4591 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4592 << 1 << E->getSourceRange();
4593 return true;
4594 }
4595
4596 ValueDecl *D = nullptr;
4597 Expr *Inner = E->IgnoreParens();
4598 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4599 D = DRE->getDecl();
4600 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4601 D = ME->getMemberDecl();
4602 }
4603
4604 // If it's a field, require the containing struct to have a
4605 // complete definition so that we can compute the layout.
4606 //
4607 // This can happen in C++11 onwards, either by naming the member
4608 // in a way that is not transformed into a member access expression
4609 // (in an unevaluated operand, for instance), or by naming the member
4610 // in a trailing-return-type.
4611 //
4612 // For the record, since __alignof__ on expressions is a GCC
4613 // extension, GCC seems to permit this but always gives the
4614 // nonsensical answer 0.
4615 //
4616 // We don't really need the layout here --- we could instead just
4617 // directly check for all the appropriate alignment-lowing
4618 // attributes --- but that would require duplicating a lot of
4619 // logic that just isn't worth duplicating for such a marginal
4620 // use-case.
4621 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4622 // Fast path this check, since we at least know the record has a
4623 // definition if we can find a member of it.
4624 if (!FD->getParent()->isCompleteDefinition()) {
4625 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4626 << E->getSourceRange();
4627 return true;
4628 }
4629
4630 // Otherwise, if it's a field, and the field doesn't have
4631 // reference type, then it must have a complete type (or be a
4632 // flexible array member, which we explicitly want to
4633 // white-list anyway), which makes the following checks trivial.
4634 if (!FD->getType()->isReferenceType())
4635 return false;
4636 }
4637
4638 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4639}
4640
4641bool Sema::CheckVecStepExpr(Expr *E) {
4642 E = E->IgnoreParens();
4643
4644 // Cannot know anything else if the expression is dependent.
4645 if (E->isTypeDependent())
4646 return false;
4647
4648 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4649}
4650
4651static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4652 CapturingScopeInfo *CSI) {
4653 assert(T->isVariablyModifiedType());
4654 assert(CSI != nullptr);
4655
4656 // We're going to walk down into the type and look for VLA expressions.
4657 do {
4658 const Type *Ty = T.getTypePtr();
4659 switch (Ty->getTypeClass()) {
4660#define TYPE(Class, Base)
4661#define ABSTRACT_TYPE(Class, Base)
4662#define NON_CANONICAL_TYPE(Class, Base)
4663#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4664#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4665#include "clang/AST/TypeNodes.inc"
4666 T = QualType();
4667 break;
4668 // These types are never variably-modified.
4669 case Type::Builtin:
4670 case Type::Complex:
4671 case Type::Vector:
4672 case Type::ExtVector:
4673 case Type::ConstantMatrix:
4674 case Type::Record:
4675 case Type::Enum:
4676 case Type::TemplateSpecialization:
4677 case Type::ObjCObject:
4678 case Type::ObjCInterface:
4679 case Type::ObjCObjectPointer:
4680 case Type::ObjCTypeParam:
4681 case Type::Pipe:
4682 case Type::BitInt:
4683 case Type::HLSLInlineSpirv:
4684 llvm_unreachable("type class is never variably-modified!");
4685 case Type::Adjusted:
4686 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4687 break;
4688 case Type::Decayed:
4689 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4690 break;
4691 case Type::ArrayParameter:
4692 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4693 break;
4694 case Type::Pointer:
4695 T = cast<PointerType>(Val: Ty)->getPointeeType();
4696 break;
4697 case Type::BlockPointer:
4698 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4699 break;
4700 case Type::LValueReference:
4701 case Type::RValueReference:
4702 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4703 break;
4704 case Type::MemberPointer:
4705 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4706 break;
4707 case Type::ConstantArray:
4708 case Type::IncompleteArray:
4709 // Losing element qualification here is fine.
4710 T = cast<ArrayType>(Val: Ty)->getElementType();
4711 break;
4712 case Type::VariableArray: {
4713 // Losing element qualification here is fine.
4714 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4715
4716 // Unknown size indication requires no size computation.
4717 // Otherwise, evaluate and record it.
4718 auto Size = VAT->getSizeExpr();
4719 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4720 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4721 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4722
4723 T = VAT->getElementType();
4724 break;
4725 }
4726 case Type::FunctionProto:
4727 case Type::FunctionNoProto:
4728 T = cast<FunctionType>(Val: Ty)->getReturnType();
4729 break;
4730 case Type::Paren:
4731 case Type::TypeOf:
4732 case Type::UnaryTransform:
4733 case Type::Attributed:
4734 case Type::BTFTagAttributed:
4735 case Type::OverflowBehavior:
4736 case Type::HLSLAttributedResource:
4737 case Type::SubstTemplateTypeParm:
4738 case Type::MacroQualified:
4739 case Type::CountAttributed:
4740 case Type::LateParsedAttr:
4741 // Keep walking after single level desugaring.
4742 T = T.getSingleStepDesugaredType(Context);
4743 break;
4744 case Type::Typedef:
4745 T = cast<TypedefType>(Val: Ty)->desugar();
4746 break;
4747 case Type::Decltype:
4748 T = cast<DecltypeType>(Val: Ty)->desugar();
4749 break;
4750 case Type::PackIndexing:
4751 T = cast<PackIndexingType>(Val: Ty)->desugar();
4752 break;
4753 case Type::Using:
4754 T = cast<UsingType>(Val: Ty)->desugar();
4755 break;
4756 case Type::Auto:
4757 case Type::DeducedTemplateSpecialization:
4758 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4759 break;
4760 case Type::TypeOfExpr:
4761 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4762 break;
4763 case Type::Atomic:
4764 T = cast<AtomicType>(Val: Ty)->getValueType();
4765 break;
4766 case Type::PredefinedSugar:
4767 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4768 break;
4769 }
4770 } while (!T.isNull() && T->isVariablyModifiedType());
4771}
4772
4773bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4774 SourceLocation OpLoc,
4775 SourceRange ExprRange,
4776 UnaryExprOrTypeTrait ExprKind,
4777 StringRef KWName) {
4778 if (ExprType->isDependentType())
4779 return false;
4780
4781 // These builtins evaluate with the operand type as written; a reference is
4782 // not looked through.
4783 if (ExprKind == UETT_VectorElements)
4784 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4785 ArgRange: ExprRange);
4786 if (ExprKind == UETT_VecStep)
4787 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4788 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4789 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4790 ArgRange: ExprRange);
4791
4792 // C++ [expr.sizeof]p2:
4793 // When applied to a reference or a reference type, the result
4794 // is the size of the referenced type.
4795 // C++11 [expr.alignof]p3:
4796 // When alignof is applied to a reference type, the result
4797 // shall be the alignment of the referenced type.
4798 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4799 ExprType = Ref->getPointeeType();
4800
4801 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4802 // When alignof or _Alignof is applied to an array type, the result
4803 // is the alignment of the element type.
4804 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4805 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4806 // If the trait is 'alignof' in C before C2y, the ability to apply the
4807 // trait to an incomplete array is an extension.
4808 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4809 ExprType->isIncompleteArrayType())
4810 DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::alignof_incomplete_array);
4811 ExprType = Context.getBaseElementType(QT: ExprType);
4812 }
4813
4814 // Explicitly list some types as extensions.
4815 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4816 TraitKind: ExprKind))
4817 return false;
4818
4819 if (RequireCompleteSizedType(
4820 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4821 Args: KWName, Args: ExprRange))
4822 return true;
4823
4824 if (ExprType->isFunctionType()) {
4825 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4826 return true;
4827 }
4828
4829 if (ExprKind == UETT_CountOf) {
4830 // The type has to be an array type. We already checked for incomplete
4831 // types above.
4832 if (!ExprType->isArrayType()) {
4833 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4834 return true;
4835 }
4836 }
4837
4838 // WebAssembly tables are always illegal operands to unary expressions and
4839 // type traits.
4840 if (Context.getTargetInfo().getTriple().isWasm() &&
4841 ExprType->isWebAssemblyTableType()) {
4842 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4843 << getTraitSpelling(T: ExprKind);
4844 return true;
4845 }
4846
4847 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4848 TraitKind: ExprKind))
4849 return true;
4850
4851 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4852 if (auto *TT = ExprType->getAs<TypedefType>()) {
4853 for (auto I = FunctionScopes.rbegin(),
4854 E = std::prev(x: FunctionScopes.rend());
4855 I != E; ++I) {
4856 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4857 if (CSI == nullptr)
4858 break;
4859 DeclContext *DC = nullptr;
4860 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4861 DC = LSI->CallOperator;
4862 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4863 DC = CRSI->TheCapturedDecl;
4864 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4865 DC = BSI->TheDecl;
4866 if (DC) {
4867 if (DC->containsDecl(D: TT->getDecl()))
4868 break;
4869 captureVariablyModifiedType(Context, T: ExprType, CSI);
4870 }
4871 }
4872 }
4873 }
4874
4875 return false;
4876}
4877
4878ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4879 SourceLocation OpLoc,
4880 UnaryExprOrTypeTrait ExprKind,
4881 SourceRange R) {
4882 if (!TInfo)
4883 return ExprError();
4884
4885 QualType T = TInfo->getType();
4886
4887 if (!T->isDependentType() &&
4888 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4889 KWName: getTraitSpelling(T: ExprKind)))
4890 return ExprError();
4891
4892 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4893 // properly deal with VLAs in nested calls of sizeof and typeof.
4894 if (currentEvaluationContext().isUnevaluated() &&
4895 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4896 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4897 TInfo->getType()->isVariablyModifiedType())
4898 TInfo = TransformToPotentiallyEvaluated(TInfo);
4899
4900 // It's possible that the transformation above failed.
4901 if (!TInfo)
4902 return ExprError();
4903
4904 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4905 return new (Context) UnaryExprOrTypeTraitExpr(
4906 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4907}
4908
4909ExprResult
4910Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4911 UnaryExprOrTypeTrait ExprKind) {
4912 ExprResult PE = CheckPlaceholderExpr(E);
4913 if (PE.isInvalid())
4914 return ExprError();
4915
4916 E = PE.get();
4917
4918 // Verify that the operand is valid.
4919 bool isInvalid = false;
4920 if (E->isTypeDependent()) {
4921 // Delay type-checking for type-dependent expressions.
4922 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4923 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4924 } else if (ExprKind == UETT_VecStep) {
4925 isInvalid = CheckVecStepExpr(E);
4926 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4927 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4928 isInvalid = true;
4929 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4930 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4931 isInvalid = true;
4932 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4933 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4934 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4935 }
4936
4937 if (isInvalid)
4938 return ExprError();
4939
4940 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4941 E->getType()->isVariableArrayType()) {
4942 PE = TransformToPotentiallyEvaluated(E);
4943 if (PE.isInvalid()) return ExprError();
4944 E = PE.get();
4945 }
4946
4947 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4948 return new (Context) UnaryExprOrTypeTraitExpr(
4949 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4950}
4951
4952ExprResult
4953Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4954 UnaryExprOrTypeTrait ExprKind, bool IsType,
4955 void *TyOrEx, SourceRange ArgRange) {
4956 // If error parsing type, ignore.
4957 if (!TyOrEx) return ExprError();
4958
4959 if (IsType) {
4960 TypeSourceInfo *TInfo;
4961 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4962 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4963 }
4964
4965 Expr *ArgEx = (Expr *)TyOrEx;
4966 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4967 return Result;
4968}
4969
4970bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4971 SourceLocation OpLoc, SourceRange R) {
4972 if (!TInfo)
4973 return true;
4974 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4975 ExprKind: UETT_AlignOf, KWName);
4976}
4977
4978bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4979 SourceLocation OpLoc, SourceRange R) {
4980 TypeSourceInfo *TInfo;
4981 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4982 TInfo: &TInfo);
4983 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4984}
4985
4986static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4987 bool IsReal) {
4988 if (V.get()->isTypeDependent())
4989 return S.Context.DependentTy;
4990
4991 // _Real and _Imag are only l-values for normal l-values.
4992 if (V.get()->getObjectKind() != OK_Ordinary) {
4993 V = S.DefaultLvalueConversion(E: V.get());
4994 if (V.isInvalid())
4995 return QualType();
4996 }
4997
4998 // These operators return the element type of a complex type.
4999 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5000 return CT->getElementType();
5001
5002 // Otherwise they pass through real integer and floating point types here.
5003 if (V.get()->getType()->isArithmeticType())
5004 return V.get()->getType();
5005
5006 // Test for placeholders.
5007 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
5008 if (PR.isInvalid()) return QualType();
5009 if (PR.get() != V.get()) {
5010 V = PR;
5011 return CheckRealImagOperand(S, V, Loc, IsReal);
5012 }
5013
5014 // Reject anything else.
5015 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
5016 << (IsReal ? "__real" : "__imag");
5017 return QualType();
5018}
5019
5020
5021
5022ExprResult
5023Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5024 tok::TokenKind Kind, Expr *Input) {
5025 UnaryOperatorKind Opc;
5026 switch (Kind) {
5027 default: llvm_unreachable("Unknown unary op!");
5028 case tok::plusplus: Opc = UO_PostInc; break;
5029 case tok::minusminus: Opc = UO_PostDec; break;
5030 }
5031
5032 // Since this might is a postfix expression, get rid of ParenListExprs.
5033 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
5034 if (Result.isInvalid()) return ExprError();
5035 Input = Result.get();
5036
5037 return BuildUnaryOp(S, OpLoc, Opc, Input);
5038}
5039
5040/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5041///
5042/// \return true on error
5043static bool checkArithmeticOnObjCPointer(Sema &S,
5044 SourceLocation opLoc,
5045 Expr *op) {
5046 assert(op->getType()->isObjCObjectPointerType());
5047 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5048 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5049 return false;
5050
5051 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
5052 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5053 << op->getSourceRange();
5054 return true;
5055}
5056
5057static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5058 auto *BaseNoParens = Base->IgnoreParens();
5059 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5060 return MSProp->getPropertyDecl()->getType()->isArrayType();
5061 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
5062}
5063
5064// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5065// Typically this is DependentTy, but can sometimes be more precise.
5066//
5067// There are cases when we could determine a non-dependent type:
5068// - LHS and RHS may have non-dependent types despite being type-dependent
5069// (e.g. unbounded array static members of the current instantiation)
5070// - one may be a dependent-sized array with known element type
5071// - one may be a dependent-typed valid index (enum in current instantiation)
5072//
5073// We *always* return a dependent type, in such cases it is DependentTy.
5074// This avoids creating type-dependent expressions with non-dependent types.
5075// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5076static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5077 const ASTContext &Ctx) {
5078 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5079 QualType LTy = LHS->getType(), RTy = RHS->getType();
5080 QualType Result = Ctx.DependentTy;
5081 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5082 if (const PointerType *PT = LTy->getAs<PointerType>())
5083 Result = PT->getPointeeType();
5084 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5085 Result = AT->getElementType();
5086 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5087 if (const PointerType *PT = RTy->getAs<PointerType>())
5088 Result = PT->getPointeeType();
5089 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5090 Result = AT->getElementType();
5091 }
5092 // Ensure we return a dependent type.
5093 return Result->isDependentType() ? Result : Ctx.DependentTy;
5094}
5095
5096ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5097 SourceLocation lbLoc,
5098 MultiExprArg ArgExprs,
5099 SourceLocation rbLoc) {
5100
5101 if (base && !base->getType().isNull() &&
5102 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5103 auto *AS = cast<ArraySectionExpr>(Val: base);
5104 if (AS->isOMPArraySection())
5105 return OpenMP().ActOnOMPArraySectionExpr(
5106 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5107 /*Length*/ nullptr,
5108 /*Stride=*/nullptr, RBLoc: rbLoc);
5109
5110 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5111 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5112 RBLoc: rbLoc);
5113 }
5114
5115 // Since this might be a postfix expression, get rid of ParenListExprs.
5116 if (isa<ParenListExpr>(Val: base)) {
5117 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5118 if (result.isInvalid())
5119 return ExprError();
5120 base = result.get();
5121 }
5122
5123 // Check if base and idx form a MatrixSubscriptExpr.
5124 //
5125 // Helper to check for comma expressions, which are not allowed as indices for
5126 // matrix subscript expressions.
5127 //
5128 // In C++23, we get multiple arguments instead of a comma expression.
5129 auto CheckAndReportCommaError = [&](Expr *E) {
5130 if (ArgExprs.size() > 1 ||
5131 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5132 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5133 << SourceRange(base->getBeginLoc(), rbLoc);
5134 return true;
5135 }
5136 return false;
5137 };
5138 // The matrix subscript operator ([][])is considered a single operator.
5139 // Separating the index expressions by parenthesis is not allowed.
5140 if (base && !base->getType().isNull() &&
5141 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5142 !isa<MatrixSubscriptExpr>(Val: base)) {
5143 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5144 << SourceRange(base->getBeginLoc(), rbLoc);
5145 return ExprError();
5146 }
5147 // If the base is a MatrixSubscriptExpr, try to create a new
5148 // MatrixSubscriptExpr.
5149 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5150 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5151 if (CheckAndReportCommaError(ArgExprs.front()))
5152 return ExprError();
5153
5154 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5155 RowIdx: matSubscriptE->getRowIdx(),
5156 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5157 }
5158 if (base->getType()->isWebAssemblyTableType()) {
5159 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5160 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5161 return ExprError();
5162 }
5163
5164 CheckInvalidBuiltinCountedByRef(E: base,
5165 K: BuiltinCountedByRefKind::ArraySubscript);
5166
5167 // Handle any non-overload placeholder types in the base and index
5168 // expressions. We can't handle overloads here because the other
5169 // operand might be an overloadable type, in which case the overload
5170 // resolution for the operator overload should get the first crack
5171 // at the overload.
5172 bool IsMSPropertySubscript = false;
5173 if (base->getType()->isNonOverloadPlaceholderType()) {
5174 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5175 if (!IsMSPropertySubscript) {
5176 ExprResult result = CheckPlaceholderExpr(E: base);
5177 if (result.isInvalid())
5178 return ExprError();
5179 base = result.get();
5180 }
5181 }
5182
5183 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5184 if (base->getType()->isMatrixType()) {
5185 if (CheckAndReportCommaError(ArgExprs.front()))
5186 return ExprError();
5187
5188 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5189 RBLoc: rbLoc);
5190 }
5191
5192 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5193 Expr *idx = ArgExprs[0];
5194 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5195 (isa<CXXOperatorCallExpr>(Val: idx) &&
5196 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5197 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5198 << SourceRange(base->getBeginLoc(), rbLoc);
5199 }
5200 }
5201
5202 if (ArgExprs.size() == 1 &&
5203 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5204 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5205 if (result.isInvalid())
5206 return ExprError();
5207 ArgExprs[0] = result.get();
5208 } else {
5209 if (CheckArgsForPlaceholders(args: ArgExprs))
5210 return ExprError();
5211 }
5212
5213 // Build an unanalyzed expression if either operand is type-dependent.
5214 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5215 (base->isTypeDependent() ||
5216 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5217 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5218 return new (Context) ArraySubscriptExpr(
5219 base, ArgExprs.front(),
5220 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5221 VK_LValue, OK_Ordinary, rbLoc);
5222 }
5223
5224 // MSDN, property (C++)
5225 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5226 // This attribute can also be used in the declaration of an empty array in a
5227 // class or structure definition. For example:
5228 // __declspec(property(get=GetX, put=PutX)) int x[];
5229 // The above statement indicates that x[] can be used with one or more array
5230 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5231 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5232 if (IsMSPropertySubscript) {
5233 if (ArgExprs.size() > 1) {
5234 Diag(Loc: base->getExprLoc(),
5235 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5236 return ExprError();
5237 }
5238
5239 // Build MS property subscript expression if base is MS property reference
5240 // or MS property subscript.
5241 return new (Context)
5242 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5243 VK_LValue, OK_Ordinary, rbLoc);
5244 }
5245
5246 // Use C++ overloaded-operator rules if either operand has record
5247 // type. The spec says to do this if either type is *overloadable*,
5248 // but enum types can't declare subscript operators or conversion
5249 // operators, so there's nothing interesting for overload resolution
5250 // to do if there aren't any record types involved.
5251 //
5252 // ObjC pointers have their own subscripting logic that is not tied
5253 // to overload resolution and so should not take this path.
5254 //
5255 // Issue a better diagnostic if we tried to pass multiple arguments to
5256 // a builtin subscript operator rather than diagnosing this as a generic
5257 // overload resolution failure.
5258 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5259 !base->getType()->isRecordType() &&
5260 !base->getType()->isObjCObjectPointerType()) {
5261 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5262 << base->getType() << base->getSourceRange();
5263 return ExprError();
5264 }
5265
5266 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5267 ((base->getType()->isRecordType() ||
5268 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5269 ArgExprs[0]->getType()->isRecordType())))) {
5270 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5271 }
5272
5273 ExprResult Res =
5274 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5275
5276 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5277 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5278
5279 return Res;
5280}
5281
5282ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5283 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5284 InitializationKind Kind =
5285 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5286 InitializationSequence InitSeq(*this, Entity, Kind, E);
5287 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5288}
5289
5290ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5291 Expr *RowIdx,
5292 SourceLocation RBLoc) {
5293 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5294 if (BaseR.isInvalid())
5295 return BaseR;
5296 Base = BaseR.get();
5297
5298 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5299 if (RowR.isInvalid())
5300 return RowR;
5301 RowIdx = RowR.get();
5302
5303 // Build an unanalyzed expression if any of the operands is type-dependent.
5304 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5305 return new (Context)
5306 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5307
5308 // Check that IndexExpr is an integer expression. If it is a constant
5309 // expression, check that it is less than Dim (= the number of elements in the
5310 // corresponding dimension).
5311 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5312 bool IsColumnIdx) -> Expr * {
5313 if (!IndexExpr->getType()->isIntegerType() &&
5314 !IndexExpr->isTypeDependent()) {
5315 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5316 << IsColumnIdx;
5317 return nullptr;
5318 }
5319
5320 if (std::optional<llvm::APSInt> Idx =
5321 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5322 if ((*Idx < 0 || *Idx >= Dim)) {
5323 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5324 << IsColumnIdx << Dim;
5325 return nullptr;
5326 }
5327 }
5328
5329 ExprResult ConvExpr = IndexExpr;
5330 assert(!ConvExpr.isInvalid() &&
5331 "should be able to convert any integer type to size type");
5332 return ConvExpr.get();
5333 };
5334
5335 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5336 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5337 if (!RowIdx)
5338 return ExprError();
5339
5340 QualType RowVecQT =
5341 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5342
5343 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5344}
5345
5346ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5347 Expr *ColumnIdx,
5348 SourceLocation RBLoc) {
5349 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5350 if (BaseR.isInvalid())
5351 return BaseR;
5352 Base = BaseR.get();
5353
5354 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5355 if (RowR.isInvalid())
5356 return RowR;
5357 RowIdx = RowR.get();
5358
5359 if (!ColumnIdx)
5360 return new (Context) MatrixSubscriptExpr(
5361 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5362
5363 // Build an unanalyzed expression if any of the operands is type-dependent.
5364 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5365 ColumnIdx->isTypeDependent())
5366 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5367 Context.DependentTy, RBLoc);
5368
5369 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5370 if (ColumnR.isInvalid())
5371 return ColumnR;
5372 ColumnIdx = ColumnR.get();
5373
5374 // Check that IndexExpr is an integer expression. If it is a constant
5375 // expression, check that it is less than Dim (= the number of elements in the
5376 // corresponding dimension).
5377 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5378 bool IsColumnIdx) -> Expr * {
5379 if (!IndexExpr->getType()->isIntegerType() &&
5380 !IndexExpr->isTypeDependent()) {
5381 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5382 << IsColumnIdx;
5383 return nullptr;
5384 }
5385
5386 if (std::optional<llvm::APSInt> Idx =
5387 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5388 if ((*Idx < 0 || *Idx >= Dim)) {
5389 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5390 << IsColumnIdx << Dim;
5391 return nullptr;
5392 }
5393 }
5394
5395 ExprResult ConvExpr = IndexExpr;
5396 assert(!ConvExpr.isInvalid() &&
5397 "should be able to convert any integer type to size type");
5398 return ConvExpr.get();
5399 };
5400
5401 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5402 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5403 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5404 if (!RowIdx || !ColumnIdx)
5405 return ExprError();
5406
5407 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5408 MTy->getElementType(), RBLoc);
5409}
5410
5411void Sema::CheckAddressOfNoDeref(const Expr *E) {
5412 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5413 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5414
5415 // For expressions like `&(*s).b`, the base is recorded and what should be
5416 // checked.
5417 const MemberExpr *Member = nullptr;
5418 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5419 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5420
5421 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5422}
5423
5424void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5425 if (isUnevaluatedContext())
5426 return;
5427
5428 QualType ResultTy = E->getType();
5429 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5430
5431 // Bail if the element is an array since it is not memory access.
5432 if (isa<ArrayType>(Val: ResultTy))
5433 return;
5434
5435 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5436 LastRecord.PossibleDerefs.insert(Ptr: E);
5437 return;
5438 }
5439
5440 // Check if the base type is a pointer to a member access of a struct
5441 // marked with noderef.
5442 const Expr *Base = E->getBase();
5443 QualType BaseTy = Base->getType();
5444 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5445 // Not a pointer access
5446 return;
5447
5448 const MemberExpr *Member = nullptr;
5449 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5450 Member->isArrow())
5451 Base = Member->getBase();
5452
5453 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5454 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5455 LastRecord.PossibleDerefs.insert(Ptr: E);
5456 }
5457}
5458
5459ExprResult
5460Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5461 Expr *Idx, SourceLocation RLoc) {
5462 Expr *LHSExp = Base;
5463 Expr *RHSExp = Idx;
5464
5465 ExprValueKind VK = VK_LValue;
5466 ExprObjectKind OK = OK_Ordinary;
5467
5468 // Per C++ core issue 1213, the result is an xvalue if either operand is
5469 // a non-lvalue array, and an lvalue otherwise.
5470 if (getLangOpts().CPlusPlus11) {
5471 for (auto *Op : {LHSExp, RHSExp}) {
5472 Op = Op->IgnoreImplicit();
5473 if (Op->getType()->isArrayType() && !Op->isLValue())
5474 VK = VK_XValue;
5475 }
5476 }
5477
5478 // Perform default conversions.
5479 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5480 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5481 if (Result.isInvalid())
5482 return ExprError();
5483 LHSExp = Result.get();
5484 }
5485 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5486 if (Result.isInvalid())
5487 return ExprError();
5488 RHSExp = Result.get();
5489
5490 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5491
5492 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5493 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5494 // in the subscript position. As a result, we need to derive the array base
5495 // and index from the expression types.
5496 Expr *BaseExpr, *IndexExpr;
5497 QualType ResultType;
5498 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5499 BaseExpr = LHSExp;
5500 IndexExpr = RHSExp;
5501 ResultType =
5502 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5503 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5504 BaseExpr = LHSExp;
5505 IndexExpr = RHSExp;
5506 ResultType = PTy->getPointeeType();
5507 } else if (const ObjCObjectPointerType *PTy =
5508 LHSTy->getAs<ObjCObjectPointerType>()) {
5509 BaseExpr = LHSExp;
5510 IndexExpr = RHSExp;
5511
5512 // Use custom logic if this should be the pseudo-object subscript
5513 // expression.
5514 if (!LangOpts.isSubscriptPointerArithmetic())
5515 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5516 getterMethod: nullptr, setterMethod: nullptr);
5517
5518 ResultType = PTy->getPointeeType();
5519 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5520 // Handle the uncommon case of "123[Ptr]".
5521 BaseExpr = RHSExp;
5522 IndexExpr = LHSExp;
5523 ResultType = PTy->getPointeeType();
5524 } else if (const ObjCObjectPointerType *PTy =
5525 RHSTy->getAs<ObjCObjectPointerType>()) {
5526 // Handle the uncommon case of "123[Ptr]".
5527 BaseExpr = RHSExp;
5528 IndexExpr = LHSExp;
5529 ResultType = PTy->getPointeeType();
5530 if (!LangOpts.isSubscriptPointerArithmetic()) {
5531 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5532 << ResultType << BaseExpr->getSourceRange();
5533 return ExprError();
5534 }
5535 } else if (LHSTy->isSubscriptableVectorType()) {
5536 if (LHSTy->isBuiltinType() &&
5537 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5538 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5539 if (BTy->isSVEBool())
5540 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5541 << LHSExp->getSourceRange()
5542 << RHSExp->getSourceRange());
5543 ResultType = BTy->getSveEltType(Ctx: Context);
5544 } else {
5545 const VectorType *VTy = LHSTy->getAs<VectorType>();
5546 ResultType = VTy->getElementType();
5547 }
5548 BaseExpr = LHSExp; // vectors: V[123]
5549 IndexExpr = RHSExp;
5550 // We apply C++ DR1213 to vector subscripting too.
5551 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5552 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5553 if (Materialized.isInvalid())
5554 return ExprError();
5555 LHSExp = Materialized.get();
5556 }
5557 VK = LHSExp->getValueKind();
5558 if (VK != VK_PRValue)
5559 OK = OK_VectorComponent;
5560
5561 QualType BaseType = BaseExpr->getType();
5562 Qualifiers BaseQuals = BaseType.getQualifiers();
5563 Qualifiers MemberQuals = ResultType.getQualifiers();
5564 Qualifiers Combined = BaseQuals + MemberQuals;
5565 if (Combined != MemberQuals)
5566 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5567 } else if (LHSTy->isArrayType()) {
5568 // If we see an array that wasn't promoted by
5569 // DefaultFunctionArrayLvalueConversion, it must be an array that
5570 // wasn't promoted because of the C90 rule that doesn't
5571 // allow promoting non-lvalue arrays. Warn, then
5572 // force the promotion here.
5573 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5574 << LHSExp->getSourceRange();
5575 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5576 CK: CK_ArrayToPointerDecay).get();
5577 LHSTy = LHSExp->getType();
5578
5579 BaseExpr = LHSExp;
5580 IndexExpr = RHSExp;
5581 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5582 } else if (RHSTy->isArrayType()) {
5583 // Same as previous, except for 123[f().a] case
5584 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5585 << RHSExp->getSourceRange();
5586 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5587 CK: CK_ArrayToPointerDecay).get();
5588 RHSTy = RHSExp->getType();
5589
5590 BaseExpr = RHSExp;
5591 IndexExpr = LHSExp;
5592 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5593 } else {
5594 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5595 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5596 }
5597 // C99 6.5.2.1p1
5598 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5599 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5600 << IndexExpr->getSourceRange());
5601
5602 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5603 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5604 !IndexExpr->isTypeDependent()) {
5605 std::optional<llvm::APSInt> IntegerContantExpr =
5606 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5607 if (!IntegerContantExpr.has_value() ||
5608 IntegerContantExpr.value().isNegative())
5609 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5610 }
5611
5612 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5613 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5614 // type. Note that Functions are not objects, and that (in C99 parlance)
5615 // incomplete types are not object types.
5616 if (ResultType->isFunctionType()) {
5617 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5618 << ResultType << BaseExpr->getSourceRange();
5619 return ExprError();
5620 }
5621
5622 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5623 // GNU extension: subscripting on pointer to void
5624 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5625 << BaseExpr->getSourceRange();
5626
5627 // C forbids expressions of unqualified void type from being l-values.
5628 // See IsCForbiddenLValueType.
5629 if (!ResultType.hasQualifiers())
5630 VK = VK_PRValue;
5631 } else if (!ResultType->isDependentType() &&
5632 !ResultType.isWebAssemblyReferenceType() &&
5633 RequireCompleteSizedType(
5634 Loc: LLoc, T: ResultType,
5635 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5636 return ExprError();
5637
5638 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5639 !ResultType.isCForbiddenLValueType());
5640
5641 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5642 FunctionScopes.size() > 1) {
5643 if (auto *TT =
5644 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5645 for (auto I = FunctionScopes.rbegin(),
5646 E = std::prev(x: FunctionScopes.rend());
5647 I != E; ++I) {
5648 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5649 if (CSI == nullptr)
5650 break;
5651 DeclContext *DC = nullptr;
5652 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5653 DC = LSI->CallOperator;
5654 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5655 DC = CRSI->TheCapturedDecl;
5656 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5657 DC = BSI->TheDecl;
5658 if (DC) {
5659 if (DC->containsDecl(D: TT->getDecl()))
5660 break;
5661 captureVariablyModifiedType(
5662 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5663 }
5664 }
5665 }
5666 }
5667
5668 return new (Context)
5669 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5670}
5671
5672bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5673 ParmVarDecl *Param, Expr *RewrittenInit,
5674 bool SkipImmediateInvocations) {
5675 if (Param->hasUnparsedDefaultArg()) {
5676 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5677 // If we've already cleared out the location for the default argument,
5678 // that means we're parsing it right now.
5679 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5680 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5681 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5682 Param->setInvalidDecl();
5683 return true;
5684 }
5685
5686 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5687 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5688 Diag(Loc: UnparsedDefaultArgLocs[Param],
5689 DiagID: diag::note_default_argument_declared_here);
5690 return true;
5691 }
5692
5693 if (Param->hasUninstantiatedDefaultArg()) {
5694 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5695 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5696 return true;
5697 }
5698
5699 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5700 assert(Init && "default argument but no initializer?");
5701
5702 // If the default expression creates temporaries, we need to
5703 // push them to the current stack of expression temporaries so they'll
5704 // be properly destroyed.
5705 // FIXME: We should really be rebuilding the default argument with new
5706 // bound temporaries; see the comment in PR5810.
5707 // We don't need to do that with block decls, though, because
5708 // blocks in default argument expression can never capture anything.
5709 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5710 // Set the "needs cleanups" bit regardless of whether there are
5711 // any explicit objects.
5712 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5713 // Append all the objects to the cleanup list. Right now, this
5714 // should always be a no-op, because blocks in default argument
5715 // expressions should never be able to capture anything.
5716 assert(!InitWithCleanup->getNumObjects() &&
5717 "default argument expression has capturing blocks?");
5718 }
5719 // C++ [expr.const]p15.1:
5720 // An expression or conversion is in an immediate function context if it is
5721 // potentially evaluated and [...] its innermost enclosing non-block scope
5722 // is a function parameter scope of an immediate function.
5723 EnterExpressionEvaluationContext EvalContext(
5724 *this,
5725 FD->isImmediateFunction()
5726 ? ExpressionEvaluationContext::ImmediateFunctionContext
5727 : ExpressionEvaluationContext::PotentiallyEvaluated,
5728 Param);
5729 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5730 SkipImmediateInvocations;
5731 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5732 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5733 });
5734 return false;
5735}
5736
5737struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5738 const ASTContext &Context;
5739 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5740 ShouldVisitImplicitCode = true;
5741 }
5742
5743 bool HasImmediateCalls = false;
5744
5745 bool VisitCallExpr(CallExpr *E) override {
5746 if (const FunctionDecl *FD = E->getDirectCallee())
5747 HasImmediateCalls |= FD->isImmediateFunction();
5748 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5749 }
5750
5751 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5752 if (const FunctionDecl *FD = E->getConstructor())
5753 HasImmediateCalls |= FD->isImmediateFunction();
5754 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5755 }
5756
5757 // SourceLocExpr are not immediate invocations
5758 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5759 // need to be rebuilt so that they refer to the correct SourceLocation and
5760 // DeclContext.
5761 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5762 HasImmediateCalls = true;
5763 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5764 }
5765
5766 // A nested lambda might have parameters with immediate invocations
5767 // in their default arguments.
5768 // The compound statement is not visited (as it does not constitute a
5769 // subexpression).
5770 // FIXME: We should consider visiting and transforming captures
5771 // with init expressions.
5772 bool VisitLambdaExpr(LambdaExpr *E) override {
5773 return VisitCXXMethodDecl(D: E->getCallOperator());
5774 }
5775
5776 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5777 return TraverseStmt(S: E->getExpr());
5778 }
5779
5780 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5781 return TraverseStmt(S: E->getExpr());
5782 }
5783};
5784
5785struct EnsureImmediateInvocationInDefaultArgs
5786 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5787 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5788 : TreeTransform(SemaRef) {}
5789
5790 bool AlwaysRebuild() { return true; }
5791
5792 // Lambda can only have immediate invocations in the default
5793 // args of their parameters, which is transformed upon calling the closure.
5794 // The body is not a subexpression, so we have nothing to do.
5795 // FIXME: Immediate calls in capture initializers should be transformed.
5796 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5797 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5798
5799 // Make sure we don't rebuild the this pointer as it would
5800 // cause it to incorrectly point it to the outermost class
5801 // in the case of nested struct initialization.
5802 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5803
5804 // Rewrite to source location to refer to the context in which they are used.
5805 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5806 DeclContext *DC = E->getParentContext();
5807 if (DC == SemaRef.CurContext)
5808 return E;
5809
5810 // FIXME: During instantiation, because the rebuild of defaults arguments
5811 // is not always done in the context of the template instantiator,
5812 // we run the risk of producing a dependent source location
5813 // that would never be rebuilt.
5814 // This usually happens during overload resolution, or in contexts
5815 // where the value of the source location does not matter.
5816 // However, we should find a better way to deal with source location
5817 // of function templates.
5818 if (!SemaRef.CurrentInstantiationScope ||
5819 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5820 DC = SemaRef.CurContext;
5821
5822 return getDerived().RebuildSourceLocExpr(
5823 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5824 }
5825};
5826
5827ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5828 FunctionDecl *FD, ParmVarDecl *Param,
5829 Expr *Init) {
5830 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5831
5832 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5833 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5834 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5835 InitializationContext =
5836 OutermostDeclarationWithDelayedImmediateInvocations();
5837 if (!InitializationContext.has_value())
5838 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5839
5840 if (!Init && !Param->hasUnparsedDefaultArg()) {
5841 // Mark that we are replacing a default argument first.
5842 // If we are instantiating a template we won't have to
5843 // retransform immediate calls.
5844 // C++ [expr.const]p15.1:
5845 // An expression or conversion is in an immediate function context if it
5846 // is potentially evaluated and [...] its innermost enclosing non-block
5847 // scope is a function parameter scope of an immediate function.
5848 EnterExpressionEvaluationContext EvalContext(
5849 *this,
5850 FD->isImmediateFunction()
5851 ? ExpressionEvaluationContext::ImmediateFunctionContext
5852 : ExpressionEvaluationContext::PotentiallyEvaluated,
5853 Param);
5854
5855 if (Param->hasUninstantiatedDefaultArg()) {
5856 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5857 return ExprError();
5858 }
5859 // CWG2631
5860 // An immediate invocation that is not evaluated where it appears is
5861 // evaluated and checked for whether it is a constant expression at the
5862 // point where the enclosing initializer is used in a function call.
5863 ImmediateCallVisitor V(getASTContext());
5864 if (!NestedDefaultChecking)
5865 V.TraverseDecl(D: Param);
5866
5867 // Rewrite the call argument that was created from the corresponding
5868 // parameter's default argument.
5869 if (V.HasImmediateCalls ||
5870 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5871 if (V.HasImmediateCalls)
5872 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5873 CallLoc, Param, CurContext};
5874 // Pass down lifetime extending flag, and collect temporaries in
5875 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5876 currentEvaluationContext().InLifetimeExtendingContext =
5877 parentEvaluationContext().InLifetimeExtendingContext;
5878 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5879 ExprResult Res;
5880 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5881 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5882 /*NotCopy=*/NotCopyInit: false);
5883 });
5884 if (Res.isInvalid())
5885 return ExprError();
5886 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5887 EqualLoc: Res.get()->getBeginLoc());
5888 if (Res.isInvalid())
5889 return ExprError();
5890 Init = Res.get();
5891 }
5892 }
5893
5894 if (CheckCXXDefaultArgExpr(
5895 CallLoc, FD, Param, RewrittenInit: Init,
5896 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5897 return ExprError();
5898
5899 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5900 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5901}
5902
5903static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5904 FieldDecl *Field) {
5905 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5906 return Pattern;
5907 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5908 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5909 DeclContext::lookup_result Lookup =
5910 ClassPattern->lookup(Name: Field->getDeclName());
5911 auto Rng = llvm::make_filter_range(
5912 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5913 if (Rng.empty())
5914 return nullptr;
5915 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5916 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5917 // && "Duplicated instantiation pattern for field decl");
5918 return cast<FieldDecl>(Val: *Rng.begin());
5919}
5920
5921ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
5922 FieldDecl *Field,
5923 const InitializedEntity &Entity,
5924 bool NestedDefaultChecking,
5925 bool NeedRebuild) {
5926 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5927
5928 if (!Field->getInClassInitializer() &&
5929 isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5930 // Maybe we haven't instantiated the in-class initializer. Go check the
5931 // pattern FieldDecl to see if it has one.
5932 FieldDecl *Pattern =
5933 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5934 assert(Pattern && "We must have set the Pattern!");
5935 if (!Pattern->hasInClassInitializer() ||
5936 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5937 TemplateArgs: getTemplateInstantiationArgs(D: Field)))
5938 return ExprError();
5939 }
5940
5941 Expr *InClassInit = Field->getInClassInitializer();
5942 if (!InClassInit) {
5943 // DR1351:
5944 // If the brace-or-equal-initializer of a non-static data member
5945 // invokes a defaulted default constructor of its class or of an
5946 // enclosing class in a potentially evaluated subexpression, the
5947 // program is ill-formed.
5948 //
5949 // This resolution is unworkable: the exception specification of the
5950 // default constructor can be needed in an unevaluated context, in
5951 // particular, in the operand of a noexcept-expression, and we can be
5952 // unable to compute an exception specification for an enclosed class.
5953 //
5954 // Any attempt to resolve the exception specification of a defaulted default
5955 // constructor before the initializer is lexically complete will ultimately
5956 // come here at which point we can diagnose it.
5957 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5958 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5959 << OutermostClass << Field;
5960 Diag(Loc: Field->getEndLoc(),
5961 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5962 // Recover by marking the field invalid, unless we're in a SFINAE context.
5963 if (!isSFINAEContext())
5964 Field->setInvalidDecl();
5965 return ExprError();
5966 }
5967
5968 // CWG2631
5969 // An immediate invocation that is not evaluated where it appears is
5970 // evaluated and checked for whether it is a constant expression at the
5971 // point where the enclosing initializer is used in a [...] a constructor
5972 // definition, or an aggregate initialization.
5973 ImmediateCallVisitor V(getASTContext());
5974 if (!NestedDefaultChecking)
5975 V.TraverseDecl(D: Field);
5976
5977 // CWG1815
5978 // Support lifetime extension of temporary created by aggregate
5979 // initialization using a default member initializer. We should rebuild
5980 // the initializer in a lifetime extension context if the initializer
5981 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5982 // extension code recurses into the default initializer and does lifetime
5983 // extension when warranted.
5984 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(Val: InClassInit);
5985 Expr *Init = InClassInit;
5986 if (!InClassInit->containsErrors() &&
5987 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5988 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5989 CurContext};
5990 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5991 NestedDefaultChecking;
5992 // Pass down lifetime extending flag, and collect temporaries in
5993 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
5994 currentEvaluationContext().InLifetimeExtendingContext =
5995 parentEvaluationContext().InLifetimeExtendingContext;
5996
5997 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5998 ExprResult Res;
5999 runWithSufficientStackSpace(Loc, Fn: [&] {
6000 Res = Immediate.TransformInitializer(Init: InClassInit,
6001 /*CXXDirectInit=*/NotCopyInit: false);
6002 });
6003 if (!Res.isInvalid())
6004 Res = ConvertMemberDefaultInitExpression(FD: Field, Entity, InitExpr: Res.get(), InitLoc: Loc);
6005 if (Res.isInvalid()) {
6006 Field->setInvalidDecl();
6007 return ExprError();
6008 }
6009 Init = Res.get();
6010 }
6011
6012 if (!NestedDefaultChecking)
6013 runWithSufficientStackSpace(Loc, Fn: [&] {
6014 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/false);
6015 });
6016 return Init;
6017}
6018
6019ExprResult Sema::BuildCXXCtorDefaultInitExpr(SourceLocation Loc,
6020 FieldDecl *Field) {
6021 assert(Field->hasInClassInitializer());
6022
6023 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6024
6025 // C++11 [class.base.init]p7:
6026 // The initialization of each base and member constitutes a
6027 // full-expression.
6028 // So this initializer gets an evaluation context of its own, and is finished
6029 // as a full-expression below.
6030 EnterExpressionEvaluationContext EvalContext(
6031 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6032 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6033
6034 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6035 if (!InitContext)
6036 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6037
6038 // [class.temporary]/p7:
6039 // If such a temporary object would otherwise be destroyed at the end of the
6040 // for-range-initializer full-expression, the object persists for the lifetime
6041 // of the reference initialized by the for-range-initializer.
6042 //
6043 // A default member initializer used by a constructor is a separate
6044 // full-expression, we don't need extend temporaries lifetime in this
6045 // situation, the NeedRebuild will always false.
6046 ExprResult Init = BuildCXXDefaultInitInternal(
6047 Loc, Field,
6048 Entity: InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: Field),
6049 NestedDefaultChecking, /*NeedRebuild=*/false);
6050 if (Init.isInvalid())
6051 return ExprError();
6052
6053 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscardedValue=*/false);
6054 if (Init.isInvalid()) {
6055 Field->setInvalidDecl();
6056 return ExprError();
6057 }
6058
6059 return CXXDefaultInitExpr::Create(
6060 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6061 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6062}
6063
6064ExprResult
6065Sema::BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
6066 const InitializedEntity &MemberEntity) {
6067 assert(Field->hasInClassInitializer());
6068
6069 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6070
6071 // Unlike a mem-initializer, this initializer is a subexpression of the
6072 // full-expression containing the aggregate initialization. It is evaluated
6073 // exactly as that full-expression is, so inherit the enclosing context kind
6074 // rather than forcing a potentially evaluated one.
6075 EnterExpressionEvaluationContext EvalContext(
6076 *this, currentEvaluationContext().Context, Field);
6077 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6078
6079 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6080 if (!InitContext)
6081 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6082
6083 // [class.temporary]/p7:
6084 // If such a temporary object would otherwise be destroyed at the end of the
6085 // for-range-initializer full-expression, the object persists for the lifetime
6086 // of the reference initialized by the for-range-initializer.
6087 //
6088 // A default member initializer used by an aggregate initialization belongs to
6089 // the full-expression containing the aggregate initialization. we need extend
6090 // temporaries lifetime in this situation, the NeedRebuild will always true.
6091
6092 // CWG1815: always rebuild, never share the AST built when the field was
6093 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6094 // collected in this context, which is what lets the aggregate initialization
6095 // lifetime-extend them; sharing one AST would also make several uses of the
6096 // same field fight over its extension. A mem-initializer has no such need,
6097 // as its temporaries die at the end of the initializer itself.
6098 ExprResult Init = BuildCXXDefaultInitInternal(
6099 Loc, Field, Entity: MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6100 if (Init.isInvalid())
6101 return ExprError();
6102
6103 // Deliberately not finished as a full-expression: leaving the temporaries it
6104 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6105 // them into the enclosing context, which eventually wraps them all in a
6106 // single ExprWithCleanups. They are then destroyed at the end of the
6107 // containing full-expression, in reverse construction order.
6108
6109 return CXXDefaultInitExpr::Create(
6110 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6111 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6112}
6113
6114VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
6115 const FunctionProtoType *Proto,
6116 Expr *Fn) {
6117 if (Proto && Proto->isVariadic()) {
6118 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6119 return VariadicCallType::Constructor;
6120 else if (Fn && Fn->getType()->isBlockPointerType())
6121 return VariadicCallType::Block;
6122 else if (FDecl) {
6123 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6124 if (Method->isInstance())
6125 return VariadicCallType::Method;
6126 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6127 return VariadicCallType::Method;
6128 return VariadicCallType::Function;
6129 }
6130 return VariadicCallType::DoesNotApply;
6131}
6132
6133namespace {
6134class FunctionCallCCC final : public FunctionCallFilterCCC {
6135public:
6136 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6137 unsigned NumArgs, MemberExpr *ME)
6138 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6139 FunctionName(FuncName) {}
6140
6141 bool ValidateCandidate(const TypoCorrection &candidate) override {
6142 if (!candidate.getCorrectionSpecifier() ||
6143 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6144 return false;
6145 }
6146
6147 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6148 }
6149
6150 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6151 return std::make_unique<FunctionCallCCC>(args&: *this);
6152 }
6153
6154private:
6155 const IdentifierInfo *const FunctionName;
6156};
6157}
6158
6159static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6160 FunctionDecl *FDecl,
6161 ArrayRef<Expr *> Args) {
6162 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6163 DeclarationName FuncName = FDecl->getDeclName();
6164 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6165
6166 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6167 if (TypoCorrection Corrected = S.CorrectTypo(
6168 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6169 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6170 Mode: CorrectTypoKind::ErrorRecovery)) {
6171 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6172 if (Corrected.isOverloaded()) {
6173 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6174 OverloadCandidateSet::iterator Best;
6175 for (NamedDecl *CD : Corrected) {
6176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6177 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6178 CandidateSet&: OCS);
6179 }
6180 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6181 case OR_Success:
6182 ND = Best->FoundDecl;
6183 Corrected.setCorrectionDecl(ND);
6184 break;
6185 default:
6186 break;
6187 }
6188 }
6189 ND = ND->getUnderlyingDecl();
6190 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6191 return Corrected;
6192 }
6193 }
6194 return TypoCorrection();
6195}
6196
6197// [C++26][[expr.unary.op]/p4
6198// A pointer to member is only formed when an explicit &
6199// is used and its operand is a qualified-id not enclosed in parentheses.
6200static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6201 if (!isa<ParenExpr>(Val: Fn))
6202 return false;
6203
6204 Fn = Fn->IgnoreParens();
6205
6206 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6207 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6208 return false;
6209 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6210 return DRE->hasQualifier();
6211 }
6212 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6213 return bool(OVL->getQualifier());
6214 return false;
6215}
6216
6217bool
6218Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6219 FunctionDecl *FDecl,
6220 const FunctionProtoType *Proto,
6221 ArrayRef<Expr *> Args,
6222 SourceLocation RParenLoc,
6223 bool IsExecConfig) {
6224 // Bail out early if calling a builtin with custom typechecking.
6225 // For HLSL builtin aliases, argument conversion is still needed because
6226 // overload resolution may have selected a conversion sequence (e.g.,
6227 // vector-to-scalar truncation) that must be applied before the custom
6228 // type checker runs.
6229 if (FDecl)
6230 if (unsigned ID = FDecl->getBuiltinID())
6231 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6232 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6233 return false;
6234
6235 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6236 // assignment, to the types of the corresponding parameter, ...
6237
6238 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6239 bool HasExplicitObjectParameter =
6240 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6241 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6242 unsigned NumParams = Proto->getNumParams();
6243 bool Invalid = false;
6244 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6245 unsigned FnKind = Fn->getType()->isBlockPointerType()
6246 ? 1 /* block */
6247 : (IsExecConfig ? 3 /* kernel function (exec config) */
6248 : 0 /* function */);
6249
6250 // If too few arguments are available (and we don't have default
6251 // arguments for the remaining parameters), don't make the call.
6252 if (Args.size() < NumParams) {
6253 if (Args.size() < MinArgs) {
6254 TypoCorrection TC;
6255 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6256 unsigned diag_id =
6257 MinArgs == NumParams && !Proto->isVariadic()
6258 ? diag::err_typecheck_call_too_few_args_suggest
6259 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6260 diagnoseTypo(
6261 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6262 << FnKind << MinArgs - ExplicitObjectParameterOffset
6263 << static_cast<unsigned>(Args.size()) -
6264 ExplicitObjectParameterOffset
6265 << HasExplicitObjectParameter << TC.getCorrectionRange());
6266 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6267 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6268 ->getDeclName())
6269 Diag(Loc: RParenLoc,
6270 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6271 ? diag::err_typecheck_call_too_few_args_one
6272 : diag::err_typecheck_call_too_few_args_at_least_one)
6273 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6274 << HasExplicitObjectParameter << Fn->getSourceRange();
6275 else
6276 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6277 ? diag::err_typecheck_call_too_few_args
6278 : diag::err_typecheck_call_too_few_args_at_least)
6279 << FnKind << MinArgs - ExplicitObjectParameterOffset
6280 << static_cast<unsigned>(Args.size()) -
6281 ExplicitObjectParameterOffset
6282 << HasExplicitObjectParameter << Fn->getSourceRange();
6283
6284 // Emit the location of the prototype.
6285 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6286 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6287 << FDecl << FDecl->getParametersSourceRange();
6288
6289 return true;
6290 }
6291 // We reserve space for the default arguments when we create
6292 // the call expression, before calling ConvertArgumentsForCall.
6293 assert((Call->getNumArgs() == NumParams) &&
6294 "We should have reserved space for the default arguments before!");
6295 }
6296
6297 // If too many are passed and not variadic, error on the extras and drop
6298 // them.
6299 if (Args.size() > NumParams) {
6300 if (!Proto->isVariadic()) {
6301 TypoCorrection TC;
6302 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6303 unsigned diag_id =
6304 MinArgs == NumParams && !Proto->isVariadic()
6305 ? diag::err_typecheck_call_too_many_args_suggest
6306 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6307 diagnoseTypo(
6308 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6309 << FnKind << NumParams - ExplicitObjectParameterOffset
6310 << static_cast<unsigned>(Args.size()) -
6311 ExplicitObjectParameterOffset
6312 << HasExplicitObjectParameter << TC.getCorrectionRange());
6313 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6314 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6315 ->getDeclName())
6316 Diag(Loc: Args[NumParams]->getBeginLoc(),
6317 DiagID: MinArgs == NumParams
6318 ? diag::err_typecheck_call_too_many_args_one
6319 : diag::err_typecheck_call_too_many_args_at_most_one)
6320 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6321 << static_cast<unsigned>(Args.size()) -
6322 ExplicitObjectParameterOffset
6323 << HasExplicitObjectParameter << Fn->getSourceRange()
6324 << SourceRange(Args[NumParams]->getBeginLoc(),
6325 Args.back()->getEndLoc());
6326 else
6327 Diag(Loc: Args[NumParams]->getBeginLoc(),
6328 DiagID: MinArgs == NumParams
6329 ? diag::err_typecheck_call_too_many_args
6330 : diag::err_typecheck_call_too_many_args_at_most)
6331 << FnKind << NumParams - ExplicitObjectParameterOffset
6332 << static_cast<unsigned>(Args.size()) -
6333 ExplicitObjectParameterOffset
6334 << HasExplicitObjectParameter << Fn->getSourceRange()
6335 << SourceRange(Args[NumParams]->getBeginLoc(),
6336 Args.back()->getEndLoc());
6337
6338 // Emit the location of the prototype.
6339 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6340 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6341 << FDecl << FDecl->getParametersSourceRange();
6342
6343 // This deletes the extra arguments.
6344 Call->shrinkNumArgs(NewNumArgs: NumParams);
6345 return true;
6346 }
6347 }
6348 SmallVector<Expr *, 8> AllArgs;
6349 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6350
6351 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6352 AllArgs, CallType);
6353 if (Invalid)
6354 return true;
6355 unsigned TotalNumArgs = AllArgs.size();
6356 for (unsigned i = 0; i < TotalNumArgs; ++i)
6357 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6358
6359 Call->computeDependence();
6360 return false;
6361}
6362
6363bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6364 const FunctionProtoType *Proto,
6365 unsigned FirstParam, ArrayRef<Expr *> Args,
6366 SmallVectorImpl<Expr *> &AllArgs,
6367 VariadicCallType CallType, bool AllowExplicit,
6368 bool IsListInitialization) {
6369 unsigned NumParams = Proto->getNumParams();
6370 bool Invalid = false;
6371 size_t ArgIx = 0;
6372 // Continue to check argument types (even if we have too few/many args).
6373 for (unsigned i = FirstParam; i < NumParams; i++) {
6374 QualType ProtoArgType = Proto->getParamType(i);
6375
6376 Expr *Arg;
6377 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6378 if (ArgIx < Args.size()) {
6379 Arg = Args[ArgIx++];
6380
6381 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6382 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6383 return true;
6384
6385 // Strip the unbridged-cast placeholder expression off, if applicable.
6386 bool CFAudited = false;
6387 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6388 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6389 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6390 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6391 else if (getLangOpts().ObjCAutoRefCount &&
6392 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6393 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6394 CFAudited = true;
6395
6396 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6397 ProtoArgType->isBlockPointerType())
6398 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6399 BE->getBlockDecl()->setDoesNotEscape();
6400 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6401 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6402 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6403 if (ArgExpr.isInvalid())
6404 return true;
6405 Arg = ArgExpr.getAs<Expr>();
6406 }
6407
6408 InitializedEntity Entity =
6409 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6410 Type: ProtoArgType)
6411 : InitializedEntity::InitializeParameter(
6412 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6413
6414 // Remember that parameter belongs to a CF audited API.
6415 if (CFAudited)
6416 Entity.setParameterCFAudited();
6417
6418 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6419 // function boundaries is a common oversight.
6420 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6421 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6422 bool isPedantic =
6423 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6424 Diag(Loc: Arg->getExprLoc(),
6425 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6426 : diag::warn_obt_discarded_at_function_boundary)
6427 << Arg->getType() << ProtoArgType;
6428 }
6429
6430 ExprResult ArgE = PerformCopyInitialization(
6431 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6432 if (ArgE.isInvalid())
6433 return true;
6434
6435 Arg = ArgE.getAs<Expr>();
6436 } else {
6437 assert(Param && "can't use default arguments without a known callee");
6438
6439 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6440 if (ArgExpr.isInvalid())
6441 return true;
6442
6443 Arg = ArgExpr.getAs<Expr>();
6444 }
6445
6446 // Check for array bounds violations for each argument to the call. This
6447 // check only triggers warnings when the argument isn't a more complex Expr
6448 // with its own checking, such as a BinaryOperator.
6449 CheckArrayAccess(E: Arg);
6450
6451 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6452 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6453
6454 AllArgs.push_back(Elt: Arg);
6455 }
6456
6457 // If this is a variadic call, handle args passed through "...".
6458 if (CallType != VariadicCallType::DoesNotApply) {
6459 // Assume that extern "C" functions with variadic arguments that
6460 // return __unknown_anytype aren't *really* variadic.
6461 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6462 FDecl->isExternC()) {
6463 for (Expr *A : Args.slice(N: ArgIx)) {
6464 QualType paramType; // ignored
6465 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6466 Invalid |= arg.isInvalid();
6467 AllArgs.push_back(Elt: arg.get());
6468 }
6469
6470 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6471 } else {
6472 for (Expr *A : Args.slice(N: ArgIx)) {
6473 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6474 Invalid |= Arg.isInvalid();
6475 AllArgs.push_back(Elt: Arg.get());
6476 }
6477 }
6478
6479 // Check for array bounds violations.
6480 for (Expr *A : Args.slice(N: ArgIx))
6481 CheckArrayAccess(E: A);
6482 }
6483 return Invalid;
6484}
6485
6486static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6487 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6488 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6489 TL = DTL.getOriginalLoc();
6490 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6491 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6492 << ATL.getLocalSourceRange();
6493}
6494
6495void
6496Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6497 ParmVarDecl *Param,
6498 const Expr *ArgExpr) {
6499 // Static array parameters are not supported in C++.
6500 if (!Param || getLangOpts().CPlusPlus)
6501 return;
6502
6503 QualType OrigTy = Param->getOriginalType();
6504
6505 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6506 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6507 return;
6508
6509 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6510 NPC: Expr::NPC_NeverValueDependent)) {
6511 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6512 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6513 return;
6514 }
6515
6516 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6517 if (!CAT)
6518 return;
6519
6520 const ConstantArrayType *ArgCAT =
6521 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6522 if (!ArgCAT)
6523 return;
6524
6525 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6526 T2: ArgCAT->getElementType())) {
6527 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6528 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6529 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6530 << (unsigned)CAT->getZExtSize() << 0;
6531 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6532 }
6533 return;
6534 }
6535
6536 std::optional<CharUnits> ArgSize =
6537 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6538 std::optional<CharUnits> ParmSize =
6539 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6540 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6541 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6542 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6543 << (unsigned)ParmSize->getQuantity() << 1;
6544 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6545 }
6546}
6547
6548/// Given a function expression of unknown-any type, try to rebuild it
6549/// to have a function type.
6550static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6551
6552/// Is the given type a placeholder that we need to lower out
6553/// immediately during argument processing?
6554static bool isPlaceholderToRemoveAsArg(QualType type) {
6555 // Placeholders are never sugared.
6556 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6557 if (!placeholder) return false;
6558
6559 switch (placeholder->getKind()) {
6560 // Ignore all the non-placeholder types.
6561#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6562 case BuiltinType::Id:
6563#include "clang/Basic/OpenCLImageTypes.def"
6564#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6565 case BuiltinType::Id:
6566#include "clang/Basic/OpenCLExtensionTypes.def"
6567 // In practice we'll never use this, since all SVE types are sugared
6568 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6569#define SVE_TYPE(Name, Id, SingletonId) \
6570 case BuiltinType::Id:
6571#include "clang/Basic/AArch64ACLETypes.def"
6572#define PPC_VECTOR_TYPE(Name, Id, Size) \
6573 case BuiltinType::Id:
6574#include "clang/Basic/PPCTypes.def"
6575#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6576#include "clang/Basic/RISCVVTypes.def"
6577#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6578#include "clang/Basic/WebAssemblyReferenceTypes.def"
6579#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6580#include "clang/Basic/AMDGPUTypes.def"
6581#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6582#include "clang/Basic/HLSLIntangibleTypes.def"
6583#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6584#include "clang/Basic/SPIRVTypes.def"
6585#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6586#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6587#include "clang/AST/BuiltinTypes.def"
6588 return false;
6589
6590 case BuiltinType::UnresolvedTemplate:
6591 // We cannot lower out overload sets; they might validly be resolved
6592 // by the call machinery.
6593 case BuiltinType::Overload:
6594 return false;
6595
6596 // Unbridged casts in ARC can be handled in some call positions and
6597 // should be left in place.
6598 case BuiltinType::ARCUnbridgedCast:
6599 return false;
6600
6601 // Pseudo-objects should be converted as soon as possible.
6602 case BuiltinType::PseudoObject:
6603 return true;
6604
6605 // The debugger mode could theoretically but currently does not try
6606 // to resolve unknown-typed arguments based on known parameter types.
6607 case BuiltinType::UnknownAny:
6608 return true;
6609
6610 // These are always invalid as call arguments and should be reported.
6611 case BuiltinType::BoundMember:
6612 case BuiltinType::BuiltinFn:
6613 case BuiltinType::IncompleteMatrixIdx:
6614 case BuiltinType::ArraySection:
6615 case BuiltinType::OMPArrayShaping:
6616 case BuiltinType::OMPIterator:
6617 return true;
6618
6619 }
6620 llvm_unreachable("bad builtin type kind");
6621}
6622
6623bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6624 // Apply this processing to all the arguments at once instead of
6625 // dying at the first failure.
6626 bool hasInvalid = false;
6627 for (size_t i = 0, e = args.size(); i != e; i++) {
6628 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6629 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6630 if (result.isInvalid()) hasInvalid = true;
6631 else args[i] = result.get();
6632 }
6633 }
6634 return hasInvalid;
6635}
6636
6637/// If a builtin function has a pointer argument with no explicit address
6638/// space, then it should be able to accept a pointer to any address
6639/// space as input. In order to do this, we need to replace the
6640/// standard builtin declaration with one that uses the same address space
6641/// as the call.
6642///
6643/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6644/// it does not contain any pointer arguments without
6645/// an address space qualifer. Otherwise the rewritten
6646/// FunctionDecl is returned.
6647/// TODO: Handle pointer return types.
6648static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6649 FunctionDecl *FDecl,
6650 MultiExprArg ArgExprs) {
6651
6652 QualType DeclType = FDecl->getType();
6653 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6654
6655 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6656 ArgExprs.size() < FT->getNumParams())
6657 return nullptr;
6658
6659 bool NeedsNewDecl = false;
6660 unsigned i = 0;
6661 SmallVector<QualType, 8> OverloadParams;
6662
6663 {
6664 // The lvalue conversions in this loop are only for type resolution and
6665 // don't actually occur.
6666 EnterExpressionEvaluationContext Unevaluated(
6667 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6668 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6669
6670 for (QualType ParamType : FT->param_types()) {
6671
6672 // Convert array arguments to pointer to simplify type lookup.
6673 ExprResult ArgRes =
6674 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6675 if (ArgRes.isInvalid())
6676 return nullptr;
6677 Expr *Arg = ArgRes.get();
6678 QualType ArgType = Arg->getType();
6679 if (!ParamType->isPointerType() ||
6680 ParamType->getPointeeType().hasAddressSpace() ||
6681 !ArgType->isPointerType() ||
6682 !ArgType->getPointeeType().hasAddressSpace() ||
6683 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6684 OverloadParams.push_back(Elt: ParamType);
6685 continue;
6686 }
6687
6688 QualType PointeeType = ParamType->getPointeeType();
6689 NeedsNewDecl = true;
6690 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6691
6692 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6693 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6694 }
6695 }
6696
6697 if (!NeedsNewDecl)
6698 return nullptr;
6699
6700 FunctionProtoType::ExtProtoInfo EPI;
6701 EPI.Variadic = FT->isVariadic();
6702 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6703 Args: OverloadParams, EPI);
6704 DeclContext *Parent = FDecl->getParent();
6705 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6706 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6707 N: FDecl->getIdentifier(), T: OverloadTy,
6708 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6709 isInlineSpecified: false,
6710 /*hasPrototype=*/hasWrittenPrototype: true);
6711 SmallVector<ParmVarDecl*, 16> Params;
6712 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6713 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6714 QualType ParamType = FT->getParamType(i);
6715 ParmVarDecl *Parm =
6716 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6717 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6718 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6719 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6720 Params.push_back(Elt: Parm);
6721 }
6722 OverloadDecl->setParams(Params);
6723 // We cannot merge host/device attributes of redeclarations. They have to
6724 // be consistent when created.
6725 if (Sema->LangOpts.CUDA) {
6726 if (FDecl->hasAttr<CUDAHostAttr>())
6727 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6728 if (FDecl->hasAttr<CUDADeviceAttr>())
6729 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6730 }
6731 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6732 return OverloadDecl;
6733}
6734
6735static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6736 FunctionDecl *Callee,
6737 MultiExprArg ArgExprs) {
6738 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6739 // similar attributes) really don't like it when functions are called with an
6740 // invalid number of args.
6741 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6742 /*PartialOverloading=*/false) &&
6743 !Callee->isVariadic())
6744 return;
6745 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6746 return;
6747
6748 if (const EnableIfAttr *Attr =
6749 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6750 S.Diag(Loc: Fn->getBeginLoc(),
6751 DiagID: isa<CXXMethodDecl>(Val: Callee)
6752 ? diag::err_ovl_no_viable_member_function_in_call
6753 : diag::err_ovl_no_viable_function_in_call)
6754 << Callee << Callee->getSourceRange();
6755 S.Diag(Loc: Callee->getLocation(),
6756 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6757 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6758 return;
6759 }
6760}
6761
6762static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6763 const UnresolvedMemberExpr *const UME, Sema &S) {
6764
6765 const auto GetFunctionLevelDCIfCXXClass =
6766 [](Sema &S) -> const CXXRecordDecl * {
6767 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6768 if (!DC || !DC->getParent())
6769 return nullptr;
6770
6771 // If the call to some member function was made from within a member
6772 // function body 'M' return return 'M's parent.
6773 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6774 return MD->getParent()->getCanonicalDecl();
6775 // else the call was made from within a default member initializer of a
6776 // class, so return the class.
6777 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6778 return RD->getCanonicalDecl();
6779 return nullptr;
6780 };
6781 // If our DeclContext is neither a member function nor a class (in the
6782 // case of a lambda in a default member initializer), we can't have an
6783 // enclosing 'this'.
6784
6785 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6786 if (!CurParentClass)
6787 return false;
6788
6789 // The naming class for implicit member functions call is the class in which
6790 // name lookup starts.
6791 const CXXRecordDecl *const NamingClass =
6792 UME->getNamingClass()->getCanonicalDecl();
6793 assert(NamingClass && "Must have naming class even for implicit access");
6794
6795 // If the unresolved member functions were found in a 'naming class' that is
6796 // related (either the same or derived from) to the class that contains the
6797 // member function that itself contained the implicit member access.
6798
6799 return CurParentClass == NamingClass ||
6800 CurParentClass->isDerivedFrom(Base: NamingClass);
6801}
6802
6803static void
6804tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6805 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6806
6807 if (!UME)
6808 return;
6809
6810 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6811 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6812 // already been captured, or if this is an implicit member function call (if
6813 // it isn't, an attempt to capture 'this' should already have been made).
6814 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6815 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6816 return;
6817
6818 // Check if the naming class in which the unresolved members were found is
6819 // related (same as or is a base of) to the enclosing class.
6820
6821 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6822 return;
6823
6824
6825 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6826 // If the enclosing function is not dependent, then this lambda is
6827 // capture ready, so if we can capture this, do so.
6828 if (!EnclosingFunctionCtx->isDependentContext()) {
6829 // If the current lambda and all enclosing lambdas can capture 'this' -
6830 // then go ahead and capture 'this' (since our unresolved overload set
6831 // contains at least one non-static member function).
6832 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6833 S.CheckCXXThisCapture(Loc: CallLoc);
6834 } else if (S.CurContext->isDependentContext()) {
6835 // ... since this is an implicit member reference, that might potentially
6836 // involve a 'this' capture, mark 'this' for potential capture in
6837 // enclosing lambdas.
6838 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6839 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6840 }
6841}
6842
6843// Once a call is fully resolved, warn for unqualified calls to specific
6844// C++ standard functions, like move and forward.
6845static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6846 const CallExpr *Call) {
6847 // We are only checking unary move and forward so exit early here.
6848 if (Call->getNumArgs() != 1)
6849 return;
6850
6851 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6852 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6853 return;
6854 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6855 if (!DRE || !DRE->getLocation().isValid())
6856 return;
6857
6858 if (DRE->getQualifier())
6859 return;
6860
6861 const FunctionDecl *FD = Call->getDirectCallee();
6862 if (!FD)
6863 return;
6864
6865 // Only warn for some functions deemed more frequent or problematic.
6866 unsigned BuiltinID = FD->getBuiltinID();
6867 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6868 return;
6869
6870 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6871 << FD->getQualifiedNameAsString()
6872 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6873}
6874
6875ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6876 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6877 Expr *ExecConfig) {
6878 ExprResult Call =
6879 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6880 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6881 if (Call.isInvalid())
6882 return Call;
6883
6884 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6885 // language modes.
6886 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6887 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6888 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6889 << ULE->getName();
6890 }
6891
6892 if (LangOpts.OpenMP)
6893 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6894 ExecConfig);
6895 if (LangOpts.CPlusPlus) {
6896 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6897 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6898
6899 // If we previously found that the id-expression of this call refers to a
6900 // consteval function but the call is dependent, we should not treat is an
6901 // an invalid immediate call.
6902 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6903 DRE && Call.get()->isValueDependent()) {
6904 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6905 }
6906 }
6907 return Call;
6908}
6909
6910// Any type that could be used to form a callable expression
6911static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6912 QualType T = E->getType();
6913 if (T->isDependentType())
6914 return true;
6915
6916 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6917 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6918 T->isFunctionType() || T->isFunctionReferenceType() ||
6919 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6920 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6921 return true;
6922
6923 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6924 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6925}
6926
6927ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6928 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6929 Expr *ExecConfig, bool IsExecConfig,
6930 bool AllowRecovery) {
6931 // Since this might be a postfix expression, get rid of ParenListExprs.
6932 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6933 if (Result.isInvalid()) return ExprError();
6934 Fn = Result.get();
6935
6936 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6937 // later, when we check boolean conditions, for now we merely forward it
6938 // without any additional checking.
6939 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6940 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6941 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6942
6943 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6944 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6945 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6946 return CallExpr::Create(
6947 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6948 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6949 }
6950 }
6951
6952 if (CheckArgsForPlaceholders(args: ArgExprs))
6953 return ExprError();
6954
6955 // The result of __builtin_counted_by_ref cannot be used as a function
6956 // argument. It allows leaking and modification of bounds safety information.
6957 for (const Expr *Arg : ArgExprs)
6958 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6959 K: BuiltinCountedByRefKind::FunctionArg))
6960 return ExprError();
6961
6962 if (getLangOpts().CPlusPlus) {
6963 // If this is a pseudo-destructor expression, build the call immediately.
6964 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6965 if (!ArgExprs.empty()) {
6966 // Pseudo-destructor calls should not have any arguments.
6967 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6968 << FixItHint::CreateRemoval(
6969 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6970 ArgExprs.back()->getEndLoc()));
6971 }
6972
6973 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6974 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6975 }
6976 if (Fn->getType() == Context.PseudoObjectTy) {
6977 ExprResult result = CheckPlaceholderExpr(E: Fn);
6978 if (result.isInvalid()) return ExprError();
6979 Fn = result.get();
6980 }
6981
6982 // Determine whether this is a dependent call inside a C++ template,
6983 // in which case we won't do any semantic analysis now.
6984 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6985 if (ExecConfig) {
6986 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6987 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6988 Ty: Context.DependentTy, VK: VK_PRValue,
6989 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6990 } else {
6991
6992 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6993 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6994 CallLoc: Fn->getBeginLoc());
6995
6996 // If the type of the function itself is not dependent
6997 // check that it is a reasonable as a function, as type deduction
6998 // later assume the CallExpr has a sensible TYPE.
6999 if (!MayBeFunctionType(Context, E: Fn))
7000 return ExprError(
7001 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7002 << Fn->getType() << Fn->getSourceRange());
7003
7004 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7005 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7006 }
7007 }
7008
7009 // Determine whether this is a call to an object (C++ [over.call.object]).
7010 if (Fn->getType()->isRecordType())
7011 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
7012 RParenLoc);
7013
7014 if (Fn->getType() == Context.UnknownAnyTy) {
7015 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7016 if (result.isInvalid()) return ExprError();
7017 Fn = result.get();
7018 }
7019
7020 if (Fn->getType() == Context.BoundMemberTy) {
7021 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7022 RParenLoc, ExecConfig, IsExecConfig,
7023 AllowRecovery);
7024 }
7025 }
7026
7027 // Check for overloaded calls. This can happen even in C due to extensions.
7028 if (Fn->getType() == Context.OverloadTy) {
7029 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
7030
7031 // We aren't supposed to apply this logic if there's an '&' involved.
7032 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
7033 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
7034 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7035 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7036 OverloadExpr *ovl = find.Expression;
7037 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
7038 return BuildOverloadedCallExpr(
7039 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
7040 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
7041 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7042 RParenLoc, ExecConfig, IsExecConfig,
7043 AllowRecovery);
7044 }
7045 }
7046
7047 // If we're directly calling a function, get the appropriate declaration.
7048 if (Fn->getType() == Context.UnknownAnyTy) {
7049 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7050 if (result.isInvalid()) return ExprError();
7051 Fn = result.get();
7052 }
7053
7054 Expr *NakedFn = Fn->IgnoreParens();
7055
7056 bool CallingNDeclIndirectly = false;
7057 NamedDecl *NDecl = nullptr;
7058 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
7059 if (UnOp->getOpcode() == UO_AddrOf) {
7060 CallingNDeclIndirectly = true;
7061 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7062 }
7063 }
7064
7065 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
7066 NDecl = DRE->getDecl();
7067
7068 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
7069 if (FDecl && FDecl->getBuiltinID()) {
7070 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7071 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7072 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
7073 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
7074 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
7075 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7076 }
7077 }
7078
7079 // Rewrite the function decl for this builtin by replacing parameters
7080 // with no explicit address space with the address space of the arguments
7081 // in ArgExprs.
7082 if ((FDecl =
7083 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
7084 NDecl = FDecl;
7085 Fn = DeclRefExpr::Create(
7086 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
7087 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
7088 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
7089 }
7090 }
7091 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
7092 NDecl = ME->getMemberDecl();
7093
7094 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
7095 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7096 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
7097 return ExprError();
7098
7099 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
7100
7101 // If this expression is a call to a builtin function in HIP compilation,
7102 // allow a pointer-type argument to default address space to be passed as a
7103 // pointer-type parameter to a non-default address space. If Arg is declared
7104 // in the default address space and Param is declared in a non-default
7105 // address space, perform an implicit address space cast to the parameter
7106 // type.
7107 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7108 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7109 ++Idx) {
7110 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7111 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7112 !ArgExprs[Idx]->getType()->isPointerType())
7113 continue;
7114
7115 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7116 auto ArgTy = ArgExprs[Idx]->getType();
7117 auto ArgPtTy = ArgTy->getPointeeType();
7118 auto ArgAS = ArgPtTy.getAddressSpace();
7119
7120 // Add address space cast if target address spaces are different
7121 bool NeedImplicitASC =
7122 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7123 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7124 // or from specific AS which has target AS matching that of Param.
7125 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7126 if (!NeedImplicitASC)
7127 continue;
7128
7129 // First, ensure that the Arg is an RValue.
7130 if (ArgExprs[Idx]->isGLValue()) {
7131 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7132 if (Res.isInvalid())
7133 return ExprError();
7134 ArgExprs[Idx] = Res.get();
7135 }
7136
7137 // Construct a new arg type with address space of Param
7138 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7139 ArgPtQuals.setAddressSpace(ParamAS);
7140 auto NewArgPtTy =
7141 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7142 auto NewArgTy =
7143 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7144 Qs: ArgTy.getQualifiers());
7145
7146 // Finally perform an implicit address space cast
7147 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7148 CK: CK_AddressSpaceConversion)
7149 .get();
7150 }
7151 }
7152 }
7153
7154 if (Context.isDependenceAllowed() &&
7155 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7156 assert(!getLangOpts().CPlusPlus);
7157 assert((Fn->containsErrors() ||
7158 llvm::any_of(ArgExprs,
7159 [](clang::Expr *E) { return E->containsErrors(); })) &&
7160 "should only occur in error-recovery path.");
7161 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7162 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7163 }
7164 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7165 Config: ExecConfig, IsExecConfig);
7166}
7167
7168Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7169 MultiExprArg CallArgs) {
7170 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7171 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7172 Sema::LookupOrdinaryName);
7173 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7174
7175 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7176 assert(BuiltInDecl && "failed to find builtin declaration");
7177
7178 ExprResult DeclRef =
7179 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7180 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7181
7182 ExprResult Call =
7183 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7184
7185 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7186 return Call.get();
7187}
7188
7189ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7190 SourceLocation BuiltinLoc,
7191 SourceLocation RParenLoc) {
7192 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7193 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7194}
7195
7196ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7197 SourceLocation BuiltinLoc,
7198 SourceLocation RParenLoc) {
7199 ExprValueKind VK = VK_PRValue;
7200 ExprObjectKind OK = OK_Ordinary;
7201 QualType SrcTy = E->getType();
7202 if (!SrcTy->isDependentType() &&
7203 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7204 return ExprError(
7205 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7206 << DestTy << SrcTy << E->getSourceRange());
7207 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7208}
7209
7210ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7211 SourceLocation BuiltinLoc,
7212 SourceLocation RParenLoc) {
7213 TypeSourceInfo *TInfo;
7214 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7215 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7216}
7217
7218ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7219 SourceLocation LParenLoc,
7220 ArrayRef<Expr *> Args,
7221 SourceLocation RParenLoc, Expr *Config,
7222 bool IsExecConfig, ADLCallKind UsesADL) {
7223 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7224 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7225
7226 auto IsSJLJ = [&] {
7227 switch (BuiltinID) {
7228 case Builtin::BI__builtin_longjmp:
7229 case Builtin::BI__builtin_setjmp:
7230 case Builtin::BI__sigsetjmp:
7231 case Builtin::BI_longjmp:
7232 case Builtin::BI_setjmp:
7233 case Builtin::BIlongjmp:
7234 case Builtin::BIsetjmp:
7235 case Builtin::BIsiglongjmp:
7236 case Builtin::BIsigsetjmp:
7237 return true;
7238 default:
7239 return false;
7240 }
7241 };
7242
7243 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7244 if (!CurrentDefer.empty() && IsSJLJ()) {
7245 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7246 // for more than just blocks (e.g. lambdas, nested classes...).
7247 Scope *DeferParent = CurrentDefer.back().first;
7248 Scope *Block = CurScope->getBlockParent();
7249 if (DeferParent->Contains(rhs: *CurScope) &&
7250 (!Block || !DeferParent->Contains(rhs: *Block)))
7251 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7252 }
7253
7254 // Functions with 'interrupt' attribute cannot be called directly.
7255 if (FDecl) {
7256 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7257 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7258 return ExprError();
7259 }
7260 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7261 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7262 return ExprError();
7263 }
7264 }
7265
7266 // X86 interrupt handlers may only call routines with attribute
7267 // no_caller_saved_registers since there is no efficient way to
7268 // save and restore the non-GPR state.
7269 if (auto *Caller = getCurFunctionDecl()) {
7270 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7271 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7272 const TargetInfo &TI = Context.getTargetInfo();
7273 bool HasNonGPRRegisters =
7274 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7275 if (HasNonGPRRegisters &&
7276 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7277 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7278 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7279 if (FDecl)
7280 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7281 }
7282 }
7283 }
7284
7285 // Extract the return type from the builtin function pointer type.
7286 QualType ResultTy;
7287 if (BuiltinID)
7288 ResultTy = FDecl->getCallResultType();
7289 else
7290 ResultTy = Context.BoolTy;
7291
7292 // Promote the function operand.
7293 // We special-case function promotion here because we only allow promoting
7294 // builtin functions to function pointers in the callee of a call.
7295 ExprResult Result;
7296 if (BuiltinID &&
7297 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7298 // FIXME Several builtins still have setType in
7299 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7300 // Builtins.td to ensure they are correct before removing setType calls.
7301 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7302 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7303 } else
7304 Result = CallExprUnaryConversions(E: Fn);
7305 if (Result.isInvalid())
7306 return ExprError();
7307 Fn = Result.get();
7308
7309 // Check for a valid function type, but only if it is not a builtin which
7310 // requires custom type checking. These will be handled by
7311 // CheckBuiltinFunctionCall below just after creation of the call expression.
7312 const FunctionType *FuncT = nullptr;
7313 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7314 retry:
7315 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7316 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7317 // have type pointer to function".
7318 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7319 if (!FuncT)
7320 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7321 << Fn->getType() << Fn->getSourceRange());
7322 } else if (const BlockPointerType *BPT =
7323 Fn->getType()->getAs<BlockPointerType>()) {
7324 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7325 } else {
7326 // Handle calls to expressions of unknown-any type.
7327 if (Fn->getType() == Context.UnknownAnyTy) {
7328 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7329 if (rewrite.isInvalid())
7330 return ExprError();
7331 Fn = rewrite.get();
7332 goto retry;
7333 }
7334
7335 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7336 << Fn->getType() << Fn->getSourceRange());
7337 }
7338 }
7339
7340 // Get the number of parameters in the function prototype, if any.
7341 // We will allocate space for max(Args.size(), NumParams) arguments
7342 // in the call expression.
7343 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7344 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7345
7346 CallExpr *TheCall;
7347 if (Config) {
7348 assert(UsesADL == ADLCallKind::NotADL &&
7349 "CUDAKernelCallExpr should not use ADL");
7350 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7351 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7352 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7353 } else {
7354 TheCall =
7355 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7356 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7357 }
7358
7359 // Bail out early if calling a builtin with custom type checking.
7360 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7361 // For HLSL builtin aliases, the call was resolved via overload resolution
7362 // which may have selected a conversion sequence (e.g., vector-to-scalar
7363 // truncation). Convert arguments to match the declared prototype before
7364 // the custom type checker runs, otherwise the builtin will operate on
7365 // the unconverted argument types.
7366 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7367 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7368 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7369 IsExecConfig))
7370 return ExprError();
7371 }
7372 }
7373 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7374 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7375 E = CheckForImmediateInvocation(E, Decl: FDecl);
7376 return E;
7377 }
7378
7379 if (getLangOpts().CUDA) {
7380 if (Config) {
7381 // CUDA: Kernel calls must be to global functions
7382 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7383 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7384 << FDecl << Fn->getSourceRange());
7385
7386 // CUDA: Kernel function must have 'void' return type
7387 if (!FuncT->getReturnType()->isVoidType() &&
7388 !FuncT->getReturnType()->getAs<AutoType>() &&
7389 !FuncT->getReturnType()->isInstantiationDependentType())
7390 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7391 << Fn->getType() << Fn->getSourceRange());
7392 } else {
7393 // CUDA: Calls to global functions must be configured
7394 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7395 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7396 << FDecl << Fn->getSourceRange());
7397 }
7398 }
7399
7400 // Check for a valid return type
7401 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7402 FD: FDecl))
7403 return ExprError();
7404
7405 // We know the result type of the call, set it.
7406 TheCall->setType(FuncT->getCallResultType(Context));
7407 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7408
7409 // WebAssembly tables can't be used as arguments.
7410 if (Context.getTargetInfo().getTriple().isWasm()) {
7411 for (const Expr *Arg : Args) {
7412 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7413 return ExprError(Diag(Loc: Arg->getExprLoc(),
7414 DiagID: diag::err_wasm_table_as_function_parameter));
7415 }
7416 }
7417 }
7418
7419 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7420 // replaces sampler DeclRefExprs with their integer initializers.
7421 if (getLangOpts().OpenCL && FDecl) {
7422 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7423 }
7424
7425 if (Proto) {
7426 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7427 IsExecConfig))
7428 return ExprError();
7429 } else {
7430 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7431
7432 if (FDecl) {
7433 // Check if we have too few/too many template arguments, based
7434 // on our knowledge of the function definition.
7435 const FunctionDecl *Def = nullptr;
7436 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7437 Proto = Def->getType()->getAs<FunctionProtoType>();
7438 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7439 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7440 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7441 }
7442
7443 // If the function we're calling isn't a function prototype, but we have
7444 // a function prototype from a prior declaratiom, use that prototype.
7445 if (!FDecl->hasPrototype())
7446 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7447 }
7448
7449 // If we still haven't found a prototype to use but there are arguments to
7450 // the call, diagnose this as calling a function without a prototype.
7451 // However, if we found a function declaration, check to see if
7452 // -Wdeprecated-non-prototype was disabled where the function was declared.
7453 // If so, we will silence the diagnostic here on the assumption that this
7454 // interface is intentional and the user knows what they're doing. We will
7455 // also silence the diagnostic if there is a function declaration but it
7456 // was implicitly defined (the user already gets diagnostics about the
7457 // creation of the implicit function declaration, so the additional warning
7458 // is not helpful).
7459 if (!Proto && !Args.empty() &&
7460 (!FDecl || (!FDecl->isImplicit() &&
7461 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7462 Loc: FDecl->getLocation()))))
7463 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7464 << (FDecl != nullptr) << FDecl;
7465
7466 // Promote the arguments (C99 6.5.2.2p6).
7467 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7468 Expr *Arg = Args[i];
7469
7470 if (Proto && i < Proto->getNumParams()) {
7471 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7472 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7473 ExprResult ArgE =
7474 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7475 if (ArgE.isInvalid())
7476 return true;
7477
7478 Arg = ArgE.getAs<Expr>();
7479
7480 } else {
7481 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7482
7483 if (ArgE.isInvalid())
7484 return true;
7485
7486 Arg = ArgE.getAs<Expr>();
7487 }
7488
7489 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7490 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7491 return ExprError();
7492
7493 TheCall->setArg(Arg: i, ArgExpr: Arg);
7494 }
7495 TheCall->computeDependence();
7496 }
7497
7498 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7499 if (Method->isImplicitObjectMemberFunction())
7500 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7501 << Fn->getSourceRange() << 0);
7502
7503 // Check for sentinels
7504 if (NDecl)
7505 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7506
7507 // Warn for unions passing across security boundary (CMSE).
7508 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7509 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7510 if (const auto *RT =
7511 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7512 if (RT->getDecl()->isOrContainsUnion())
7513 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7514 << 0 << i;
7515 }
7516 }
7517 }
7518
7519 // Do special checking on direct calls to functions.
7520 if (FDecl) {
7521 if (CheckFunctionCall(FDecl, TheCall, Proto))
7522 return ExprError();
7523
7524 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7525 checkFortifiedLibcArgument(FD: FDecl, TheCall);
7526
7527 if (BuiltinID)
7528 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7529 } else if (NDecl) {
7530 if (CheckPointerCall(NDecl, TheCall, Proto))
7531 return ExprError();
7532 } else {
7533 if (CheckOtherCall(TheCall, Proto))
7534 return ExprError();
7535 }
7536
7537 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7538}
7539
7540ExprResult
7541Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7542 SourceLocation RParenLoc, Expr *InitExpr) {
7543 assert(Ty && "ActOnCompoundLiteral(): missing type");
7544 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7545
7546 TypeSourceInfo *TInfo;
7547 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7548 if (!TInfo)
7549 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7550
7551 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7552}
7553
7554ExprResult
7555Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7556 SourceLocation RParenLoc, Expr *LiteralExpr) {
7557 QualType literalType = TInfo->getType();
7558
7559 if (literalType->isArrayType()) {
7560 if (RequireCompleteSizedType(
7561 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7562 DiagID: diag::err_array_incomplete_or_sizeless_type,
7563 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7564 return ExprError();
7565 if (literalType->isVariableArrayType()) {
7566 // C23 6.7.10p4: An entity of variable length array type shall not be
7567 // initialized except by an empty initializer.
7568 //
7569 // The C extension warnings are issued from ParseBraceInitializer() and
7570 // do not need to be issued here. However, we continue to issue an error
7571 // in the case there are initializers or we are compiling C++. We allow
7572 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7573 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7574 // FIXME: should we allow this construct in C++ when it makes sense to do
7575 // so?
7576 //
7577 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7578 // shall specify an object type or an array of unknown size, but not a
7579 // variable length array type. This seems odd, as it allows 'int a[size] =
7580 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7581 // says, this is what's implemented here for C (except for the extension
7582 // that permits constant foldable size arrays)
7583
7584 auto diagID = LangOpts.CPlusPlus
7585 ? diag::err_variable_object_no_init
7586 : diag::err_compound_literal_with_vla_type;
7587 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7588 FailedFoldDiagID: diagID))
7589 return ExprError();
7590 }
7591 } else if (!literalType->isDependentType() &&
7592 RequireCompleteType(Loc: LParenLoc, T: literalType,
7593 DiagID: diag::err_typecheck_decl_incomplete_type,
7594 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7595 return ExprError();
7596
7597 InitializedEntity Entity
7598 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7599 InitializationKind Kind
7600 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7601 TypeRange: SourceRange(LParenLoc, RParenLoc),
7602 /*InitList=*/true);
7603 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7604 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7605 ResultType: &literalType);
7606 if (Result.isInvalid())
7607 return ExprError();
7608 LiteralExpr = Result.get();
7609
7610 // We treat the compound literal as being at file scope if it's not in a
7611 // function or method body, or within the function's prototype scope. This
7612 // means the following compound literal is not at file scope:
7613 // void func(char *para[(int [1]){ 0 }[0]);
7614 const Scope *S = getCurScope();
7615 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7616 !S->isInCFunctionScope() &&
7617 (!S || !S->isFunctionPrototypeScope());
7618
7619 // In C, compound literals are l-values for some reason.
7620 // For GCC compatibility, in C++, file-scope array compound literals with
7621 // constant initializers are also l-values, and compound literals are
7622 // otherwise prvalues.
7623 //
7624 // (GCC also treats C++ list-initialized file-scope array prvalues with
7625 // constant initializers as l-values, but that's non-conforming, so we don't
7626 // follow it there.)
7627 //
7628 // FIXME: It would be better to handle the lvalue cases as materializing and
7629 // lifetime-extending a temporary object, but our materialized temporaries
7630 // representation only supports lifetime extension from a variable, not "out
7631 // of thin air".
7632 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7633 // is bound to the result of applying array-to-pointer decay to the compound
7634 // literal.
7635 // FIXME: GCC supports compound literals of reference type, which should
7636 // obviously have a value kind derived from the kind of reference involved.
7637 ExprValueKind VK =
7638 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7639 ? VK_PRValue
7640 : VK_LValue;
7641
7642 // C99 6.5.2.5
7643 // "If the compound literal occurs outside the body of a function, the
7644 // initializer list shall consist of constant expressions."
7645 if (IsFileScope)
7646 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7647 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7648 Expr *Init = ILE->getInit(Init: i);
7649 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7650 !Init->isConstantInitializer(Ctx&: Context)) {
7651 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7652 << Init->getSourceBitField();
7653 return ExprError();
7654 }
7655
7656 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7657 }
7658
7659 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7660 LiteralExpr, IsFileScope);
7661 if (IsFileScope) {
7662 if (!LiteralExpr->isTypeDependent() &&
7663 !LiteralExpr->isValueDependent() &&
7664 !literalType->isDependentType()) // C99 6.5.2.5p3
7665 if (CheckForConstantInitializer(Init: LiteralExpr))
7666 return ExprError();
7667 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7668 literalType.getAddressSpace() != LangAS::Default) {
7669 // Embedded-C extensions to C99 6.5.2.5:
7670 // "If the compound literal occurs inside the body of a function, the
7671 // type name shall not be qualified by an address-space qualifier."
7672 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7673 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7674 return ExprError();
7675 }
7676
7677 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7678 // Compound literals that have automatic storage duration are destroyed at
7679 // the end of the scope in C; in C++, they're just temporaries.
7680
7681 // Emit diagnostics if it is or contains a C union type that is non-trivial
7682 // to destruct.
7683 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7684 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7685 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7686 NonTrivialKind: NTCUK_Destruct);
7687
7688 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7689 Cleanup.setExprNeedsCleanups(true);
7690 ExprCleanupObjects.push_back(Elt: E);
7691 if (literalType.isDestructedType()) {
7692 getCurFunction()->setHasBranchProtectedScope();
7693 }
7694 }
7695
7696 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7697 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7698 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7699 Loc: E->getInitializer()->getExprLoc());
7700
7701 return MaybeBindToTemporary(E);
7702}
7703
7704ExprResult
7705Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7706 SourceLocation RBraceLoc) {
7707 // Only produce each kind of designated initialization diagnostic once.
7708 SourceLocation FirstDesignator;
7709 bool DiagnosedArrayDesignator = false;
7710 bool DiagnosedNestedDesignator = false;
7711 bool DiagnosedMixedDesignator = false;
7712
7713 // Check that any designated initializers are syntactically valid in the
7714 // current language mode.
7715 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7716 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7717 if (FirstDesignator.isInvalid())
7718 FirstDesignator = DIE->getBeginLoc();
7719
7720 if (!getLangOpts().CPlusPlus)
7721 break;
7722
7723 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7724 DiagnosedNestedDesignator = true;
7725 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7726 << DIE->getDesignatorsSourceRange();
7727 }
7728
7729 for (auto &Desig : DIE->designators()) {
7730 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7731 DiagnosedArrayDesignator = true;
7732 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7733 << Desig.getSourceRange();
7734 }
7735 }
7736
7737 if (!DiagnosedMixedDesignator &&
7738 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7739 DiagnosedMixedDesignator = true;
7740 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7741 << DIE->getSourceRange();
7742 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7743 << InitArgList[0]->getSourceRange();
7744 }
7745 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7746 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7747 DiagnosedMixedDesignator = true;
7748 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7749 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7750 << DIE->getSourceRange();
7751 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7752 << InitArgList[I]->getSourceRange();
7753 }
7754 }
7755
7756 if (FirstDesignator.isValid()) {
7757 // Only diagnose designated initiaization as a C++20 extension if we didn't
7758 // already diagnose use of (non-C++20) C99 designator syntax.
7759 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7760 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7761 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7762 ? diag::warn_cxx17_compat_designated_init
7763 : diag::ext_cxx_designated_init);
7764 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7765 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7766 }
7767 }
7768
7769 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7770}
7771
7772ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7773 MultiExprArg InitArgList,
7774 SourceLocation RBraceLoc, bool IsExplicit) {
7775 // Semantic analysis for initializers is done by ActOnDeclarator() and
7776 // CheckInitializer() - it requires knowledge of the object being initialized.
7777
7778 // Immediately handle non-overload placeholders. Overloads can be
7779 // resolved contextually, but everything else here can't.
7780 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7781 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7782 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7783
7784 // Ignore failures; dropping the entire initializer list because
7785 // of one failure would be terrible for indexing/etc.
7786 if (result.isInvalid()) continue;
7787
7788 InitArgList[I] = result.get();
7789 }
7790 }
7791
7792 InitListExpr *E = new (Context)
7793 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7794 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7795 return E;
7796}
7797
7798void Sema::maybeExtendBlockObject(ExprResult &E) {
7799 assert(E.get()->getType()->isBlockPointerType());
7800 assert(E.get()->isPRValue());
7801
7802 // Only do this in an r-value context.
7803 if (!getLangOpts().ObjCAutoRefCount) return;
7804
7805 E = ImplicitCastExpr::Create(
7806 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7807 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7808 Cleanup.setExprNeedsCleanups(true);
7809}
7810
7811CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7812 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7813 // Also, callers should have filtered out the invalid cases with
7814 // pointers. Everything else should be possible.
7815
7816 QualType SrcTy = Src.get()->getType();
7817 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7818 return CK_NoOp;
7819
7820 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7821 case Type::STK_MemberPointer:
7822 llvm_unreachable("member pointer type in C");
7823
7824 case Type::STK_CPointer:
7825 case Type::STK_BlockPointer:
7826 case Type::STK_ObjCObjectPointer:
7827 switch (DestTy->getScalarTypeKind()) {
7828 case Type::STK_CPointer: {
7829 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7830 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7831 if (SrcAS != DestAS)
7832 return CK_AddressSpaceConversion;
7833 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7834 return CK_NoOp;
7835 return CK_BitCast;
7836 }
7837 case Type::STK_BlockPointer:
7838 return (SrcKind == Type::STK_BlockPointer
7839 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7840 case Type::STK_ObjCObjectPointer:
7841 if (SrcKind == Type::STK_ObjCObjectPointer)
7842 return CK_BitCast;
7843 if (SrcKind == Type::STK_CPointer)
7844 return CK_CPointerToObjCPointerCast;
7845 maybeExtendBlockObject(E&: Src);
7846 return CK_BlockPointerToObjCPointerCast;
7847 case Type::STK_Bool:
7848 return CK_PointerToBoolean;
7849 case Type::STK_Integral:
7850 return CK_PointerToIntegral;
7851 case Type::STK_Floating:
7852 case Type::STK_FloatingComplex:
7853 case Type::STK_IntegralComplex:
7854 case Type::STK_MemberPointer:
7855 case Type::STK_FixedPoint:
7856 llvm_unreachable("illegal cast from pointer");
7857 }
7858 llvm_unreachable("Should have returned before this");
7859
7860 case Type::STK_FixedPoint:
7861 switch (DestTy->getScalarTypeKind()) {
7862 case Type::STK_FixedPoint:
7863 return CK_FixedPointCast;
7864 case Type::STK_Bool:
7865 return CK_FixedPointToBoolean;
7866 case Type::STK_Integral:
7867 return CK_FixedPointToIntegral;
7868 case Type::STK_Floating:
7869 return CK_FixedPointToFloating;
7870 case Type::STK_IntegralComplex:
7871 case Type::STK_FloatingComplex:
7872 Diag(Loc: Src.get()->getExprLoc(),
7873 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7874 << DestTy;
7875 return CK_IntegralCast;
7876 case Type::STK_CPointer:
7877 case Type::STK_ObjCObjectPointer:
7878 case Type::STK_BlockPointer:
7879 case Type::STK_MemberPointer:
7880 llvm_unreachable("illegal cast to pointer type");
7881 }
7882 llvm_unreachable("Should have returned before this");
7883
7884 case Type::STK_Bool: // casting from bool is like casting from an integer
7885 case Type::STK_Integral:
7886 switch (DestTy->getScalarTypeKind()) {
7887 case Type::STK_CPointer:
7888 case Type::STK_ObjCObjectPointer:
7889 case Type::STK_BlockPointer:
7890 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7891 NPC: Expr::NPC_ValueDependentIsNull))
7892 return CK_NullToPointer;
7893 return CK_IntegralToPointer;
7894 case Type::STK_Bool:
7895 return CK_IntegralToBoolean;
7896 case Type::STK_Integral:
7897 return CK_IntegralCast;
7898 case Type::STK_Floating:
7899 return CK_IntegralToFloating;
7900 case Type::STK_IntegralComplex:
7901 Src = ImpCastExprToType(E: Src.get(),
7902 Type: DestTy->castAs<ComplexType>()->getElementType(),
7903 CK: CK_IntegralCast);
7904 return CK_IntegralRealToComplex;
7905 case Type::STK_FloatingComplex:
7906 Src = ImpCastExprToType(E: Src.get(),
7907 Type: DestTy->castAs<ComplexType>()->getElementType(),
7908 CK: CK_IntegralToFloating);
7909 return CK_FloatingRealToComplex;
7910 case Type::STK_MemberPointer:
7911 llvm_unreachable("member pointer type in C");
7912 case Type::STK_FixedPoint:
7913 return CK_IntegralToFixedPoint;
7914 }
7915 llvm_unreachable("Should have returned before this");
7916
7917 case Type::STK_Floating:
7918 switch (DestTy->getScalarTypeKind()) {
7919 case Type::STK_Floating:
7920 return CK_FloatingCast;
7921 case Type::STK_Bool:
7922 return CK_FloatingToBoolean;
7923 case Type::STK_Integral:
7924 return CK_FloatingToIntegral;
7925 case Type::STK_FloatingComplex:
7926 Src = ImpCastExprToType(E: Src.get(),
7927 Type: DestTy->castAs<ComplexType>()->getElementType(),
7928 CK: CK_FloatingCast);
7929 return CK_FloatingRealToComplex;
7930 case Type::STK_IntegralComplex:
7931 Src = ImpCastExprToType(E: Src.get(),
7932 Type: DestTy->castAs<ComplexType>()->getElementType(),
7933 CK: CK_FloatingToIntegral);
7934 return CK_IntegralRealToComplex;
7935 case Type::STK_CPointer:
7936 case Type::STK_ObjCObjectPointer:
7937 case Type::STK_BlockPointer:
7938 llvm_unreachable("valid float->pointer cast?");
7939 case Type::STK_MemberPointer:
7940 llvm_unreachable("member pointer type in C");
7941 case Type::STK_FixedPoint:
7942 return CK_FloatingToFixedPoint;
7943 }
7944 llvm_unreachable("Should have returned before this");
7945
7946 case Type::STK_FloatingComplex:
7947 switch (DestTy->getScalarTypeKind()) {
7948 case Type::STK_FloatingComplex:
7949 return CK_FloatingComplexCast;
7950 case Type::STK_IntegralComplex:
7951 return CK_FloatingComplexToIntegralComplex;
7952 case Type::STK_Floating: {
7953 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7954 if (Context.hasSameType(T1: ET, T2: DestTy))
7955 return CK_FloatingComplexToReal;
7956 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7957 return CK_FloatingCast;
7958 }
7959 case Type::STK_Bool:
7960 return CK_FloatingComplexToBoolean;
7961 case Type::STK_Integral:
7962 Src = ImpCastExprToType(E: Src.get(),
7963 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7964 CK: CK_FloatingComplexToReal);
7965 return CK_FloatingToIntegral;
7966 case Type::STK_CPointer:
7967 case Type::STK_ObjCObjectPointer:
7968 case Type::STK_BlockPointer:
7969 llvm_unreachable("valid complex float->pointer cast?");
7970 case Type::STK_MemberPointer:
7971 llvm_unreachable("member pointer type in C");
7972 case Type::STK_FixedPoint:
7973 Diag(Loc: Src.get()->getExprLoc(),
7974 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7975 << SrcTy;
7976 return CK_IntegralCast;
7977 }
7978 llvm_unreachable("Should have returned before this");
7979
7980 case Type::STK_IntegralComplex:
7981 switch (DestTy->getScalarTypeKind()) {
7982 case Type::STK_FloatingComplex:
7983 return CK_IntegralComplexToFloatingComplex;
7984 case Type::STK_IntegralComplex:
7985 return CK_IntegralComplexCast;
7986 case Type::STK_Integral: {
7987 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7988 if (Context.hasSameType(T1: ET, T2: DestTy))
7989 return CK_IntegralComplexToReal;
7990 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7991 return CK_IntegralCast;
7992 }
7993 case Type::STK_Bool:
7994 return CK_IntegralComplexToBoolean;
7995 case Type::STK_Floating:
7996 Src = ImpCastExprToType(E: Src.get(),
7997 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7998 CK: CK_IntegralComplexToReal);
7999 return CK_IntegralToFloating;
8000 case Type::STK_CPointer:
8001 case Type::STK_ObjCObjectPointer:
8002 case Type::STK_BlockPointer:
8003 llvm_unreachable("valid complex int->pointer cast?");
8004 case Type::STK_MemberPointer:
8005 llvm_unreachable("member pointer type in C");
8006 case Type::STK_FixedPoint:
8007 Diag(Loc: Src.get()->getExprLoc(),
8008 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8009 << SrcTy;
8010 return CK_IntegralCast;
8011 }
8012 llvm_unreachable("Should have returned before this");
8013 }
8014
8015 llvm_unreachable("Unhandled scalar cast");
8016}
8017
8018static bool breakDownVectorType(QualType type, uint64_t &len,
8019 QualType &eltType) {
8020 // Vectors are simple.
8021 if (const VectorType *vecType = type->getAs<VectorType>()) {
8022 len = vecType->getNumElements();
8023 eltType = vecType->getElementType();
8024 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8025 return true;
8026 }
8027
8028 // We allow lax conversion to and from non-vector types, but only if
8029 // they're real types (i.e. non-complex, non-pointer scalar types).
8030 if (!type->isRealType()) return false;
8031
8032 len = 1;
8033 eltType = type;
8034 return true;
8035}
8036
8037bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8038 assert(srcTy->isVectorType() || destTy->isVectorType());
8039
8040 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8041 if (!FirstType->isSVESizelessBuiltinType())
8042 return false;
8043
8044 const auto *VecTy = SecondType->getAs<VectorType>();
8045 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8046 };
8047
8048 return ValidScalableConversion(srcTy, destTy) ||
8049 ValidScalableConversion(destTy, srcTy);
8050}
8051
8052bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8053 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8054 return false;
8055
8056 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8057 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8058
8059 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8060 matSrcType->getNumColumns() == matDestType->getNumColumns();
8061}
8062
8063bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8064 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8065
8066 uint64_t SrcLen, DestLen;
8067 QualType SrcEltTy, DestEltTy;
8068 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
8069 return false;
8070 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
8071 return false;
8072
8073 // ASTContext::getTypeSize will return the size rounded up to a
8074 // power of 2, so instead of using that, we need to use the raw
8075 // element size multiplied by the element count.
8076 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
8077 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
8078
8079 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8080}
8081
8082bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8083 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8084 "expected at least one type to be a vector here");
8085
8086 bool IsSrcTyAltivec =
8087 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8088 VectorKind::AltiVecVector) ||
8089 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8090 VectorKind::AltiVecBool) ||
8091 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8092 VectorKind::AltiVecPixel));
8093
8094 bool IsDestTyAltivec = DestTy->isVectorType() &&
8095 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8096 VectorKind::AltiVecVector) ||
8097 (DestTy->castAs<VectorType>()->getVectorKind() ==
8098 VectorKind::AltiVecBool) ||
8099 (DestTy->castAs<VectorType>()->getVectorKind() ==
8100 VectorKind::AltiVecPixel));
8101
8102 return (IsSrcTyAltivec || IsDestTyAltivec);
8103}
8104
8105bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8106 assert(destTy->isVectorType() || srcTy->isVectorType());
8107
8108 // Disallow lax conversions between scalars and ExtVectors (these
8109 // conversions are allowed for other vector types because common headers
8110 // depend on them). Most scalar OP ExtVector cases are handled by the
8111 // splat path anyway, which does what we want (convert, not bitcast).
8112 // What this rules out for ExtVectors is crazy things like char4*float.
8113 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8114 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8115
8116 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8117}
8118
8119bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8120 assert(destTy->isVectorType() || srcTy->isVectorType());
8121
8122 switch (Context.getLangOpts().getLaxVectorConversions()) {
8123 case LangOptions::LaxVectorConversionKind::None:
8124 return false;
8125
8126 case LangOptions::LaxVectorConversionKind::Integer:
8127 if (!srcTy->isIntegralOrEnumerationType()) {
8128 auto *Vec = srcTy->getAs<VectorType>();
8129 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8130 return false;
8131 }
8132 if (!destTy->isIntegralOrEnumerationType()) {
8133 auto *Vec = destTy->getAs<VectorType>();
8134 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8135 return false;
8136 }
8137 // OK, integer (vector) -> integer (vector) bitcast.
8138 break;
8139
8140 case LangOptions::LaxVectorConversionKind::All:
8141 break;
8142 }
8143
8144 return areLaxCompatibleVectorTypes(srcTy, destTy);
8145}
8146
8147bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8148 CastKind &Kind) {
8149 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8150 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8151 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8152 << DestTy << SrcTy << R;
8153 }
8154 } else if (SrcTy->isMatrixType()) {
8155 return Diag(Loc: R.getBegin(),
8156 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8157 << SrcTy << DestTy << R;
8158 } else if (DestTy->isMatrixType()) {
8159 return Diag(Loc: R.getBegin(),
8160 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8161 << DestTy << SrcTy << R;
8162 }
8163
8164 Kind = CK_MatrixCast;
8165 return false;
8166}
8167
8168bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8169 CastKind &Kind) {
8170 assert(VectorTy->isVectorType() && "Not a vector type!");
8171
8172 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8173 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8174 return Diag(Loc: R.getBegin(),
8175 DiagID: Ty->isVectorType() ?
8176 diag::err_invalid_conversion_between_vectors :
8177 diag::err_invalid_conversion_between_vector_and_integer)
8178 << VectorTy << Ty << R;
8179 } else
8180 return Diag(Loc: R.getBegin(),
8181 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8182 << VectorTy << Ty << R;
8183
8184 Kind = CK_BitCast;
8185 return false;
8186}
8187
8188ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8189 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8190
8191 if (DestElemTy == SplattedExpr->getType())
8192 return SplattedExpr;
8193
8194 assert(DestElemTy->isFloatingType() ||
8195 DestElemTy->isIntegralOrEnumerationType());
8196
8197 CastKind CK;
8198 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8199 // OpenCL requires that we convert `true` boolean expressions to -1, but
8200 // only when splatting vectors.
8201 if (DestElemTy->isFloatingType()) {
8202 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8203 // in two steps: boolean to signed integral, then to floating.
8204 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8205 CK: CK_BooleanToSignedIntegral);
8206 SplattedExpr = CastExprRes.get();
8207 CK = CK_IntegralToFloating;
8208 } else {
8209 CK = CK_BooleanToSignedIntegral;
8210 }
8211 } else {
8212 ExprResult CastExprRes = SplattedExpr;
8213 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8214 if (CastExprRes.isInvalid())
8215 return ExprError();
8216 SplattedExpr = CastExprRes.get();
8217 }
8218 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8219}
8220
8221ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8222 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8223
8224 if (DestElemTy == SplattedExpr->getType())
8225 return SplattedExpr;
8226
8227 assert(DestElemTy->isFloatingType() ||
8228 DestElemTy->isIntegralOrEnumerationType());
8229
8230 ExprResult CastExprRes = SplattedExpr;
8231 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8232 if (CastExprRes.isInvalid())
8233 return ExprError();
8234 SplattedExpr = CastExprRes.get();
8235
8236 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8237}
8238
8239ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8240 Expr *CastExpr, CastKind &Kind) {
8241 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8242
8243 QualType SrcTy = CastExpr->getType();
8244
8245 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8246 // an ExtVectorType.
8247 // In OpenCL, casts between vectors of different types are not allowed.
8248 // (See OpenCL 6.2).
8249 if (SrcTy->isVectorType()) {
8250 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8251 (getLangOpts().OpenCL &&
8252 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8253 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8254 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8255 << DestTy << SrcTy << R;
8256 return ExprError();
8257 }
8258 Kind = CK_BitCast;
8259 return CastExpr;
8260 }
8261
8262 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8263 // conversion will take place first from scalar to elt type, and then
8264 // splat from elt type to vector.
8265 if (SrcTy->isPointerType())
8266 return Diag(Loc: R.getBegin(),
8267 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8268 << DestTy << SrcTy << R;
8269
8270 Kind = CK_VectorSplat;
8271 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8272}
8273
8274/// Check that a call to alloc_size function specifies sufficient space for the
8275/// destination type.
8276static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8277 const Expr *E) {
8278 QualType SourceType = E->getType();
8279 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8280 DestType == SourceType)
8281 return;
8282
8283 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8284 if (!CE)
8285 return;
8286
8287 // Find the total size allocated by the function call.
8288 if (!CE->getCalleeAllocSizeAttr())
8289 return;
8290 std::optional<llvm::APInt> AllocSize =
8291 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8292 // Allocations of size zero are permitted as a special case. They are usually
8293 // done intentionally.
8294 if (!AllocSize || AllocSize->isZero())
8295 return;
8296 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8297
8298 QualType TargetType = DestType->getPointeeType();
8299 // Find the destination size. As a special case function types have size of
8300 // one byte to match the sizeof operator behavior.
8301 auto LhsSize = TargetType->isFunctionType()
8302 ? CharUnits::One()
8303 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8304 if (LhsSize && Size < LhsSize)
8305 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8306 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8307}
8308
8309ExprResult
8310Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8311 Declarator &D, ParsedType &Ty,
8312 SourceLocation RParenLoc, Expr *CastExpr) {
8313 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8314 "ActOnCastExpr(): missing type or expr");
8315
8316 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8317 if (D.isInvalidType())
8318 return ExprError();
8319
8320 if (getLangOpts().CPlusPlus) {
8321 // Check that there are no default arguments (C++ only).
8322 CheckExtraCXXDefaultArguments(D);
8323 }
8324
8325 checkUnusedDeclAttributes(D);
8326
8327 QualType castType = castTInfo->getType();
8328 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8329
8330 bool isVectorLiteral = false;
8331
8332 // Check for an altivec or OpenCL literal,
8333 // i.e. all the elements are integer constants.
8334 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8335 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8336 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8337 && castType->isVectorType() && (PE || PLE)) {
8338 if (PLE && PLE->getNumExprs() == 0) {
8339 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8340 return ExprError();
8341 }
8342 if (PE || PLE->getNumExprs() == 1) {
8343 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8344 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8345 isVectorLiteral = true;
8346 }
8347 else
8348 isVectorLiteral = true;
8349 }
8350
8351 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8352 // then handle it as such.
8353 if (isVectorLiteral)
8354 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8355
8356 // If the Expr being casted is a ParenListExpr, handle it specially.
8357 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8358 // sequence of BinOp comma operators.
8359 if (isa<ParenListExpr>(Val: CastExpr)) {
8360 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8361 if (Result.isInvalid()) return ExprError();
8362 CastExpr = Result.get();
8363 }
8364
8365 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8366 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8367
8368 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8369
8370 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8371
8372 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8373
8374 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8375
8376 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8377}
8378
8379ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8380 SourceLocation RParenLoc, Expr *E,
8381 TypeSourceInfo *TInfo) {
8382 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8383 "Expected paren or paren list expression");
8384
8385 Expr **exprs;
8386 unsigned numExprs;
8387 Expr *subExpr;
8388 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8389 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8390 LiteralLParenLoc = PE->getLParenLoc();
8391 LiteralRParenLoc = PE->getRParenLoc();
8392 exprs = PE->getExprs();
8393 numExprs = PE->getNumExprs();
8394 } else { // isa<ParenExpr> by assertion at function entrance
8395 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8396 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8397 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8398 exprs = &subExpr;
8399 numExprs = 1;
8400 }
8401
8402 QualType Ty = TInfo->getType();
8403 assert(Ty->isVectorType() && "Expected vector type");
8404
8405 SmallVector<Expr *, 8> initExprs;
8406 const VectorType *VTy = Ty->castAs<VectorType>();
8407 unsigned numElems = VTy->getNumElements();
8408
8409 // '(...)' form of vector initialization in AltiVec: the number of
8410 // initializers must be one or must match the size of the vector.
8411 // If a single value is specified in the initializer then it will be
8412 // replicated to all the components of the vector
8413 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8414 SrcTy: VTy->getElementType()))
8415 return ExprError();
8416 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8417 // The number of initializers must be one or must match the size of the
8418 // vector. If a single value is specified in the initializer then it will
8419 // be replicated to all the components of the vector
8420 if (numExprs == 1) {
8421 QualType ElemTy = VTy->getElementType();
8422 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8423 if (Literal.isInvalid())
8424 return ExprError();
8425 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8426 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8427 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8428 }
8429 else if (numExprs < numElems) {
8430 Diag(Loc: E->getExprLoc(),
8431 DiagID: diag::err_incorrect_number_of_vector_initializers);
8432 return ExprError();
8433 }
8434 else
8435 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8436 }
8437 else {
8438 // For OpenCL, when the number of initializers is a single value,
8439 // it will be replicated to all components of the vector.
8440 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8441 numExprs == 1) {
8442 QualType SrcTy = exprs[0]->getType();
8443 if (!SrcTy->isArithmeticType()) {
8444 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8445 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8446 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8447 return ExprError();
8448 }
8449 QualType ElemTy = VTy->getElementType();
8450 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8451 if (Literal.isInvalid())
8452 return ExprError();
8453 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8454 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8455 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8456 }
8457
8458 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8459 }
8460 // FIXME: This means that pretty-printing the final AST will produce curly
8461 // braces instead of the original commas.
8462 InitListExpr *initE =
8463 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8464 LiteralRParenLoc, /*isExplicit=*/false);
8465 initE->setType(Ty);
8466 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8467}
8468
8469ExprResult
8470Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8471 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8472 if (!E)
8473 return OrigExpr;
8474
8475 ExprResult Result(E->getExpr(Init: 0));
8476
8477 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8478 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8479 RHSExpr: E->getExpr(Init: i));
8480
8481 if (Result.isInvalid()) return ExprError();
8482
8483 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8484}
8485
8486ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8487 SourceLocation R,
8488 MultiExprArg Val) {
8489 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8490}
8491
8492ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8493 unsigned NumUserSpecifiedExprs,
8494 SourceLocation InitLoc,
8495 SourceLocation LParenLoc,
8496 SourceLocation RParenLoc) {
8497 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8498 InitLoc, LParenLoc, RParenLoc);
8499}
8500
8501bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8502 SourceLocation QuestionLoc) {
8503 const Expr *NullExpr = LHSExpr;
8504 const Expr *NonPointerExpr = RHSExpr;
8505 Expr::NullPointerConstantKind NullKind =
8506 NullExpr->isNullPointerConstant(Ctx&: Context,
8507 NPC: Expr::NPC_ValueDependentIsNotNull);
8508
8509 if (NullKind == Expr::NPCK_NotNull) {
8510 NullExpr = RHSExpr;
8511 NonPointerExpr = LHSExpr;
8512 NullKind =
8513 NullExpr->isNullPointerConstant(Ctx&: Context,
8514 NPC: Expr::NPC_ValueDependentIsNotNull);
8515 }
8516
8517 if (NullKind == Expr::NPCK_NotNull)
8518 return false;
8519
8520 if (NullKind == Expr::NPCK_ZeroExpression)
8521 return false;
8522
8523 if (NullKind == Expr::NPCK_ZeroLiteral) {
8524 // In this case, check to make sure that we got here from a "NULL"
8525 // string in the source code.
8526 NullExpr = NullExpr->IgnoreParenImpCasts();
8527 SourceLocation loc = NullExpr->getExprLoc();
8528 if (!findMacroSpelling(loc, name: "NULL"))
8529 return false;
8530 }
8531
8532 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8533 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8534 << NonPointerExpr->getType() << DiagType
8535 << NonPointerExpr->getSourceRange();
8536 return true;
8537}
8538
8539/// Return false if the condition expression is valid, true otherwise.
8540static bool checkCondition(Sema &S, const Expr *Cond,
8541 SourceLocation QuestionLoc) {
8542 QualType CondTy = Cond->getType();
8543
8544 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8545 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8546 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8547 << CondTy << Cond->getSourceRange();
8548 return true;
8549 }
8550
8551 // C99 6.5.15p2
8552 if (CondTy->isScalarType()) return false;
8553
8554 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8555 << CondTy << Cond->getSourceRange();
8556 return true;
8557}
8558
8559/// Return false if the NullExpr can be promoted to PointerTy,
8560/// true otherwise.
8561static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8562 QualType PointerTy) {
8563 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8564 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8565 NPC: Expr::NPC_ValueDependentIsNull))
8566 return true;
8567
8568 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8569 return false;
8570}
8571
8572/// Checks compatibility between two pointers and return the resulting
8573/// type.
8574static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8575 ExprResult &RHS,
8576 SourceLocation Loc) {
8577 QualType LHSTy = LHS.get()->getType();
8578 QualType RHSTy = RHS.get()->getType();
8579
8580 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8581 // Two identical pointers types are always compatible.
8582 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8583 }
8584
8585 QualType lhptee, rhptee;
8586
8587 // Get the pointee types.
8588 bool IsBlockPointer = false;
8589 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8590 lhptee = LHSBTy->getPointeeType();
8591 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8592 IsBlockPointer = true;
8593 } else {
8594 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8595 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8596 }
8597
8598 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8599 // differently qualified versions of compatible types, the result type is
8600 // a pointer to an appropriately qualified version of the composite
8601 // type.
8602
8603 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8604 // clause doesn't make sense for our extensions. E.g. address space 2 should
8605 // be incompatible with address space 3: they may live on different devices or
8606 // anything.
8607 Qualifiers lhQual = lhptee.getQualifiers();
8608 Qualifiers rhQual = rhptee.getQualifiers();
8609
8610 LangAS ResultAddrSpace = LangAS::Default;
8611 LangAS LAddrSpace = lhQual.getAddressSpace();
8612 LangAS RAddrSpace = rhQual.getAddressSpace();
8613
8614 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8615 // spaces is disallowed.
8616 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8617 ResultAddrSpace = LAddrSpace;
8618 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8619 ResultAddrSpace = RAddrSpace;
8620 else {
8621 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8622 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8623 << RHS.get()->getSourceRange();
8624 return QualType();
8625 }
8626
8627 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8628 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8629 lhQual.removeCVRQualifiers();
8630 rhQual.removeCVRQualifiers();
8631
8632 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8633 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8634 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8635 << RHS.get()->getSourceRange();
8636 return QualType();
8637 }
8638
8639 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8640 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8641 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8642 // qual types are compatible iff
8643 // * corresponded types are compatible
8644 // * CVR qualifiers are equal
8645 // * address spaces are equal
8646 // Thus for conditional operator we merge CVR and address space unqualified
8647 // pointees and if there is a composite type we return a pointer to it with
8648 // merged qualifiers.
8649 LHSCastKind =
8650 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8651 RHSCastKind =
8652 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8653 lhQual.removeAddressSpace();
8654 rhQual.removeAddressSpace();
8655
8656 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8657 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8658
8659 QualType CompositeTy = S.Context.mergeTypes(
8660 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8661 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8662
8663 if (CompositeTy.isNull()) {
8664 // In this situation, we assume void* type. No especially good
8665 // reason, but this is what gcc does, and we do have to pick
8666 // to get a consistent AST.
8667 QualType incompatTy;
8668 incompatTy = S.Context.getPointerType(
8669 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8670 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8671 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8672
8673 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8674 // for casts between types with incompatible address space qualifiers.
8675 // For the following code the compiler produces casts between global and
8676 // local address spaces of the corresponded innermost pointees:
8677 // local int *global *a;
8678 // global int *global *b;
8679 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8680 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8681 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8682 << RHS.get()->getSourceRange();
8683
8684 return incompatTy;
8685 }
8686
8687 // The pointer types are compatible.
8688 // In case of OpenCL ResultTy should have the address space qualifier
8689 // which is a superset of address spaces of both the 2nd and the 3rd
8690 // operands of the conditional operator.
8691 QualType ResultTy = [&, ResultAddrSpace]() {
8692 if (S.getLangOpts().OpenCL) {
8693 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8694 CompositeQuals.setAddressSpace(ResultAddrSpace);
8695 return S.Context
8696 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8697 .withCVRQualifiers(CVR: MergedCVRQual);
8698 }
8699 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8700 }();
8701 if (IsBlockPointer)
8702 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8703 else
8704 ResultTy = S.Context.getPointerType(T: ResultTy);
8705
8706 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8707 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8708 return ResultTy;
8709}
8710
8711/// Return the resulting type when the operands are both block pointers.
8712static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8713 ExprResult &LHS,
8714 ExprResult &RHS,
8715 SourceLocation Loc) {
8716 QualType LHSTy = LHS.get()->getType();
8717 QualType RHSTy = RHS.get()->getType();
8718
8719 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8720 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8721 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8722 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8723 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8724 return destType;
8725 }
8726 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8727 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8728 << RHS.get()->getSourceRange();
8729 return QualType();
8730 }
8731
8732 // We have 2 block pointer types.
8733 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8734}
8735
8736/// Return the resulting type when the operands are both pointers.
8737static QualType
8738checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8739 ExprResult &RHS,
8740 SourceLocation Loc) {
8741 // get the pointer types
8742 QualType LHSTy = LHS.get()->getType();
8743 QualType RHSTy = RHS.get()->getType();
8744
8745 // get the "pointed to" types
8746 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8747 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8748
8749 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8750 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8751 // Figure out necessary qualifiers (C99 6.5.15p6)
8752 QualType destPointee
8753 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8754 QualType destType = S.Context.getPointerType(T: destPointee);
8755 // Add qualifiers if necessary.
8756 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8757 // Promote to void*.
8758 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8759 return destType;
8760 }
8761 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8762 QualType destPointee
8763 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8764 QualType destType = S.Context.getPointerType(T: destPointee);
8765 // Add qualifiers if necessary.
8766 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8767 // Promote to void*.
8768 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8769 return destType;
8770 }
8771
8772 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8773}
8774
8775/// Return false if the first expression is not an integer and the second
8776/// expression is not a pointer, true otherwise.
8777static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8778 Expr* PointerExpr, SourceLocation Loc,
8779 bool IsIntFirstExpr) {
8780 if (!PointerExpr->getType()->isPointerType() ||
8781 !Int.get()->getType()->isIntegerType())
8782 return false;
8783
8784 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8785 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8786
8787 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8788 << Expr1->getType() << Expr2->getType()
8789 << Expr1->getSourceRange() << Expr2->getSourceRange();
8790 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8791 CK: CK_IntegralToPointer);
8792 return true;
8793}
8794
8795/// Simple conversion between integer and floating point types.
8796///
8797/// Used when handling the OpenCL conditional operator where the
8798/// condition is a vector while the other operands are scalar.
8799///
8800/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8801/// types are either integer or floating type. Between the two
8802/// operands, the type with the higher rank is defined as the "result
8803/// type". The other operand needs to be promoted to the same type. No
8804/// other type promotion is allowed. We cannot use
8805/// UsualArithmeticConversions() for this purpose, since it always
8806/// promotes promotable types.
8807static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8808 ExprResult &RHS,
8809 SourceLocation QuestionLoc) {
8810 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8811 if (LHS.isInvalid())
8812 return QualType();
8813 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8814 if (RHS.isInvalid())
8815 return QualType();
8816
8817 // For conversion purposes, we ignore any qualifiers.
8818 // For example, "const float" and "float" are equivalent.
8819 QualType LHSType =
8820 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8821 QualType RHSType =
8822 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8823
8824 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8825 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8826 << LHSType << LHS.get()->getSourceRange();
8827 return QualType();
8828 }
8829
8830 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8831 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8832 << RHSType << RHS.get()->getSourceRange();
8833 return QualType();
8834 }
8835
8836 // If both types are identical, no conversion is needed.
8837 if (LHSType == RHSType)
8838 return LHSType;
8839
8840 // Now handle "real" floating types (i.e. float, double, long double).
8841 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8842 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8843 /*IsCompAssign = */ false);
8844
8845 // Finally, we have two differing integer types.
8846 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8847 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8848}
8849
8850/// Convert scalar operands to a vector that matches the
8851/// condition in length.
8852///
8853/// Used when handling the OpenCL conditional operator where the
8854/// condition is a vector while the other operands are scalar.
8855///
8856/// We first compute the "result type" for the scalar operands
8857/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8858/// into a vector of that type where the length matches the condition
8859/// vector type. s6.11.6 requires that the element types of the result
8860/// and the condition must have the same number of bits.
8861static QualType
8862OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8863 QualType CondTy, SourceLocation QuestionLoc) {
8864 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8865 if (ResTy.isNull()) return QualType();
8866
8867 const VectorType *CV = CondTy->getAs<VectorType>();
8868 assert(CV);
8869
8870 // Determine the vector result type
8871 unsigned NumElements = CV->getNumElements();
8872 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8873
8874 // Ensure that all types have the same number of bits
8875 if (S.Context.getTypeSize(T: CV->getElementType())
8876 != S.Context.getTypeSize(T: ResTy)) {
8877 // Since VectorTy is created internally, it does not pretty print
8878 // with an OpenCL name. Instead, we just print a description.
8879 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8880 SmallString<64> Str;
8881 llvm::raw_svector_ostream OS(Str);
8882 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8883 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8884 << CondTy << OS.str();
8885 return QualType();
8886 }
8887
8888 // Convert operands to the vector result type
8889 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8890 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8891
8892 return VectorTy;
8893}
8894
8895/// Return false if this is a valid OpenCL condition vector
8896static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8897 SourceLocation QuestionLoc) {
8898 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8899 // integral type.
8900 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8901 assert(CondTy);
8902 QualType EleTy = CondTy->getElementType();
8903 if (EleTy->isIntegerType()) return false;
8904
8905 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8906 << Cond->getType() << Cond->getSourceRange();
8907 return true;
8908}
8909
8910/// Return false if the vector condition type and the vector
8911/// result type are compatible.
8912///
8913/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8914/// number of elements, and their element types have the same number
8915/// of bits.
8916static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8917 SourceLocation QuestionLoc) {
8918 const VectorType *CV = CondTy->getAs<VectorType>();
8919 const VectorType *RV = VecResTy->getAs<VectorType>();
8920 assert(CV && RV);
8921
8922 if (CV->getNumElements() != RV->getNumElements()) {
8923 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8924 << CondTy << VecResTy;
8925 return true;
8926 }
8927
8928 QualType CVE = CV->getElementType();
8929 QualType RVE = RV->getElementType();
8930
8931 // Boolean vectors are permitted outside of OpenCL mode.
8932 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8933 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8934 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8935 << CondTy << VecResTy;
8936 return true;
8937 }
8938
8939 return false;
8940}
8941
8942/// Return the resulting type for the conditional operator in
8943/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8944/// s6.3.i) when the condition is a vector type.
8945static QualType
8946OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8947 ExprResult &LHS, ExprResult &RHS,
8948 SourceLocation QuestionLoc) {
8949 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8950 if (Cond.isInvalid())
8951 return QualType();
8952 QualType CondTy = Cond.get()->getType();
8953
8954 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8955 return QualType();
8956
8957 // If either operand is a vector then find the vector type of the
8958 // result as specified in OpenCL v1.1 s6.3.i.
8959 if (LHS.get()->getType()->isVectorType() ||
8960 RHS.get()->getType()->isVectorType()) {
8961 bool IsBoolVecLang =
8962 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8963 QualType VecResTy =
8964 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8965 /*isCompAssign*/ IsCompAssign: false,
8966 /*AllowBothBool*/ true,
8967 /*AllowBoolConversions*/ AllowBoolConversion: false,
8968 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8969 /*ReportInvalid*/ true);
8970 if (VecResTy.isNull())
8971 return QualType();
8972 // The result type must match the condition type as specified in
8973 // OpenCL v1.1 s6.11.6.
8974 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8975 return QualType();
8976 return VecResTy;
8977 }
8978
8979 // Both operands are scalar.
8980 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8981}
8982
8983/// Return true if the Expr is block type
8984static bool checkBlockType(Sema &S, const Expr *E) {
8985 if (E->getType()->isBlockPointerType()) {
8986 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8987 return true;
8988 }
8989
8990 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8991 QualType Ty = CE->getCallee()->getType();
8992 if (Ty->isBlockPointerType()) {
8993 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8994 return true;
8995 }
8996 }
8997 return false;
8998}
8999
9000/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9001/// In that case, LHS = cond.
9002/// C99 6.5.15
9003QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9004 ExprResult &RHS, ExprValueKind &VK,
9005 ExprObjectKind &OK,
9006 SourceLocation QuestionLoc) {
9007
9008 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
9009 if (!LHSResult.isUsable()) return QualType();
9010 LHS = LHSResult;
9011
9012 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
9013 if (!RHSResult.isUsable()) return QualType();
9014 RHS = RHSResult;
9015
9016 // C++ is sufficiently different to merit its own checker.
9017 if (getLangOpts().CPlusPlus)
9018 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
9019
9020 VK = VK_PRValue;
9021 OK = OK_Ordinary;
9022
9023 if (Context.isDependenceAllowed() &&
9024 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9025 RHS.get()->isTypeDependent())) {
9026 assert(!getLangOpts().CPlusPlus);
9027 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9028 RHS.get()->containsErrors()) &&
9029 "should only occur in error-recovery path.");
9030 return Context.DependentTy;
9031 }
9032
9033 // The OpenCL operator with a vector condition is sufficiently
9034 // different to merit its own checker.
9035 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9036 Cond.get()->getType()->isExtVectorType())
9037 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
9038
9039 // First, check the condition.
9040 Cond = UsualUnaryConversions(E: Cond.get());
9041 if (Cond.isInvalid())
9042 return QualType();
9043 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
9044 return QualType();
9045
9046 // Handle vectors.
9047 if (LHS.get()->getType()->isVectorType() ||
9048 RHS.get()->getType()->isVectorType())
9049 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
9050 /*AllowBothBool*/ true,
9051 /*AllowBoolConversions*/ AllowBoolConversion: false,
9052 /*AllowBooleanOperation*/ AllowBoolOperation: false,
9053 /*ReportInvalid*/ true);
9054
9055 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
9056 ACK: ArithConvKind::Conditional);
9057 if (LHS.isInvalid() || RHS.isInvalid())
9058 return QualType();
9059
9060 // WebAssembly tables are not allowed as conditional LHS or RHS.
9061 QualType LHSTy = LHS.get()->getType();
9062 QualType RHSTy = RHS.get()->getType();
9063 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9064 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
9065 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9066 return QualType();
9067 }
9068
9069 // Diagnose attempts to convert between __ibm128, __float128 and long double
9070 // where such conversions currently can't be handled.
9071 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
9072 Diag(Loc: QuestionLoc,
9073 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9074 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9075 return QualType();
9076 }
9077
9078 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9079 // selection operator (?:).
9080 if (getLangOpts().OpenCL &&
9081 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
9082 return QualType();
9083 }
9084
9085 // If both operands have arithmetic type, do the usual arithmetic conversions
9086 // to find a common type: C99 6.5.15p3,5.
9087 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9088 // Disallow invalid arithmetic conversions, such as those between bit-
9089 // precise integers types of different sizes, or between a bit-precise
9090 // integer and another type.
9091 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9092 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9093 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9094 << RHS.get()->getSourceRange();
9095 return QualType();
9096 }
9097
9098 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
9099 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
9100
9101 return ResTy;
9102 }
9103
9104 // If both operands are the same structure or union type, the result is that
9105 // type.
9106 // FIXME: Type of conditional expression must be complete in C mode.
9107 if (LHSTy->isRecordType() &&
9108 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
9109 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9110 Y: RHSTy.getUnqualifiedType());
9111
9112 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9113 // The following || allows only one side to be void (a GCC-ism).
9114 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9115 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9116 // UsualArithmeticConversions already handled the case where both sides
9117 // are the same type.
9118 } else if (RHSTy->isVoidType()) {
9119 ResTy = RHSTy;
9120 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9121 << RHS.get()->getSourceRange();
9122 } else {
9123 ResTy = LHSTy;
9124 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9125 << LHS.get()->getSourceRange();
9126 }
9127 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9128 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9129 return ResTy;
9130 }
9131
9132 // C23 6.5.15p7:
9133 // ... if both the second and third operands have nullptr_t type, the
9134 // result also has that type.
9135 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9136 return ResTy;
9137
9138 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9139 // the type of the other operand."
9140 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9141 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9142
9143 // All objective-c pointer type analysis is done here.
9144 QualType compositeType =
9145 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9146 if (LHS.isInvalid() || RHS.isInvalid())
9147 return QualType();
9148 if (!compositeType.isNull())
9149 return compositeType;
9150
9151
9152 // Handle block pointer types.
9153 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9154 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9155 Loc: QuestionLoc);
9156
9157 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9158 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9159 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9160 Loc: QuestionLoc);
9161
9162 // GCC compatibility: soften pointer/integer mismatch. Note that
9163 // null pointers have been filtered out by this point.
9164 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9165 /*IsIntFirstExpr=*/true))
9166 return RHSTy;
9167 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9168 /*IsIntFirstExpr=*/false))
9169 return LHSTy;
9170
9171 // Emit a better diagnostic if one of the expressions is a null pointer
9172 // constant and the other is not a pointer type. In this case, the user most
9173 // likely forgot to take the address of the other expression.
9174 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9175 return QualType();
9176
9177 // Finally, if the LHS and RHS types are canonically the same type, we can
9178 // use the common sugared type.
9179 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9180 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9181
9182 // Otherwise, the operands are not compatible.
9183 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9184 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9185 << RHS.get()->getSourceRange();
9186 return QualType();
9187}
9188
9189/// SuggestParentheses - Emit a note with a fixit hint that wraps
9190/// ParenRange in parentheses.
9191static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9192 const PartialDiagnostic &Note,
9193 SourceRange ParenRange) {
9194 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9195 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9196 EndLoc.isValid()) {
9197 Self.Diag(Loc, PD: Note)
9198 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9199 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9200 } else {
9201 // We can't display the parentheses, so just show the bare note.
9202 Self.Diag(Loc, PD: Note) << ParenRange;
9203 }
9204}
9205
9206static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9207 return BinaryOperator::isAdditiveOp(Opc) ||
9208 BinaryOperator::isMultiplicativeOp(Opc) ||
9209 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9210 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9211 // not any of the logical operators. Bitwise-xor is commonly used as a
9212 // logical-xor because there is no logical-xor operator. The logical
9213 // operators, including uses of xor, have a high false positive rate for
9214 // precedence warnings.
9215}
9216
9217/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9218/// expression, either using a built-in or overloaded operator,
9219/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9220/// expression.
9221static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9222 const Expr **RHSExprs) {
9223 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9224 E = E->IgnoreImpCasts();
9225 E = E->IgnoreConversionOperatorSingleStep();
9226 E = E->IgnoreImpCasts();
9227 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9228 E = MTE->getSubExpr();
9229 E = E->IgnoreImpCasts();
9230 }
9231
9232 // Built-in binary operator.
9233 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9234 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9235 *Opcode = OP->getOpcode();
9236 *RHSExprs = OP->getRHS();
9237 return true;
9238 }
9239
9240 // Overloaded operator.
9241 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9242 if (Call->getNumArgs() != 2)
9243 return false;
9244
9245 // Make sure this is really a binary operator that is safe to pass into
9246 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9247 OverloadedOperatorKind OO = Call->getOperator();
9248 if (OO < OO_Plus || OO > OO_Arrow ||
9249 OO == OO_PlusPlus || OO == OO_MinusMinus)
9250 return false;
9251
9252 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9253 if (IsArithmeticOp(Opc: OpKind)) {
9254 *Opcode = OpKind;
9255 *RHSExprs = Call->getArg(Arg: 1);
9256 return true;
9257 }
9258 }
9259
9260 return false;
9261}
9262
9263/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9264/// or is a logical expression such as (x==y) which has int type, but is
9265/// commonly interpreted as boolean.
9266static bool ExprLooksBoolean(const Expr *E) {
9267 E = E->IgnoreParenImpCasts();
9268
9269 if (E->getType()->isBooleanType())
9270 return true;
9271 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9272 return OP->isComparisonOp() || OP->isLogicalOp();
9273 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9274 return OP->getOpcode() == UO_LNot;
9275 if (E->getType()->isPointerType())
9276 return true;
9277 // FIXME: What about overloaded operator calls returning "unspecified boolean
9278 // type"s (commonly pointer-to-members)?
9279
9280 return false;
9281}
9282
9283/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9284/// and binary operator are mixed in a way that suggests the programmer assumed
9285/// the conditional operator has higher precedence, for example:
9286/// "int x = a + someBinaryCondition ? 1 : 2".
9287static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9288 Expr *Condition, const Expr *LHSExpr,
9289 const Expr *RHSExpr) {
9290 BinaryOperatorKind CondOpcode;
9291 const Expr *CondRHS;
9292
9293 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9294 return;
9295 if (!ExprLooksBoolean(E: CondRHS))
9296 return;
9297
9298 // The condition is an arithmetic binary expression, with a right-
9299 // hand side that looks boolean, so warn.
9300
9301 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9302 ? diag::warn_precedence_bitwise_conditional
9303 : diag::warn_precedence_conditional;
9304
9305 Self.Diag(Loc: OpLoc, DiagID)
9306 << Condition->getSourceRange()
9307 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9308
9309 SuggestParentheses(
9310 Self, Loc: OpLoc,
9311 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9312 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9313 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9314
9315 SuggestParentheses(Self, Loc: OpLoc,
9316 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9317 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9318}
9319
9320/// Compute the nullability of a conditional expression.
9321static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9322 QualType LHSTy, QualType RHSTy,
9323 ASTContext &Ctx) {
9324 if (!ResTy->isAnyPointerType())
9325 return ResTy;
9326
9327 auto GetNullability = [](QualType Ty) {
9328 NullabilityKindOrNone Kind = Ty->getNullability();
9329 if (Kind) {
9330 // For our purposes, treat _Nullable_result as _Nullable.
9331 if (*Kind == NullabilityKind::NullableResult)
9332 return NullabilityKind::Nullable;
9333 return *Kind;
9334 }
9335 return NullabilityKind::Unspecified;
9336 };
9337
9338 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9339 NullabilityKind MergedKind;
9340
9341 // Compute nullability of a binary conditional expression.
9342 if (IsBin) {
9343 if (LHSKind == NullabilityKind::NonNull)
9344 MergedKind = NullabilityKind::NonNull;
9345 else
9346 MergedKind = RHSKind;
9347 // Compute nullability of a normal conditional expression.
9348 } else {
9349 if (LHSKind == NullabilityKind::Nullable ||
9350 RHSKind == NullabilityKind::Nullable)
9351 MergedKind = NullabilityKind::Nullable;
9352 else if (LHSKind == NullabilityKind::NonNull)
9353 MergedKind = RHSKind;
9354 else if (RHSKind == NullabilityKind::NonNull)
9355 MergedKind = LHSKind;
9356 else
9357 MergedKind = NullabilityKind::Unspecified;
9358 }
9359
9360 // Return if ResTy already has the correct nullability.
9361 if (GetNullability(ResTy) == MergedKind)
9362 return ResTy;
9363
9364 // Strip all nullability from ResTy.
9365 while (ResTy->getNullability())
9366 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9367
9368 // Create a new AttributedType with the new nullability kind.
9369 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9370}
9371
9372ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9373 SourceLocation ColonLoc,
9374 Expr *CondExpr, Expr *LHSExpr,
9375 Expr *RHSExpr) {
9376 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9377 // was the condition.
9378 OpaqueValueExpr *opaqueValue = nullptr;
9379 Expr *commonExpr = nullptr;
9380 if (!LHSExpr) {
9381 commonExpr = CondExpr;
9382 // Lower out placeholder types first. This is important so that we don't
9383 // try to capture a placeholder. This happens in few cases in C++; such
9384 // as Objective-C++'s dictionary subscripting syntax.
9385 if (commonExpr->hasPlaceholderType()) {
9386 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9387 if (!result.isUsable()) return ExprError();
9388 commonExpr = result.get();
9389 }
9390 // We usually want to apply unary conversions *before* saving, except
9391 // in the special case of a C++ l-value conditional.
9392 if (!(getLangOpts().CPlusPlus
9393 && !commonExpr->isTypeDependent()
9394 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9395 && commonExpr->isGLValue()
9396 && commonExpr->isOrdinaryOrBitFieldObject()
9397 && RHSExpr->isOrdinaryOrBitFieldObject()
9398 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9399 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9400 if (commonRes.isInvalid())
9401 return ExprError();
9402 commonExpr = commonRes.get();
9403 }
9404
9405 // If the common expression is a class or array prvalue, materialize it
9406 // so that we can safely refer to it multiple times.
9407 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9408 commonExpr->getType()->isArrayType())) {
9409 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9410 if (MatExpr.isInvalid())
9411 return ExprError();
9412 commonExpr = MatExpr.get();
9413 }
9414
9415 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9416 commonExpr->getType(),
9417 commonExpr->getValueKind(),
9418 commonExpr->getObjectKind(),
9419 commonExpr);
9420 LHSExpr = CondExpr = opaqueValue;
9421 }
9422
9423 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9424 ExprValueKind VK = VK_PRValue;
9425 ExprObjectKind OK = OK_Ordinary;
9426 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9427 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9428 VK, OK, QuestionLoc);
9429 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9430 RHS.isInvalid())
9431 return ExprError();
9432
9433 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9434 RHSExpr: RHS.get());
9435
9436 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9437
9438 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9439 Ctx&: Context);
9440
9441 if (!commonExpr)
9442 return new (Context)
9443 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9444 RHS.get(), result, VK, OK);
9445
9446 return new (Context) BinaryConditionalOperator(
9447 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9448 ColonLoc, result, VK, OK);
9449}
9450
9451bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9452 unsigned FromAttributes = 0, ToAttributes = 0;
9453 if (const auto *FromFn =
9454 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9455 FromAttributes =
9456 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9457 if (const auto *ToFn =
9458 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9459 ToAttributes =
9460 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9461
9462 return FromAttributes != ToAttributes;
9463}
9464
9465// checkPointerTypesForAssignment - This is a very tricky routine (despite
9466// being closely modeled after the C99 spec:-). The odd characteristic of this
9467// routine is it effectively iqnores the qualifiers on the top level pointee.
9468// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9469// FIXME: add a couple examples in this comment.
9470static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9471 QualType LHSType,
9472 QualType RHSType,
9473 SourceLocation Loc) {
9474 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9475 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9476
9477 // get the "pointed to" type (ignoring qualifiers at the top level)
9478 const Type *lhptee, *rhptee;
9479 Qualifiers lhq, rhq;
9480 std::tie(args&: lhptee, args&: lhq) =
9481 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9482 std::tie(args&: rhptee, args&: rhq) =
9483 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9484
9485 AssignConvertType ConvTy = AssignConvertType::Compatible;
9486
9487 // C99 6.5.16.1p1: This following citation is common to constraints
9488 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9489 // qualifiers of the type *pointed to* by the right;
9490
9491 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9492 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9493 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9494 // Ignore lifetime for further calculation.
9495 lhq.removeObjCLifetime();
9496 rhq.removeObjCLifetime();
9497 }
9498
9499 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9500 // Treat address-space mismatches as fatal.
9501 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9502 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9503
9504 // It's okay to add or remove GC or lifetime qualifiers when converting to
9505 // and from void*.
9506 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9507 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9508 Ctx: S.getASTContext()) &&
9509 (lhptee->isVoidType() || rhptee->isVoidType()))
9510 ; // keep old
9511
9512 // Treat lifetime mismatches as fatal.
9513 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9514 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9515
9516 // Treat pointer-auth mismatches as fatal.
9517 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9518 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9519
9520 // For GCC/MS compatibility, other qualifier mismatches are treated
9521 // as still compatible in C.
9522 else
9523 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9524 }
9525
9526 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9527 // incomplete type and the other is a pointer to a qualified or unqualified
9528 // version of void...
9529 if (lhptee->isVoidType()) {
9530 if (rhptee->isIncompleteOrObjectType())
9531 return ConvTy;
9532
9533 // As an extension, we allow cast to/from void* to function pointer.
9534 assert(rhptee->isFunctionType());
9535 return AssignConvertType::FunctionVoidPointer;
9536 }
9537
9538 if (rhptee->isVoidType()) {
9539 // In C, void * to another pointer type is compatible, but we want to note
9540 // that there will be an implicit conversion happening here.
9541 if (lhptee->isIncompleteOrObjectType())
9542 return ConvTy == AssignConvertType::Compatible &&
9543 !S.getLangOpts().CPlusPlus
9544 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9545 : ConvTy;
9546
9547 // As an extension, we allow cast to/from void* to function pointer.
9548 assert(lhptee->isFunctionType());
9549 return AssignConvertType::FunctionVoidPointer;
9550 }
9551
9552 if (!S.Diags.isIgnored(
9553 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9554 Loc) &&
9555 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9556 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9557 return AssignConvertType::IncompatibleFunctionPointerStrict;
9558
9559 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9560 // unqualified versions of compatible types, ...
9561 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9562
9563 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9564 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9565 QualType LUnderlying =
9566 ltrans->isOverflowBehaviorType()
9567 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9568 : ltrans;
9569 QualType RUnderlying =
9570 rtrans->isOverflowBehaviorType()
9571 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9572 : rtrans;
9573
9574 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9575 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9576
9577 ltrans = LUnderlying;
9578 rtrans = RUnderlying;
9579 }
9580 }
9581
9582 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9583 // Check if the pointee types are compatible ignoring the sign.
9584 // We explicitly check for char so that we catch "char" vs
9585 // "unsigned char" on systems where "char" is unsigned.
9586 if (lhptee->isCharType())
9587 ltrans = S.Context.UnsignedCharTy;
9588 else if (lhptee->hasSignedIntegerRepresentation())
9589 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9590
9591 if (rhptee->isCharType())
9592 rtrans = S.Context.UnsignedCharTy;
9593 else if (rhptee->hasSignedIntegerRepresentation())
9594 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9595
9596 if (ltrans == rtrans) {
9597 // Types are compatible ignoring the sign. Qualifier incompatibility
9598 // takes priority over sign incompatibility because the sign
9599 // warning can be disabled.
9600 if (!S.IsAssignConvertCompatible(ConvTy))
9601 return ConvTy;
9602
9603 return AssignConvertType::IncompatiblePointerSign;
9604 }
9605
9606 // If we are a multi-level pointer, it's possible that our issue is simply
9607 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9608 // the eventual target type is the same and the pointers have the same
9609 // level of indirection, this must be the issue.
9610 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9611 do {
9612 std::tie(args&: lhptee, args&: lhq) =
9613 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9614 std::tie(args&: rhptee, args&: rhq) =
9615 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9616
9617 // Inconsistent address spaces at this point is invalid, even if the
9618 // address spaces would be compatible.
9619 // FIXME: This doesn't catch address space mismatches for pointers of
9620 // different nesting levels, like:
9621 // __local int *** a;
9622 // int ** b = a;
9623 // It's not clear how to actually determine when such pointers are
9624 // invalidly incompatible.
9625 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9626 return AssignConvertType::
9627 IncompatibleNestedPointerAddressSpaceMismatch;
9628
9629 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9630
9631 if (lhptee == rhptee)
9632 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9633 }
9634
9635 // General pointer incompatibility takes priority over qualifiers.
9636 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9637 return AssignConvertType::IncompatibleFunctionPointer;
9638 return AssignConvertType::IncompatiblePointer;
9639 }
9640 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9641 // hasSameType, so we can skip further checks.
9642 const auto *LFT = ltrans->getAs<FunctionType>();
9643 const auto *RFT = rtrans->getAs<FunctionType>();
9644 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9645 // The invocation of IsFunctionConversion below will try to transform rtrans
9646 // to obtain an exact match for ltrans. This should not fail because of
9647 // mismatches in result type and parameter types, they were already checked
9648 // by typesAreCompatible above. So we will recreate rtrans (or where
9649 // appropriate ltrans) using the result type and parameter types from ltrans
9650 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9651 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9652 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9653 if (LFPT && RFPT) {
9654 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9655 Args: LFPT->getParamTypes(),
9656 EPI: RFPT->getExtProtoInfo());
9657 } else if (LFPT) {
9658 FunctionProtoType::ExtProtoInfo EPI;
9659 EPI.ExtInfo = RFT->getExtInfo();
9660 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9661 Args: LFPT->getParamTypes(), EPI);
9662 } else if (RFPT) {
9663 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9664 // all of its ExtProtoInfo. Transform ltrans instead.
9665 FunctionProtoType::ExtProtoInfo EPI;
9666 EPI.ExtInfo = LFT->getExtInfo();
9667 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9668 Args: RFPT->getParamTypes(), EPI);
9669 } else {
9670 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9671 Info: RFT->getExtInfo());
9672 }
9673 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9674 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9675 return AssignConvertType::IncompatibleFunctionPointer;
9676 }
9677 return ConvTy;
9678}
9679
9680/// checkBlockPointerTypesForAssignment - This routine determines whether two
9681/// block pointer types are compatible or whether a block and normal pointer
9682/// are compatible. It is more restrict than comparing two function pointer
9683// types.
9684static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9685 QualType LHSType,
9686 QualType RHSType) {
9687 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9688 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9689
9690 QualType lhptee, rhptee;
9691
9692 // get the "pointed to" type (ignoring qualifiers at the top level)
9693 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9694 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9695
9696 // In C++, the types have to match exactly.
9697 if (S.getLangOpts().CPlusPlus)
9698 return AssignConvertType::IncompatibleBlockPointer;
9699
9700 AssignConvertType ConvTy = AssignConvertType::Compatible;
9701
9702 // For blocks we enforce that qualifiers are identical.
9703 Qualifiers LQuals = lhptee.getLocalQualifiers();
9704 Qualifiers RQuals = rhptee.getLocalQualifiers();
9705 if (S.getLangOpts().OpenCL) {
9706 LQuals.removeAddressSpace();
9707 RQuals.removeAddressSpace();
9708 }
9709 if (LQuals != RQuals)
9710 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9711
9712 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9713 // assignment.
9714 // The current behavior is similar to C++ lambdas. A block might be
9715 // assigned to a variable iff its return type and parameters are compatible
9716 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9717 // an assignment. Presumably it should behave in way that a function pointer
9718 // assignment does in C, so for each parameter and return type:
9719 // * CVR and address space of LHS should be a superset of CVR and address
9720 // space of RHS.
9721 // * unqualified types should be compatible.
9722 if (S.getLangOpts().OpenCL) {
9723 if (!S.Context.typesAreBlockPointerCompatible(
9724 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9725 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9726 return AssignConvertType::IncompatibleBlockPointer;
9727 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9728 return AssignConvertType::IncompatibleBlockPointer;
9729
9730 return ConvTy;
9731}
9732
9733/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9734/// for assignment compatibility.
9735static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9736 QualType LHSType,
9737 QualType RHSType) {
9738 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9739 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9740
9741 if (LHSType->isObjCBuiltinType()) {
9742 // Class is not compatible with ObjC object pointers.
9743 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9744 !RHSType->isObjCQualifiedClassType())
9745 return AssignConvertType::IncompatiblePointer;
9746 return AssignConvertType::Compatible;
9747 }
9748 if (RHSType->isObjCBuiltinType()) {
9749 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9750 !LHSType->isObjCQualifiedClassType())
9751 return AssignConvertType::IncompatiblePointer;
9752 return AssignConvertType::Compatible;
9753 }
9754 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9755 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9756
9757 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9758 // make an exception for id<P>
9759 !LHSType->isObjCQualifiedIdType())
9760 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9761
9762 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9763 return AssignConvertType::Compatible;
9764 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9765 return AssignConvertType::IncompatibleObjCQualifiedId;
9766 return AssignConvertType::IncompatiblePointer;
9767}
9768
9769AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9770 QualType LHSType,
9771 QualType RHSType) {
9772 // Fake up an opaque expression. We don't actually care about what
9773 // cast operations are required, so if CheckAssignmentConstraints
9774 // adds casts to this they'll be wasted, but fortunately that doesn't
9775 // usually happen on valid code.
9776 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9777 ExprResult RHSPtr = &RHSExpr;
9778 CastKind K;
9779
9780 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9781}
9782
9783/// This helper function returns true if QT is a vector type that has element
9784/// type ElementType.
9785static bool isVector(QualType QT, QualType ElementType) {
9786 if (const VectorType *VT = QT->getAs<VectorType>())
9787 return VT->getElementType().getCanonicalType() == ElementType;
9788 return false;
9789}
9790
9791/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9792/// has code to accommodate several GCC extensions when type checking
9793/// pointers. Here are some objectionable examples that GCC considers warnings:
9794///
9795/// int a, *pint;
9796/// short *pshort;
9797/// struct foo *pfoo;
9798///
9799/// pint = pshort; // warning: assignment from incompatible pointer type
9800/// a = pint; // warning: assignment makes integer from pointer without a cast
9801/// pint = a; // warning: assignment makes pointer from integer without a cast
9802/// pint = pfoo; // warning: assignment from incompatible pointer type
9803///
9804/// As a result, the code for dealing with pointers is more complex than the
9805/// C99 spec dictates.
9806///
9807/// Sets 'Kind' for any result kind except Incompatible.
9808AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9809 ExprResult &RHS,
9810 CastKind &Kind,
9811 bool ConvertRHS) {
9812 QualType RHSType = RHS.get()->getType();
9813 QualType OrigLHSType = LHSType;
9814
9815 // Get canonical types. We're not formatting these types, just comparing
9816 // them.
9817 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9818 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9819
9820 // Common case: no conversion required.
9821 if (LHSType == RHSType) {
9822 Kind = CK_NoOp;
9823 return AssignConvertType::Compatible;
9824 }
9825
9826 // If the LHS has an __auto_type, there are no additional type constraints
9827 // to be worried about.
9828 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9829 if (AT->isGNUAutoType()) {
9830 Kind = CK_NoOp;
9831 return AssignConvertType::Compatible;
9832 }
9833 }
9834
9835 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9836 switch (OBTResult) {
9837 case ASTContext::OBTAssignResult::IncompatibleKinds:
9838 Kind = CK_NoOp;
9839 return AssignConvertType::IncompatibleOBTKinds;
9840 case ASTContext::OBTAssignResult::Discards:
9841 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9842 return AssignConvertType::CompatibleOBTDiscards;
9843 case ASTContext::OBTAssignResult::Compatible:
9844 case ASTContext::OBTAssignResult::NotApplicable:
9845 break;
9846 }
9847
9848 // Check for incompatible OBT types in pointer pointee types
9849 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9850 QualType LHSPointee = LHSType->getPointeeType();
9851 QualType RHSPointee = RHSType->getPointeeType();
9852 if ((LHSPointee->isOverflowBehaviorType() ||
9853 RHSPointee->isOverflowBehaviorType()) &&
9854 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9855 Kind = CK_NoOp;
9856 return AssignConvertType::IncompatibleOBTKinds;
9857 }
9858 }
9859
9860 // If we have an atomic type, try a non-atomic assignment, then just add an
9861 // atomic qualification step.
9862 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9863 AssignConvertType Result =
9864 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9865 if (!IsAssignConvertCompatible(ConvTy: Result))
9866 return Result;
9867 if (Kind != CK_NoOp && ConvertRHS)
9868 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9869 Kind = CK_NonAtomicToAtomic;
9870 return Result;
9871 }
9872
9873 // If the left-hand side is a reference type, then we are in a
9874 // (rare!) case where we've allowed the use of references in C,
9875 // e.g., as a parameter type in a built-in function. In this case,
9876 // just make sure that the type referenced is compatible with the
9877 // right-hand side type. The caller is responsible for adjusting
9878 // LHSType so that the resulting expression does not have reference
9879 // type.
9880 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9881 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9882 Kind = CK_LValueBitCast;
9883 return AssignConvertType::Compatible;
9884 }
9885 return AssignConvertType::Incompatible;
9886 }
9887
9888 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9889 // of an ExtVector type to the same ExtVector type.
9890 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9891 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9892 // Implicit conversions require the same number of elements.
9893 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9894 return AssignConvertType::Incompatible;
9895
9896 if (LHSType->isExtVectorBoolType() &&
9897 RHSExtType->getElementType()->isIntegerType()) {
9898 Kind = CK_IntegralToBoolean;
9899 return AssignConvertType::Compatible;
9900 }
9901 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9902 if (Context.getLangOpts().OpenCL &&
9903 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9904 Kind = CK_BitCast;
9905 return AssignConvertType::Compatible;
9906 }
9907 return AssignConvertType::Incompatible;
9908 }
9909 if (RHSType->isArithmeticType()) {
9910 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9911 if (ConvertRHS)
9912 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9913 Kind = CK_VectorSplat;
9914 return AssignConvertType::Compatible;
9915 }
9916 }
9917
9918 // Conversions to or from vector type.
9919 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9920 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9921 // Allow assignments of an AltiVec vector type to an equivalent GCC
9922 // vector type and vice versa
9923 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9924 Kind = CK_BitCast;
9925 return AssignConvertType::Compatible;
9926 }
9927
9928 // If we are allowing lax vector conversions, and LHS and RHS are both
9929 // vectors, the total size only needs to be the same. This is a bitcast;
9930 // no bits are changed but the result type is different.
9931 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9932 // The default for lax vector conversions with Altivec vectors will
9933 // change, so if we are converting between vector types where
9934 // at least one is an Altivec vector, emit a warning.
9935 if (Context.getTargetInfo().getTriple().isPPC() &&
9936 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9937 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9938 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9939 << RHSType << LHSType;
9940 Kind = CK_BitCast;
9941 return AssignConvertType::IncompatibleVectors;
9942 }
9943 }
9944
9945 // When the RHS comes from another lax conversion (e.g. binops between
9946 // scalars and vectors) the result is canonicalized as a vector. When the
9947 // LHS is also a vector, the lax is allowed by the condition above. Handle
9948 // the case where LHS is a scalar.
9949 if (LHSType->isScalarType()) {
9950 const VectorType *VecType = RHSType->getAs<VectorType>();
9951 if (VecType && VecType->getNumElements() == 1 &&
9952 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9953 if (Context.getTargetInfo().getTriple().isPPC() &&
9954 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9955 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9956 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9957 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9958 << RHSType << LHSType;
9959 ExprResult *VecExpr = &RHS;
9960 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9961 Kind = CK_BitCast;
9962 return AssignConvertType::Compatible;
9963 }
9964 }
9965
9966 // Allow assignments between fixed-length and sizeless SVE vectors.
9967 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9968 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9969 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9970 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9971 Kind = CK_BitCast;
9972 return AssignConvertType::Compatible;
9973 }
9974
9975 // Allow assignments between fixed-length and sizeless RVV vectors.
9976 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9977 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9978 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9979 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9980 Kind = CK_BitCast;
9981 return AssignConvertType::Compatible;
9982 }
9983 }
9984
9985 return AssignConvertType::Incompatible;
9986 }
9987
9988 // Diagnose attempts to convert between __ibm128, __float128 and long double
9989 // where such conversions currently can't be handled.
9990 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9991 return AssignConvertType::Incompatible;
9992
9993 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9994 // discards the imaginary part.
9995 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9996 !LHSType->getAs<ComplexType>())
9997 return AssignConvertType::Incompatible;
9998
9999 // Arithmetic conversions.
10000 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10001 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10002 if (ConvertRHS)
10003 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
10004 return AssignConvertType::Compatible;
10005 }
10006
10007 // Conversions to normal pointers.
10008 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
10009 // U* -> T*
10010 if (isa<PointerType>(Val: RHSType)) {
10011 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10012 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10013 if (AddrSpaceL != AddrSpaceR)
10014 Kind = CK_AddressSpaceConversion;
10015 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
10016 Kind = CK_NoOp;
10017 else
10018 Kind = CK_BitCast;
10019 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
10020 Loc: RHS.get()->getBeginLoc());
10021 }
10022
10023 // int -> T*
10024 if (RHSType->isIntegerType()) {
10025 Kind = CK_IntegralToPointer; // FIXME: null?
10026 return AssignConvertType::IntToPointer;
10027 }
10028
10029 // C pointers are not compatible with ObjC object pointers,
10030 // with two exceptions:
10031 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10032 // - conversions to void*
10033 if (LHSPointer->getPointeeType()->isVoidType()) {
10034 Kind = CK_BitCast;
10035 return AssignConvertType::Compatible;
10036 }
10037
10038 // - conversions from 'Class' to the redefinition type
10039 if (RHSType->isObjCClassType() &&
10040 Context.hasSameType(T1: LHSType,
10041 T2: Context.getObjCClassRedefinitionType())) {
10042 Kind = CK_BitCast;
10043 return AssignConvertType::Compatible;
10044 }
10045
10046 Kind = CK_BitCast;
10047 return AssignConvertType::IncompatiblePointer;
10048 }
10049
10050 // U^ -> void*
10051 if (RHSType->getAs<BlockPointerType>()) {
10052 if (LHSPointer->getPointeeType()->isVoidType()) {
10053 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10054 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10055 ->getPointeeType()
10056 .getAddressSpace();
10057 Kind =
10058 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10059 return AssignConvertType::Compatible;
10060 }
10061 }
10062
10063 return AssignConvertType::Incompatible;
10064 }
10065
10066 // Conversions to block pointers.
10067 if (isa<BlockPointerType>(Val: LHSType)) {
10068 // U^ -> T^
10069 if (RHSType->isBlockPointerType()) {
10070 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10071 ->getPointeeType()
10072 .getAddressSpace();
10073 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10074 ->getPointeeType()
10075 .getAddressSpace();
10076 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10077 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10078 }
10079
10080 // int or null -> T^
10081 if (RHSType->isIntegerType()) {
10082 Kind = CK_IntegralToPointer; // FIXME: null
10083 return AssignConvertType::IntToBlockPointer;
10084 }
10085
10086 // id -> T^
10087 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10088 Kind = CK_AnyPointerToBlockPointerCast;
10089 return AssignConvertType::Compatible;
10090 }
10091
10092 // void* -> T^
10093 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10094 if (RHSPT->getPointeeType()->isVoidType()) {
10095 Kind = CK_AnyPointerToBlockPointerCast;
10096 return AssignConvertType::Compatible;
10097 }
10098
10099 return AssignConvertType::Incompatible;
10100 }
10101
10102 // Conversions to Objective-C pointers.
10103 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10104 // A* -> B*
10105 if (RHSType->isObjCObjectPointerType()) {
10106 Kind = CK_BitCast;
10107 AssignConvertType result =
10108 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10109 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10110 result == AssignConvertType::Compatible &&
10111 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10112 result = AssignConvertType::IncompatibleObjCWeakRef;
10113 return result;
10114 }
10115
10116 // int or null -> A*
10117 if (RHSType->isIntegerType()) {
10118 Kind = CK_IntegralToPointer; // FIXME: null
10119 return AssignConvertType::IntToPointer;
10120 }
10121
10122 // In general, C pointers are not compatible with ObjC object pointers,
10123 // with two exceptions:
10124 if (isa<PointerType>(Val: RHSType)) {
10125 Kind = CK_CPointerToObjCPointerCast;
10126
10127 // - conversions from 'void*'
10128 if (RHSType->isVoidPointerType()) {
10129 return AssignConvertType::Compatible;
10130 }
10131
10132 // - conversions to 'Class' from its redefinition type
10133 if (LHSType->isObjCClassType() &&
10134 Context.hasSameType(T1: RHSType,
10135 T2: Context.getObjCClassRedefinitionType())) {
10136 return AssignConvertType::Compatible;
10137 }
10138
10139 return AssignConvertType::IncompatiblePointer;
10140 }
10141
10142 // Only under strict condition T^ is compatible with an Objective-C pointer.
10143 if (RHSType->isBlockPointerType() &&
10144 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10145 if (ConvertRHS)
10146 maybeExtendBlockObject(E&: RHS);
10147 Kind = CK_BlockPointerToObjCPointerCast;
10148 return AssignConvertType::Compatible;
10149 }
10150
10151 return AssignConvertType::Incompatible;
10152 }
10153
10154 // Conversion to nullptr_t (C23 only)
10155 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10156 RHS.get()->isNullPointerConstant(Ctx&: Context,
10157 NPC: Expr::NPC_ValueDependentIsNull)) {
10158 // null -> nullptr_t
10159 Kind = CK_NullToPointer;
10160 return AssignConvertType::Compatible;
10161 }
10162
10163 // Conversions from pointers that are not covered by the above.
10164 if (isa<PointerType>(Val: RHSType)) {
10165 // T* -> _Bool
10166 if (LHSType == Context.BoolTy) {
10167 Kind = CK_PointerToBoolean;
10168 return AssignConvertType::Compatible;
10169 }
10170
10171 // T* -> int
10172 if (LHSType->isIntegerType()) {
10173 Kind = CK_PointerToIntegral;
10174 return AssignConvertType::PointerToInt;
10175 }
10176
10177 return AssignConvertType::Incompatible;
10178 }
10179
10180 // Conversions from Objective-C pointers that are not covered by the above.
10181 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10182 // T* -> _Bool
10183 if (LHSType == Context.BoolTy) {
10184 Kind = CK_PointerToBoolean;
10185 return AssignConvertType::Compatible;
10186 }
10187
10188 // T* -> int
10189 if (LHSType->isIntegerType()) {
10190 Kind = CK_PointerToIntegral;
10191 return AssignConvertType::PointerToInt;
10192 }
10193
10194 return AssignConvertType::Incompatible;
10195 }
10196
10197 // struct A -> struct B
10198 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10199 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10200 Kind = CK_NoOp;
10201 return AssignConvertType::Compatible;
10202 }
10203 }
10204
10205 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10206 Kind = CK_IntToOCLSampler;
10207 return AssignConvertType::Compatible;
10208 }
10209
10210 return AssignConvertType::Incompatible;
10211}
10212
10213/// Constructs a transparent union from an expression that is
10214/// used to initialize the transparent union.
10215static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10216 ExprResult &EResult, QualType UnionType,
10217 FieldDecl *Field) {
10218 // Build an initializer list that designates the appropriate member
10219 // of the transparent union.
10220 Expr *E = EResult.get();
10221 InitListExpr *Initializer = new (C) InitListExpr(
10222 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10223 Initializer->setType(UnionType);
10224 Initializer->setInitializedFieldInUnion(Field);
10225
10226 // Build a compound literal constructing a value of the transparent
10227 // union type from this initializer list.
10228 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10229 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10230 VK_PRValue, Initializer, false);
10231}
10232
10233AssignConvertType
10234Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10235 ExprResult &RHS) {
10236 QualType RHSType = RHS.get()->getType();
10237
10238 // If the ArgType is a Union type, we want to handle a potential
10239 // transparent_union GCC extension.
10240 const RecordType *UT = ArgType->getAsUnionType();
10241 if (!UT)
10242 return AssignConvertType::Incompatible;
10243
10244 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10245 if (!UD->hasAttr<TransparentUnionAttr>())
10246 return AssignConvertType::Incompatible;
10247
10248 // The field to initialize within the transparent union.
10249 FieldDecl *InitField = nullptr;
10250 // It's compatible if the expression matches any of the fields.
10251 for (auto *it : UD->fields()) {
10252 if (it->getType()->isPointerType()) {
10253 // If the transparent union contains a pointer type, we allow:
10254 // 1) void pointer
10255 // 2) null pointer constant
10256 if (RHSType->isPointerType())
10257 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10258 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10259 InitField = it;
10260 break;
10261 }
10262
10263 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10264 NPC: Expr::NPC_ValueDependentIsNull)) {
10265 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10266 CK: CK_NullToPointer);
10267 InitField = it;
10268 break;
10269 }
10270 }
10271
10272 CastKind Kind;
10273 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10274 AssignConvertType::Compatible) {
10275 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10276 InitField = it;
10277 break;
10278 }
10279 }
10280
10281 if (!InitField)
10282 return AssignConvertType::Incompatible;
10283
10284 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10285 return AssignConvertType::Compatible;
10286}
10287
10288AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10289 ExprResult &CallerRHS,
10290 bool Diagnose,
10291 bool DiagnoseCFAudited,
10292 bool ConvertRHS) {
10293 // We need to be able to tell the caller whether we diagnosed a problem, if
10294 // they ask us to issue diagnostics.
10295 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10296
10297 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10298 // we can't avoid *all* modifications at the moment, so we need some somewhere
10299 // to put the updated value.
10300 ExprResult LocalRHS = CallerRHS;
10301 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10302
10303 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10304 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10305 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10306 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10307 Diag(Loc: RHS.get()->getExprLoc(),
10308 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10309 << RHS.get()->getSourceRange();
10310 }
10311 }
10312 }
10313
10314 if (getLangOpts().CPlusPlus) {
10315 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10316 // C++ 5.17p3: If the left operand is not of class type, the
10317 // expression is implicitly converted (C++ 4) to the
10318 // cv-unqualified type of the left operand.
10319 QualType RHSType = RHS.get()->getType();
10320 if (Diagnose) {
10321 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10322 Action: AssignmentAction::Assigning);
10323 } else {
10324 ImplicitConversionSequence ICS =
10325 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10326 /*SuppressUserConversions=*/false,
10327 AllowExplicit: AllowedExplicit::None,
10328 /*InOverloadResolution=*/false,
10329 /*CStyle=*/false,
10330 /*AllowObjCWritebackConversion=*/false);
10331 if (ICS.isFailure())
10332 return AssignConvertType::Incompatible;
10333 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10334 ICS, Action: AssignmentAction::Assigning);
10335 }
10336 if (RHS.isInvalid())
10337 return AssignConvertType::Incompatible;
10338 AssignConvertType result = AssignConvertType::Compatible;
10339 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10340 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10341 result = AssignConvertType::IncompatibleObjCWeakRef;
10342
10343 // Check if OBT is being discarded during assignment
10344 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10345 if (RHSType->isOverflowBehaviorType() &&
10346 !LHSType->isOverflowBehaviorType()) {
10347 result = AssignConvertType::CompatibleOBTDiscards;
10348 }
10349
10350 return result;
10351 }
10352
10353 // FIXME: Currently, we fall through and treat C++ classes like C
10354 // structures.
10355 // FIXME: We also fall through for atomics; not sure what should
10356 // happen there, though.
10357 } else if (RHS.get()->getType() == Context.OverloadTy) {
10358 // As a set of extensions to C, we support overloading on functions. These
10359 // functions need to be resolved here.
10360 DeclAccessPair DAP;
10361 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10362 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10363 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10364 else
10365 return AssignConvertType::Incompatible;
10366 }
10367
10368 // For HLSL records, insert derived-to-base conversion if needed.
10369 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10370 QualType RHSType = RHS.get()->getType();
10371 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10372 CXXBasePaths Paths;
10373 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10374 CXXCastPath CastPath;
10375 BuildBasePathArray(Paths, BasePath&: CastPath);
10376 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10377 BasePath: &CastPath);
10378 }
10379 }
10380 }
10381
10382 // This check seems unnatural, however it is necessary to ensure the proper
10383 // conversion of functions/arrays. If the conversion were done for all
10384 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10385 // expressions that suppress this implicit conversion (&, sizeof). This needs
10386 // to happen before we check for null pointer conversions because C does not
10387 // undergo the same implicit conversions as C++ does above (by the calls to
10388 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10389 // lvalue to rvalue cast before checking for null pointer constraints. This
10390 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10391 //
10392 // Suppress this for references: C++ 8.5.3p5.
10393 if (!LHSType->isReferenceType()) {
10394 // FIXME: We potentially allocate here even if ConvertRHS is false.
10395 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10396 if (RHS.isInvalid())
10397 return AssignConvertType::Incompatible;
10398 }
10399
10400 // The constraints are expressed in terms of the atomic, qualified, or
10401 // unqualified type of the LHS.
10402 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10403
10404 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10405 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10406 if ((LHSTypeAfterConversion->isPointerType() ||
10407 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10408 LHSTypeAfterConversion->isBlockPointerType()) &&
10409 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10410 RHS.get()->isNullPointerConstant(Ctx&: Context,
10411 NPC: Expr::NPC_ValueDependentIsNull))) {
10412 AssignConvertType Ret = AssignConvertType::Compatible;
10413 if (Diagnose || ConvertRHS) {
10414 CastKind Kind;
10415 CXXCastPath Path;
10416 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10417 /*IgnoreBaseAccess=*/false, Diagnose);
10418
10419 // If there is a conversion of some kind, check to see what kind of
10420 // pointer conversion happened so we can diagnose a C++ compatibility
10421 // diagnostic if the conversion is invalid. This only matters if the RHS
10422 // is some kind of void pointer. We have a carve-out when the RHS is from
10423 // a macro expansion because the use of a macro may indicate different
10424 // code between C and C++. Consider: char *s = NULL; where NULL is
10425 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10426 // C++, which is valid in C++.
10427 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10428 !RHS.get()->getBeginLoc().isMacroID()) {
10429 QualType CanRHS =
10430 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10431 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10432 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10433 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10434 Loc: RHS.get()->getExprLoc());
10435 // Anything that's not considered perfectly compatible would be
10436 // incompatible in C++.
10437 if (Ret != AssignConvertType::Compatible)
10438 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10439 }
10440 }
10441
10442 if (ConvertRHS)
10443 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10444 }
10445 return Ret;
10446 }
10447 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10448 // unqualified bool, and the right operand is a pointer or its type is
10449 // nullptr_t.
10450 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10451 RHS.get()->getType()->isNullPtrType()) {
10452 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10453 // only handles nullptr -> _Bool due to needing an extra conversion
10454 // step.
10455 // We model this by converting from nullptr -> void * and then let the
10456 // conversion from void * -> _Bool happen naturally.
10457 if (Diagnose || ConvertRHS) {
10458 CastKind Kind;
10459 CXXCastPath Path;
10460 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10461 /*IgnoreBaseAccess=*/false, Diagnose);
10462 if (ConvertRHS)
10463 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10464 BasePath: &Path);
10465 }
10466 }
10467
10468 // OpenCL queue_t type assignment.
10469 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10470 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10471 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10472 return AssignConvertType::Compatible;
10473 }
10474
10475 CastKind Kind;
10476 AssignConvertType result =
10477 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10478
10479 // If assigning a void * created by an allocation function call to some other
10480 // type, check that the allocated size is sufficient for that type.
10481 if (result != AssignConvertType::Incompatible &&
10482 RHS.get()->getType()->isVoidPointerType())
10483 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10484
10485 // C99 6.5.16.1p2: The value of the right operand is converted to the
10486 // type of the assignment expression.
10487 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10488 // so that we can use references in built-in functions even in C.
10489 // The getNonReferenceType() call makes sure that the resulting expression
10490 // does not have reference type.
10491 if (result != AssignConvertType::Incompatible &&
10492 RHS.get()->getType() != LHSType) {
10493 QualType Ty = LHSType.getNonLValueExprType(Context);
10494 Expr *E = RHS.get();
10495
10496 // Check for various Objective-C errors. If we are not reporting
10497 // diagnostics and just checking for errors, e.g., during overload
10498 // resolution, return Incompatible to indicate the failure.
10499 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10500 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10501 CCK: CheckedConversionKind::Implicit, Diagnose,
10502 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10503 if (!Diagnose)
10504 return AssignConvertType::Incompatible;
10505 }
10506 if (getLangOpts().ObjC &&
10507 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10508 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10509 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10510 if (!Diagnose)
10511 return AssignConvertType::Incompatible;
10512 // Replace the expression with a corrected version and continue so we
10513 // can find further errors.
10514 RHS = E;
10515 return AssignConvertType::Compatible;
10516 }
10517
10518 if (ConvertRHS)
10519 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10520 }
10521
10522 return result;
10523}
10524
10525namespace {
10526/// The original operand to an operator, prior to the application of the usual
10527/// arithmetic conversions and converting the arguments of a builtin operator
10528/// candidate.
10529struct OriginalOperand {
10530 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10531 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10532 Op = MTE->getSubExpr();
10533 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10534 Op = BTE->getSubExpr();
10535 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10536 Orig = ICE->getSubExprAsWritten();
10537 Conversion = ICE->getConversionFunction();
10538 }
10539 }
10540
10541 QualType getType() const { return Orig->getType(); }
10542
10543 Expr *Orig;
10544 NamedDecl *Conversion;
10545};
10546}
10547
10548QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10549 ExprResult &RHS) {
10550 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10551
10552 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10553 << OrigLHS.getType() << OrigRHS.getType()
10554 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10555
10556 // If a user-defined conversion was applied to either of the operands prior
10557 // to applying the built-in operator rules, tell the user about it.
10558 if (OrigLHS.Conversion) {
10559 Diag(Loc: OrigLHS.Conversion->getLocation(),
10560 DiagID: diag::note_typecheck_invalid_operands_converted)
10561 << 0 << LHS.get()->getType();
10562 }
10563 if (OrigRHS.Conversion) {
10564 Diag(Loc: OrigRHS.Conversion->getLocation(),
10565 DiagID: diag::note_typecheck_invalid_operands_converted)
10566 << 1 << RHS.get()->getType();
10567 }
10568
10569 return QualType();
10570}
10571
10572QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10573 ExprResult &RHS) {
10574 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10575 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10576
10577 bool LHSNatVec = LHSType->isVectorType();
10578 bool RHSNatVec = RHSType->isVectorType();
10579
10580 if (!(LHSNatVec && RHSNatVec)) {
10581 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10582 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10583 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10584 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10585 << Vector->getSourceRange();
10586 return QualType();
10587 }
10588
10589 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10590 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10591 << RHS.get()->getSourceRange();
10592
10593 return QualType();
10594}
10595
10596/// Try to convert a value of non-vector type to a vector type by converting
10597/// the type to the element type of the vector and then performing a splat.
10598/// If the language is OpenCL, we only use conversions that promote scalar
10599/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10600/// for float->int.
10601///
10602/// OpenCL V2.0 6.2.6.p2:
10603/// An error shall occur if any scalar operand type has greater rank
10604/// than the type of the vector element.
10605///
10606/// \param scalar - if non-null, actually perform the conversions
10607/// \return true if the operation fails (but without diagnosing the failure)
10608static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10609 QualType scalarTy,
10610 QualType vectorEltTy,
10611 QualType vectorTy,
10612 unsigned &DiagID) {
10613 // The conversion to apply to the scalar before splatting it,
10614 // if necessary.
10615 CastKind scalarCast = CK_NoOp;
10616
10617 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10618 scalarCast = CK_IntegralToBoolean;
10619 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10620 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10621 (scalarTy->isIntegerType() &&
10622 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10623 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10624 return true;
10625 }
10626 if (!scalarTy->isIntegralType(Ctx: S.Context))
10627 return true;
10628 scalarCast = CK_IntegralCast;
10629 } else if (vectorEltTy->isRealFloatingType()) {
10630 if (scalarTy->isRealFloatingType()) {
10631 if (S.getLangOpts().OpenCL &&
10632 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10633 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10634 return true;
10635 }
10636 scalarCast = CK_FloatingCast;
10637 }
10638 else if (scalarTy->isIntegralType(Ctx: S.Context))
10639 scalarCast = CK_IntegralToFloating;
10640 else
10641 return true;
10642 } else {
10643 return true;
10644 }
10645
10646 // Adjust scalar if desired.
10647 if (scalar) {
10648 if (scalarCast != CK_NoOp)
10649 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10650 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10651 }
10652 return false;
10653}
10654
10655/// Convert vector E to a vector with the same number of elements but different
10656/// element type.
10657static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10658 const auto *VecTy = E->getType()->getAs<VectorType>();
10659 assert(VecTy && "Expression E must be a vector");
10660 QualType NewVecTy =
10661 VecTy->isExtVectorType()
10662 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10663 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10664 VecKind: VecTy->getVectorKind());
10665
10666 // Look through the implicit cast. Return the subexpression if its type is
10667 // NewVecTy.
10668 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10669 if (ICE->getSubExpr()->getType() == NewVecTy)
10670 return ICE->getSubExpr();
10671
10672 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10673 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10674}
10675
10676/// Test if a (constant) integer Int can be casted to another integer type
10677/// IntTy without losing precision.
10678static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10679 QualType OtherIntTy) {
10680 Expr *E = Int->get();
10681 if (E->containsErrors() || E->isInstantiationDependent())
10682 return false;
10683
10684 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10685
10686 // Reject cases where the value of the Int is unknown as that would
10687 // possibly cause truncation, but accept cases where the scalar can be
10688 // demoted without loss of precision.
10689 Expr::EvalResult EVResult;
10690 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10691 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10692 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10693 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10694
10695 if (CstInt) {
10696 // If the scalar is constant and is of a higher order and has more active
10697 // bits that the vector element type, reject it.
10698 llvm::APSInt Result = EVResult.Val.getInt();
10699 unsigned NumBits = IntSigned
10700 ? (Result.isNegative() ? Result.getSignificantBits()
10701 : Result.getActiveBits())
10702 : Result.getActiveBits();
10703 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10704 return true;
10705
10706 // If the signedness of the scalar type and the vector element type
10707 // differs and the number of bits is greater than that of the vector
10708 // element reject it.
10709 return (IntSigned != OtherIntSigned &&
10710 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10711 }
10712
10713 // Reject cases where the value of the scalar is not constant and it's
10714 // order is greater than that of the vector element type.
10715 return (Order < 0);
10716}
10717
10718/// Test if a (constant) integer Int can be casted to floating point type
10719/// FloatTy without losing precision.
10720static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10721 QualType FloatTy) {
10722 if (Int->get()->containsErrors())
10723 return false;
10724
10725 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10726
10727 // Determine if the integer constant can be expressed as a floating point
10728 // number of the appropriate type.
10729 Expr::EvalResult EVResult;
10730 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10731
10732 uint64_t Bits = 0;
10733 if (CstInt) {
10734 // Reject constants that would be truncated if they were converted to
10735 // the floating point type. Test by simple to/from conversion.
10736 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10737 // could be avoided if there was a convertFromAPInt method
10738 // which could signal back if implicit truncation occurred.
10739 llvm::APSInt Result = EVResult.Val.getInt();
10740 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10741 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10742 RM: llvm::APFloat::rmTowardZero);
10743 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10744 !IntTy->hasSignedIntegerRepresentation());
10745 bool Ignored = false;
10746 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10747 IsExact: &Ignored);
10748 if (Result != ConvertBack)
10749 return true;
10750 } else {
10751 // Reject types that cannot be fully encoded into the mantissa of
10752 // the float.
10753 Bits = S.Context.getTypeSize(T: IntTy);
10754 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10755 S.Context.getFloatTypeSemantics(T: FloatTy));
10756 if (Bits > FloatPrec)
10757 return true;
10758 }
10759
10760 return false;
10761}
10762
10763/// Attempt to convert and splat Scalar into a vector whose types matches
10764/// Vector following GCC conversion rules. The rule is that implicit
10765/// conversion can occur when Scalar can be casted to match Vector's element
10766/// type without causing truncation of Scalar.
10767static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10768 ExprResult *Vector) {
10769 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10770 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10771 QualType VectorEltTy;
10772
10773 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10774 assert(!isa<ExtVectorType>(VT) &&
10775 "ExtVectorTypes should not be handled here!");
10776 VectorEltTy = VT->getElementType();
10777 } else if (VectorTy->isSveVLSBuiltinType()) {
10778 VectorEltTy =
10779 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10780 } else {
10781 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10782 }
10783
10784 // Reject cases where the vector element type or the scalar element type are
10785 // not integral or floating point types.
10786 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10787 return true;
10788
10789 // The conversion to apply to the scalar before splatting it,
10790 // if necessary.
10791 CastKind ScalarCast = CK_NoOp;
10792
10793 // Accept cases where the vector elements are integers and the scalar is
10794 // an integer.
10795 // FIXME: Notionally if the scalar was a floating point value with a precise
10796 // integral representation, we could cast it to an appropriate integer
10797 // type and then perform the rest of the checks here. GCC will perform
10798 // this conversion in some cases as determined by the input language.
10799 // We should accept it on a language independent basis.
10800 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10801 ScalarTy->isIntegralType(Ctx: S.Context) &&
10802 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10803
10804 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10805 return true;
10806
10807 ScalarCast = CK_IntegralCast;
10808 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10809 ScalarTy->isRealFloatingType()) {
10810 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10811 ScalarCast = CK_FloatingToIntegral;
10812 else
10813 return true;
10814 } else if (VectorEltTy->isRealFloatingType()) {
10815 if (ScalarTy->isRealFloatingType()) {
10816
10817 // Reject cases where the scalar type is not a constant and has a higher
10818 // Order than the vector element type.
10819 llvm::APFloat Result(0.0);
10820
10821 // Determine whether this is a constant scalar. In the event that the
10822 // value is dependent (and thus cannot be evaluated by the constant
10823 // evaluator), skip the evaluation. This will then diagnose once the
10824 // expression is instantiated.
10825 bool CstScalar = Scalar->get()->isValueDependent() ||
10826 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10827 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10828 if (!CstScalar && Order < 0)
10829 return true;
10830
10831 // If the scalar cannot be safely casted to the vector element type,
10832 // reject it.
10833 if (CstScalar) {
10834 bool Truncated = false;
10835 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10836 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10837 if (Truncated)
10838 return true;
10839 }
10840
10841 ScalarCast = CK_FloatingCast;
10842 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10843 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10844 return true;
10845
10846 ScalarCast = CK_IntegralToFloating;
10847 } else
10848 return true;
10849 } else if (ScalarTy->isEnumeralType())
10850 return true;
10851
10852 // Adjust scalar if desired.
10853 if (ScalarCast != CK_NoOp)
10854 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10855 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10856 return false;
10857}
10858
10859QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10860 SourceLocation Loc, bool IsCompAssign,
10861 bool AllowBothBool,
10862 bool AllowBoolConversions,
10863 bool AllowBoolOperation,
10864 bool ReportInvalid) {
10865 if (!IsCompAssign) {
10866 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10867 if (LHS.isInvalid())
10868 return QualType();
10869 }
10870 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10871 if (RHS.isInvalid())
10872 return QualType();
10873
10874 // For conversion purposes, we ignore any qualifiers.
10875 // For example, "const float" and "float" are equivalent.
10876 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10877 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10878
10879 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10880 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10881 assert(LHSVecType || RHSVecType);
10882
10883 if (getLangOpts().HLSL)
10884 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10885 IsCompAssign);
10886
10887 // Any operation with MFloat8 type is only possible with C intrinsics
10888 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10889 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10890 return InvalidOperands(Loc, LHS, RHS);
10891
10892 // AltiVec-style "vector bool op vector bool" combinations are allowed
10893 // for some operators but not others.
10894 if (!AllowBothBool && LHSVecType &&
10895 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10896 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10897 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10898
10899 // This operation may not be performed on boolean vectors.
10900 if (!AllowBoolOperation &&
10901 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10902 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10903
10904 // If the vector types are identical, return.
10905 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10906 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10907
10908 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10909 if (LHSVecType && RHSVecType &&
10910 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10911 if (isa<ExtVectorType>(Val: LHSVecType)) {
10912 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10913 return LHSType;
10914 }
10915
10916 if (!IsCompAssign)
10917 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10918 return RHSType;
10919 }
10920
10921 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10922 // can be mixed, with the result being the non-bool type. The non-bool
10923 // operand must have integer element type.
10924 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10925 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10926 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10927 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10928 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10929 LHSVecType->getElementType()->isIntegerType() &&
10930 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10931 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10932 return LHSType;
10933 }
10934 if (!IsCompAssign &&
10935 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10936 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10937 RHSVecType->getElementType()->isIntegerType()) {
10938 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10939 return RHSType;
10940 }
10941 }
10942
10943 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10944 // invalid since the ambiguity can affect the ABI.
10945 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10946 unsigned &SVEorRVV) {
10947 const VectorType *VecType = SecondType->getAs<VectorType>();
10948 SVEorRVV = 0;
10949 if (FirstType->isSizelessBuiltinType() && VecType) {
10950 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10951 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10952 return true;
10953 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10954 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10955 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10956 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10957 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10958 SVEorRVV = 1;
10959 return true;
10960 }
10961 }
10962
10963 return false;
10964 };
10965
10966 unsigned SVEorRVV;
10967 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10968 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10969 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10970 << SVEorRVV << LHSType << RHSType;
10971 return QualType();
10972 }
10973
10974 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10975 // invalid since the ambiguity can affect the ABI.
10976 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10977 unsigned &SVEorRVV) {
10978 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10979 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10980
10981 SVEorRVV = 0;
10982 if (FirstVecType && SecondVecType) {
10983 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10984 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10985 SecondVecType->getVectorKind() ==
10986 VectorKind::SveFixedLengthPredicate)
10987 return true;
10988 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10989 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10990 SecondVecType->getVectorKind() ==
10991 VectorKind::RVVFixedLengthMask_1 ||
10992 SecondVecType->getVectorKind() ==
10993 VectorKind::RVVFixedLengthMask_2 ||
10994 SecondVecType->getVectorKind() ==
10995 VectorKind::RVVFixedLengthMask_4) {
10996 SVEorRVV = 1;
10997 return true;
10998 }
10999 }
11000 return false;
11001 }
11002
11003 if (SecondVecType &&
11004 SecondVecType->getVectorKind() == VectorKind::Generic) {
11005 if (FirstType->isSVESizelessBuiltinType())
11006 return true;
11007 if (FirstType->isRVVSizelessBuiltinType()) {
11008 SVEorRVV = 1;
11009 return true;
11010 }
11011 }
11012
11013 return false;
11014 };
11015
11016 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11017 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11018 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
11019 << SVEorRVV << LHSType << RHSType;
11020 return QualType();
11021 }
11022
11023 // If there's a vector type and a scalar, try to convert the scalar to
11024 // the vector element type and splat.
11025 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11026 if (!RHSVecType) {
11027 if (isa<ExtVectorType>(Val: LHSVecType)) {
11028 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
11029 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
11030 DiagID))
11031 return LHSType;
11032 } else {
11033 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11034 return LHSType;
11035 }
11036 }
11037 if (!LHSVecType) {
11038 if (isa<ExtVectorType>(Val: RHSVecType)) {
11039 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
11040 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
11041 vectorTy: RHSType, DiagID))
11042 return RHSType;
11043 } else {
11044 if (LHS.get()->isLValue() ||
11045 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11046 return RHSType;
11047 }
11048 }
11049
11050 // FIXME: The code below also handles conversion between vectors and
11051 // non-scalars, we should break this down into fine grained specific checks
11052 // and emit proper diagnostics.
11053 QualType VecType = LHSVecType ? LHSType : RHSType;
11054 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11055 QualType OtherType = LHSVecType ? RHSType : LHSType;
11056 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11057 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
11058 if (Context.getTargetInfo().getTriple().isPPC() &&
11059 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
11060 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
11061 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11062 // If we're allowing lax vector conversions, only the total (data) size
11063 // needs to be the same. For non compound assignment, if one of the types is
11064 // scalar, the result is always the vector type.
11065 if (!IsCompAssign) {
11066 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
11067 return VecType;
11068 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11069 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11070 // type. Note that this is already done by non-compound assignments in
11071 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11072 // <1 x T> -> T. The result is also a vector type.
11073 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11074 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11075 ExprResult *RHSExpr = &RHS;
11076 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
11077 return VecType;
11078 }
11079 }
11080
11081 // Okay, the expression is invalid.
11082
11083 // If there's a non-vector, non-real operand, diagnose that.
11084 if ((!RHSVecType && !RHSType->isRealType()) ||
11085 (!LHSVecType && !LHSType->isRealType())) {
11086 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11087 << LHSType << RHSType
11088 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11089 return QualType();
11090 }
11091
11092 // OpenCL V1.1 6.2.6.p1:
11093 // If the operands are of more than one vector type, then an error shall
11094 // occur. Implicit conversions between vector types are not permitted, per
11095 // section 6.2.1.
11096 if (getLangOpts().OpenCL &&
11097 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
11098 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
11099 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
11100 << RHSType;
11101 return QualType();
11102 }
11103
11104
11105 // If there is a vector type that is not a ExtVector and a scalar, we reach
11106 // this point if scalar could not be converted to the vector's element type
11107 // without truncation.
11108 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11109 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11110 QualType Scalar = LHSVecType ? RHSType : LHSType;
11111 QualType Vector = LHSVecType ? LHSType : RHSType;
11112 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11113 Diag(Loc,
11114 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11115 << ScalarOrVector << Scalar << Vector;
11116
11117 return QualType();
11118 }
11119
11120 // Otherwise, use the generic diagnostic.
11121 Diag(Loc, DiagID)
11122 << LHSType << RHSType
11123 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11124 return QualType();
11125}
11126
11127QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11128 SourceLocation Loc,
11129 bool IsCompAssign,
11130 ArithConvKind OperationKind) {
11131 if (!IsCompAssign) {
11132 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11133 if (LHS.isInvalid())
11134 return QualType();
11135 }
11136 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11137 if (RHS.isInvalid())
11138 return QualType();
11139
11140 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11141 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11142
11143 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11144 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11145
11146 unsigned DiagID = diag::err_typecheck_invalid_operands;
11147 if ((OperationKind == ArithConvKind::Arithmetic) &&
11148 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11149 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11150 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11151 << RHS.get()->getSourceRange();
11152 return QualType();
11153 }
11154
11155 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11156 return LHSType;
11157
11158 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11159 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11160 return LHSType;
11161 }
11162 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11163 if (LHS.get()->isLValue() ||
11164 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11165 return RHSType;
11166 }
11167
11168 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11169 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11170 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11171 << LHSType << RHSType << LHS.get()->getSourceRange()
11172 << RHS.get()->getSourceRange();
11173 return QualType();
11174 }
11175
11176 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11177 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11178 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11179 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11180 << LHSType << RHSType << LHS.get()->getSourceRange()
11181 << RHS.get()->getSourceRange();
11182 return QualType();
11183 }
11184
11185 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11186 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11187 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11188 bool ScalarOrVector =
11189 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11190
11191 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11192 << ScalarOrVector << Scalar << Vector;
11193
11194 return QualType();
11195 }
11196
11197 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11198 << RHS.get()->getSourceRange();
11199 return QualType();
11200}
11201
11202// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11203// expression. These are mainly cases where the null pointer is used as an
11204// integer instead of a pointer.
11205static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11206 SourceLocation Loc, bool IsCompare) {
11207 // The canonical way to check for a GNU null is with isNullPointerConstant,
11208 // but we use a bit of a hack here for speed; this is a relatively
11209 // hot path, and isNullPointerConstant is slow.
11210 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11211 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11212
11213 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11214
11215 // Avoid analyzing cases where the result will either be invalid (and
11216 // diagnosed as such) or entirely valid and not something to warn about.
11217 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11218 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11219 return;
11220
11221 // Comparison operations would not make sense with a null pointer no matter
11222 // what the other expression is.
11223 if (!IsCompare) {
11224 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11225 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11226 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11227 return;
11228 }
11229
11230 // The rest of the operations only make sense with a null pointer
11231 // if the other expression is a pointer.
11232 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11233 NonNullType->canDecayToPointerType())
11234 return;
11235
11236 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11237 << LHSNull /* LHS is NULL */ << NonNullType
11238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11239}
11240
11241static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11242 SourceLocation OpLoc) {
11243 // If the divisor is real, then this is real/real or complex/real division.
11244 // Either way there can be no precision loss.
11245 auto *CT = DivisorTy->getAs<ComplexType>();
11246 if (!CT)
11247 return;
11248
11249 QualType ElementType = CT->getElementType().getCanonicalType();
11250 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11251 LangOptions::ComplexRangeKind::CX_Promoted;
11252 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11253 return;
11254
11255 ASTContext &Ctx = S.getASTContext();
11256 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11257 const llvm::fltSemantics &ElementTypeSemantics =
11258 Ctx.getFloatTypeSemantics(T: ElementType);
11259 const llvm::fltSemantics &HigherElementTypeSemantics =
11260 Ctx.getFloatTypeSemantics(T: HigherElementType);
11261
11262 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11263 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11264 (HigherElementType == Ctx.LongDoubleTy &&
11265 !Ctx.getTargetInfo().hasLongDoubleType())) {
11266 // Retain the location of the first use of higher precision type.
11267 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11268 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11269 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11270 if (Type == HigherElementType) {
11271 Num++;
11272 return;
11273 }
11274 }
11275 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11276 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11277 }
11278}
11279
11280static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11281 SourceLocation Loc) {
11282 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11283 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11284 if (!LUE || !RUE)
11285 return;
11286 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11287 RUE->getKind() != UETT_SizeOf)
11288 return;
11289
11290 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11291 QualType LHSTy = LHSArg->getType();
11292 QualType RHSTy;
11293
11294 if (RUE->isArgumentType())
11295 RHSTy = RUE->getArgumentType().getNonReferenceType();
11296 else
11297 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11298
11299 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11300 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11301 return;
11302
11303 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11304 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11305 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11306 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11307 << LHSArgDecl;
11308 }
11309 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11310 QualType ArrayElemTy = ArrayTy->getElementType();
11311 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11312 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11313 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11314 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11315 return;
11316 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11317 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11318 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11319 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11320 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11321 << LHSArgDecl;
11322 }
11323
11324 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11325 }
11326}
11327
11328static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11329 ExprResult &RHS,
11330 SourceLocation Loc, bool IsDiv) {
11331 // Check for division/remainder by zero.
11332 Expr::EvalResult RHSValue;
11333 if (!RHS.get()->isValueDependent() &&
11334 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11335 RHSValue.Val.getInt() == 0)
11336 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11337 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11338 << IsDiv << RHS.get()->getSourceRange());
11339}
11340
11341static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11342 const ExprResult &LHS, const ExprResult &RHS,
11343 BinaryOperatorKind Opc) {
11344 if (!LHS.isUsable() || !RHS.isUsable())
11345 return;
11346 const Expr *LHSExpr = LHS.get();
11347 const Expr *RHSExpr = RHS.get();
11348 const QualType LHSType = LHSExpr->getType();
11349 const QualType RHSType = RHSExpr->getType();
11350 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11351 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11352 if (!LHSIsScoped && !RHSIsScoped)
11353 return;
11354 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11355 return;
11356 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11357 return;
11358 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11359 return;
11360 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11361 SourceLocation BeginLoc = expr->getBeginLoc();
11362 QualType IntType = type->castAs<EnumType>()
11363 ->getDecl()
11364 ->getDefinitionOrSelf()
11365 ->getIntegerType();
11366 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11367 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11368 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11369 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11370 };
11371 if (LHSIsScoped) {
11372 DiagnosticHelper(LHSExpr, LHSType);
11373 }
11374 if (RHSIsScoped) {
11375 DiagnosticHelper(RHSExpr, RHSType);
11376 }
11377}
11378
11379QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11380 SourceLocation Loc,
11381 BinaryOperatorKind Opc) {
11382 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11383 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11384
11385 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11386
11387 QualType LHSTy = LHS.get()->getType();
11388 QualType RHSTy = RHS.get()->getType();
11389 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11390 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11391 /*AllowBothBool*/ getLangOpts().AltiVec,
11392 /*AllowBoolConversions*/ false,
11393 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11394 /*ReportInvalid*/ true);
11395 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11396 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11397 OperationKind: ArithConvKind::Arithmetic);
11398 if (!IsDiv &&
11399 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11400 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11401 // For division, only matrix-by-scalar is supported. Other combinations with
11402 // matrix types are invalid.
11403 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11404 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11405
11406 QualType compType = UsualArithmeticConversions(
11407 LHS, RHS, Loc,
11408 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11409 if (LHS.isInvalid() || RHS.isInvalid())
11410 return QualType();
11411
11412 if (compType.isNull() || !compType->isArithmeticType()) {
11413 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11414 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11415 return ResultTy;
11416 }
11417 if (IsDiv) {
11418 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11419 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11420 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11421 }
11422 return compType;
11423}
11424
11425QualType Sema::CheckRemainderOperands(
11426 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11427 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11428
11429 // Note: This check is here to simplify the double exclusions of
11430 // scalar and vector HLSL checks. No getLangOpts().HLSL
11431 // is needed since all languages exlcude doubles.
11432 if (LHS.get()->getType()->isDoubleType() ||
11433 RHS.get()->getType()->isDoubleType() ||
11434 (LHS.get()->getType()->isVectorType() && LHS.get()
11435 ->getType()
11436 ->getAs<VectorType>()
11437 ->getElementType()
11438 ->isDoubleType()) ||
11439 (RHS.get()->getType()->isVectorType() && RHS.get()
11440 ->getType()
11441 ->getAs<VectorType>()
11442 ->getElementType()
11443 ->isDoubleType()))
11444 return InvalidOperands(Loc, LHS, RHS);
11445
11446 if (LHS.get()->getType()->isVectorType() ||
11447 RHS.get()->getType()->isVectorType()) {
11448 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11449 RHS.get()->getType()->hasIntegerRepresentation()) ||
11450 (getLangOpts().HLSL &&
11451 (LHS.get()->getType()->hasFloatingRepresentation() ||
11452 RHS.get()->getType()->hasFloatingRepresentation())))
11453 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11454 /*AllowBothBool*/ getLangOpts().AltiVec,
11455 /*AllowBoolConversions*/ false,
11456 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11457 /*ReportInvalid*/ true);
11458 return InvalidOperands(Loc, LHS, RHS);
11459 }
11460
11461 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11462 RHS.get()->getType()->isSveVLSBuiltinType()) {
11463 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11464 RHS.get()->getType()->hasIntegerRepresentation())
11465 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11466 OperationKind: ArithConvKind::Arithmetic);
11467
11468 return InvalidOperands(Loc, LHS, RHS);
11469 }
11470
11471 QualType compType = UsualArithmeticConversions(
11472 LHS, RHS, Loc,
11473 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11474 if (LHS.isInvalid() || RHS.isInvalid())
11475 return QualType();
11476
11477 if (compType.isNull() ||
11478 (!compType->isIntegerType() &&
11479 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11480 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11481 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11482 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11483 return ResultTy;
11484 }
11485 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11486 return compType;
11487}
11488
11489/// Diagnose invalid arithmetic on two void pointers.
11490static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11491 Expr *LHSExpr, Expr *RHSExpr) {
11492 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11493 ? diag::err_typecheck_pointer_arith_void_type
11494 : diag::ext_gnu_void_ptr)
11495 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11496 << RHSExpr->getSourceRange();
11497}
11498
11499/// Diagnose invalid arithmetic on a void pointer.
11500static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11501 Expr *Pointer) {
11502 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11503 ? diag::err_typecheck_pointer_arith_void_type
11504 : diag::ext_gnu_void_ptr)
11505 << 0 /* one pointer */ << Pointer->getSourceRange();
11506}
11507
11508/// Diagnose invalid arithmetic on a null pointer.
11509///
11510/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11511/// idiom, which we recognize as a GNU extension.
11512///
11513static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11514 Expr *Pointer, bool IsGNUIdiom) {
11515 if (IsGNUIdiom)
11516 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11517 << Pointer->getSourceRange();
11518 else
11519 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11520 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11521}
11522
11523/// Diagnose invalid subraction on a null pointer.
11524///
11525static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11526 Expr *Pointer, bool BothNull) {
11527 // Null - null is valid in C++ [expr.add]p7
11528 if (BothNull && S.getLangOpts().CPlusPlus)
11529 return;
11530
11531 // Is this s a macro from a system header?
11532 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11533 return;
11534
11535 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11536 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11537 << S.getLangOpts().CPlusPlus
11538 << Pointer->getSourceRange());
11539}
11540
11541/// Diagnose invalid arithmetic on two function pointers.
11542static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11543 Expr *LHS, Expr *RHS) {
11544 assert(LHS->getType()->isAnyPointerType());
11545 assert(RHS->getType()->isAnyPointerType());
11546 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11547 ? diag::err_typecheck_pointer_arith_function_type
11548 : diag::ext_gnu_ptr_func_arith)
11549 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11550 // We only show the second type if it differs from the first.
11551 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11552 T2: RHS->getType())
11553 << RHS->getType()->getPointeeType()
11554 << LHS->getSourceRange() << RHS->getSourceRange();
11555}
11556
11557/// Diagnose invalid arithmetic on a function pointer.
11558static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11559 Expr *Pointer) {
11560 assert(Pointer->getType()->isAnyPointerType());
11561 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11562 ? diag::err_typecheck_pointer_arith_function_type
11563 : diag::ext_gnu_ptr_func_arith)
11564 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11565 << 0 /* one pointer, so only one type */
11566 << Pointer->getSourceRange();
11567}
11568
11569/// Emit error if Operand is incomplete pointer type
11570///
11571/// \returns True if pointer has incomplete type
11572static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11573 Expr *Operand) {
11574 QualType ResType = Operand->getType();
11575 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11576 ResType = ResAtomicType->getValueType();
11577
11578 assert(ResType->isAnyPointerType());
11579 QualType PointeeTy = ResType->getPointeeType();
11580 return S.RequireCompleteSizedType(
11581 Loc, T: PointeeTy,
11582 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11583 Args: Operand->getSourceRange());
11584}
11585
11586/// Check the validity of an arithmetic pointer operand.
11587///
11588/// If the operand has pointer type, this code will check for pointer types
11589/// which are invalid in arithmetic operations. These will be diagnosed
11590/// appropriately, including whether or not the use is supported as an
11591/// extension.
11592///
11593/// \returns True when the operand is valid to use (even if as an extension).
11594static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11595 Expr *Operand) {
11596 QualType ResType = Operand->getType();
11597 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11598 ResType = ResAtomicType->getValueType();
11599
11600 if (!ResType->isAnyPointerType()) return true;
11601
11602 QualType PointeeTy = ResType->getPointeeType();
11603 if (PointeeTy->isVoidType()) {
11604 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11605 return !S.getLangOpts().CPlusPlus;
11606 }
11607 if (PointeeTy->isFunctionType()) {
11608 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11609 return !S.getLangOpts().CPlusPlus;
11610 }
11611
11612 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11613
11614 return true;
11615}
11616
11617/// Check the validity of a binary arithmetic operation w.r.t. pointer
11618/// operands.
11619///
11620/// This routine will diagnose any invalid arithmetic on pointer operands much
11621/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11622/// for emitting a single diagnostic even for operations where both LHS and RHS
11623/// are (potentially problematic) pointers.
11624///
11625/// \returns True when the operand is valid to use (even if as an extension).
11626static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11627 Expr *LHSExpr, Expr *RHSExpr) {
11628 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11629 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11630 if (!isLHSPointer && !isRHSPointer) return true;
11631
11632 QualType LHSPointeeTy, RHSPointeeTy;
11633 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11634 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11635
11636 // if both are pointers check if operation is valid wrt address spaces
11637 if (isLHSPointer && isRHSPointer) {
11638 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11639 Ctx: S.getASTContext())) {
11640 S.Diag(Loc,
11641 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11642 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11643 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11644 return false;
11645 }
11646 }
11647
11648 // Check for arithmetic on pointers to incomplete types.
11649 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11650 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11651 if (isLHSVoidPtr || isRHSVoidPtr) {
11652 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11653 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11654 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11655
11656 return !S.getLangOpts().CPlusPlus;
11657 }
11658
11659 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11660 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11661 if (isLHSFuncPtr || isRHSFuncPtr) {
11662 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11663 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11664 Pointer: RHSExpr);
11665 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11666
11667 return !S.getLangOpts().CPlusPlus;
11668 }
11669
11670 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11671 return false;
11672 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11673 return false;
11674
11675 return true;
11676}
11677
11678/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11679/// literal.
11680static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11681 Expr *LHSExpr, Expr *RHSExpr) {
11682 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11683 Expr* IndexExpr = RHSExpr;
11684 if (!StrExpr) {
11685 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11686 IndexExpr = LHSExpr;
11687 }
11688
11689 bool IsStringPlusInt = StrExpr &&
11690 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11691 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11692 return;
11693
11694 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11695 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11696 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11697
11698 // Only print a fixit for "str" + int, not for int + "str".
11699 if (IndexExpr == RHSExpr) {
11700 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11701 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11702 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11703 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11704 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11705 } else
11706 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11707}
11708
11709/// Emit a warning when adding a char literal to a string.
11710static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11711 Expr *LHSExpr, Expr *RHSExpr) {
11712 const Expr *StringRefExpr = LHSExpr;
11713 const CharacterLiteral *CharExpr =
11714 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11715
11716 if (!CharExpr) {
11717 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11718 StringRefExpr = RHSExpr;
11719 }
11720
11721 if (!CharExpr || !StringRefExpr)
11722 return;
11723
11724 const QualType StringType = StringRefExpr->getType();
11725
11726 // Return if not a PointerType.
11727 if (!StringType->isAnyPointerType())
11728 return;
11729
11730 // Return if not a CharacterType.
11731 if (!StringType->getPointeeType()->isAnyCharacterType())
11732 return;
11733
11734 ASTContext &Ctx = Self.getASTContext();
11735 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11736
11737 const QualType CharType = CharExpr->getType();
11738 if (!CharType->isAnyCharacterType() &&
11739 CharType->isIntegerType() &&
11740 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11741 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11742 << DiagRange << Ctx.CharTy;
11743 } else {
11744 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11745 << DiagRange << CharExpr->getType();
11746 }
11747
11748 // Only print a fixit for str + char, not for char + str.
11749 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11750 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11751 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11752 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11753 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11754 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11755 } else {
11756 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11757 }
11758}
11759
11760/// Emit error when two pointers are incompatible.
11761static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11762 Expr *LHSExpr, Expr *RHSExpr) {
11763 assert(LHSExpr->getType()->isAnyPointerType());
11764 assert(RHSExpr->getType()->isAnyPointerType());
11765 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11766 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11767 << RHSExpr->getSourceRange();
11768}
11769
11770// C99 6.5.6
11771QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11772 SourceLocation Loc, BinaryOperatorKind Opc,
11773 QualType* CompLHSTy) {
11774 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11775
11776 if (LHS.get()->getType()->isVectorType() ||
11777 RHS.get()->getType()->isVectorType()) {
11778 QualType compType =
11779 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11780 /*AllowBothBool*/ getLangOpts().AltiVec,
11781 /*AllowBoolConversions*/ getLangOpts().ZVector,
11782 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11783 /*ReportInvalid*/ true);
11784 if (CompLHSTy) *CompLHSTy = compType;
11785 return compType;
11786 }
11787
11788 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11789 RHS.get()->getType()->isSveVLSBuiltinType()) {
11790 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11791 OperationKind: ArithConvKind::Arithmetic);
11792 if (CompLHSTy)
11793 *CompLHSTy = compType;
11794 return compType;
11795 }
11796
11797 if (LHS.get()->getType()->isConstantMatrixType() ||
11798 RHS.get()->getType()->isConstantMatrixType()) {
11799 QualType compType =
11800 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11801 if (CompLHSTy)
11802 *CompLHSTy = compType;
11803 return compType;
11804 }
11805
11806 QualType compType = UsualArithmeticConversions(
11807 LHS, RHS, Loc,
11808 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11809 if (LHS.isInvalid() || RHS.isInvalid())
11810 return QualType();
11811
11812 // Diagnose "string literal" '+' int and string '+' "char literal".
11813 if (Opc == BO_Add) {
11814 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11815 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11816 }
11817
11818 // handle the common case first (both operands are arithmetic).
11819 if (!compType.isNull() && compType->isArithmeticType()) {
11820 if (CompLHSTy) *CompLHSTy = compType;
11821 return compType;
11822 }
11823
11824 // Type-checking. Ultimately the pointer's going to be in PExp;
11825 // note that we bias towards the LHS being the pointer.
11826 Expr *PExp = LHS.get(), *IExp = RHS.get();
11827
11828 bool isObjCPointer;
11829 if (PExp->getType()->isPointerType()) {
11830 isObjCPointer = false;
11831 } else if (PExp->getType()->isObjCObjectPointerType()) {
11832 isObjCPointer = true;
11833 } else {
11834 std::swap(a&: PExp, b&: IExp);
11835 if (PExp->getType()->isPointerType()) {
11836 isObjCPointer = false;
11837 } else if (PExp->getType()->isObjCObjectPointerType()) {
11838 isObjCPointer = true;
11839 } else {
11840 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11841 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11842 return ResultTy;
11843 }
11844 }
11845 assert(PExp->getType()->isAnyPointerType());
11846
11847 if (!IExp->getType()->isIntegerType())
11848 return InvalidOperands(Loc, LHS, RHS);
11849
11850 // Adding to a null pointer results in undefined behavior.
11851 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11852 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11853 // In C++ adding zero to a null pointer is defined.
11854 Expr::EvalResult KnownVal;
11855 if (!getLangOpts().CPlusPlus ||
11856 (!IExp->isValueDependent() &&
11857 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11858 KnownVal.Val.getInt() != 0))) {
11859 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11860 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11861 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11862 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11863 }
11864 }
11865
11866 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11867 return QualType();
11868
11869 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11870 return QualType();
11871
11872 // Arithmetic on label addresses is normally allowed, except when we add
11873 // a ptrauth signature to the addresses.
11874 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11875 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11876 << /*addition*/ 1;
11877 return QualType();
11878 }
11879
11880 // Check array bounds for pointer arithemtic
11881 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11882
11883 if (CompLHSTy) {
11884 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11885 if (LHSTy.isNull()) {
11886 LHSTy = LHS.get()->getType();
11887 if (Context.isPromotableIntegerType(T: LHSTy))
11888 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11889 }
11890 *CompLHSTy = LHSTy;
11891 }
11892
11893 return PExp->getType();
11894}
11895
11896/// Determine whether the size of \p T is provably zero: some array dimension
11897/// is provably zero or the base element type has zero size. A variable
11898/// dimension that does not fold to an integer constant is assumed nonzero.
11899static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T) {
11900 while (const ArrayType *AT = Ctx.getAsArrayType(T)) {
11901 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
11902 if (CAT->isZeroSize())
11903 return true;
11904 } else if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
11905 if (const Expr *Bound = VAT->getSizeExpr())
11906 if (std::optional<llvm::APSInt> Size =
11907 Bound->getIntegerConstantExpr(Ctx))
11908 if (*Size == 0)
11909 return true;
11910 }
11911 T = AT->getElementType();
11912 }
11913 return !T->isIncompleteType() && Ctx.getTypeSizeInChars(T).isZero();
11914}
11915
11916// C99 6.5.6
11917QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11918 SourceLocation Loc,
11919 BinaryOperatorKind Opc,
11920 QualType *CompLHSTy) {
11921 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11922
11923 if (LHS.get()->getType()->isVectorType() ||
11924 RHS.get()->getType()->isVectorType()) {
11925 QualType compType =
11926 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11927 /*AllowBothBool*/ getLangOpts().AltiVec,
11928 /*AllowBoolConversions*/ getLangOpts().ZVector,
11929 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11930 /*ReportInvalid*/ true);
11931 if (CompLHSTy) *CompLHSTy = compType;
11932 return compType;
11933 }
11934
11935 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11936 RHS.get()->getType()->isSveVLSBuiltinType()) {
11937 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11938 OperationKind: ArithConvKind::Arithmetic);
11939 if (CompLHSTy)
11940 *CompLHSTy = compType;
11941 return compType;
11942 }
11943
11944 if (LHS.get()->getType()->isConstantMatrixType() ||
11945 RHS.get()->getType()->isConstantMatrixType()) {
11946 QualType compType =
11947 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11948 if (CompLHSTy)
11949 *CompLHSTy = compType;
11950 return compType;
11951 }
11952
11953 QualType compType = UsualArithmeticConversions(
11954 LHS, RHS, Loc,
11955 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11956 if (LHS.isInvalid() || RHS.isInvalid())
11957 return QualType();
11958
11959 // Enforce type constraints: C99 6.5.6p3.
11960
11961 // Handle the common case first (both operands are arithmetic).
11962 if (!compType.isNull() && compType->isArithmeticType()) {
11963 if (CompLHSTy) *CompLHSTy = compType;
11964 return compType;
11965 }
11966
11967 // Either ptr - int or ptr - ptr.
11968 if (LHS.get()->getType()->isAnyPointerType()) {
11969 QualType lpointee = LHS.get()->getType()->getPointeeType();
11970
11971 // Diagnose bad cases where we step over interface counts.
11972 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11973 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11974 return QualType();
11975
11976 // Arithmetic on label addresses is normally allowed, except when we add
11977 // a ptrauth signature to the addresses.
11978 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11979 getLangOpts().PointerAuthIndirectGotos) {
11980 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11981 << /*subtraction*/ 0;
11982 return QualType();
11983 }
11984
11985 // The result type of a pointer-int computation is the pointer type.
11986 if (RHS.get()->getType()->isIntegerType()) {
11987 // Subtracting from a null pointer should produce a warning.
11988 // The last argument to the diagnose call says this doesn't match the
11989 // GNU int-to-pointer idiom.
11990 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11991 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11992 // In C++ adding zero to a null pointer is defined.
11993 Expr::EvalResult KnownVal;
11994 if (!getLangOpts().CPlusPlus ||
11995 (!RHS.get()->isValueDependent() &&
11996 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11997 KnownVal.Val.getInt() != 0))) {
11998 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11999 }
12000 }
12001
12002 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
12003 return QualType();
12004
12005 // Check array bounds for pointer arithemtic
12006 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
12007 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12008
12009 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12010 return LHS.get()->getType();
12011 }
12012
12013 // Handle pointer-pointer subtractions.
12014 if (const PointerType *RHSPTy
12015 = RHS.get()->getType()->getAs<PointerType>()) {
12016 QualType rpointee = RHSPTy->getPointeeType();
12017
12018 if (getLangOpts().CPlusPlus) {
12019 // Pointee types must be the same: C++ [expr.add]
12020 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
12021 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12022 }
12023 } else {
12024 // Pointee types must be compatible C99 6.5.6p3
12025 if (!Context.typesAreCompatible(
12026 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
12027 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
12028 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12029 return QualType();
12030 }
12031 }
12032
12033 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
12034 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
12035 return QualType();
12036
12037 // For pointer subtraction, if the address spaces differ but overlap,
12038 // convert both pointers to the composite (superset) address space.
12039 // This is needed because address spaces may use different
12040 // representations, such as a private offset vs a flat address.
12041 LangAS LAddrSpace = lpointee.getAddressSpace();
12042 LangAS RAddrSpace = rpointee.getAddressSpace();
12043 if (LAddrSpace != RAddrSpace) {
12044 Qualifiers LQual = lpointee.getQualifiers();
12045 Qualifiers RQual = rpointee.getQualifiers();
12046 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(other: RQual, Ctx: Context)
12047 ? LAddrSpace
12048 : RAddrSpace;
12049
12050 if (LAddrSpace != ResultAddrSpace) {
12051 QualType NewPteTy = Context.getAddrSpaceQualType(
12052 T: lpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12053 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12054 LHS =
12055 ImpCastExprToType(E: LHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12056 }
12057 if (RAddrSpace != ResultAddrSpace) {
12058 QualType NewPteTy = Context.getAddrSpaceQualType(
12059 T: rpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12060 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12061 RHS =
12062 ImpCastExprToType(E: RHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12063 }
12064 }
12065
12066 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12067 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12068 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12069 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12070
12071 // Subtracting nullptr or from nullptr is suspect
12072 if (LHSIsNullPtr)
12073 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
12074 if (RHSIsNullPtr)
12075 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
12076
12077 // The pointee type may have zero size. As an extension, a structure or
12078 // union may have zero size or an array may have zero length. In this
12079 // case subtraction does not make sense. For a variably modified type,
12080 // warn only when the size is provably zero.
12081 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12082 isProvablyZeroSize(Ctx: Context, T: rpointee))
12083 Diag(Loc, DiagID: diag::warn_sub_ptr_zero_size_types)
12084 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12085 << RHS.get()->getSourceRange();
12086
12087 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12088 return Context.getPointerDiffType();
12089 }
12090 }
12091
12092 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12093 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12094 return ResultTy;
12095}
12096
12097static bool isScopedEnumerationType(QualType T) {
12098 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12099 return ET->getDecl()->isScoped();
12100 return false;
12101}
12102
12103static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12104 SourceLocation Loc, BinaryOperatorKind Opc,
12105 QualType LHSType) {
12106 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12107 // so skip remaining warnings as we don't want to modify values within Sema.
12108 if (S.getLangOpts().OpenCL)
12109 return;
12110
12111 if (Opc == BO_Shr &&
12112 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
12113 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
12114
12115 // Check right/shifter operand
12116 Expr::EvalResult RHSResult;
12117 if (RHS.get()->isValueDependent() ||
12118 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
12119 return;
12120 llvm::APSInt Right = RHSResult.Val.getInt();
12121
12122 if (Right.isNegative()) {
12123 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12124 PD: S.PDiag(DiagID: diag::warn_shift_negative)
12125 << RHS.get()->getSourceRange());
12126 return;
12127 }
12128
12129 QualType LHSExprType = LHS.get()->getType();
12130 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
12131 if (LHSExprType->isBitIntType())
12132 LeftSize = S.Context.getIntWidth(T: LHSExprType);
12133 else if (LHSExprType->isFixedPointType()) {
12134 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
12135 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12136 }
12137 if (Right.uge(RHS: LeftSize)) {
12138 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12139 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
12140 << RHS.get()->getSourceRange());
12141 return;
12142 }
12143
12144 // FIXME: We probably need to handle fixed point types specially here.
12145 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12146 return;
12147
12148 // When left shifting an ICE which is signed, we can check for overflow which
12149 // according to C++ standards prior to C++2a has undefined behavior
12150 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12151 // more than the maximum value representable in the result type, so never
12152 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12153 // expression is still probably a bug.)
12154 Expr::EvalResult LHSResult;
12155 if (LHS.get()->isValueDependent() ||
12156 LHSType->hasUnsignedIntegerRepresentation() ||
12157 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12158 return;
12159 llvm::APSInt Left = LHSResult.Val.getInt();
12160
12161 // Don't warn if signed overflow is defined, then all the rest of the
12162 // diagnostics will not be triggered because the behavior is defined.
12163 // Also don't warn in C++20 mode (and newer), as signed left shifts
12164 // always wrap and never overflow.
12165 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12166 return;
12167
12168 // If LHS does not have a non-negative value then, the
12169 // behavior is undefined before C++2a. Warn about it.
12170 if (Left.isNegative()) {
12171 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
12172 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
12173 << LHS.get()->getSourceRange());
12174 return;
12175 }
12176
12177 llvm::APInt ResultBits =
12178 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12179 if (ResultBits.ule(RHS: LeftSize))
12180 return;
12181 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12182 Result = Result.shl(ShiftAmt: Right);
12183
12184 // Print the bit representation of the signed integer as an unsigned
12185 // hexadecimal number.
12186 SmallString<40> HexResult;
12187 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12188
12189 // If we are only missing a sign bit, this is less likely to result in actual
12190 // bugs -- if the result is cast back to an unsigned type, it will have the
12191 // expected value. Thus we place this behind a different warning that can be
12192 // turned off separately if needed.
12193 if (ResultBits - 1 == LeftSize) {
12194 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12195 << HexResult << LHSType
12196 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12197 return;
12198 }
12199
12200 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12201 << HexResult.str() << Result.getSignificantBits() << LHSType
12202 << Left.getBitWidth() << LHS.get()->getSourceRange()
12203 << RHS.get()->getSourceRange();
12204}
12205
12206/// Return the resulting type when a vector is shifted
12207/// by a scalar or vector shift amount.
12208static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12209 SourceLocation Loc, bool IsCompAssign) {
12210 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12211 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12212 !LHS.get()->getType()->isVectorType()) {
12213 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12214 << RHS.get()->getType() << LHS.get()->getType()
12215 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12216 return QualType();
12217 }
12218
12219 if (!IsCompAssign) {
12220 LHS = S.UsualUnaryConversions(E: LHS.get());
12221 if (LHS.isInvalid()) return QualType();
12222 }
12223
12224 RHS = S.UsualUnaryConversions(E: RHS.get());
12225 if (RHS.isInvalid()) return QualType();
12226
12227 QualType LHSType = LHS.get()->getType();
12228 // Note that LHS might be a scalar because the routine calls not only in
12229 // OpenCL case.
12230 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12231 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12232
12233 // Note that RHS might not be a vector.
12234 QualType RHSType = RHS.get()->getType();
12235 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12236 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12237
12238 // Do not allow shifts for boolean vectors.
12239 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12240 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12241 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12242 << LHS.get()->getType() << RHS.get()->getType()
12243 << LHS.get()->getSourceRange();
12244 return QualType();
12245 }
12246
12247 // The operands need to be integers.
12248 if (!LHSEleType->isIntegerType()) {
12249 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12250 << LHS.get()->getType() << LHS.get()->getSourceRange();
12251 return QualType();
12252 }
12253
12254 if (!RHSEleType->isIntegerType()) {
12255 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12256 << RHS.get()->getType() << RHS.get()->getSourceRange();
12257 return QualType();
12258 }
12259
12260 if (!LHSVecTy) {
12261 assert(RHSVecTy);
12262 if (IsCompAssign)
12263 return RHSType;
12264 if (LHSEleType != RHSEleType) {
12265 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12266 LHSEleType = RHSEleType;
12267 }
12268 QualType VecTy =
12269 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12270 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12271 LHSType = VecTy;
12272 } else if (RHSVecTy) {
12273 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12274 // are applied component-wise. So if RHS is a vector, then ensure
12275 // that the number of elements is the same as LHS...
12276 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12277 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12278 << LHS.get()->getType() << RHS.get()->getType()
12279 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12280 return QualType();
12281 }
12282 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12283 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12284 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12285 if (LHSBT != RHSBT &&
12286 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12287 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12288 << LHS.get()->getType() << RHS.get()->getType()
12289 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12290 }
12291 }
12292 } else {
12293 // ...else expand RHS to match the number of elements in LHS.
12294 QualType VecTy =
12295 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12296 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12297 }
12298
12299 return LHSType;
12300}
12301
12302static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12303 ExprResult &RHS, SourceLocation Loc,
12304 bool IsCompAssign) {
12305 if (!IsCompAssign) {
12306 LHS = S.UsualUnaryConversions(E: LHS.get());
12307 if (LHS.isInvalid())
12308 return QualType();
12309 }
12310
12311 RHS = S.UsualUnaryConversions(E: RHS.get());
12312 if (RHS.isInvalid())
12313 return QualType();
12314
12315 QualType LHSType = LHS.get()->getType();
12316 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12317 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12318 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12319 : LHSType;
12320
12321 // Note that RHS might not be a vector
12322 QualType RHSType = RHS.get()->getType();
12323 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12324 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12325 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12326 : RHSType;
12327
12328 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12329 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12330 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12331 << LHSType << RHSType << LHS.get()->getSourceRange();
12332 return QualType();
12333 }
12334
12335 if (!LHSEleType->isIntegerType()) {
12336 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12337 << LHS.get()->getType() << LHS.get()->getSourceRange();
12338 return QualType();
12339 }
12340
12341 if (!RHSEleType->isIntegerType()) {
12342 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12343 << RHS.get()->getType() << RHS.get()->getSourceRange();
12344 return QualType();
12345 }
12346
12347 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12348 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12349 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12350 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12351 << LHSType << RHSType << LHS.get()->getSourceRange()
12352 << RHS.get()->getSourceRange();
12353 return QualType();
12354 }
12355
12356 if (!LHSType->isSveVLSBuiltinType()) {
12357 assert(RHSType->isSveVLSBuiltinType());
12358 if (IsCompAssign)
12359 return RHSType;
12360 if (LHSEleType != RHSEleType) {
12361 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12362 LHSEleType = RHSEleType;
12363 }
12364 const llvm::ElementCount VecSize =
12365 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12366 QualType VecTy =
12367 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12368 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12369 LHSType = VecTy;
12370 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12371 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12372 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12373 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12374 << LHSType << RHSType << LHS.get()->getSourceRange()
12375 << RHS.get()->getSourceRange();
12376 return QualType();
12377 }
12378 } else {
12379 const llvm::ElementCount VecSize =
12380 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12381 if (LHSEleType != RHSEleType) {
12382 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12383 RHSEleType = LHSEleType;
12384 }
12385 QualType VecTy =
12386 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12387 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12388 }
12389
12390 return LHSType;
12391}
12392
12393// C99 6.5.7
12394QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12395 SourceLocation Loc, BinaryOperatorKind Opc,
12396 bool IsCompAssign) {
12397 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12398
12399 // Vector shifts promote their scalar inputs to vector type.
12400 if (LHS.get()->getType()->isVectorType() ||
12401 RHS.get()->getType()->isVectorType()) {
12402 if (LangOpts.ZVector) {
12403 // The shift operators for the z vector extensions work basically
12404 // like general shifts, except that neither the LHS nor the RHS is
12405 // allowed to be a "vector bool".
12406 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12407 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12408 return InvalidOperands(Loc, LHS, RHS);
12409 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12410 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12411 return InvalidOperands(Loc, LHS, RHS);
12412 }
12413 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12414 }
12415
12416 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12417 RHS.get()->getType()->isSveVLSBuiltinType())
12418 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12419
12420 // Shifts don't perform usual arithmetic conversions, they just do integer
12421 // promotions on each operand. C99 6.5.7p3
12422
12423 // For the LHS, do usual unary conversions, but then reset them away
12424 // if this is a compound assignment.
12425 ExprResult OldLHS = LHS;
12426 LHS = UsualUnaryConversions(E: LHS.get());
12427 if (LHS.isInvalid())
12428 return QualType();
12429 QualType LHSType = LHS.get()->getType();
12430 if (IsCompAssign) LHS = OldLHS;
12431
12432 // The RHS is simpler.
12433 RHS = UsualUnaryConversions(E: RHS.get());
12434 if (RHS.isInvalid())
12435 return QualType();
12436 QualType RHSType = RHS.get()->getType();
12437
12438 // C99 6.5.7p2: Each of the operands shall have integer type.
12439 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12440 if ((!LHSType->isFixedPointOrIntegerType() &&
12441 !LHSType->hasIntegerRepresentation()) ||
12442 !RHSType->hasIntegerRepresentation()) {
12443 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12444 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12445 return ResultTy;
12446 }
12447
12448 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12449
12450 // "The type of the result is that of the promoted left operand."
12451 return LHSType;
12452}
12453
12454/// Diagnose bad pointer comparisons.
12455static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12456 ExprResult &LHS, ExprResult &RHS,
12457 bool IsError) {
12458 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12459 : diag::ext_typecheck_comparison_of_distinct_pointers)
12460 << LHS.get()->getType() << RHS.get()->getType()
12461 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12462}
12463
12464/// Returns false if the pointers are converted to a composite type,
12465/// true otherwise.
12466static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12467 ExprResult &LHS, ExprResult &RHS) {
12468 // C++ [expr.rel]p2:
12469 // [...] Pointer conversions (4.10) and qualification
12470 // conversions (4.4) are performed on pointer operands (or on
12471 // a pointer operand and a null pointer constant) to bring
12472 // them to their composite pointer type. [...]
12473 //
12474 // C++ [expr.eq]p1 uses the same notion for (in)equality
12475 // comparisons of pointers.
12476
12477 QualType LHSType = LHS.get()->getType();
12478 QualType RHSType = RHS.get()->getType();
12479 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12480 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12481
12482 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12483 if (T.isNull()) {
12484 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12485 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12486 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12487 else
12488 S.InvalidOperands(Loc, LHS, RHS);
12489 return true;
12490 }
12491
12492 return false;
12493}
12494
12495static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12496 ExprResult &LHS,
12497 ExprResult &RHS,
12498 bool IsError) {
12499 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12500 : diag::ext_typecheck_comparison_of_fptr_to_void)
12501 << LHS.get()->getType() << RHS.get()->getType()
12502 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12503}
12504
12505static bool isObjCObjectLiteral(ExprResult &E) {
12506 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12507 case Stmt::ObjCArrayLiteralClass:
12508 case Stmt::ObjCDictionaryLiteralClass:
12509 case Stmt::ObjCStringLiteralClass:
12510 case Stmt::ObjCBoxedExprClass:
12511 return true;
12512 default:
12513 // Note that ObjCBoolLiteral is NOT an object literal!
12514 return false;
12515 }
12516}
12517
12518static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12519 const ObjCObjectPointerType *Type =
12520 LHS->getType()->getAs<ObjCObjectPointerType>();
12521
12522 // If this is not actually an Objective-C object, bail out.
12523 if (!Type)
12524 return false;
12525
12526 // Get the LHS object's interface type.
12527 QualType InterfaceType = Type->getPointeeType();
12528
12529 // If the RHS isn't an Objective-C object, bail out.
12530 if (!RHS->getType()->isObjCObjectPointerType())
12531 return false;
12532
12533 // Try to find the -isEqual: method.
12534 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12535 ObjCMethodDecl *Method =
12536 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12537 /*IsInstance=*/true);
12538 if (!Method) {
12539 if (Type->isObjCIdType()) {
12540 // For 'id', just check the global pool.
12541 Method =
12542 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12543 /*receiverId=*/receiverIdOrClass: true);
12544 } else {
12545 // Check protocols.
12546 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12547 /*IsInstance=*/true);
12548 }
12549 }
12550
12551 if (!Method)
12552 return false;
12553
12554 QualType T = Method->parameters()[0]->getType();
12555 if (!T->isObjCObjectPointerType())
12556 return false;
12557
12558 QualType R = Method->getReturnType();
12559 if (!R->isScalarType())
12560 return false;
12561
12562 return true;
12563}
12564
12565static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12566 ExprResult &LHS, ExprResult &RHS,
12567 BinaryOperator::Opcode Opc){
12568 Expr *Literal;
12569 Expr *Other;
12570 if (isObjCObjectLiteral(E&: LHS)) {
12571 Literal = LHS.get();
12572 Other = RHS.get();
12573 } else {
12574 Literal = RHS.get();
12575 Other = LHS.get();
12576 }
12577
12578 // Don't warn on comparisons against nil.
12579 Other = Other->IgnoreParenCasts();
12580 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12581 NPC: Expr::NPC_ValueDependentIsNotNull))
12582 return;
12583
12584 // This should be kept in sync with warn_objc_literal_comparison.
12585 // LK_String should always be after the other literals, since it has its own
12586 // warning flag.
12587 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12588 assert(LiteralKind != SemaObjC::LK_Block);
12589 if (LiteralKind == SemaObjC::LK_None) {
12590 llvm_unreachable("Unknown Objective-C object literal kind");
12591 }
12592
12593 if (LiteralKind == SemaObjC::LK_String)
12594 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12595 << Literal->getSourceRange();
12596 else
12597 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12598 << LiteralKind << Literal->getSourceRange();
12599
12600 if (BinaryOperator::isEqualityOp(Opc) &&
12601 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12602 SourceLocation Start = LHS.get()->getBeginLoc();
12603 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12604 CharSourceRange OpRange =
12605 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12606
12607 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12608 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12609 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12610 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12611 }
12612}
12613
12614/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12615static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12616 ExprResult &RHS, SourceLocation Loc,
12617 BinaryOperatorKind Opc) {
12618 // Check that left hand side is !something.
12619 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12620 if (!UO || UO->getOpcode() != UO_LNot) return;
12621
12622 // Only check if the right hand side is non-bool arithmetic type.
12623 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12624
12625 // Make sure that the something in !something is not bool.
12626 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12627 if (SubExpr->isKnownToHaveBooleanValue()) return;
12628
12629 // Emit warning.
12630 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12631 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12632 << Loc << IsBitwiseOp;
12633
12634 // First note suggest !(x < y)
12635 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12636 SourceLocation FirstClose = RHS.get()->getEndLoc();
12637 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12638 if (FirstClose.isInvalid())
12639 FirstOpen = SourceLocation();
12640 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12641 << IsBitwiseOp
12642 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12643 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12644
12645 // Second note suggests (!x) < y
12646 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12647 SourceLocation SecondClose = LHS.get()->getEndLoc();
12648 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12649 if (SecondClose.isInvalid())
12650 SecondOpen = SourceLocation();
12651 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12652 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12653 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12654}
12655
12656// Returns true if E refers to a non-weak array.
12657static bool checkForArray(const Expr *E) {
12658 const ValueDecl *D = nullptr;
12659 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12660 D = DR->getDecl();
12661 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12662 if (Mem->isImplicitAccess())
12663 D = Mem->getMemberDecl();
12664 }
12665 if (!D)
12666 return false;
12667 return D->getType()->isArrayType() && !D->isWeak();
12668}
12669
12670/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12671/// pointer and size is an unsigned integer. Return whether the result is
12672/// always true/false.
12673static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12674 const Expr *RHS,
12675 BinaryOperatorKind Opc) {
12676 if (!LHS->getType()->isPointerType() ||
12677 S.getLangOpts().PointerOverflowDefined)
12678 return std::nullopt;
12679
12680 // Canonicalize to >= or < predicate.
12681 switch (Opc) {
12682 case BO_GE:
12683 case BO_LT:
12684 break;
12685 case BO_GT:
12686 std::swap(a&: LHS, b&: RHS);
12687 Opc = BO_LT;
12688 break;
12689 case BO_LE:
12690 std::swap(a&: LHS, b&: RHS);
12691 Opc = BO_GE;
12692 break;
12693 default:
12694 return std::nullopt;
12695 }
12696
12697 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12698 if (!BO || BO->getOpcode() != BO_Add)
12699 return std::nullopt;
12700
12701 Expr *Other;
12702 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12703 Other = BO->getRHS();
12704 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12705 Other = BO->getLHS();
12706 else
12707 return std::nullopt;
12708
12709 if (!Other->getType()->isUnsignedIntegerType())
12710 return std::nullopt;
12711
12712 return Opc == BO_GE;
12713}
12714
12715/// Diagnose some forms of syntactically-obvious tautological comparison.
12716static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12717 Expr *LHS, Expr *RHS,
12718 BinaryOperatorKind Opc) {
12719 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12720 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12721
12722 QualType LHSType = LHS->getType();
12723 QualType RHSType = RHS->getType();
12724 if (LHSType->hasFloatingRepresentation() ||
12725 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12726 S.inTemplateInstantiation())
12727 return;
12728
12729 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12730 // Tautological diagnostics.
12731 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12732 return;
12733
12734 // Comparisons between two array types are ill-formed for operator<=>, so
12735 // we shouldn't emit any additional warnings about it.
12736 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12737 return;
12738
12739 // For non-floating point types, check for self-comparisons of the form
12740 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12741 // often indicate logic errors in the program.
12742 //
12743 // NOTE: Don't warn about comparison expressions resulting from macro
12744 // expansion. Also don't warn about comparisons which are only self
12745 // comparisons within a template instantiation. The warnings should catch
12746 // obvious cases in the definition of the template anyways. The idea is to
12747 // warn when the typed comparison operator will always evaluate to the same
12748 // result.
12749
12750 // Used for indexing into %select in warn_comparison_always
12751 enum {
12752 AlwaysConstant,
12753 AlwaysTrue,
12754 AlwaysFalse,
12755 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12756 };
12757
12758 // C++1a [array.comp]:
12759 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12760 // operands of array type.
12761 // C++2a [depr.array.comp]:
12762 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12763 // operands of array type are deprecated.
12764 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12765 RHSStripped->getType()->isArrayType()) {
12766 auto IsDeprArrayComparionIgnored =
12767 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12768 auto DiagID = S.getLangOpts().CPlusPlus26
12769 ? diag::warn_array_comparison_cxx26
12770 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12771 ? diag::warn_array_comparison
12772 : diag::warn_depr_array_comparison;
12773 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12774 << LHSStripped->getType() << RHSStripped->getType();
12775 // Carry on to produce the tautological comparison warning, if this
12776 // expression is potentially-evaluated, we can resolve the array to a
12777 // non-weak declaration, and so on.
12778 }
12779
12780 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12781 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12782 unsigned Result;
12783 switch (Opc) {
12784 case BO_EQ:
12785 case BO_LE:
12786 case BO_GE:
12787 Result = AlwaysTrue;
12788 break;
12789 case BO_NE:
12790 case BO_LT:
12791 case BO_GT:
12792 Result = AlwaysFalse;
12793 break;
12794 case BO_Cmp:
12795 Result = AlwaysEqual;
12796 break;
12797 default:
12798 Result = AlwaysConstant;
12799 break;
12800 }
12801 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12802 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12803 << 0 /*self-comparison*/
12804 << Result);
12805 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12806 // What is it always going to evaluate to?
12807 unsigned Result;
12808 switch (Opc) {
12809 case BO_EQ: // e.g. array1 == array2
12810 Result = AlwaysFalse;
12811 break;
12812 case BO_NE: // e.g. array1 != array2
12813 Result = AlwaysTrue;
12814 break;
12815 default: // e.g. array1 <= array2
12816 // The best we can say is 'a constant'
12817 Result = AlwaysConstant;
12818 break;
12819 }
12820 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12821 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12822 << 1 /*array comparison*/
12823 << Result);
12824 } else if (std::optional<bool> Res =
12825 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12826 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12827 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12828 << 2 /*pointer comparison*/
12829 << (*Res ? AlwaysTrue : AlwaysFalse));
12830 }
12831 }
12832
12833 if (isa<CastExpr>(Val: LHSStripped))
12834 LHSStripped = LHSStripped->IgnoreParenCasts();
12835 if (isa<CastExpr>(Val: RHSStripped))
12836 RHSStripped = RHSStripped->IgnoreParenCasts();
12837
12838 // Warn about comparisons against a string constant (unless the other
12839 // operand is null); the user probably wants string comparison function.
12840 Expr *LiteralString = nullptr;
12841 Expr *LiteralStringStripped = nullptr;
12842 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12843 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12844 NPC: Expr::NPC_ValueDependentIsNull)) {
12845 LiteralString = LHS;
12846 LiteralStringStripped = LHSStripped;
12847 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12848 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12849 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12850 NPC: Expr::NPC_ValueDependentIsNull)) {
12851 LiteralString = RHS;
12852 LiteralStringStripped = RHSStripped;
12853 }
12854
12855 if (LiteralString) {
12856 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12857 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12858 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12859 << LiteralString->getSourceRange());
12860 }
12861}
12862
12863static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12864 switch (CK) {
12865 default: {
12866#ifndef NDEBUG
12867 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12868 << "\n";
12869#endif
12870 llvm_unreachable("unhandled cast kind");
12871 }
12872 case CK_UserDefinedConversion:
12873 return ICK_Identity;
12874 case CK_LValueToRValue:
12875 return ICK_Lvalue_To_Rvalue;
12876 case CK_ArrayToPointerDecay:
12877 return ICK_Array_To_Pointer;
12878 case CK_FunctionToPointerDecay:
12879 return ICK_Function_To_Pointer;
12880 case CK_IntegralCast:
12881 return ICK_Integral_Conversion;
12882 case CK_FloatingCast:
12883 return ICK_Floating_Conversion;
12884 case CK_IntegralToFloating:
12885 case CK_FloatingToIntegral:
12886 return ICK_Floating_Integral;
12887 case CK_IntegralComplexCast:
12888 case CK_FloatingComplexCast:
12889 case CK_FloatingComplexToIntegralComplex:
12890 case CK_IntegralComplexToFloatingComplex:
12891 return ICK_Complex_Conversion;
12892 case CK_FloatingComplexToReal:
12893 case CK_FloatingRealToComplex:
12894 case CK_IntegralComplexToReal:
12895 case CK_IntegralRealToComplex:
12896 return ICK_Complex_Real;
12897 case CK_HLSLArrayRValue:
12898 return ICK_HLSL_Array_RValue;
12899 }
12900}
12901
12902static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12903 QualType FromType,
12904 SourceLocation Loc) {
12905 // Check for a narrowing implicit conversion.
12906 StandardConversionSequence SCS;
12907 SCS.setAsIdentityConversion();
12908 SCS.setToType(Idx: 0, T: FromType);
12909 SCS.setToType(Idx: 1, T: ToType);
12910 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12911 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12912
12913 APValue PreNarrowingValue;
12914 QualType PreNarrowingType;
12915 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12916 ConstantType&: PreNarrowingType,
12917 /*IgnoreFloatToIntegralConversion*/ true)) {
12918 case NK_Dependent_Narrowing:
12919 // Implicit conversion to a narrower type, but the expression is
12920 // value-dependent so we can't tell whether it's actually narrowing.
12921 case NK_Not_Narrowing:
12922 return false;
12923
12924 case NK_Constant_Narrowing:
12925 // Implicit conversion to a narrower type, and the value is not a constant
12926 // expression.
12927 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12928 << /*Constant*/ 1
12929 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12930 return true;
12931
12932 case NK_Variable_Narrowing:
12933 // Implicit conversion to a narrower type, and the value is not a constant
12934 // expression.
12935 case NK_Type_Narrowing:
12936 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12937 << /*Constant*/ 0 << FromType << ToType;
12938 // TODO: It's not a constant expression, but what if the user intended it
12939 // to be? Can we produce notes to help them figure out why it isn't?
12940 return true;
12941 }
12942 llvm_unreachable("unhandled case in switch");
12943}
12944
12945static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12946 ExprResult &LHS,
12947 ExprResult &RHS,
12948 SourceLocation Loc) {
12949 QualType LHSType = LHS.get()->getType();
12950 QualType RHSType = RHS.get()->getType();
12951 // Dig out the original argument type and expression before implicit casts
12952 // were applied. These are the types/expressions we need to check the
12953 // [expr.spaceship] requirements against.
12954 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12955 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12956 QualType LHSStrippedType = LHSStripped.get()->getType();
12957 QualType RHSStrippedType = RHSStripped.get()->getType();
12958
12959 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12960 // other is not, the program is ill-formed.
12961 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12962 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12963 return QualType();
12964 }
12965
12966 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12967 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12968 RHSStrippedType->isEnumeralType();
12969 if (NumEnumArgs == 1) {
12970 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12971 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12972 if (OtherTy->hasFloatingRepresentation()) {
12973 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12974 return QualType();
12975 }
12976 }
12977 if (NumEnumArgs == 2) {
12978 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12979 // type E, the operator yields the result of converting the operands
12980 // to the underlying type of E and applying <=> to the converted operands.
12981 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12982 S.InvalidOperands(Loc, LHS, RHS);
12983 return QualType();
12984 }
12985 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12986 assert(IntType->isArithmeticType());
12987
12988 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12989 // promote the boolean type, and all other promotable integer types, to
12990 // avoid this.
12991 if (S.Context.isPromotableIntegerType(T: IntType))
12992 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12993
12994 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12995 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12996 LHSType = RHSType = IntType;
12997 }
12998
12999 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13000 // usual arithmetic conversions are applied to the operands.
13001 QualType Type =
13002 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13003 if (LHS.isInvalid() || RHS.isInvalid())
13004 return QualType();
13005 if (Type.isNull()) {
13006 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13007 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
13008 return ResultTy;
13009 }
13010
13011 std::optional<ComparisonCategoryType> CCT =
13012 getComparisonCategoryForBuiltinCmp(T: Type);
13013 if (!CCT)
13014 return S.InvalidOperands(Loc, LHS, RHS);
13015
13016 bool HasNarrowing = checkThreeWayNarrowingConversion(
13017 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
13018 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
13019 Loc: RHS.get()->getBeginLoc());
13020 if (HasNarrowing)
13021 return QualType();
13022
13023 assert(!Type.isNull() && "composite type for <=> has not been set");
13024
13025 return S.CheckComparisonCategoryType(
13026 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
13027}
13028
13029static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13030 ExprResult &RHS,
13031 SourceLocation Loc,
13032 BinaryOperatorKind Opc) {
13033 if (Opc == BO_Cmp)
13034 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13035
13036 // C99 6.5.8p3 / C99 6.5.9p4
13037 QualType Type =
13038 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13039 if (LHS.isInvalid() || RHS.isInvalid())
13040 return QualType();
13041 if (Type.isNull()) {
13042 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13043 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13044 return ResultTy;
13045 }
13046 assert(Type->isArithmeticType() || Type->isEnumeralType());
13047
13048 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13049 return S.InvalidOperands(Loc, LHS, RHS);
13050
13051 // Check for comparisons of floating point operands using != and ==.
13052 if (Type->hasFloatingRepresentation())
13053 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13054
13055 // The result of comparisons is 'bool' in C++, 'int' in C.
13056 return S.Context.getLogicalOperationType();
13057}
13058
13059void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13060 if (!NullE.get()->getType()->isAnyPointerType())
13061 return;
13062 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
13063 if (!E.get()->getType()->isAnyPointerType() &&
13064 E.get()->isNullPointerConstant(Ctx&: Context,
13065 NPC: Expr::NPC_ValueDependentIsNotNull) ==
13066 Expr::NPCK_ZeroExpression) {
13067 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
13068 if (CL->getValue() == 0)
13069 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13070 << NullValue
13071 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13072 Code: NullValue ? "NULL" : "(void *)0");
13073 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
13074 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13075 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
13076 if (T == Context.CharTy)
13077 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13078 << NullValue
13079 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13080 Code: NullValue ? "NULL" : "(void *)0");
13081 }
13082 }
13083}
13084
13085// C99 6.5.8, C++ [expr.rel]
13086QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13087 SourceLocation Loc,
13088 BinaryOperatorKind Opc) {
13089 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13090 bool IsThreeWay = Opc == BO_Cmp;
13091 bool IsOrdered = IsRelational || IsThreeWay;
13092 auto IsAnyPointerType = [](ExprResult E) {
13093 QualType Ty = E.get()->getType();
13094 return Ty->isPointerType() || Ty->isMemberPointerType();
13095 };
13096
13097 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13098 // type, array-to-pointer, ..., conversions are performed on both operands to
13099 // bring them to their composite type.
13100 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13101 // any type-related checks.
13102 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13103 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13104 if (LHS.isInvalid())
13105 return QualType();
13106 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13107 if (RHS.isInvalid())
13108 return QualType();
13109 } else {
13110 LHS = DefaultLvalueConversion(E: LHS.get());
13111 if (LHS.isInvalid())
13112 return QualType();
13113 RHS = DefaultLvalueConversion(E: RHS.get());
13114 if (RHS.isInvalid())
13115 return QualType();
13116 }
13117
13118 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
13119 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13120 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
13121 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
13122 }
13123
13124 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13125 RHS.get()->getType()->isConstantMatrixType()))
13126 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13127
13128 // Handle vector comparisons separately.
13129 if (LHS.get()->getType()->isVectorType() ||
13130 RHS.get()->getType()->isVectorType())
13131 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13132
13133 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13134 RHS.get()->getType()->isSveVLSBuiltinType())
13135 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13136
13137 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13138 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13139
13140 QualType LHSType = LHS.get()->getType();
13141 QualType RHSType = RHS.get()->getType();
13142 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13143 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13144 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
13145
13146 if ((LHSType->isPointerType() &&
13147 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13148 (RHSType->isPointerType() &&
13149 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13150 return InvalidOperands(Loc, LHS, RHS);
13151
13152 const Expr::NullPointerConstantKind LHSNullKind =
13153 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13154 const Expr::NullPointerConstantKind RHSNullKind =
13155 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13156 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13157 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13158
13159 auto computeResultTy = [&]() {
13160 if (Opc != BO_Cmp)
13161 return QualType(Context.getLogicalOperationType());
13162 assert(getLangOpts().CPlusPlus);
13163 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13164
13165 QualType CompositeTy = LHS.get()->getType();
13166 assert(!CompositeTy->isReferenceType());
13167
13168 std::optional<ComparisonCategoryType> CCT =
13169 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13170 if (!CCT)
13171 return InvalidOperands(Loc, LHS, RHS);
13172
13173 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13174 // P0946R0: Comparisons between a null pointer constant and an object
13175 // pointer result in std::strong_equality, which is ill-formed under
13176 // P1959R0.
13177 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13178 << (LHSIsNull ? LHS.get()->getSourceRange()
13179 : RHS.get()->getSourceRange());
13180 return QualType();
13181 }
13182
13183 return CheckComparisonCategoryType(
13184 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13185 };
13186
13187 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13188 bool IsEquality = Opc == BO_EQ;
13189 if (RHSIsNull)
13190 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13191 Range: RHS.get()->getSourceRange());
13192 else
13193 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13194 Range: LHS.get()->getSourceRange());
13195 }
13196
13197 if (IsOrdered && LHSType->isFunctionPointerType() &&
13198 RHSType->isFunctionPointerType()) {
13199 // Valid unless a relational comparison of function pointers
13200 bool IsError = Opc == BO_Cmp;
13201 auto DiagID =
13202 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13203 : getLangOpts().CPlusPlus
13204 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13205 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13206 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13207 << RHS.get()->getSourceRange();
13208 if (IsError)
13209 return QualType();
13210 }
13211
13212 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13213 (RHSType->isIntegerType() && !RHSIsNull)) {
13214 // Skip normal pointer conversion checks in this case; we have better
13215 // diagnostics for this below.
13216 } else if (getLangOpts().CPlusPlus) {
13217 // Equality comparison of a function pointer to a void pointer is invalid,
13218 // but we allow it as an extension.
13219 // FIXME: If we really want to allow this, should it be part of composite
13220 // pointer type computation so it works in conditionals too?
13221 if (!IsOrdered &&
13222 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13223 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13224 // This is a gcc extension compatibility comparison.
13225 // In a SFINAE context, we treat this as a hard error to maintain
13226 // conformance with the C++ standard.
13227 bool IsError = isSFINAEContext();
13228 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13229
13230 if (IsError)
13231 return QualType();
13232
13233 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13234 return computeResultTy();
13235 }
13236
13237 // C++ [expr.eq]p2:
13238 // If at least one operand is a pointer [...] bring them to their
13239 // composite pointer type.
13240 // C++ [expr.spaceship]p6
13241 // If at least one of the operands is of pointer type, [...] bring them
13242 // to their composite pointer type.
13243 // C++ [expr.rel]p2:
13244 // If both operands are pointers, [...] bring them to their composite
13245 // pointer type.
13246 // For <=>, the only valid non-pointer types are arrays and functions, and
13247 // we already decayed those, so this is really the same as the relational
13248 // comparison rule.
13249 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13250 (IsOrdered ? 2 : 1) &&
13251 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13252 RHSType->isObjCObjectPointerType()))) {
13253 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13254 return QualType();
13255 return computeResultTy();
13256 }
13257 } else if (LHSType->isPointerType() &&
13258 RHSType->isPointerType()) { // C99 6.5.8p2
13259 // All of the following pointer-related warnings are GCC extensions, except
13260 // when handling null pointer constants.
13261 QualType LCanPointeeTy =
13262 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13263 QualType RCanPointeeTy =
13264 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13265
13266 // C99 6.5.9p2 and C99 6.5.8p2
13267 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13268 T2: RCanPointeeTy.getUnqualifiedType())) {
13269 if (IsRelational) {
13270 // Pointers both need to point to complete or incomplete types
13271 if ((LCanPointeeTy->isIncompleteType() !=
13272 RCanPointeeTy->isIncompleteType()) &&
13273 !getLangOpts().C11) {
13274 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13276 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13277 << RCanPointeeTy->isIncompleteType();
13278 }
13279 }
13280 } else if (!IsRelational &&
13281 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13282 // Valid unless comparison between non-null pointer and function pointer
13283 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13284 && !LHSIsNull && !RHSIsNull)
13285 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13286 /*isError*/IsError: false);
13287 } else {
13288 // Invalid
13289 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13290 }
13291 if (LCanPointeeTy != RCanPointeeTy) {
13292 // Treat NULL constant as a special case in OpenCL.
13293 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13294 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13295 Ctx: getASTContext())) {
13296 Diag(Loc,
13297 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13298 << LHSType << RHSType << 0 /* comparison */
13299 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13300 }
13301 }
13302 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13303 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13304 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13305 : CK_BitCast;
13306
13307 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13308 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13309 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13310 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13311 bool ChangingCFIUncheckedCallee =
13312 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13313
13314 if (LHSIsNull && !RHSIsNull)
13315 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13316 else if (!ChangingCFIUncheckedCallee)
13317 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13318 }
13319 return computeResultTy();
13320 }
13321
13322
13323 // C++ [expr.eq]p4:
13324 // Two operands of type std::nullptr_t or one operand of type
13325 // std::nullptr_t and the other a null pointer constant compare
13326 // equal.
13327 // C23 6.5.9p5:
13328 // If both operands have type nullptr_t or one operand has type nullptr_t
13329 // and the other is a null pointer constant, they compare equal if the
13330 // former is a null pointer.
13331 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13332 if (LHSType->isNullPtrType()) {
13333 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13334 return computeResultTy();
13335 }
13336 if (RHSType->isNullPtrType()) {
13337 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13338 return computeResultTy();
13339 }
13340 }
13341
13342 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13343 // C23 6.5.9p6:
13344 // Otherwise, at least one operand is a pointer. If one is a pointer and
13345 // the other is a null pointer constant or has type nullptr_t, they
13346 // compare equal
13347 if (LHSIsNull && RHSType->isPointerType()) {
13348 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13349 return computeResultTy();
13350 }
13351 if (RHSIsNull && LHSType->isPointerType()) {
13352 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13353 return computeResultTy();
13354 }
13355 }
13356
13357 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13358 // These aren't covered by the composite pointer type rules.
13359 if (!IsOrdered && RHSType->isNullPtrType() &&
13360 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13361 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13362 return computeResultTy();
13363 }
13364 if (!IsOrdered && LHSType->isNullPtrType() &&
13365 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13366 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13367 return computeResultTy();
13368 }
13369
13370 if (getLangOpts().CPlusPlus) {
13371 if (IsRelational &&
13372 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13373 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13374 // HACK: Relational comparison of nullptr_t against a pointer type is
13375 // invalid per DR583, but we allow it within std::less<> and friends,
13376 // since otherwise common uses of it break.
13377 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13378 // friends to have std::nullptr_t overload candidates.
13379 DeclContext *DC = CurContext;
13380 if (isa<FunctionDecl>(Val: DC))
13381 DC = DC->getParent();
13382 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13383 if (CTSD->isInStdNamespace() &&
13384 llvm::StringSwitch<bool>(CTSD->getName())
13385 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13386 .Default(Value: false)) {
13387 if (RHSType->isNullPtrType())
13388 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13389 else
13390 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13391 return computeResultTy();
13392 }
13393 }
13394 }
13395
13396 // C++ [expr.eq]p2:
13397 // If at least one operand is a pointer to member, [...] bring them to
13398 // their composite pointer type.
13399 if (!IsOrdered &&
13400 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13401 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13402 return QualType();
13403 else
13404 return computeResultTy();
13405 }
13406 }
13407
13408 // Handle block pointer types.
13409 if (!IsOrdered && LHSType->isBlockPointerType() &&
13410 RHSType->isBlockPointerType()) {
13411 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13412 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13413
13414 if (!LHSIsNull && !RHSIsNull &&
13415 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13416 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13417 << LHSType << RHSType << LHS.get()->getSourceRange()
13418 << RHS.get()->getSourceRange();
13419 }
13420 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13421 return computeResultTy();
13422 }
13423
13424 // Allow block pointers to be compared with null pointer constants.
13425 if (!IsOrdered
13426 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13427 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13428 if (!LHSIsNull && !RHSIsNull) {
13429 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13430 ->getPointeeType()->isVoidType())
13431 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13432 ->getPointeeType()->isVoidType())))
13433 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13434 << LHSType << RHSType << LHS.get()->getSourceRange()
13435 << RHS.get()->getSourceRange();
13436 }
13437 if (LHSIsNull && !RHSIsNull)
13438 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13439 CK: RHSType->isPointerType() ? CK_BitCast
13440 : CK_AnyPointerToBlockPointerCast);
13441 else
13442 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13443 CK: LHSType->isPointerType() ? CK_BitCast
13444 : CK_AnyPointerToBlockPointerCast);
13445 return computeResultTy();
13446 }
13447
13448 if (LHSType->isObjCObjectPointerType() ||
13449 RHSType->isObjCObjectPointerType()) {
13450 const PointerType *LPT = LHSType->getAs<PointerType>();
13451 const PointerType *RPT = RHSType->getAs<PointerType>();
13452 if (LPT || RPT) {
13453 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13454 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13455
13456 if (!LPtrToVoid && !RPtrToVoid &&
13457 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13458 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13459 /*isError*/IsError: false);
13460 }
13461 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13462 // the RHS, but we have test coverage for this behavior.
13463 // FIXME: Consider using convertPointersToCompositeType in C++.
13464 if (LHSIsNull && !RHSIsNull) {
13465 Expr *E = LHS.get();
13466 if (getLangOpts().ObjCAutoRefCount)
13467 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13468 CCK: CheckedConversionKind::Implicit);
13469 LHS = ImpCastExprToType(E, Type: RHSType,
13470 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13471 }
13472 else {
13473 Expr *E = RHS.get();
13474 if (getLangOpts().ObjCAutoRefCount)
13475 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13476 CCK: CheckedConversionKind::Implicit,
13477 /*Diagnose=*/true,
13478 /*DiagnoseCFAudited=*/false, Opc);
13479 RHS = ImpCastExprToType(E, Type: LHSType,
13480 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13481 }
13482 return computeResultTy();
13483 }
13484 if (LHSType->isObjCObjectPointerType() &&
13485 RHSType->isObjCObjectPointerType()) {
13486 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13487 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13488 /*isError*/IsError: false);
13489 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13490 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13491
13492 if (LHSIsNull && !RHSIsNull)
13493 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13494 else
13495 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13496 return computeResultTy();
13497 }
13498
13499 if (!IsOrdered && LHSType->isBlockPointerType() &&
13500 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13501 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13502 CK: CK_BlockPointerToObjCPointerCast);
13503 return computeResultTy();
13504 } else if (!IsOrdered &&
13505 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13506 RHSType->isBlockPointerType()) {
13507 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13508 CK: CK_BlockPointerToObjCPointerCast);
13509 return computeResultTy();
13510 }
13511 }
13512 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13513 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13514 unsigned DiagID = 0;
13515 bool isError = false;
13516 if (LangOpts.DebuggerSupport) {
13517 // Under a debugger, allow the comparison of pointers to integers,
13518 // since users tend to want to compare addresses.
13519 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13520 (RHSIsNull && RHSType->isIntegerType())) {
13521 if (IsOrdered) {
13522 isError = getLangOpts().CPlusPlus;
13523 DiagID =
13524 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13525 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13526 }
13527 } else if (getLangOpts().CPlusPlus) {
13528 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13529 isError = true;
13530 } else if (IsOrdered)
13531 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13532 else
13533 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13534
13535 if (DiagID) {
13536 Diag(Loc, DiagID)
13537 << LHSType << RHSType << LHS.get()->getSourceRange()
13538 << RHS.get()->getSourceRange();
13539 if (isError)
13540 return QualType();
13541 }
13542
13543 if (LHSType->isIntegerType())
13544 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13545 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13546 else
13547 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13548 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13549 return computeResultTy();
13550 }
13551
13552 // Handle block pointers.
13553 if (!IsOrdered && RHSIsNull
13554 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13555 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13556 return computeResultTy();
13557 }
13558 if (!IsOrdered && LHSIsNull
13559 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13560 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13561 return computeResultTy();
13562 }
13563
13564 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13565 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13566 return computeResultTy();
13567 }
13568
13569 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13570 return computeResultTy();
13571 }
13572
13573 if (LHSIsNull && RHSType->isQueueT()) {
13574 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13575 return computeResultTy();
13576 }
13577
13578 if (LHSType->isQueueT() && RHSIsNull) {
13579 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13580 return computeResultTy();
13581 }
13582 }
13583
13584 return InvalidOperands(Loc, LHS, RHS);
13585}
13586
13587QualType Sema::GetSignedVectorType(QualType V) {
13588 const VectorType *VTy = V->castAs<VectorType>();
13589 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13590
13591 if (isa<ExtVectorType>(Val: VTy)) {
13592 if (VTy->isExtVectorBoolType())
13593 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13594 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13595 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13596 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13597 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13598 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13599 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13600 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13601 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13602 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13603 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13604 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13605 "Unhandled vector element size in vector compare");
13606 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13607 }
13608
13609 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13610 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13611 VecKind: VectorKind::Generic);
13612 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13613 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13614 VecKind: VectorKind::Generic);
13615 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13616 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13617 VecKind: VectorKind::Generic);
13618 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13619 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13620 VecKind: VectorKind::Generic);
13621 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13622 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13623 VecKind: VectorKind::Generic);
13624 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13625 "Unhandled vector element size in vector compare");
13626 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13627 VecKind: VectorKind::Generic);
13628}
13629
13630QualType Sema::GetSignedSizelessVectorType(QualType V) {
13631 const BuiltinType *VTy = V->castAs<BuiltinType>();
13632 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13633
13634 const QualType ETy = V->getSveEltType(Ctx: Context);
13635 const auto TypeSize = Context.getTypeSize(T: ETy);
13636
13637 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13638 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13639 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13640}
13641
13642QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13643 SourceLocation Loc,
13644 BinaryOperatorKind Opc) {
13645 if (Opc == BO_Cmp) {
13646 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13647 return QualType();
13648 }
13649
13650 // Check to make sure we're operating on vectors of the same type and width,
13651 // Allowing one side to be a scalar of element type.
13652 QualType vType =
13653 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13654 /*AllowBothBool*/ true,
13655 /*AllowBoolConversions*/ getLangOpts().ZVector,
13656 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13657 /*ReportInvalid*/ true);
13658 if (vType.isNull())
13659 return vType;
13660
13661 QualType LHSType = LHS.get()->getType();
13662
13663 // Determine the return type of a vector compare. By default clang will return
13664 // a scalar for all vector compares except vector bool and vector pixel.
13665 // With the gcc compiler we will always return a vector type and with the xl
13666 // compiler we will always return a scalar type. This switch allows choosing
13667 // which behavior is prefered.
13668 if (getLangOpts().AltiVec) {
13669 switch (getLangOpts().getAltivecSrcCompat()) {
13670 case LangOptions::AltivecSrcCompatKind::Mixed:
13671 // If AltiVec, the comparison results in a numeric type, i.e.
13672 // bool for C++, int for C
13673 if (vType->castAs<VectorType>()->getVectorKind() ==
13674 VectorKind::AltiVecVector)
13675 return Context.getLogicalOperationType();
13676 else
13677 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13678 break;
13679 case LangOptions::AltivecSrcCompatKind::GCC:
13680 // For GCC we always return the vector type.
13681 break;
13682 case LangOptions::AltivecSrcCompatKind::XL:
13683 return Context.getLogicalOperationType();
13684 break;
13685 }
13686 }
13687
13688 // For non-floating point types, check for self-comparisons of the form
13689 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13690 // often indicate logic errors in the program.
13691 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13692
13693 // Check for comparisons of floating point operands using != and ==.
13694 if (LHSType->hasFloatingRepresentation()) {
13695 assert(RHS.get()->getType()->hasFloatingRepresentation());
13696 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13697 }
13698
13699 // Return a signed type for the vector.
13700 return GetSignedVectorType(V: vType);
13701}
13702
13703QualType Sema::CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
13704 SourceLocation Loc,
13705 BinaryOperatorKind Opc) {
13706 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13707 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13708
13709 QualType MatrixTy =
13710 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13711 if (MatrixTy.isNull())
13712 return QualType();
13713
13714 if (!LHS.get()->getType()->isMatrixType()) {
13715 LHS = prepareMatrixSplat(MatrixTy, SplattedExpr: LHS.get());
13716 if (LHS.isInvalid())
13717 return QualType();
13718 LHS = ImpCastExprToType(E: LHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13719 }
13720 if (!RHS.get()->getType()->isMatrixType()) {
13721 RHS = prepareMatrixSplat(MatrixTy, SplattedExpr: RHS.get());
13722 if (RHS.isInvalid())
13723 return QualType();
13724 RHS = ImpCastExprToType(E: RHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13725 }
13726
13727 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13728 return Context.getConstantMatrixType(ElementType: Context.BoolTy, NumRows: MT->getNumRows(),
13729 NumColumns: MT->getNumColumns());
13730}
13731
13732QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13733 ExprResult &RHS,
13734 SourceLocation Loc,
13735 BinaryOperatorKind Opc) {
13736 if (Opc == BO_Cmp) {
13737 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13738 return QualType();
13739 }
13740
13741 // Check to make sure we're operating on vectors of the same type and width,
13742 // Allowing one side to be a scalar of element type.
13743 QualType vType = CheckSizelessVectorOperands(
13744 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13745
13746 if (vType.isNull())
13747 return vType;
13748
13749 QualType LHSType = LHS.get()->getType();
13750
13751 // For non-floating point types, check for self-comparisons of the form
13752 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13753 // often indicate logic errors in the program.
13754 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13755
13756 // Check for comparisons of floating point operands using != and ==.
13757 if (LHSType->hasFloatingRepresentation()) {
13758 assert(RHS.get()->getType()->hasFloatingRepresentation());
13759 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13760 }
13761
13762 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13763 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13764
13765 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13766 RHSBuiltinTy->isSVEBool())
13767 return LHSType;
13768
13769 // Return a signed type for the vector.
13770 return GetSignedSizelessVectorType(V: vType);
13771}
13772
13773static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13774 const ExprResult &XorRHS,
13775 const SourceLocation Loc) {
13776 // Do not diagnose macros.
13777 if (Loc.isMacroID())
13778 return;
13779
13780 // Do not diagnose if both LHS and RHS are macros.
13781 if (XorLHS.get()->getExprLoc().isMacroID() &&
13782 XorRHS.get()->getExprLoc().isMacroID())
13783 return;
13784
13785 bool Negative = false;
13786 bool ExplicitPlus = false;
13787 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13788 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13789
13790 if (!LHSInt)
13791 return;
13792 if (!RHSInt) {
13793 // Check negative literals.
13794 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13795 UnaryOperatorKind Opc = UO->getOpcode();
13796 if (Opc != UO_Minus && Opc != UO_Plus)
13797 return;
13798 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13799 if (!RHSInt)
13800 return;
13801 Negative = (Opc == UO_Minus);
13802 ExplicitPlus = !Negative;
13803 } else {
13804 return;
13805 }
13806 }
13807
13808 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13809 llvm::APInt RightSideValue = RHSInt->getValue();
13810 if (LeftSideValue != 2 && LeftSideValue != 10)
13811 return;
13812
13813 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13814 return;
13815
13816 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13817 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13818 llvm::StringRef ExprStr =
13819 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13820
13821 CharSourceRange XorRange =
13822 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13823 llvm::StringRef XorStr =
13824 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13825 // Do not diagnose if xor keyword/macro is used.
13826 if (XorStr == "xor")
13827 return;
13828
13829 std::string LHSStr = std::string(Lexer::getSourceText(
13830 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13831 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13832 std::string RHSStr = std::string(Lexer::getSourceText(
13833 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13834 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13835
13836 if (Negative) {
13837 RightSideValue = -RightSideValue;
13838 RHSStr = "-" + RHSStr;
13839 } else if (ExplicitPlus) {
13840 RHSStr = "+" + RHSStr;
13841 }
13842
13843 StringRef LHSStrRef = LHSStr;
13844 StringRef RHSStrRef = RHSStr;
13845 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13846 // literals.
13847 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13848 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13849 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13850 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13851 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13852 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13853 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13854 return;
13855
13856 bool SuggestXor =
13857 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13858 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13859 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13860 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13861 std::string SuggestedExpr = "1 << " + RHSStr;
13862 bool Overflow = false;
13863 llvm::APInt One = (LeftSideValue - 1);
13864 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13865 if (Overflow) {
13866 if (RightSideIntValue < 64)
13867 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13868 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13869 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13870 else if (RightSideIntValue == 64)
13871 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13872 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13873 else
13874 return;
13875 } else {
13876 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13877 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13878 << toString(I: PowValue, Radix: 10, Signed: true)
13879 << FixItHint::CreateReplacement(
13880 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13881 }
13882
13883 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13884 << ("0x2 ^ " + RHSStr) << SuggestXor;
13885 } else if (LeftSideValue == 10) {
13886 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13887 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13888 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13889 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13890 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13891 << ("0xA ^ " + RHSStr) << SuggestXor;
13892 }
13893}
13894
13895QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13896 SourceLocation Loc,
13897 BinaryOperatorKind Opc) {
13898 // Ensure that either both operands are of the same vector type, or
13899 // one operand is of a vector type and the other is of its element type.
13900 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13901 /*AllowBothBool*/ true,
13902 /*AllowBoolConversions*/ false,
13903 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13904 /*ReportInvalid*/ false);
13905 if (vType.isNull())
13906 return InvalidOperands(Loc, LHS, RHS);
13907 if (getLangOpts().OpenCL &&
13908 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13909 vType->hasFloatingRepresentation())
13910 return InvalidOperands(Loc, LHS, RHS);
13911 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13912 // usage of the logical operators && and || with vectors in C. This
13913 // check could be notionally dropped.
13914 if (!getLangOpts().CPlusPlus &&
13915 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13916 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13917 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13918 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13919 // `select` functions.
13920 if (getLangOpts().HLSL &&
13921 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13922 (void)InvalidOperands(Loc, LHS, RHS);
13923 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13924 return QualType();
13925 }
13926
13927 return GetSignedVectorType(V: LHS.get()->getType());
13928}
13929
13930QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13931 SourceLocation Loc,
13932 BinaryOperatorKind Opc) {
13933
13934 if (!getLangOpts().HLSL) {
13935 SemaRef.Diag(Loc, DiagID: diag::err_matrix_logical_operations_supported_for_hlsl);
13936 return QualType();
13937 }
13938
13939 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13940 (void)InvalidOperands(Loc, LHS, RHS);
13941 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13942 return QualType();
13943 }
13944 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13945 << getLangOpts().getHLSLVersion();
13946 return QualType();
13947}
13948
13949QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13950 SourceLocation Loc,
13951 bool IsCompAssign) {
13952 if (!IsCompAssign) {
13953 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13954 if (LHS.isInvalid())
13955 return QualType();
13956 }
13957 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13958 if (RHS.isInvalid())
13959 return QualType();
13960
13961 // For conversion purposes, we ignore any qualifiers.
13962 // For example, "const float" and "float" are equivalent.
13963 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13964 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13965
13966 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13967 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13968 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13969
13970 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13971 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13972
13973 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13974 // case we have to return InvalidOperands.
13975 ExprResult OriginalLHS = LHS;
13976 ExprResult OriginalRHS = RHS;
13977 if (LHSMatType && !RHSMatType) {
13978 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13979 if (!RHS.isInvalid())
13980 return LHSType;
13981
13982 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13983 }
13984
13985 if (!LHSMatType && RHSMatType) {
13986 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13987 if (!LHS.isInvalid())
13988 return RHSType;
13989 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13990 }
13991
13992 return InvalidOperands(Loc, LHS, RHS);
13993}
13994
13995QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13996 SourceLocation Loc,
13997 bool IsCompAssign) {
13998 if (!IsCompAssign) {
13999 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
14000 if (LHS.isInvalid())
14001 return QualType();
14002 }
14003 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
14004 if (RHS.isInvalid())
14005 return QualType();
14006
14007 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14008 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14009 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14010
14011 if (LHSMatType && RHSMatType) {
14012 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14013 return InvalidOperands(Loc, LHS, RHS);
14014
14015 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
14016 return Context.getCommonSugaredType(
14017 X: LHS.get()->getType().getUnqualifiedType(),
14018 Y: RHS.get()->getType().getUnqualifiedType());
14019
14020 QualType LHSELTy = LHSMatType->getElementType(),
14021 RHSELTy = RHSMatType->getElementType();
14022 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
14023 return InvalidOperands(Loc, LHS, RHS);
14024
14025 return Context.getConstantMatrixType(
14026 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
14027 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
14028 }
14029 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14030}
14031
14032static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
14033 switch (Opc) {
14034 default:
14035 return false;
14036 case BO_And:
14037 case BO_AndAssign:
14038 case BO_Or:
14039 case BO_OrAssign:
14040 case BO_Xor:
14041 case BO_XorAssign:
14042 return true;
14043 }
14044}
14045
14046inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
14047 SourceLocation Loc,
14048 BinaryOperatorKind Opc) {
14049 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
14050
14051 bool IsCompAssign =
14052 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14053
14054 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14055
14056 if (LHS.get()->getType()->isVectorType() ||
14057 RHS.get()->getType()->isVectorType()) {
14058 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14059 RHS.get()->getType()->hasIntegerRepresentation())
14060 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
14061 /*AllowBothBool*/ true,
14062 /*AllowBoolConversions*/ getLangOpts().ZVector,
14063 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
14064 /*ReportInvalid*/ true);
14065 return InvalidOperands(Loc, LHS, RHS);
14066 }
14067
14068 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14069 RHS.get()->getType()->isSveVLSBuiltinType()) {
14070 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14071 RHS.get()->getType()->hasIntegerRepresentation())
14072 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14073 OperationKind: ArithConvKind::BitwiseOp);
14074 return InvalidOperands(Loc, LHS, RHS);
14075 }
14076
14077 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14078 RHS.get()->getType()->isSveVLSBuiltinType()) {
14079 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14080 RHS.get()->getType()->hasIntegerRepresentation())
14081 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14082 OperationKind: ArithConvKind::BitwiseOp);
14083 return InvalidOperands(Loc, LHS, RHS);
14084 }
14085
14086 if (Opc == BO_And)
14087 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
14088
14089 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14090 RHS.get()->getType()->hasFloatingRepresentation())
14091 return InvalidOperands(Loc, LHS, RHS);
14092
14093 ExprResult LHSResult = LHS, RHSResult = RHS;
14094 QualType compType = UsualArithmeticConversions(
14095 LHS&: LHSResult, RHS&: RHSResult, Loc,
14096 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
14097 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14098 return QualType();
14099 LHS = LHSResult.get();
14100 RHS = RHSResult.get();
14101
14102 if (Opc == BO_Xor)
14103 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
14104
14105 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14106 return compType;
14107 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14108 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14109 return ResultTy;
14110}
14111
14112// C99 6.5.[13,14]
14113inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14114 SourceLocation Loc,
14115 BinaryOperatorKind Opc) {
14116 // Check vector operands differently.
14117 if (LHS.get()->getType()->isVectorType() ||
14118 RHS.get()->getType()->isVectorType())
14119 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14120
14121 if (LHS.get()->getType()->isConstantMatrixType() ||
14122 RHS.get()->getType()->isConstantMatrixType())
14123 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14124
14125 bool EnumConstantInBoolContext = false;
14126 for (const ExprResult &HS : {LHS, RHS}) {
14127 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
14128 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
14129 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14130 EnumConstantInBoolContext = true;
14131 }
14132 }
14133
14134 if (EnumConstantInBoolContext)
14135 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
14136
14137 // WebAssembly tables can't be used with logical operators.
14138 QualType LHSTy = LHS.get()->getType();
14139 QualType RHSTy = RHS.get()->getType();
14140 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
14141 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
14142 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14143 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14144 return InvalidOperands(Loc, LHS, RHS);
14145 }
14146
14147 // Diagnose cases where the user write a logical and/or but probably meant a
14148 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14149 // is a constant.
14150 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14151 !LHS.get()->getType()->isBooleanType() &&
14152 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14153 // Don't warn in macros or template instantiations.
14154 !Loc.isMacroID() && !inTemplateInstantiation()) {
14155 // If the RHS can be constant folded, and if it constant folds to something
14156 // that isn't 0 or 1 (which indicate a potential logical operation that
14157 // happened to fold to true/false) then warn.
14158 // Parens on the RHS are ignored.
14159 Expr::EvalResult EVResult;
14160 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
14161 llvm::APSInt Result = EVResult.Val.getInt();
14162 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14163 !RHS.get()->getExprLoc().isMacroID()) ||
14164 (Result != 0 && Result != 1)) {
14165 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
14166 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14167 // Suggest replacing the logical operator with the bitwise version
14168 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
14169 << (Opc == BO_LAnd ? "&" : "|")
14170 << FixItHint::CreateReplacement(
14171 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
14172 Code: Opc == BO_LAnd ? "&" : "|");
14173 if (Opc == BO_LAnd)
14174 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14175 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
14176 << FixItHint::CreateRemoval(
14177 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
14178 RHS.get()->getEndLoc()));
14179 }
14180 }
14181 }
14182
14183 if (!Context.getLangOpts().CPlusPlus) {
14184 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14185 // not operate on the built-in scalar and vector float types.
14186 if (Context.getLangOpts().OpenCL &&
14187 Context.getLangOpts().OpenCLVersion < 120) {
14188 if (LHS.get()->getType()->isFloatingType() ||
14189 RHS.get()->getType()->isFloatingType())
14190 return InvalidOperands(Loc, LHS, RHS);
14191 }
14192
14193 LHS = UsualUnaryConversions(E: LHS.get());
14194 if (LHS.isInvalid())
14195 return QualType();
14196
14197 RHS = UsualUnaryConversions(E: RHS.get());
14198 if (RHS.isInvalid())
14199 return QualType();
14200
14201 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14202 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
14203 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14204 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
14205
14206 if (!LHS.get()->getType()->isScalarType() ||
14207 !RHS.get()->getType()->isScalarType())
14208 return InvalidOperands(Loc, LHS, RHS);
14209
14210 return Context.IntTy;
14211 }
14212
14213 // The following is safe because we only use this method for
14214 // non-overloadable operands.
14215
14216 // C++ [expr.log.and]p1
14217 // C++ [expr.log.or]p1
14218 // The operands are both contextually converted to type bool.
14219 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14220 if (LHSRes.isInvalid()) {
14221 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14222 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14223 return ResultTy;
14224 }
14225 LHS = LHSRes;
14226
14227 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14228 if (RHSRes.isInvalid()) {
14229 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14230 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14231 return ResultTy;
14232 }
14233 RHS = RHSRes;
14234
14235 // C++ [expr.log.and]p2
14236 // C++ [expr.log.or]p2
14237 // The result is a bool.
14238 return Context.BoolTy;
14239}
14240
14241static bool IsReadonlyMessage(Expr *E, Sema &S) {
14242 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14243 if (!ME) return false;
14244 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14245 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14246 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14247 if (!Base) return false;
14248 return Base->getMethodDecl() != nullptr;
14249}
14250
14251/// Is the given expression (which must be 'const') a reference to a
14252/// variable which was originally non-const, but which has become
14253/// 'const' due to being captured within a block?
14254enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14255static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14256 assert(E->isLValue() && E->getType().isConstQualified());
14257 E = E->IgnoreParens();
14258
14259 // Must be a reference to a declaration from an enclosing scope.
14260 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14261 if (!DRE) return NCCK_None;
14262 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14263
14264 ValueDecl *Value = DRE->getDecl();
14265
14266 // The declaration must be a value which is not declared 'const'.
14267 if (Value->getType().isConstQualified())
14268 return NCCK_None;
14269
14270 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14271 if (Binding) {
14272 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14273 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14274 return NCCK_Lambda;
14275 }
14276
14277 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14278 if (!Var)
14279 return NCCK_None;
14280 if (Var->getType()->isReferenceType())
14281 return NCCK_None;
14282
14283 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14284
14285 // Decide whether the first capture was for a block or a lambda.
14286 DeclContext *DC = S.CurContext, *Prev = nullptr;
14287 // Decide whether the first capture was for a block or a lambda.
14288 while (DC) {
14289 // For init-capture, it is possible that the variable belongs to the
14290 // template pattern of the current context.
14291 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14292 if (Var->isInitCapture() &&
14293 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14294 break;
14295 if (DC == Var->getDeclContext())
14296 break;
14297 Prev = DC;
14298 DC = DC->getParent();
14299 }
14300 // Unless we have an init-capture, we've gone one step too far.
14301 if (!Var->isInitCapture())
14302 DC = Prev;
14303 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14304}
14305
14306static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14307 Ty = Ty.getNonReferenceType();
14308 if (IsDereference && Ty->isPointerType())
14309 Ty = Ty->getPointeeType();
14310 return !Ty.isConstQualified();
14311}
14312
14313// Update err_typecheck_assign_const and note_typecheck_assign_const
14314// when this enum is changed.
14315enum {
14316 ConstFunction,
14317 ConstVariable,
14318 ConstMember,
14319 NestedConstMember,
14320 ConstUnknown, // Keep as last element
14321};
14322
14323/// Emit the "read-only variable not assignable" error and print notes to give
14324/// more information about why the variable is not assignable, such as pointing
14325/// to the declaration of a const variable, showing that a method is const, or
14326/// that the function is returning a const reference.
14327static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14328 SourceLocation Loc) {
14329 SourceRange ExprRange = E->getSourceRange();
14330
14331 // Only emit one error on the first const found. All other consts will emit
14332 // a note to the error.
14333 bool DiagnosticEmitted = false;
14334
14335 // Track if the current expression is the result of a dereference, and if the
14336 // next checked expression is the result of a dereference.
14337 bool IsDereference = false;
14338 bool NextIsDereference = false;
14339
14340 // Loop to process MemberExpr chains.
14341 while (true) {
14342 IsDereference = NextIsDereference;
14343
14344 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14345 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14346 NextIsDereference = ME->isArrow();
14347 const ValueDecl *VD = ME->getMemberDecl();
14348 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14349 // Mutable fields can be modified even if the class is const.
14350 if (Field->isMutable()) {
14351 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14352 break;
14353 }
14354
14355 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14356 if (!DiagnosticEmitted) {
14357 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14358 << ExprRange << ConstMember << false /*static*/ << Field
14359 << Field->getType();
14360 DiagnosticEmitted = true;
14361 }
14362 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14363 << ConstMember << false /*static*/ << Field << Field->getType()
14364 << Field->getSourceRange();
14365 }
14366 E = ME->getBase();
14367 continue;
14368 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14369 if (VDecl->getType().isConstQualified()) {
14370 if (!DiagnosticEmitted) {
14371 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14372 << ExprRange << ConstMember << true /*static*/ << VDecl
14373 << VDecl->getType();
14374 DiagnosticEmitted = true;
14375 }
14376 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14377 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14378 << VDecl->getSourceRange();
14379 }
14380 // Static fields do not inherit constness from parents.
14381 break;
14382 }
14383 break; // End MemberExpr
14384 } else if (const ArraySubscriptExpr *ASE =
14385 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14386 E = ASE->getBase()->IgnoreParenImpCasts();
14387 continue;
14388 } else if (const ExtVectorElementExpr *EVE =
14389 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14390 E = EVE->getBase()->IgnoreParenImpCasts();
14391 continue;
14392 }
14393 break;
14394 }
14395
14396 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14397 // Function calls
14398 const FunctionDecl *FD = CE->getDirectCallee();
14399 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14400 if (!DiagnosticEmitted) {
14401 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14402 << ConstFunction << FD;
14403 DiagnosticEmitted = true;
14404 }
14405 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14406 DiagID: diag::note_typecheck_assign_const)
14407 << ConstFunction << FD << FD->getReturnType()
14408 << FD->getReturnTypeSourceRange();
14409 }
14410 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14411 // Point to variable declaration.
14412 if (const ValueDecl *VD = DRE->getDecl()) {
14413 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14414 if (!DiagnosticEmitted) {
14415 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14416 << ExprRange << ConstVariable << VD << VD->getType();
14417 DiagnosticEmitted = true;
14418 }
14419 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14420 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14421 }
14422 }
14423 } else if (isa<CXXThisExpr>(Val: E)) {
14424 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14425 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14426 if (MD->isConst()) {
14427 if (!DiagnosticEmitted) {
14428 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14429 << ExprRange << MD;
14430 DiagnosticEmitted = true;
14431 }
14432 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14433 << MD << MD->getSourceRange();
14434 }
14435 }
14436 }
14437 }
14438
14439 if (DiagnosticEmitted)
14440 return;
14441
14442 // Can't determine a more specific message, so display the generic error.
14443 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14444}
14445
14446enum OriginalExprKind {
14447 OEK_Variable,
14448 OEK_Member,
14449 OEK_LValue
14450};
14451
14452static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14453 const RecordType *Ty,
14454 SourceLocation Loc, SourceRange Range,
14455 OriginalExprKind OEK,
14456 bool &DiagnosticEmitted) {
14457 std::vector<const RecordType *> RecordTypeList;
14458 RecordTypeList.push_back(x: Ty);
14459 unsigned NextToCheckIndex = 0;
14460 // We walk the record hierarchy breadth-first to ensure that we print
14461 // diagnostics in field nesting order.
14462 while (RecordTypeList.size() > NextToCheckIndex) {
14463 bool IsNested = NextToCheckIndex > 0;
14464 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14465 ->getDecl()
14466 ->getDefinitionOrSelf()
14467 ->fields()) {
14468 // First, check every field for constness.
14469 QualType FieldTy = Field->getType();
14470 if (FieldTy.isConstQualified()) {
14471 if (!DiagnosticEmitted) {
14472 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14473 << Range << NestedConstMember << OEK << VD
14474 << IsNested << Field;
14475 DiagnosticEmitted = true;
14476 }
14477 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14478 << NestedConstMember << IsNested << Field
14479 << FieldTy << Field->getSourceRange();
14480 }
14481
14482 // Then we append it to the list to check next in order.
14483 FieldTy = FieldTy.getCanonicalType();
14484 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14485 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14486 RecordTypeList.push_back(x: FieldRecTy);
14487 }
14488 }
14489 ++NextToCheckIndex;
14490 }
14491}
14492
14493/// Emit an error for the case where a record we are trying to assign to has a
14494/// const-qualified field somewhere in its hierarchy.
14495static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14496 SourceLocation Loc) {
14497 QualType Ty = E->getType();
14498 assert(Ty->isRecordType() && "lvalue was not record?");
14499 SourceRange Range = E->getSourceRange();
14500 const auto *RTy = Ty->getAsCanonical<RecordType>();
14501 bool DiagEmitted = false;
14502
14503 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14504 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14505 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14506 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14507 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14508 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14509 else
14510 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14511 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14512 if (!DiagEmitted)
14513 DiagnoseConstAssignment(S, E, Loc);
14514}
14515
14516/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14517/// emit an error and return true. If so, return false.
14518static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14519 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14520
14521 S.CheckShadowingDeclModification(E, Loc);
14522
14523 SourceLocation OrigLoc = Loc;
14524 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14525 Loc: &Loc);
14526 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14527 IsLV = Expr::MLV_InvalidMessageExpression;
14528 if (IsLV == Expr::MLV_Valid)
14529 return false;
14530
14531 unsigned DiagID = 0;
14532 bool NeedType = false;
14533 switch (IsLV) { // C99 6.5.16p2
14534 case Expr::MLV_ConstQualified:
14535 // Use a specialized diagnostic when we're assigning to an object
14536 // from an enclosing function or block.
14537 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14538 if (NCCK == NCCK_Block)
14539 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14540 else
14541 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14542 break;
14543 }
14544
14545 // In ARC, use some specialized diagnostics for occasions where we
14546 // infer 'const'. These are always pseudo-strong variables.
14547 if (S.getLangOpts().ObjCAutoRefCount) {
14548 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14549 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14550 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14551
14552 // Use the normal diagnostic if it's pseudo-__strong but the
14553 // user actually wrote 'const'.
14554 if (var->isARCPseudoStrong() &&
14555 (!var->getTypeSourceInfo() ||
14556 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14557 // There are three pseudo-strong cases:
14558 // - self
14559 ObjCMethodDecl *method = S.getCurMethodDecl();
14560 if (method && var == method->getSelfDecl()) {
14561 DiagID = method->isClassMethod()
14562 ? diag::err_typecheck_arc_assign_self_class_method
14563 : diag::err_typecheck_arc_assign_self;
14564
14565 // - Objective-C externally_retained attribute.
14566 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14567 isa<ParmVarDecl>(Val: var)) {
14568 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14569
14570 // - fast enumeration variables
14571 } else {
14572 DiagID = diag::err_typecheck_arr_assign_enumeration;
14573 }
14574
14575 SourceRange Assign;
14576 if (Loc != OrigLoc)
14577 Assign = SourceRange(OrigLoc, OrigLoc);
14578 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14579 // We need to preserve the AST regardless, so migration tool
14580 // can do its job.
14581 return false;
14582 }
14583 }
14584 }
14585
14586 // If none of the special cases above are triggered, then this is a
14587 // simple const assignment.
14588 if (DiagID == 0) {
14589 DiagnoseConstAssignment(S, E, Loc);
14590 return true;
14591 }
14592
14593 break;
14594 case Expr::MLV_ConstAddrSpace:
14595 DiagnoseConstAssignment(S, E, Loc);
14596 return true;
14597 case Expr::MLV_ConstQualifiedField:
14598 DiagnoseRecursiveConstFields(S, E, Loc);
14599 return true;
14600 case Expr::MLV_ArrayType:
14601 case Expr::MLV_ArrayTemporary:
14602 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14603 NeedType = true;
14604 break;
14605 case Expr::MLV_NotObjectType:
14606 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14607 NeedType = true;
14608 break;
14609 case Expr::MLV_LValueCast:
14610 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14611 break;
14612 case Expr::MLV_Valid:
14613 llvm_unreachable("did not take early return for MLV_Valid");
14614 case Expr::MLV_InvalidExpression:
14615 case Expr::MLV_MemberFunction:
14616 case Expr::MLV_ClassTemporary: {
14617 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E)) {
14618 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14619 if (UnaryOp->getOpcode() == UO_Imag &&
14620 !Op->getType()->isAnyComplexType()) {
14621 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14622 NeedType = true;
14623 break;
14624 }
14625 }
14626
14627 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14628 break;
14629 }
14630 case Expr::MLV_IncompleteType:
14631 case Expr::MLV_IncompleteVoidType:
14632 return S.RequireCompleteType(Loc, T: E->getType(),
14633 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14634 case Expr::MLV_DuplicateVectorComponents:
14635 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14636 break;
14637 case Expr::MLV_DuplicateMatrixComponents:
14638 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14639 break;
14640 case Expr::MLV_NoSetterProperty:
14641 llvm_unreachable("readonly properties should be processed differently");
14642 case Expr::MLV_InvalidMessageExpression:
14643 DiagID = diag::err_readonly_message_assignment;
14644 break;
14645 case Expr::MLV_SubObjCPropertySetting:
14646 DiagID = diag::err_no_subobject_property_setting;
14647 break;
14648 }
14649
14650 SourceRange Assign;
14651 if (Loc != OrigLoc)
14652 Assign = SourceRange(OrigLoc, OrigLoc);
14653 if (NeedType)
14654 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14655 else
14656 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14657 return true;
14658}
14659
14660static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14661 SourceLocation Loc,
14662 Sema &Sema) {
14663 if (Sema.inTemplateInstantiation())
14664 return;
14665 if (Sema.isUnevaluatedContext())
14666 return;
14667 if (Loc.isInvalid() || Loc.isMacroID())
14668 return;
14669 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14670 return;
14671
14672 // C / C++ fields
14673 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14674 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14675 if (ML && MR) {
14676 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14677 return;
14678 const ValueDecl *LHSDecl =
14679 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14680 const ValueDecl *RHSDecl =
14681 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14682 if (LHSDecl != RHSDecl)
14683 return;
14684 if (LHSDecl->getType().isVolatileQualified())
14685 return;
14686 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14687 if (RefTy->getPointeeType().isVolatileQualified())
14688 return;
14689
14690 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14691 }
14692
14693 // Objective-C instance variables
14694 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14695 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14696 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14697 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14698 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14699 if (RL && RR && RL->getDecl() == RR->getDecl())
14700 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14701 }
14702}
14703
14704// C99 6.5.16.1
14705QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14706 SourceLocation Loc,
14707 QualType CompoundType,
14708 BinaryOperatorKind Opc) {
14709 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14710
14711 // Verify that LHS is a modifiable lvalue, and emit error if not.
14712 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14713 return QualType();
14714
14715 QualType LHSType = LHSExpr->getType();
14716 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14717 CompoundType;
14718
14719 if (RHS.isUsable()) {
14720 // Even if this check fails don't return early to allow the best
14721 // possible error recovery and to allow any subsequent diagnostics to
14722 // work.
14723 const ValueDecl *Assignee = nullptr;
14724 bool ShowFullyQualifiedAssigneeName = false;
14725 // In simple cases describe what is being assigned to
14726 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14727 Assignee = DR->getDecl();
14728 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14729 Assignee = ME->getMemberDecl();
14730 ShowFullyQualifiedAssigneeName = true;
14731 }
14732
14733 BoundsSafetyCheckAssignmentToCountAttrPtr(
14734 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14735 ShowFullyQualifiedAssigneeName);
14736 }
14737
14738 // OpenCL v1.2 s6.1.1.1 p2:
14739 // The half data type can only be used to declare a pointer to a buffer that
14740 // contains half values
14741 if (getLangOpts().OpenCL &&
14742 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14743 LHSType->isHalfType()) {
14744 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14745 << LHSType.getUnqualifiedType();
14746 return QualType();
14747 }
14748
14749 // WebAssembly tables can't be used on RHS of an assignment expression.
14750 if (RHSType->isWebAssemblyTableType()) {
14751 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14752 return QualType();
14753 }
14754
14755 AssignConvertType ConvTy;
14756 if (CompoundType.isNull()) {
14757 Expr *RHSCheck = RHS.get();
14758
14759 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14760
14761 QualType LHSTy(LHSType);
14762 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14763 if (RHS.isInvalid())
14764 return QualType();
14765 // Special case of NSObject attributes on c-style pointer types.
14766 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14767 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14768 RHSType->isObjCObjectPointerType()) ||
14769 (Context.isObjCNSObjectType(Ty: RHSType) &&
14770 LHSType->isObjCObjectPointerType())))
14771 ConvTy = AssignConvertType::Compatible;
14772
14773 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14774 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14775
14776 // If the RHS is a unary plus or minus, check to see if they = and + are
14777 // right next to each other. If so, the user may have typo'd "x =+ 4"
14778 // instead of "x += 4".
14779 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14780 RHSCheck = ICE->getSubExpr();
14781 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14782 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14783 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14784 // Only if the two operators are exactly adjacent.
14785 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14786 // And there is a space or other character before the subexpr of the
14787 // unary +/-. We don't want to warn on "x=-1".
14788 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14789 UO->getSubExpr()->getBeginLoc().isFileID()) {
14790 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14791 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14792 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14793 }
14794 }
14795
14796 if (IsAssignConvertCompatible(ConvTy)) {
14797 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14798 // Warn about retain cycles where a block captures the LHS, but
14799 // not if the LHS is a simple variable into which the block is
14800 // being stored...unless that variable can be captured by reference!
14801 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14802 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14803 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14804 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14805 }
14806
14807 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14808 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14809 // It is safe to assign a weak reference into a strong variable.
14810 // Although this code can still have problems:
14811 // id x = self.weakProp;
14812 // id y = self.weakProp;
14813 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14814 // paths through the function. This should be revisited if
14815 // -Wrepeated-use-of-weak is made flow-sensitive.
14816 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14817 // variable, which will be valid for the current autorelease scope.
14818 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14819 Loc: RHS.get()->getBeginLoc()))
14820 getCurFunction()->markSafeWeakUse(E: RHS.get());
14821
14822 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14823 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14824 }
14825 }
14826 } else {
14827 // Compound assignment "x += y"
14828 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14829 }
14830
14831 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14832 Action: AssignmentAction::Assigning))
14833 return QualType();
14834
14835 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14836
14837 AssignedEntity AE{.LHS: LHSExpr};
14838 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14839
14840 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14841 if (CompoundType.isNull()) {
14842 // C++2a [expr.ass]p5:
14843 // A simple-assignment whose left operand is of a volatile-qualified
14844 // type is deprecated unless the assignment is either a discarded-value
14845 // expression or an unevaluated operand
14846 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14847 }
14848 }
14849
14850 // C11 6.5.16p3: The type of an assignment expression is the type of the
14851 // left operand would have after lvalue conversion.
14852 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14853 // qualified type, the value has the unqualified version of the type of the
14854 // lvalue; additionally, if the lvalue has atomic type, the value has the
14855 // non-atomic version of the type of the lvalue.
14856 // C++ 5.17p1: the type of the assignment expression is that of its left
14857 // operand.
14858 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14859}
14860
14861// Scenarios to ignore if expression E is:
14862// 1. an explicit cast expression into void
14863// 2. a function call expression that returns void
14864static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14865 E = E->IgnoreParens();
14866
14867 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14868 if (CE->getCastKind() == CK_ToVoid) {
14869 return true;
14870 }
14871
14872 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14873 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14874 CE->getSubExpr()->getType()->isDependentType()) {
14875 return true;
14876 }
14877 }
14878
14879 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14880 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14881 return false;
14882}
14883
14884void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14885 // No warnings in macros
14886 if (Loc.isMacroID())
14887 return;
14888
14889 // Don't warn in template instantiations.
14890 if (inTemplateInstantiation())
14891 return;
14892
14893 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14894 // instead, skip more than needed, then call back into here with the
14895 // CommaVisitor in SemaStmt.cpp.
14896 // The listed locations are the initialization and increment portions
14897 // of a for loop. The additional checks are on the condition of
14898 // if statements, do/while loops, and for loops.
14899 if (getCurScope()->isControlScope())
14900 return;
14901
14902 // If there are multiple comma operators used together, get the RHS of the
14903 // of the comma operator as the LHS.
14904 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14905 if (BO->getOpcode() != BO_Comma)
14906 break;
14907 LHS = BO->getRHS();
14908 }
14909
14910 // Only allow some expressions on LHS to not warn.
14911 if (IgnoreCommaOperand(E: LHS, Context))
14912 return;
14913
14914 Diag(Loc, DiagID: diag::warn_comma_operator);
14915 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14916 << LHS->getSourceRange()
14917 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14918 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14919 : "(void)(")
14920 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14921 Code: ")");
14922}
14923
14924// C99 6.5.17
14925static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14926 SourceLocation Loc) {
14927 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14928 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14929 if (LHS.isInvalid() || RHS.isInvalid())
14930 return QualType();
14931
14932 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14933 // operands, but not unary promotions.
14934 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14935
14936 // So we treat the LHS as a ignored value, and in C++ we allow the
14937 // containing site to determine what should be done with the RHS.
14938 LHS = S.IgnoredValueConversions(E: LHS.get());
14939 if (LHS.isInvalid())
14940 return QualType();
14941
14942 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14943
14944 if (!S.getLangOpts().CPlusPlus) {
14945 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14946 if (RHS.isInvalid())
14947 return QualType();
14948 if (!RHS.get()->getType()->isVoidType())
14949 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14950 DiagID: diag::err_incomplete_type);
14951 }
14952
14953 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14954 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14955
14956 return RHS.get()->getType();
14957}
14958
14959/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14960/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14961static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14962 ExprValueKind &VK,
14963 ExprObjectKind &OK,
14964 SourceLocation OpLoc, bool IsInc,
14965 bool IsPrefix) {
14966 QualType ResType = Op->getType();
14967 // Atomic types can be used for increment / decrement where the non-atomic
14968 // versions can, so ignore the _Atomic() specifier for the purpose of
14969 // checking.
14970 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14971 ResType = ResAtomicType->getValueType();
14972
14973 assert(!ResType.isNull() && "no type for increment/decrement expression");
14974
14975 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14976 // Decrement of bool is not allowed.
14977 if (!IsInc) {
14978 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14979 return QualType();
14980 }
14981 // Increment of bool sets it to true, but is deprecated.
14982 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14983 : diag::warn_increment_bool)
14984 << Op->getSourceRange();
14985 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14986 // Error on enum increments and decrements in C++ mode
14987 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14988 return QualType();
14989 } else if (ResType->isRealType()) {
14990 // OK!
14991 } else if (ResType->isPointerType()) {
14992 // C99 6.5.2.4p2, 6.5.6p2
14993 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14994 return QualType();
14995 } else if (ResType->isOverflowBehaviorType()) {
14996 // OK!
14997 } else if (ResType->isObjCObjectPointerType()) {
14998 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14999 // Otherwise, we just need a complete type.
15000 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
15001 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
15002 return QualType();
15003 } else if (ResType->isAnyComplexType()) {
15004 // C99 does not support ++/-- on complex types, we allow as an extension.
15005 S.DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::increment_complex)
15006 << IsInc << Op->getSourceRange();
15007 } else if (ResType->isPlaceholderType()) {
15008 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15009 if (PR.isInvalid()) return QualType();
15010 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
15011 IsInc, IsPrefix);
15012 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15013 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15014 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15015 (ResType->castAs<VectorType>()->getVectorKind() !=
15016 VectorKind::AltiVecBool)) {
15017 // The z vector extensions allow ++ and -- for non-bool vectors.
15018 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15019 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15020 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15021 } else {
15022 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
15023 << ResType << int(IsInc) << Op->getSourceRange();
15024 return QualType();
15025 }
15026 // At this point, we know we have a real, complex or pointer type.
15027 // Now make sure the operand is a modifiable lvalue.
15028 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
15029 return QualType();
15030 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15031 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15032 // An operand with volatile-qualified type is deprecated
15033 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
15034 << IsInc << ResType;
15035 }
15036 // In C++, a prefix increment is the same type as the operand. Otherwise
15037 // (in C or with postfix), the increment is the unqualified type of the
15038 // operand.
15039 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15040 VK = VK_LValue;
15041 OK = Op->getObjectKind();
15042 return ResType;
15043 } else {
15044 VK = VK_PRValue;
15045 return ResType.getUnqualifiedType();
15046 }
15047}
15048
15049/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15050/// This routine allows us to typecheck complex/recursive expressions
15051/// where the declaration is needed for type checking. We only need to
15052/// handle cases when the expression references a function designator
15053/// or is an lvalue. Here are some examples:
15054/// - &(x) => x
15055/// - &*****f => f for f a function designator.
15056/// - &s.xx => s
15057/// - &s.zz[1].yy -> s, if zz is an array
15058/// - *(x + 1) -> x, if x is an array
15059/// - &"123"[2] -> 0
15060/// - & __real__ x -> x
15061///
15062/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15063/// members.
15064static ValueDecl *getPrimaryDecl(Expr *E) {
15065 switch (E->getStmtClass()) {
15066 case Stmt::DeclRefExprClass:
15067 return cast<DeclRefExpr>(Val: E)->getDecl();
15068 case Stmt::MemberExprClass:
15069 // If this is an arrow operator, the address is an offset from
15070 // the base's value, so the object the base refers to is
15071 // irrelevant.
15072 if (cast<MemberExpr>(Val: E)->isArrow())
15073 return nullptr;
15074 // Otherwise, the expression refers to a part of the base
15075 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
15076 case Stmt::ArraySubscriptExprClass: {
15077 // FIXME: This code shouldn't be necessary! We should catch the implicit
15078 // promotion of register arrays earlier.
15079 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
15080 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
15081 if (ICE->getSubExpr()->getType()->isArrayType())
15082 return getPrimaryDecl(E: ICE->getSubExpr());
15083 }
15084 return nullptr;
15085 }
15086 case Stmt::UnaryOperatorClass: {
15087 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
15088
15089 switch(UO->getOpcode()) {
15090 case UO_Real:
15091 case UO_Imag:
15092 case UO_Extension:
15093 return getPrimaryDecl(E: UO->getSubExpr());
15094 default:
15095 return nullptr;
15096 }
15097 }
15098 case Stmt::ParenExprClass:
15099 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
15100 case Stmt::ImplicitCastExprClass:
15101 // If the result of an implicit cast is an l-value, we care about
15102 // the sub-expression; otherwise, the result here doesn't matter.
15103 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
15104 case Stmt::CXXUuidofExprClass:
15105 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
15106 default:
15107 return nullptr;
15108 }
15109}
15110
15111namespace {
15112enum {
15113 AO_Bit_Field = 0,
15114 AO_Vector_Element = 1,
15115 AO_Property_Expansion = 2,
15116 AO_Register_Variable = 3,
15117 AO_Matrix_Element = 4,
15118 AO_No_Error = 5
15119};
15120}
15121/// Diagnose invalid operand for address of operations.
15122///
15123/// \param Type The type of operand which cannot have its address taken.
15124static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
15125 Expr *E, unsigned Type) {
15126 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
15127}
15128
15129bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
15130 const Expr *Op,
15131 const CXXMethodDecl *MD) {
15132 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
15133
15134 if (Op != DRE)
15135 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
15136 << Op->getSourceRange();
15137
15138 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15139 if (isa<CXXDestructorDecl>(Val: MD))
15140 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
15141 << DRE->getSourceRange();
15142
15143 if (DRE->getQualifier())
15144 return false;
15145
15146 if (MD->getParent()->getName().empty())
15147 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15148 << DRE->getSourceRange();
15149
15150 SmallString<32> Str;
15151 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
15152 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15153 << DRE->getSourceRange()
15154 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
15155}
15156
15157QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15158 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15159 if (PTy->getKind() == BuiltinType::Overload) {
15160 Expr *E = OrigOp.get()->IgnoreParens();
15161 if (!isa<OverloadExpr>(Val: E)) {
15162 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15163 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15164 << OrigOp.get()->getSourceRange();
15165 return QualType();
15166 }
15167
15168 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
15169 if (isa<UnresolvedMemberExpr>(Val: Ovl))
15170 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
15171 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15172 << OrigOp.get()->getSourceRange();
15173 return QualType();
15174 }
15175
15176 return Context.OverloadTy;
15177 }
15178
15179 if (PTy->getKind() == BuiltinType::UnknownAny)
15180 return Context.UnknownAnyTy;
15181
15182 if (PTy->getKind() == BuiltinType::BoundMember) {
15183 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15184 << OrigOp.get()->getSourceRange();
15185 return QualType();
15186 }
15187
15188 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15189 if (OrigOp.isInvalid()) return QualType();
15190 }
15191
15192 if (OrigOp.get()->isTypeDependent())
15193 return Context.DependentTy;
15194
15195 assert(!OrigOp.get()->hasPlaceholderType());
15196
15197 // Make sure to ignore parentheses in subsequent checks
15198 Expr *op = OrigOp.get()->IgnoreParens();
15199
15200 // In OpenCL captures for blocks called as lambda functions
15201 // are located in the private address space. Blocks used in
15202 // enqueue_kernel can be located in a different address space
15203 // depending on a vendor implementation. Thus preventing
15204 // taking an address of the capture to avoid invalid AS casts.
15205 if (LangOpts.OpenCL) {
15206 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15207 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15208 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
15209 return QualType();
15210 }
15211 }
15212
15213 if (getLangOpts().C99) {
15214 // Implement C99-only parts of addressof rules.
15215 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15216 if (uOp->getOpcode() == UO_Deref)
15217 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15218 // (assuming the deref expression is valid).
15219 return uOp->getSubExpr()->getType();
15220 }
15221 // Technically, there should be a check for array subscript
15222 // expressions here, but the result of one is always an lvalue anyway.
15223 }
15224 ValueDecl *dcl = getPrimaryDecl(E: op);
15225
15226 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15227 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15228 Loc: op->getBeginLoc()))
15229 return QualType();
15230
15231 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15232 unsigned AddressOfError = AO_No_Error;
15233
15234 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15235 bool IsError = isSFINAEContext();
15236 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15237 : diag::ext_typecheck_addrof_temporary)
15238 << op->getType() << op->getSourceRange();
15239 if (IsError)
15240 return QualType();
15241 // Materialize the temporary as an lvalue so that we can take its address.
15242 OrigOp = op =
15243 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15244 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15245 return Context.getPointerType(T: op->getType());
15246 } else if (lval == Expr::LV_MemberFunction) {
15247 // If it's an instance method, make a member pointer.
15248 // The expression must have exactly the form &A::foo.
15249
15250 // If the underlying expression isn't a decl ref, give up.
15251 if (!isa<DeclRefExpr>(Val: op)) {
15252 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15253 << OrigOp.get()->getSourceRange();
15254 return QualType();
15255 }
15256 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15257 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15258
15259 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15260 QualType MPTy = Context.getMemberPointerType(
15261 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15262
15263 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15264 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15265 // When pointer authentication is enabled, argument and return types of
15266 // vitual member functions must be complete. This is because vitrual
15267 // member function pointers are implemented using virtual dispatch
15268 // thunks and the thunks cannot be emitted if the argument or return
15269 // types are incomplete.
15270 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15271 SourceLocation DeclRefLoc,
15272 SourceLocation RetArgTypeLoc) {
15273 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15274 Diag(Loc: DeclRefLoc,
15275 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15276 Diag(Loc: RetArgTypeLoc,
15277 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15278 << T;
15279 return true;
15280 }
15281 return false;
15282 };
15283 QualType RetTy = MD->getReturnType();
15284 bool IsIncomplete =
15285 !RetTy->isVoidType() &&
15286 ReturnOrParamTypeIsIncomplete(
15287 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15288 for (auto *PVD : MD->parameters())
15289 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15290 PVD->getBeginLoc());
15291 if (IsIncomplete)
15292 return QualType();
15293 }
15294
15295 // Under the MS ABI, lock down the inheritance model now.
15296 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15297 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15298 return MPTy;
15299 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15300 // C99 6.5.3.2p1
15301 // The operand must be either an l-value or a function designator
15302 if (!op->getType()->isFunctionType()) {
15303 // Use a special diagnostic for loads from property references.
15304 if (isa<PseudoObjectExpr>(Val: op)) {
15305 AddressOfError = AO_Property_Expansion;
15306 } else {
15307 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15308 << op->getType() << op->getSourceRange();
15309 return QualType();
15310 }
15311 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15312 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15313 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15314 }
15315
15316 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15317 // The operand cannot be a bit-field
15318 AddressOfError = AO_Bit_Field;
15319 } else if (op->getObjectKind() == OK_VectorComponent) {
15320 // The operand cannot be an element of a vector
15321 AddressOfError = AO_Vector_Element;
15322 } else if (op->getObjectKind() == OK_MatrixComponent) {
15323 // The operand cannot be an element of a matrix.
15324 AddressOfError = AO_Matrix_Element;
15325 } else if (dcl) { // C99 6.5.3.2p1
15326 // We have an lvalue with a decl. Make sure the decl is not declared
15327 // with the register storage-class specifier.
15328 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15329 // in C++ it is not error to take address of a register
15330 // variable (c++03 7.1.1P3)
15331 if (vd->getStorageClass() == SC_Register &&
15332 !getLangOpts().CPlusPlus) {
15333 AddressOfError = AO_Register_Variable;
15334 }
15335 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15336 AddressOfError = AO_Property_Expansion;
15337 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15338 return Context.OverloadTy;
15339 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15340 // Okay: we can take the address of a field.
15341 // Could be a pointer to member, though, if there is an explicit
15342 // scope qualifier for the class.
15343
15344 // [C++26] [expr.prim.id.general]
15345 // If an id-expression E denotes a non-static non-type member
15346 // of some class C [...] and if E is a qualified-id, E is
15347 // not the un-parenthesized operand of the unary & operator [...]
15348 // the id-expression is transformed into a class member access expression.
15349 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15350 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15351 DeclContext *Ctx = dcl->getDeclContext();
15352 if (Ctx && Ctx->isRecord()) {
15353 if (dcl->getType()->isReferenceType()) {
15354 Diag(Loc: OpLoc,
15355 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15356 << dcl->getDeclName() << dcl->getType();
15357 return QualType();
15358 }
15359
15360 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15361 Ctx = Ctx->getParent();
15362
15363 QualType MPTy = Context.getMemberPointerType(
15364 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15365 // Under the MS ABI, lock down the inheritance model now.
15366 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15367 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15368 return MPTy;
15369 }
15370 }
15371 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15372 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15373 UnnamedGlobalConstantDecl>(Val: dcl))
15374 llvm_unreachable("Unknown/unexpected decl type");
15375 }
15376
15377 if (AddressOfError != AO_No_Error) {
15378 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15379 return QualType();
15380 }
15381
15382 if (lval == Expr::LV_IncompleteVoidType) {
15383 // Taking the address of a void variable is technically illegal, but we
15384 // allow it in cases which are otherwise valid.
15385 // Example: "extern void x; void* y = &x;".
15386 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15387 }
15388
15389 // If the operand has type "type", the result has type "pointer to type".
15390 if (op->getType()->isObjCObjectType())
15391 return Context.getObjCObjectPointerType(OIT: op->getType());
15392
15393 // Cannot take the address of WebAssembly references or tables.
15394 if (Context.getTargetInfo().getTriple().isWasm()) {
15395 QualType OpTy = op->getType();
15396 if (OpTy.isWebAssemblyReferenceType()) {
15397 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15398 << 1 << OrigOp.get()->getSourceRange();
15399 return QualType();
15400 }
15401 if (OpTy->isWebAssemblyTableType()) {
15402 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15403 << 1 << OrigOp.get()->getSourceRange();
15404 return QualType();
15405 }
15406 }
15407
15408 CheckAddressOfPackedMember(rhs: op);
15409
15410 return Context.getPointerType(T: op->getType());
15411}
15412
15413static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15414 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15415 if (!DRE)
15416 return;
15417 const Decl *D = DRE->getDecl();
15418 if (!D)
15419 return;
15420 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15421 if (!Param)
15422 return;
15423 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15424 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15425 return;
15426 if (FunctionScopeInfo *FD = S.getCurFunction())
15427 FD->ModifiedNonNullParams.insert(Ptr: Param);
15428}
15429
15430/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15431static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15432 SourceLocation OpLoc,
15433 bool IsAfterAmp = false) {
15434 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15435 if (ConvResult.isInvalid())
15436 return QualType();
15437 Op = ConvResult.get();
15438 QualType OpTy = Op->getType();
15439 QualType Result;
15440
15441 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15442 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15443 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15444 Range: Op->getSourceRange());
15445 }
15446
15447 if (const PointerType *PT = OpTy->getAs<PointerType>())
15448 {
15449 Result = PT->getPointeeType();
15450 }
15451 else if (const ObjCObjectPointerType *OPT =
15452 OpTy->getAs<ObjCObjectPointerType>())
15453 Result = OPT->getPointeeType();
15454 else {
15455 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15456 if (PR.isInvalid()) return QualType();
15457 if (PR.get() != Op)
15458 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15459 }
15460
15461 if (Result.isNull()) {
15462 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15463 << OpTy << Op->getSourceRange();
15464 return QualType();
15465 }
15466
15467 if (Result->isVoidType()) {
15468 // C++ [expr.unary.op]p1:
15469 // [...] the expression to which [the unary * operator] is applied shall
15470 // be a pointer to an object type, or a pointer to a function type
15471 LangOptions LO = S.getLangOpts();
15472 if (LO.CPlusPlus)
15473 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15474 << OpTy << Op->getSourceRange();
15475 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15476 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15477 << OpTy << Op->getSourceRange();
15478 }
15479
15480 // Dereferences are usually l-values...
15481 VK = VK_LValue;
15482
15483 // ...except that certain expressions are never l-values in C.
15484 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15485 VK = VK_PRValue;
15486
15487 return Result;
15488}
15489
15490BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15491 BinaryOperatorKind Opc;
15492 switch (Kind) {
15493 default: llvm_unreachable("Unknown binop!");
15494 case tok::periodstar: Opc = BO_PtrMemD; break;
15495 case tok::arrowstar: Opc = BO_PtrMemI; break;
15496 case tok::star: Opc = BO_Mul; break;
15497 case tok::slash: Opc = BO_Div; break;
15498 case tok::percent: Opc = BO_Rem; break;
15499 case tok::plus: Opc = BO_Add; break;
15500 case tok::minus: Opc = BO_Sub; break;
15501 case tok::lessless: Opc = BO_Shl; break;
15502 case tok::greatergreater: Opc = BO_Shr; break;
15503 case tok::lessequal: Opc = BO_LE; break;
15504 case tok::less: Opc = BO_LT; break;
15505 case tok::greaterequal: Opc = BO_GE; break;
15506 case tok::greater: Opc = BO_GT; break;
15507 case tok::exclaimequal: Opc = BO_NE; break;
15508 case tok::equalequal: Opc = BO_EQ; break;
15509 case tok::spaceship: Opc = BO_Cmp; break;
15510 case tok::amp: Opc = BO_And; break;
15511 case tok::caret: Opc = BO_Xor; break;
15512 case tok::pipe: Opc = BO_Or; break;
15513 case tok::ampamp: Opc = BO_LAnd; break;
15514 case tok::pipepipe: Opc = BO_LOr; break;
15515 case tok::equal: Opc = BO_Assign; break;
15516 case tok::starequal: Opc = BO_MulAssign; break;
15517 case tok::slashequal: Opc = BO_DivAssign; break;
15518 case tok::percentequal: Opc = BO_RemAssign; break;
15519 case tok::plusequal: Opc = BO_AddAssign; break;
15520 case tok::minusequal: Opc = BO_SubAssign; break;
15521 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15522 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15523 case tok::ampequal: Opc = BO_AndAssign; break;
15524 case tok::caretequal: Opc = BO_XorAssign; break;
15525 case tok::pipeequal: Opc = BO_OrAssign; break;
15526 case tok::comma: Opc = BO_Comma; break;
15527 }
15528 return Opc;
15529}
15530
15531static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15532 tok::TokenKind Kind) {
15533 UnaryOperatorKind Opc;
15534 switch (Kind) {
15535 default: llvm_unreachable("Unknown unary op!");
15536 case tok::plusplus: Opc = UO_PreInc; break;
15537 case tok::minusminus: Opc = UO_PreDec; break;
15538 case tok::amp: Opc = UO_AddrOf; break;
15539 case tok::star: Opc = UO_Deref; break;
15540 case tok::plus: Opc = UO_Plus; break;
15541 case tok::minus: Opc = UO_Minus; break;
15542 case tok::tilde: Opc = UO_Not; break;
15543 case tok::exclaim: Opc = UO_LNot; break;
15544 case tok::kw___real: Opc = UO_Real; break;
15545 case tok::kw___imag: Opc = UO_Imag; break;
15546 case tok::kw___extension__: Opc = UO_Extension; break;
15547 }
15548 return Opc;
15549}
15550
15551const FieldDecl *
15552Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15553 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15554 // common for setters.
15555 // struct A {
15556 // int X;
15557 // -void setX(int X) { X = X; }
15558 // +void setX(int X) { this->X = X; }
15559 // };
15560
15561 // Only consider parameters for self assignment fixes.
15562 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15563 return nullptr;
15564 const auto *Method =
15565 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15566 if (!Method)
15567 return nullptr;
15568
15569 const CXXRecordDecl *Parent = Method->getParent();
15570 // In theory this is fixable if the lambda explicitly captures this, but
15571 // that's added complexity that's rarely going to be used.
15572 if (Parent->isLambda())
15573 return nullptr;
15574
15575 // FIXME: Use an actual Lookup operation instead of just traversing fields
15576 // in order to get base class fields.
15577 auto Field =
15578 llvm::find_if(Range: Parent->fields(),
15579 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15580 return F->getDeclName() == Name;
15581 });
15582 return (Field != Parent->field_end()) ? *Field : nullptr;
15583}
15584
15585/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15586/// This warning suppressed in the event of macro expansions.
15587static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15588 SourceLocation OpLoc, bool IsBuiltin) {
15589 if (S.inTemplateInstantiation())
15590 return;
15591 if (S.isUnevaluatedContext())
15592 return;
15593 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15594 return;
15595 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15596 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15597 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15598 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15599 if (!LHSDeclRef || !RHSDeclRef ||
15600 LHSDeclRef->getLocation().isMacroID() ||
15601 RHSDeclRef->getLocation().isMacroID())
15602 return;
15603 const ValueDecl *LHSDecl =
15604 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15605 const ValueDecl *RHSDecl =
15606 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15607 if (LHSDecl != RHSDecl)
15608 return;
15609 if (LHSDecl->getType().isVolatileQualified())
15610 return;
15611 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15612 if (RefTy->getPointeeType().isVolatileQualified())
15613 return;
15614
15615 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15616 : diag::warn_self_assignment_overloaded)
15617 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15618 << RHSExpr->getSourceRange();
15619 if (const FieldDecl *SelfAssignField =
15620 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15621 Diag << 1 << SelfAssignField
15622 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15623 else
15624 Diag << 0;
15625}
15626
15627/// Check if a bitwise-& is performed on an Objective-C pointer. This
15628/// is usually indicative of introspection within the Objective-C pointer.
15629static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15630 SourceLocation OpLoc) {
15631 if (!S.getLangOpts().ObjC)
15632 return;
15633
15634 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15635 const Expr *LHS = L.get();
15636 const Expr *RHS = R.get();
15637
15638 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15639 ObjCPointerExpr = LHS;
15640 OtherExpr = RHS;
15641 }
15642 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15643 ObjCPointerExpr = RHS;
15644 OtherExpr = LHS;
15645 }
15646
15647 // This warning is deliberately made very specific to reduce false
15648 // positives with logic that uses '&' for hashing. This logic mainly
15649 // looks for code trying to introspect into tagged pointers, which
15650 // code should generally never do.
15651 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15652 unsigned Diag = diag::warn_objc_pointer_masking;
15653 // Determine if we are introspecting the result of performSelectorXXX.
15654 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15655 // Special case messages to -performSelector and friends, which
15656 // can return non-pointer values boxed in a pointer value.
15657 // Some clients may wish to silence warnings in this subcase.
15658 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15659 Selector S = ME->getSelector();
15660 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15661 if (SelArg0.starts_with(Prefix: "performSelector"))
15662 Diag = diag::warn_objc_pointer_masking_performSelector;
15663 }
15664
15665 S.Diag(Loc: OpLoc, DiagID: Diag)
15666 << ObjCPointerExpr->getSourceRange();
15667 }
15668}
15669
15670// This helper function promotes a binary operator's operands (which are of a
15671// half vector type) to a vector of floats and then truncates the result to
15672// a vector of either half or short.
15673static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15674 BinaryOperatorKind Opc, QualType ResultTy,
15675 ExprValueKind VK, ExprObjectKind OK,
15676 bool IsCompAssign, SourceLocation OpLoc,
15677 FPOptionsOverride FPFeatures) {
15678 auto &Context = S.getASTContext();
15679 assert((isVector(ResultTy, Context.HalfTy) ||
15680 isVector(ResultTy, Context.ShortTy)) &&
15681 "Result must be a vector of half or short");
15682 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15683 isVector(RHS.get()->getType(), Context.HalfTy) &&
15684 "both operands expected to be a half vector");
15685
15686 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15687 QualType BinOpResTy = RHS.get()->getType();
15688
15689 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15690 // change BinOpResTy to a vector of ints.
15691 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15692 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15693
15694 if (IsCompAssign)
15695 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15696 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15697 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15698
15699 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15700 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15701 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15702 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15703}
15704
15705/// Returns true if conversion between vectors of halfs and vectors of floats
15706/// is needed.
15707static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15708 QualType ResultTy, Expr *E0,
15709 Expr *E1 = nullptr) {
15710 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15711 return false;
15712
15713 // The conversion truncates the result to a half/short vector, so it shouldn't
15714 // apply when the result is not that type (e.g. HLSL comparisons).
15715 if (ResultTy->isVectorType() && !isVector(QT: ResultTy, ElementType: Ctx.HalfTy) &&
15716 !isVector(QT: ResultTy, ElementType: Ctx.ShortTy))
15717 return false;
15718
15719 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15720 QualType Ty = E->IgnoreImplicit()->getType();
15721
15722 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15723 // to vectors of floats. Although the element type of the vectors is __fp16,
15724 // the vectors shouldn't be treated as storage-only types. See the
15725 // discussion here: https://reviews.llvm.org/rG825235c140e7
15726 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15727 if (VT->getVectorKind() == VectorKind::Neon)
15728 return false;
15729 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15730 }
15731 return false;
15732 };
15733
15734 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15735}
15736
15737ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15738 BinaryOperatorKind Opc, Expr *LHSExpr,
15739 Expr *RHSExpr, bool ForFoldExpression) {
15740 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15741 // The syntax only allows initializer lists on the RHS of assignment,
15742 // so we don't need to worry about accepting invalid code for
15743 // non-assignment operators.
15744 // C++11 5.17p9:
15745 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15746 // of x = {} is x = T().
15747 InitializationKind Kind = InitializationKind::CreateDirectList(
15748 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15749 InitializedEntity Entity =
15750 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15751 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15752 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15753 if (Init.isInvalid())
15754 return Init;
15755 RHSExpr = Init.get();
15756 }
15757
15758 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15759 QualType ResultTy; // Result type of the binary operator.
15760 // The following two variables are used for compound assignment operators
15761 QualType CompLHSTy; // Type of LHS after promotions for computation
15762 QualType CompResultTy; // Type of computation result
15763 ExprValueKind VK = VK_PRValue;
15764 ExprObjectKind OK = OK_Ordinary;
15765 bool ConvertHalfVec = false;
15766
15767 if (!LHS.isUsable() || !RHS.isUsable())
15768 return ExprError();
15769
15770 if (getLangOpts().OpenCL) {
15771 QualType LHSTy = LHSExpr->getType();
15772 QualType RHSTy = RHSExpr->getType();
15773 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15774 // the ATOMIC_VAR_INIT macro.
15775 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15776 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15777 if (BO_Assign == Opc)
15778 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15779 else
15780 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15781 return ExprError();
15782 }
15783
15784 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15785 // only with a builtin functions and therefore should be disallowed here.
15786 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15787 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15788 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15789 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15790 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15791 return ExprError();
15792 }
15793 }
15794
15795 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15796 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15797
15798 switch (Opc) {
15799 case BO_Assign:
15800 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15801 if (getLangOpts().CPlusPlus &&
15802 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15803 VK = LHS.get()->getValueKind();
15804 OK = LHS.get()->getObjectKind();
15805 }
15806 if (!ResultTy.isNull()) {
15807 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15808 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15809
15810 // Avoid copying a block to the heap if the block is assigned to a local
15811 // auto variable that is declared in the same scope as the block. This
15812 // optimization is unsafe if the local variable is declared in an outer
15813 // scope. For example:
15814 //
15815 // BlockTy b;
15816 // {
15817 // b = ^{...};
15818 // }
15819 // // It is unsafe to invoke the block here if it wasn't copied to the
15820 // // heap.
15821 // b();
15822
15823 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15824 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15825 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15826 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15827 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15828
15829 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15830 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15831 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15832 }
15833 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15834 break;
15835 case BO_PtrMemD:
15836 case BO_PtrMemI:
15837 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15838 isIndirect: Opc == BO_PtrMemI);
15839 break;
15840 case BO_Mul:
15841 case BO_Div:
15842 ConvertHalfVec = true;
15843 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15844 break;
15845 case BO_Rem:
15846 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15847 break;
15848 case BO_Add:
15849 ConvertHalfVec = true;
15850 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15851 break;
15852 case BO_Sub:
15853 ConvertHalfVec = true;
15854 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15855 break;
15856 case BO_Shl:
15857 case BO_Shr:
15858 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15859 break;
15860 case BO_LE:
15861 case BO_LT:
15862 case BO_GE:
15863 case BO_GT:
15864 ConvertHalfVec = true;
15865 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15866
15867 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15868 !ForFoldExpression && BI && BI->isComparisonOp())
15869 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15870 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15871
15872 break;
15873 case BO_EQ:
15874 case BO_NE:
15875 ConvertHalfVec = true;
15876 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15877 break;
15878 case BO_Cmp:
15879 ConvertHalfVec = true;
15880 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15881 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15882 break;
15883 case BO_And:
15884 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15885 [[fallthrough]];
15886 case BO_Xor:
15887 case BO_Or:
15888 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15889 break;
15890 case BO_LAnd:
15891 case BO_LOr:
15892 ConvertHalfVec = true;
15893 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15894 break;
15895 case BO_MulAssign:
15896 case BO_DivAssign:
15897 ConvertHalfVec = true;
15898 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15899 CompLHSTy = CompResultTy;
15900 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15901 ResultTy =
15902 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15903 break;
15904 case BO_RemAssign:
15905 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15906 CompLHSTy = CompResultTy;
15907 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15908 ResultTy =
15909 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15910 break;
15911 case BO_AddAssign:
15912 ConvertHalfVec = true;
15913 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15914 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15915 ResultTy =
15916 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15917 break;
15918 case BO_SubAssign:
15919 ConvertHalfVec = true;
15920 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15921 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15922 ResultTy =
15923 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15924 break;
15925 case BO_ShlAssign:
15926 case BO_ShrAssign:
15927 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15928 CompLHSTy = CompResultTy;
15929 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15930 ResultTy =
15931 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15932 break;
15933 case BO_AndAssign:
15934 case BO_OrAssign: // fallthrough
15935 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15936 [[fallthrough]];
15937 case BO_XorAssign:
15938 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15939 CompLHSTy = CompResultTy;
15940 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15941 ResultTy =
15942 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15943 break;
15944 case BO_Comma:
15945 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15946 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15947 VK = RHS.get()->getValueKind();
15948 OK = RHS.get()->getObjectKind();
15949 }
15950 break;
15951 }
15952 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15953 return ExprError();
15954
15955 // Some of the binary operations require promoting operands of half vector to
15956 // float vectors and truncating the result back to half vector. For now, we do
15957 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15958 // arm64).
15959 assert(
15960 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15961 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15962 "both sides are half vectors or neither sides are");
15963 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, ResultTy,
15964 E0: LHS.get(), E1: RHS.get());
15965
15966 // Check for array bounds violations for both sides of the BinaryOperator
15967 CheckArrayAccess(E: LHS.get());
15968 CheckArrayAccess(E: RHS.get());
15969
15970 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15971 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15972 Name: &Context.Idents.get(Name: "object_setClass"),
15973 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15974 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15975 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15976 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15977 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15978 Code: "object_setClass(")
15979 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15980 Code: ",")
15981 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15982 }
15983 else
15984 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15985 }
15986 else if (const ObjCIvarRefExpr *OIRE =
15987 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15988 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15989
15990 // Opc is not a compound assignment if CompResultTy is null.
15991 if (CompResultTy.isNull()) {
15992 if (ConvertHalfVec)
15993 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15994 OpLoc, FPFeatures: CurFPFeatureOverrides());
15995 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15996 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15997 }
15998
15999 // Handle compound assignments.
16000 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16001 OK_ObjCProperty) {
16002 VK = VK_LValue;
16003 OK = LHS.get()->getObjectKind();
16004 }
16005
16006 // The LHS is not converted to the result type for fixed-point compound
16007 // assignment as the common type is computed on demand. Reset the CompLHSTy
16008 // to the LHS type we would have gotten after unary conversions.
16009 if (CompResultTy->isFixedPointType())
16010 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
16011
16012 if (ConvertHalfVec)
16013 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
16014 OpLoc, FPFeatures: CurFPFeatureOverrides());
16015
16016 return CompoundAssignOperator::Create(
16017 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
16018 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
16019}
16020
16021/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16022/// operators are mixed in a way that suggests that the programmer forgot that
16023/// comparison operators have higher precedence. The most typical example of
16024/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16025static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
16026 SourceLocation OpLoc, Expr *LHSExpr,
16027 Expr *RHSExpr) {
16028 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
16029 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
16030
16031 // Check that one of the sides is a comparison operator and the other isn't.
16032 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16033 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16034 if (isLeftComp == isRightComp)
16035 return;
16036
16037 // Bitwise operations are sometimes used as eager logical ops.
16038 // Don't diagnose this.
16039 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16040 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16041 if (isLeftBitwise || isRightBitwise)
16042 return;
16043
16044 SourceRange DiagRange = isLeftComp
16045 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16046 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16047 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16048 SourceRange ParensRange =
16049 isLeftComp
16050 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16051 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16052
16053 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
16054 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
16055 SuggestParentheses(Self, Loc: OpLoc,
16056 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
16057 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16058 SuggestParentheses(Self, Loc: OpLoc,
16059 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
16060 << BinaryOperator::getOpcodeStr(Op: Opc),
16061 ParenRange: ParensRange);
16062}
16063
16064/// It accepts a '&&' expr that is inside a '||' one.
16065/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16066/// in parentheses.
16067static void
16068EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
16069 BinaryOperator *Bop) {
16070 assert(Bop->getOpcode() == BO_LAnd);
16071 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
16072 << Bop->getSourceRange() << OpLoc;
16073 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
16074 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
16075 << Bop->getOpcodeStr(),
16076 ParenRange: Bop->getSourceRange());
16077}
16078
16079/// Look for '&&' in the left hand of a '||' expr.
16080static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
16081 Expr *LHSExpr, Expr *RHSExpr) {
16082 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
16083 if (Bop->getOpcode() == BO_LAnd) {
16084 // If it's "string_literal && a || b" don't warn since the precedence
16085 // doesn't matter.
16086 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
16087 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16088 } else if (Bop->getOpcode() == BO_LOr) {
16089 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
16090 // If it's "a || b && string_literal || c" we didn't warn earlier for
16091 // "a || b && string_literal", but warn now.
16092 if (RBop->getOpcode() == BO_LAnd &&
16093 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
16094 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
16095 }
16096 }
16097 }
16098}
16099
16100/// Look for '&&' in the right hand of a '||' expr.
16101static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
16102 Expr *LHSExpr, Expr *RHSExpr) {
16103 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
16104 if (Bop->getOpcode() == BO_LAnd) {
16105 // If it's "a || b && string_literal" don't warn since the precedence
16106 // doesn't matter.
16107 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
16108 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16109 }
16110 }
16111}
16112
16113/// Look for bitwise op in the left or right hand of a bitwise op with
16114/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16115/// the '&' expression in parentheses.
16116static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
16117 SourceLocation OpLoc, Expr *SubExpr) {
16118 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16119 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16120 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
16121 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
16122 << Bop->getSourceRange() << OpLoc;
16123 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16124 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16125 << Bop->getOpcodeStr(),
16126 ParenRange: Bop->getSourceRange());
16127 }
16128 }
16129}
16130
16131static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
16132 Expr *SubExpr, StringRef Shift) {
16133 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16134 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16135 StringRef Op = Bop->getOpcodeStr();
16136 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
16137 << Bop->getSourceRange() << OpLoc << Shift << Op;
16138 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16139 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
16140 ParenRange: Bop->getSourceRange());
16141 }
16142 }
16143}
16144
16145static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16146 Expr *LHSExpr, Expr *RHSExpr) {
16147 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
16148 if (!OCE)
16149 return;
16150
16151 FunctionDecl *FD = OCE->getDirectCallee();
16152 if (!FD || !FD->isOverloadedOperator())
16153 return;
16154
16155 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16156 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16157 return;
16158
16159 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
16160 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16161 << (Kind == OO_LessLess);
16162 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
16163 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16164 << (Kind == OO_LessLess ? "<<" : ">>"),
16165 ParenRange: OCE->getSourceRange());
16166 SuggestParentheses(
16167 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
16168 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
16169}
16170
16171/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16172/// precedence.
16173static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16174 SourceLocation OpLoc, Expr *LHSExpr,
16175 Expr *RHSExpr){
16176 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16177 if (BinaryOperator::isBitwiseOp(Opc))
16178 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16179
16180 // Diagnose "arg1 & arg2 | arg3"
16181 if ((Opc == BO_Or || Opc == BO_Xor) &&
16182 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16183 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
16184 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
16185 }
16186
16187 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16188 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16189 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16190 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16191 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16192 }
16193
16194 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16195 || Opc == BO_Shr) {
16196 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16197 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16198 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16199 }
16200
16201 // Warn on overloaded shift operators and comparisons, such as:
16202 // cout << 5 == 4;
16203 if (BinaryOperator::isComparisonOp(Opc))
16204 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16205}
16206
16207ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16208 tok::TokenKind Kind,
16209 Expr *LHSExpr, Expr *RHSExpr) {
16210 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16211 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16212 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16213
16214 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16215 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16216
16217 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
16218 ? BuiltinCountedByRefKind::Assignment
16219 : BuiltinCountedByRefKind::BinaryExpr;
16220
16221 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
16222 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
16223
16224 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16225}
16226
16227void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16228 UnresolvedSetImpl &Functions) {
16229 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16230 if (OverOp != OO_None && OverOp != OO_Equal)
16231 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16232
16233 // In C++20 onwards, we may have a second operator to look up.
16234 if (getLangOpts().CPlusPlus20) {
16235 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16236 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16237 }
16238}
16239
16240/// Build an overloaded binary operator expression in the given scope.
16241static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16242 BinaryOperatorKind Opc,
16243 Expr *LHS, Expr *RHS) {
16244 switch (Opc) {
16245 case BO_Assign:
16246 // In the non-overloaded case, we warn about self-assignment (x = x) for
16247 // both simple assignment and certain compound assignments where algebra
16248 // tells us the operation yields a constant result. When the operator is
16249 // overloaded, we can't do the latter because we don't want to assume that
16250 // those algebraic identities still apply; for example, a path-building
16251 // library might use operator/= to append paths. But it's still reasonable
16252 // to assume that simple assignment is just moving/copying values around
16253 // and so self-assignment is likely a bug.
16254 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16255 [[fallthrough]];
16256 case BO_DivAssign:
16257 case BO_RemAssign:
16258 case BO_SubAssign:
16259 case BO_AndAssign:
16260 case BO_OrAssign:
16261 case BO_XorAssign:
16262 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16263 break;
16264 default:
16265 break;
16266 }
16267
16268 // Find all of the overloaded operators visible from this point.
16269 UnresolvedSet<16> Functions;
16270 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16271
16272 // Build the (potentially-overloaded, potentially-dependent)
16273 // binary operation.
16274 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16275}
16276
16277ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16278 BinaryOperatorKind Opc, Expr *LHSExpr,
16279 Expr *RHSExpr, bool ForFoldExpression) {
16280 if (!LHSExpr || !RHSExpr)
16281 return ExprError();
16282
16283 // We want to end up calling one of SemaPseudoObject::checkAssignment
16284 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16285 // both expressions are overloadable or either is type-dependent),
16286 // or CreateBuiltinBinOp (in any other case). We also want to get
16287 // any placeholder types out of the way.
16288
16289 // Handle pseudo-objects in the LHS.
16290 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16291 // Assignments with a pseudo-object l-value need special analysis.
16292 if (pty->getKind() == BuiltinType::PseudoObject &&
16293 BinaryOperator::isAssignmentOp(Opc))
16294 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16295
16296 // Don't resolve overloads if the other type is overloadable.
16297 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16298 // We can't actually test that if we still have a placeholder,
16299 // though. Fortunately, none of the exceptions we see in that
16300 // code below are valid when the LHS is an overload set. Note
16301 // that an overload set can be dependently-typed, but it never
16302 // instantiates to having an overloadable type.
16303 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16304 if (resolvedRHS.isInvalid()) return ExprError();
16305 RHSExpr = resolvedRHS.get();
16306
16307 if (RHSExpr->isTypeDependent() ||
16308 RHSExpr->getType()->isOverloadableType())
16309 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16310 }
16311
16312 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16313 // template, diagnose the missing 'template' keyword instead of diagnosing
16314 // an invalid use of a bound member function.
16315 //
16316 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16317 // to C++1z [over.over]/1.4, but we already checked for that case above.
16318 if (Opc == BO_LT && inTemplateInstantiation() &&
16319 (pty->getKind() == BuiltinType::BoundMember ||
16320 pty->getKind() == BuiltinType::Overload)) {
16321 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16322 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16323 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16324 return isa<FunctionTemplateDecl>(Val: ND);
16325 })) {
16326 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16327 : OE->getNameLoc(),
16328 DiagID: diag::err_template_kw_missing)
16329 << OE->getName().getAsIdentifierInfo();
16330 return ExprError();
16331 }
16332 }
16333
16334 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16335 if (LHS.isInvalid()) return ExprError();
16336 LHSExpr = LHS.get();
16337 }
16338
16339 // Handle pseudo-objects in the RHS.
16340 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16341 // An overload in the RHS can potentially be resolved by the type
16342 // being assigned to.
16343 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16344 if (getLangOpts().CPlusPlus &&
16345 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16346 LHSExpr->getType()->isOverloadableType()))
16347 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16348
16349 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16350 ForFoldExpression);
16351 }
16352
16353 // Don't resolve overloads if the other type is overloadable.
16354 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16355 LHSExpr->getType()->isOverloadableType())
16356 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16357
16358 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16359 if (!resolvedRHS.isUsable()) return ExprError();
16360 RHSExpr = resolvedRHS.get();
16361 }
16362
16363 if (getLangOpts().HLSL) {
16364 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16365 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16366 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16367 return ExprError();
16368 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16369 std::optional<ExprResult> ConvRHS =
16370 HLSL().tryPerformConstantBufferConversion(BaseExpr: RHSExpr);
16371 if (ConvRHS && Context.hasSameUnqualifiedType(
16372 T1: LHSExpr->getType(), T2: ConvRHS->get()->getType())) {
16373 assert(!ConvRHS->isInvalid());
16374 RHSExpr = ConvRHS->get();
16375 }
16376 }
16377 }
16378
16379 if (getLangOpts().CPlusPlus) {
16380 bool CanOverloadBinOp =
16381 !getLangOpts().HLSL ||
16382 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16383 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16384 bool TypeDependent =
16385 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16386 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16387 RHSExpr->getType()->isOverloadableType();
16388 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16389 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16390 }
16391
16392 if (getLangOpts().RecoveryAST &&
16393 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16394 assert(!getLangOpts().CPlusPlus);
16395 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16396 "Should only occur in error-recovery path.");
16397 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16398 // C [6.15.16] p3:
16399 // An assignment expression has the value of the left operand after the
16400 // assignment, but is not an lvalue.
16401 return CompoundAssignOperator::Create(
16402 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16403 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16404 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16405 QualType ResultType;
16406 switch (Opc) {
16407 case BO_Assign:
16408 ResultType = LHSExpr->getType().getUnqualifiedType();
16409 break;
16410 case BO_LT:
16411 case BO_GT:
16412 case BO_LE:
16413 case BO_GE:
16414 case BO_EQ:
16415 case BO_NE:
16416 case BO_LAnd:
16417 case BO_LOr:
16418 // These operators have a fixed result type regardless of operands.
16419 ResultType = Context.IntTy;
16420 break;
16421 case BO_Comma:
16422 ResultType = RHSExpr->getType();
16423 break;
16424 default:
16425 ResultType = Context.DependentTy;
16426 break;
16427 }
16428 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16429 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16430 FPFeatures: CurFPFeatureOverrides());
16431 }
16432
16433 // Build a built-in binary operation.
16434 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16435}
16436
16437static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16438 if (T.isNull() || T->isDependentType())
16439 return false;
16440
16441 if (!Ctx.isPromotableIntegerType(T))
16442 return true;
16443
16444 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16445}
16446
16447ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16448 UnaryOperatorKind Opc, Expr *InputExpr,
16449 bool IsAfterAmp) {
16450 ExprResult Input = InputExpr;
16451 ExprValueKind VK = VK_PRValue;
16452 ExprObjectKind OK = OK_Ordinary;
16453 QualType resultType;
16454 bool CanOverflow = false;
16455
16456 bool ConvertHalfVec = false;
16457 if (getLangOpts().OpenCL) {
16458 QualType Ty = InputExpr->getType();
16459 // The only legal unary operation for atomics is '&'.
16460 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16461 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16462 // only with a builtin functions and therefore should be disallowed here.
16463 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16464 || Ty->isBlockPointerType())) {
16465 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16466 << InputExpr->getType()
16467 << Input.get()->getSourceRange());
16468 }
16469 }
16470
16471 if (getLangOpts().HLSL && OpLoc.isValid()) {
16472 if (Opc == UO_AddrOf)
16473 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16474 if (Opc == UO_Deref)
16475 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16476 }
16477
16478 if (InputExpr->isTypeDependent() &&
16479 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16480 resultType = Context.DependentTy;
16481 } else {
16482 switch (Opc) {
16483 case UO_PreInc:
16484 case UO_PreDec:
16485 case UO_PostInc:
16486 case UO_PostDec:
16487 resultType =
16488 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16489 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16490 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16491 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16492 break;
16493 case UO_AddrOf:
16494 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16495 CheckAddressOfNoDeref(E: InputExpr);
16496 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16497 break;
16498 case UO_Deref: {
16499 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16500 if (Input.isInvalid())
16501 return ExprError();
16502 resultType =
16503 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16504 break;
16505 }
16506 case UO_Plus:
16507 case UO_Minus:
16508 CanOverflow = Opc == UO_Minus &&
16509 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16510 Input = UsualUnaryConversions(E: Input.get());
16511 if (Input.isInvalid())
16512 return ExprError();
16513 // Unary plus and minus require promoting an operand of half vector to a
16514 // float vector and truncating the result back to a half vector. For now,
16515 // we do this only when HalfArgsAndReturns is set (that is, when the
16516 // target is arm or arm64).
16517 ConvertHalfVec = needsConversionOfHalfVec(
16518 OpRequiresConversion: true, Ctx&: Context, ResultTy: Input.get()->getType(), E0: Input.get());
16519
16520 // If the operand is a half vector, promote it to a float vector.
16521 if (ConvertHalfVec)
16522 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16523 resultType = Input.get()->getType();
16524 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16525 break;
16526 else if (resultType->isVectorType() &&
16527 // The z vector extensions don't allow + or - with bool vectors.
16528 (!Context.getLangOpts().ZVector ||
16529 resultType->castAs<VectorType>()->getVectorKind() !=
16530 VectorKind::AltiVecBool))
16531 break;
16532 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16533 break;
16534 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16535 Opc == UO_Plus && resultType->isPointerType())
16536 break;
16537
16538 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16539 << resultType << Input.get()->getSourceRange());
16540
16541 case UO_Not: // bitwise complement
16542 Input = UsualUnaryConversions(E: Input.get());
16543 if (Input.isInvalid())
16544 return ExprError();
16545 resultType = Input.get()->getType();
16546 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16547 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16548 // C99 does not support '~' for complex conjugation.
16549 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16550 << resultType << Input.get()->getSourceRange();
16551 else if (resultType->hasIntegerRepresentation())
16552 break;
16553 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16554 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16555 // on vector float types.
16556 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16557 if (!T->isIntegerType())
16558 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16559 << resultType << Input.get()->getSourceRange());
16560 } else {
16561 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16562 << resultType << Input.get()->getSourceRange());
16563 }
16564 break;
16565
16566 case UO_LNot: // logical negation
16567 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16568 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16569 if (Input.isInvalid())
16570 return ExprError();
16571 resultType = Input.get()->getType();
16572
16573 // Though we still have to promote half FP to float...
16574 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16575 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16576 .get();
16577 resultType = Context.FloatTy;
16578 }
16579
16580 // WebAsembly tables can't be used in unary expressions.
16581 if (resultType->isPointerType() &&
16582 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16583 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16584 << resultType << Input.get()->getSourceRange());
16585 }
16586
16587 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16588 // C99 6.5.3.3p1: ok, fallthrough;
16589 if (Context.getLangOpts().CPlusPlus) {
16590 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16591 // operand contextually converted to bool.
16592 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16593 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16594 } else if (Context.getLangOpts().OpenCL &&
16595 Context.getLangOpts().OpenCLVersion < 120) {
16596 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16597 // operate on scalar float types.
16598 if (!resultType->isIntegerType() && !resultType->isPointerType())
16599 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16600 << resultType << Input.get()->getSourceRange());
16601 }
16602 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16603 !resultType->hasBooleanRepresentation()) {
16604 // HLSL unary logical 'not' behaves like C++, which states that the
16605 // operand is converted to bool and the result is bool, however HLSL
16606 // extends this property to vectors.
16607 const VectorType *VTy = resultType->castAs<VectorType>();
16608 resultType =
16609 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16610
16611 Input = ImpCastExprToType(
16612 E: Input.get(), Type: resultType,
16613 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16614 .get();
16615 break;
16616 } else if (resultType->isExtVectorType()) {
16617 if (Context.getLangOpts().OpenCL &&
16618 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16619 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16620 // operate on vector float types.
16621 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16622 if (!T->isIntegerType())
16623 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16624 << resultType << Input.get()->getSourceRange());
16625 }
16626 // Vector logical not returns the signed variant of the operand type.
16627 resultType = GetSignedVectorType(V: resultType);
16628 break;
16629 } else if (Context.getLangOpts().CPlusPlus &&
16630 resultType->isVectorType()) {
16631 const VectorType *VTy = resultType->castAs<VectorType>();
16632 if (VTy->getVectorKind() != VectorKind::Generic)
16633 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16634 << resultType << Input.get()->getSourceRange());
16635
16636 // Vector logical not returns the signed variant of the operand type.
16637 resultType = GetSignedVectorType(V: resultType);
16638 break;
16639 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16640 resultType = Context.getLogicalOperationType();
16641 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16642 break;
16643 } else {
16644 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16645 << resultType << Input.get()->getSourceRange());
16646 }
16647
16648 // LNot always has type int. C99 6.5.3.3p5.
16649 // In C++, it's bool. C++ 5.3.1p8
16650 resultType = Context.getLogicalOperationType();
16651 break;
16652 case UO_Real:
16653 case UO_Imag:
16654 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16655 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16656 // ordinary complex l-values to ordinary l-values and all other values to
16657 // r-values.
16658 if (Input.isInvalid())
16659 return ExprError();
16660 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16661 if (Input.get()->isGLValue() &&
16662 Input.get()->getObjectKind() == OK_Ordinary)
16663 VK = Input.get()->getValueKind();
16664 } else if (!getLangOpts().CPlusPlus) {
16665 // In C, a volatile scalar is read by __imag. In C++, it is not.
16666 Input = DefaultLvalueConversion(E: Input.get());
16667 }
16668 break;
16669 case UO_Extension:
16670 resultType = Input.get()->getType();
16671 VK = Input.get()->getValueKind();
16672 OK = Input.get()->getObjectKind();
16673 break;
16674 case UO_Coawait:
16675 // It's unnecessary to represent the pass-through operator co_await in the
16676 // AST; just return the input expression instead.
16677 assert(!Input.get()->getType()->isDependentType() &&
16678 "the co_await expression must be non-dependant before "
16679 "building operator co_await");
16680 return Input;
16681 }
16682 }
16683 if (resultType.isNull() || Input.isInvalid())
16684 return ExprError();
16685
16686 // Check for array bounds violations in the operand of the UnaryOperator,
16687 // except for the '*' and '&' operators that have to be handled specially
16688 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16689 // that are explicitly defined as valid by the standard).
16690 if (Opc != UO_AddrOf && Opc != UO_Deref)
16691 CheckArrayAccess(E: Input.get());
16692
16693 auto *UO =
16694 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16695 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16696
16697 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16698 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16699 !isUnevaluatedContext())
16700 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16701
16702 // Convert the result back to a half vector.
16703 if (ConvertHalfVec)
16704 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16705 return UO;
16706}
16707
16708bool Sema::isQualifiedMemberAccess(Expr *E) {
16709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16710 if (!DRE->getQualifier())
16711 return false;
16712
16713 ValueDecl *VD = DRE->getDecl();
16714 if (!VD->isCXXClassMember())
16715 return false;
16716
16717 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16718 return true;
16719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16720 return Method->isImplicitObjectMemberFunction();
16721
16722 return false;
16723 }
16724
16725 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16726 if (!ULE->getQualifier())
16727 return false;
16728
16729 for (NamedDecl *D : ULE->decls()) {
16730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16731 if (Method->isImplicitObjectMemberFunction())
16732 return true;
16733 } else {
16734 // Overload set does not contain methods.
16735 break;
16736 }
16737 }
16738
16739 return false;
16740 }
16741
16742 return false;
16743}
16744
16745ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16746 UnaryOperatorKind Opc, Expr *Input,
16747 bool IsAfterAmp) {
16748 // First things first: handle placeholders so that the
16749 // overloaded-operator check considers the right type.
16750 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16751 // Increment and decrement of pseudo-object references.
16752 if (pty->getKind() == BuiltinType::PseudoObject &&
16753 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16754 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16755
16756 // extension is always a builtin operator.
16757 if (Opc == UO_Extension)
16758 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16759
16760 // & gets special logic for several kinds of placeholder.
16761 // The builtin code knows what to do.
16762 if (Opc == UO_AddrOf &&
16763 (pty->getKind() == BuiltinType::Overload ||
16764 pty->getKind() == BuiltinType::UnknownAny ||
16765 pty->getKind() == BuiltinType::BoundMember))
16766 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16767
16768 // Anything else needs to be handled now.
16769 ExprResult Result = CheckPlaceholderExpr(E: Input);
16770 if (Result.isInvalid()) return ExprError();
16771 Input = Result.get();
16772 }
16773
16774 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16775 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16776 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16777 // Find all of the overloaded operators visible from this point.
16778 UnresolvedSet<16> Functions;
16779 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16780 if (S && OverOp != OO_None)
16781 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16782
16783 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16784 }
16785
16786 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16787}
16788
16789ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16790 Expr *Input, bool IsAfterAmp) {
16791 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16792 IsAfterAmp);
16793}
16794
16795ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16796 LabelDecl *TheDecl) {
16797 TheDecl->markUsed(C&: Context);
16798 // Create the AST node. The address of a label always has type 'void*'.
16799 auto *Res = new (Context) AddrLabelExpr(
16800 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16801
16802 if (getCurFunction())
16803 getCurFunction()->AddrLabels.push_back(Elt: Res);
16804
16805 return Res;
16806}
16807
16808void Sema::ActOnStartStmtExpr() {
16809 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16810 // Make sure we diagnose jumping into a statement expression.
16811 setFunctionHasBranchProtectedScope();
16812}
16813
16814void Sema::ActOnStmtExprError() {
16815 // Note that function is also called by TreeTransform when leaving a
16816 // StmtExpr scope without rebuilding anything.
16817
16818 DiscardCleanupsInEvaluationContext();
16819 PopExpressionEvaluationContext();
16820}
16821
16822ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16823 SourceLocation RPLoc) {
16824 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16825}
16826
16827ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16828 SourceLocation RPLoc, unsigned TemplateDepth) {
16829 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16830 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16831
16832 if (hasAnyUnrecoverableErrorsInThisFunction())
16833 DiscardCleanupsInEvaluationContext();
16834 assert(!Cleanup.exprNeedsCleanups() &&
16835 "cleanups within StmtExpr not correctly bound!");
16836 PopExpressionEvaluationContext();
16837
16838 // FIXME: there are a variety of strange constraints to enforce here, for
16839 // example, it is not possible to goto into a stmt expression apparently.
16840 // More semantic analysis is needed.
16841
16842 // If there are sub-stmts in the compound stmt, take the type of the last one
16843 // as the type of the stmtexpr.
16844 QualType Ty = Context.VoidTy;
16845 bool StmtExprMayBindToTemp = false;
16846 if (!Compound->body_empty()) {
16847 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16848 if (const Expr *Value = LastStmt->getExprStmt()) {
16849 StmtExprMayBindToTemp = true;
16850 Ty = Value->getType();
16851 }
16852 }
16853 }
16854
16855 // FIXME: Check that expression type is complete/non-abstract; statement
16856 // expressions are not lvalues.
16857 Expr *ResStmtExpr =
16858 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16859 if (StmtExprMayBindToTemp)
16860 return MaybeBindToTemporary(E: ResStmtExpr);
16861 return ResStmtExpr;
16862}
16863
16864ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16865 if (ER.isInvalid())
16866 return ExprError();
16867
16868 // Do function/array conversion on the last expression, but not
16869 // lvalue-to-rvalue. However, initialize an unqualified type.
16870 ER = DefaultFunctionArrayConversion(E: ER.get());
16871 if (ER.isInvalid())
16872 return ExprError();
16873 Expr *E = ER.get();
16874
16875 if (E->isTypeDependent())
16876 return E;
16877
16878 // In ARC, if the final expression ends in a consume, splice
16879 // the consume out and bind it later. In the alternate case
16880 // (when dealing with a retainable type), the result
16881 // initialization will create a produce. In both cases the
16882 // result will be +1, and we'll need to balance that out with
16883 // a bind.
16884 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16885 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16886 return Cast->getSubExpr();
16887
16888 // FIXME: Provide a better location for the initialization.
16889 return PerformCopyInitialization(
16890 Entity: InitializedEntity::InitializeStmtExprResult(
16891 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16892 EqualLoc: SourceLocation(), Init: E);
16893}
16894
16895ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16896 TypeSourceInfo *TInfo,
16897 const Designation &Desig,
16898 SourceLocation RParenLoc) {
16899 QualType ArgTy = TInfo->getType();
16900 bool Dependent = ArgTy->isDependentType();
16901 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16902
16903 // We must have at least one component that refers to the type, and the first
16904 // one is known to be a field designator. Verify that the ArgTy represents
16905 // a struct/union/class.
16906 if (!Dependent && !ArgTy->isRecordType())
16907 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16908 << ArgTy << TypeRange);
16909
16910 // Type must be complete per C99 7.17p3 because a declaring a variable
16911 // with an incomplete type would be ill-formed.
16912 if (!Dependent
16913 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16914 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16915 return ExprError();
16916
16917 bool DidWarnAboutNonPOD = false;
16918 QualType CurrentType = ArgTy;
16919 SmallVector<OffsetOfNode, 4> Comps;
16920 SmallVector<Expr *, 4> Exprs;
16921 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16922 const Designator &D = Desig.getDesignator(Idx: I);
16923 assert(!D.isArrayRangeDesignator());
16924 if (D.isArrayDesignator()) {
16925 // Offset of an array sub-field. TODO: Should we allow vector elements?
16926 if (!CurrentType->isDependentType()) {
16927 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16928 if(!AT)
16929 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
16930 << CurrentType);
16931 CurrentType = AT->getElementType();
16932 } else
16933 CurrentType = Context.DependentTy;
16934
16935 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
16936 if (IdxRval.isInvalid())
16937 return ExprError();
16938 Expr *Idx = IdxRval.get();
16939
16940 // The expression must be an integral expression.
16941 // FIXME: An integral constant expression?
16942 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16943 !Idx->getType()->isIntegerType())
16944 return ExprError(
16945 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16946 << Idx->getSourceRange());
16947
16948 // Record this array index.
16949 Comps.push_back(
16950 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16951 Exprs.push_back(Elt: Idx);
16952 continue;
16953 }
16954
16955 assert(D.isFieldDesignator());
16956 const IdentifierInfo *Name = D.getFieldDecl();
16957
16958 // Offset of a field.
16959 if (CurrentType->isDependentType()) {
16960 // We have the offset of a field, but we can't look into the dependent
16961 // type. Just record the identifier of the field.
16962 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16963 CurrentType = Context.DependentTy;
16964 continue;
16965 }
16966
16967 // We need to have a complete type to look into.
16968 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
16969 DiagID: diag::err_offsetof_incomplete_type))
16970 return ExprError();
16971
16972 // Look for the designated field.
16973 auto *RD = CurrentType->getAsRecordDecl();
16974 if (!RD)
16975 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
16976 << CurrentType);
16977
16978 // C++ [lib.support.types]p5:
16979 // The macro offsetof accepts a restricted set of type arguments in this
16980 // International Standard. type shall be a POD structure or a POD union
16981 // (clause 9).
16982 // C++11 [support.types]p4:
16983 // If type is not a standard-layout class (Clause 9), the results are
16984 // undefined.
16985 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16986 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16987 unsigned DiagID =
16988 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16989 : diag::ext_offsetof_non_pod_type;
16990
16991 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16992 Diag(Loc: BuiltinLoc, DiagID)
16993 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
16994 << CurrentType;
16995 DidWarnAboutNonPOD = true;
16996 }
16997 }
16998
16999 // Look for the field.
17000 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17001 LookupQualifiedName(R, LookupCtx: RD);
17002 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17003 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17004 if (!MemberDecl) {
17005 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17006 MemberDecl = IndirectMemberDecl->getAnonField();
17007 }
17008
17009 if (!MemberDecl) {
17010 // Lookup could be ambiguous when looking up a placeholder variable
17011 // __builtin_offsetof(S, _).
17012 // In that case we would already have emitted a diagnostic
17013 if (!R.isAmbiguous())
17014 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
17015 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17016 return ExprError();
17017 }
17018
17019 // C99 7.17p3:
17020 // (If the specified member is a bit-field, the behavior is undefined.)
17021 //
17022 // We diagnose this as an error.
17023 if (MemberDecl->isBitField()) {
17024 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
17025 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17026 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
17027 return ExprError();
17028 }
17029
17030 RecordDecl *Parent = MemberDecl->getParent();
17031 if (IndirectMemberDecl)
17032 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
17033
17034 // If the member was found in a base class, introduce OffsetOfNodes for
17035 // the base class indirections.
17036 CXXBasePaths Paths;
17037 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
17038 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
17039 if (Paths.getDetectedVirtual()) {
17040 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
17041 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17042 return ExprError();
17043 }
17044
17045 CXXBasePath &Path = Paths.front();
17046 for (const CXXBasePathElement &B : Path)
17047 Comps.push_back(Elt: OffsetOfNode(B.Base));
17048 }
17049
17050 if (IndirectMemberDecl) {
17051 for (auto *FI : IndirectMemberDecl->chain()) {
17052 assert(isa<FieldDecl>(FI));
17053 Comps.push_back(
17054 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
17055 }
17056 } else
17057 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17058
17059 CurrentType = MemberDecl->getType().getNonReferenceType();
17060 }
17061
17062 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
17063 comps: Comps, exprs: Exprs, RParenLoc);
17064}
17065
17066ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
17067 SourceLocation TypeLoc,
17068 ParsedType ParsedArgTy,
17069 const Designation &Desig,
17070 SourceLocation RParenLoc) {
17071
17072 TypeSourceInfo *ArgTInfo;
17073 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
17074 if (ArgTy.isNull())
17075 return ExprError();
17076
17077 if (!ArgTInfo)
17078 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
17079
17080 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
17081}
17082
17083ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
17084 Expr *CondExpr,
17085 Expr *LHSExpr, Expr *RHSExpr,
17086 SourceLocation RPLoc) {
17087 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17088
17089 ExprValueKind VK = VK_PRValue;
17090 ExprObjectKind OK = OK_Ordinary;
17091 QualType resType;
17092 bool CondIsTrue = false;
17093 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17094 resType = Context.DependentTy;
17095 } else {
17096 // The conditional expression is required to be a constant expression.
17097 llvm::APSInt condEval(32);
17098 ExprResult CondICE = VerifyIntegerConstantExpression(
17099 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
17100 if (CondICE.isInvalid())
17101 return ExprError();
17102 CondExpr = CondICE.get();
17103 CondIsTrue = condEval.getZExtValue();
17104
17105 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17106 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17107
17108 resType = ActiveExpr->getType();
17109 VK = ActiveExpr->getValueKind();
17110 OK = ActiveExpr->getObjectKind();
17111 }
17112
17113 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17114 resType, VK, OK, RPLoc, CondIsTrue);
17115}
17116
17117//===----------------------------------------------------------------------===//
17118// Clang Extensions.
17119//===----------------------------------------------------------------------===//
17120
17121void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17122 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
17123
17124 if (LangOpts.CPlusPlus) {
17125 MangleNumberingContext *MCtx;
17126 Decl *ManglingContextDecl;
17127 std::tie(args&: MCtx, args&: ManglingContextDecl) =
17128 getCurrentMangleNumberContext(DC: Block->getDeclContext());
17129 if (MCtx) {
17130 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
17131 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
17132 }
17133 }
17134
17135 PushBlockScope(BlockScope: CurScope, Block);
17136 CurContext->addDecl(D: Block);
17137 if (CurScope)
17138 PushDeclContext(S: CurScope, DC: Block);
17139 else
17140 CurContext = Block;
17141
17142 getCurBlock()->HasImplicitReturnType = true;
17143
17144 // Enter a new evaluation context to insulate the block from any
17145 // cleanups from the enclosing full-expression.
17146 PushExpressionEvaluationContext(
17147 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
17148}
17149
17150void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
17151 Scope *CurScope) {
17152 assert(ParamInfo.getIdentifier() == nullptr &&
17153 "block-id should have no identifier!");
17154 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17155 BlockScopeInfo *CurBlock = getCurBlock();
17156
17157 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
17158 QualType T = Sig->getType();
17159 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
17160
17161 // GetTypeForDeclarator always produces a function type for a block
17162 // literal signature. Furthermore, it is always a FunctionProtoType
17163 // unless the function was written with a typedef.
17164 assert(T->isFunctionType() &&
17165 "GetTypeForDeclarator made a non-function block signature");
17166
17167 // Look for an explicit signature in that function type.
17168 FunctionProtoTypeLoc ExplicitSignature;
17169
17170 if ((ExplicitSignature = Sig->getTypeLoc()
17171 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17172
17173 // Check whether that explicit signature was synthesized by
17174 // GetTypeForDeclarator. If so, don't save that as part of the
17175 // written signature.
17176 if (ExplicitSignature.getLocalRangeBegin() ==
17177 ExplicitSignature.getLocalRangeEnd()) {
17178 // This would be much cheaper if we stored TypeLocs instead of
17179 // TypeSourceInfos.
17180 TypeLoc Result = ExplicitSignature.getReturnLoc();
17181 unsigned Size = Result.getFullDataSize();
17182 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
17183 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
17184
17185 ExplicitSignature = FunctionProtoTypeLoc();
17186 }
17187 }
17188
17189 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17190 CurBlock->FunctionType = T;
17191
17192 const auto *Fn = T->castAs<FunctionType>();
17193 QualType RetTy = Fn->getReturnType();
17194 bool isVariadic =
17195 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17196
17197 CurBlock->TheDecl->setIsVariadic(isVariadic);
17198
17199 // Context.DependentTy is used as a placeholder for a missing block
17200 // return type. TODO: what should we do with declarators like:
17201 // ^ * { ... }
17202 // If the answer is "apply template argument deduction"....
17203 if (RetTy != Context.DependentTy) {
17204 CurBlock->ReturnType = RetTy;
17205 CurBlock->TheDecl->setBlockMissingReturnType(false);
17206 CurBlock->HasImplicitReturnType = false;
17207 }
17208
17209 // Push block parameters from the declarator if we had them.
17210 SmallVector<ParmVarDecl*, 8> Params;
17211 if (ExplicitSignature) {
17212 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17213 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
17214 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17215 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17216 // Diagnose this as an extension in C17 and earlier.
17217 if (!getLangOpts().C23)
17218 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
17219 }
17220 Params.push_back(Elt: Param);
17221 }
17222
17223 // Fake up parameter variables if we have a typedef, like
17224 // ^ fntype { ... }
17225 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17226 for (const auto &I : Fn->param_types()) {
17227 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17228 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
17229 Params.push_back(Elt: Param);
17230 }
17231 }
17232
17233 // Set the parameters on the block decl.
17234 if (!Params.empty()) {
17235 CurBlock->TheDecl->setParams(Params);
17236 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17237 /*CheckParameterNames=*/false);
17238 }
17239
17240 // Finally we can process decl attributes.
17241 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17242
17243 // Put the parameter variables in scope.
17244 for (auto *AI : CurBlock->TheDecl->parameters()) {
17245 AI->setOwningFunction(CurBlock->TheDecl);
17246
17247 // If this has an identifier, add it to the scope stack.
17248 if (AI->getIdentifier()) {
17249 CheckShadow(S: CurBlock->TheScope, D: AI);
17250
17251 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17252 }
17253
17254 if (AI->isInvalidDecl())
17255 CurBlock->TheDecl->setInvalidDecl();
17256 }
17257}
17258
17259void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17260 // Leave the expression-evaluation context.
17261 DiscardCleanupsInEvaluationContext();
17262 PopExpressionEvaluationContext();
17263
17264 // Pop off CurBlock, handle nested blocks.
17265 PopDeclContext();
17266 PopFunctionScopeInfo();
17267}
17268
17269ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17270 Stmt *Body, Scope *CurScope) {
17271 // If blocks are disabled, emit an error.
17272 if (!LangOpts.Blocks)
17273 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17274
17275 // Leave the expression-evaluation context.
17276 if (hasAnyUnrecoverableErrorsInThisFunction())
17277 DiscardCleanupsInEvaluationContext();
17278 assert(!Cleanup.exprNeedsCleanups() &&
17279 "cleanups within block not correctly bound!");
17280 PopExpressionEvaluationContext();
17281
17282 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17283 BlockDecl *BD = BSI->TheDecl;
17284
17285 maybeAddDeclWithEffects(D: BD);
17286
17287 if (BSI->HasImplicitReturnType)
17288 deduceClosureReturnType(CSI&: *BSI);
17289
17290 QualType RetTy = Context.VoidTy;
17291 if (!BSI->ReturnType.isNull())
17292 RetTy = BSI->ReturnType;
17293
17294 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17295 QualType BlockTy;
17296
17297 // If the user wrote a function type in some form, try to use that.
17298 if (!BSI->FunctionType.isNull()) {
17299 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17300
17301 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17302 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17303
17304 // Turn protoless block types into nullary block types.
17305 if (isa<FunctionNoProtoType>(Val: FTy)) {
17306 FunctionProtoType::ExtProtoInfo EPI;
17307 EPI.ExtInfo = Ext;
17308 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17309
17310 // Otherwise, if we don't need to change anything about the function type,
17311 // preserve its sugar structure.
17312 } else if (FTy->getReturnType() == RetTy &&
17313 (!NoReturn || FTy->getNoReturnAttr())) {
17314 BlockTy = BSI->FunctionType;
17315
17316 // Otherwise, make the minimal modifications to the function type.
17317 } else {
17318 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17319 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17320 EPI.TypeQuals = Qualifiers();
17321 EPI.ExtInfo = Ext;
17322 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17323 }
17324
17325 // If we don't have a function type, just build one from nothing.
17326 } else {
17327 FunctionProtoType::ExtProtoInfo EPI;
17328 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17329 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17330 }
17331
17332 DiagnoseUnusedParameters(Parameters: BD->parameters());
17333 BlockTy = Context.getBlockPointerType(T: BlockTy);
17334
17335 // If needed, diagnose invalid gotos and switches in the block.
17336 if (getCurFunction()->NeedsScopeChecking() &&
17337 !PP.isCodeCompletionEnabled())
17338 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17339
17340 BD->setBody(cast<CompoundStmt>(Val: Body));
17341
17342 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17343 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17344
17345 // Try to apply the named return value optimization. We have to check again
17346 // if we can do this, though, because blocks keep return statements around
17347 // to deduce an implicit return type.
17348 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17349 !BD->isDependentContext())
17350 computeNRVO(Body, Scope: BSI);
17351
17352 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17353 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17354 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17355 UseContext: NonTrivialCUnionContext::FunctionReturn,
17356 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17357
17358 PopDeclContext();
17359
17360 // Set the captured variables on the block.
17361 SmallVector<BlockDecl::Capture, 4> Captures;
17362 for (Capture &Cap : BSI->Captures) {
17363 if (Cap.isInvalid() || Cap.isThisCapture())
17364 continue;
17365 // Cap.getVariable() is always a VarDecl because
17366 // blocks cannot capture structured bindings or other ValueDecl kinds.
17367 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17368 Expr *CopyExpr = nullptr;
17369 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17370 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17371 // The capture logic needs the destructor, so make sure we mark it.
17372 // Usually this is unnecessary because most local variables have
17373 // their destructors marked at declaration time, but parameters are
17374 // an exception because it's technically only the call site that
17375 // actually requires the destructor.
17376 if (isa<ParmVarDecl>(Val: Var))
17377 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17378
17379 // Enter a separate potentially-evaluated context while building block
17380 // initializers to isolate their cleanups from those of the block
17381 // itself.
17382 // FIXME: Is this appropriate even when the block itself occurs in an
17383 // unevaluated operand?
17384 EnterExpressionEvaluationContext EvalContext(
17385 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17386
17387 SourceLocation Loc = Cap.getLocation();
17388
17389 ExprResult Result = BuildDeclarationNameExpr(
17390 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17391
17392 // According to the blocks spec, the capture of a variable from
17393 // the stack requires a const copy constructor. This is not true
17394 // of the copy/move done to move a __block variable to the heap.
17395 if (!Result.isInvalid() &&
17396 !Result.get()->getType().isConstQualified()) {
17397 Result = ImpCastExprToType(E: Result.get(),
17398 Type: Result.get()->getType().withConst(),
17399 CK: CK_NoOp, VK: VK_LValue);
17400 }
17401
17402 if (!Result.isInvalid()) {
17403 Result = PerformCopyInitialization(
17404 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17405 Type: Cap.getCaptureType()),
17406 EqualLoc: Loc, Init: Result.get());
17407 }
17408
17409 // Build a full-expression copy expression if initialization
17410 // succeeded and used a non-trivial constructor. Recover from
17411 // errors by pretending that the copy isn't necessary.
17412 if (!Result.isInvalid() &&
17413 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17414 ->isTrivial()) {
17415 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17416 CopyExpr = Result.get();
17417 }
17418 }
17419 }
17420
17421 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17422 CopyExpr);
17423 Captures.push_back(Elt: NewCap);
17424 }
17425 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17426
17427 // Pop the block scope now but keep it alive to the end of this function.
17428 AnalysisBasedWarnings::Policy WP =
17429 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17430 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17431
17432 BlockExpr *Result = new (Context)
17433 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17434
17435 // If the block isn't obviously global, i.e. it captures anything at
17436 // all, then we need to do a few things in the surrounding context:
17437 if (Result->getBlockDecl()->hasCaptures()) {
17438 // First, this expression has a new cleanup object.
17439 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17440 Cleanup.setExprNeedsCleanups(true);
17441
17442 // It also gets a branch-protected scope if any of the captured
17443 // variables needs destruction.
17444 for (const auto &CI : Result->getBlockDecl()->captures()) {
17445 const VarDecl *var = CI.getVariable();
17446 if (var->getType().isDestructedType() != QualType::DK_none) {
17447 setFunctionHasBranchProtectedScope();
17448 break;
17449 }
17450 }
17451 }
17452
17453 if (getCurFunction())
17454 getCurFunction()->addBlock(BD);
17455
17456 // This can happen if the block's return type is deduced, but
17457 // the return expression is invalid.
17458 if (BD->isInvalidDecl())
17459 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17460 SubExprs: {Result}, T: Result->getType());
17461 return Result;
17462}
17463
17464ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17465 SourceLocation RPLoc) {
17466 TypeSourceInfo *TInfo;
17467 GetTypeFromParser(Ty, TInfo: &TInfo);
17468 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17469}
17470
17471ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17472 Expr *E, TypeSourceInfo *TInfo,
17473 SourceLocation RPLoc) {
17474 Expr *OrigExpr = E;
17475 VAArgExpr::VarArgKind VAKind = VAArgExpr::VA_Std;
17476
17477 // CUDA device global function does not support varargs.
17478 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17479 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17480 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17481 if (T == CUDAFunctionTarget::Global)
17482 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17483 }
17484 }
17485
17486 // NVPTX does not support va_arg expression.
17487 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17488 Context.getTargetInfo().getTriple().isNVPTX())
17489 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17490
17491 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17492 // as Microsoft ABI on an actual Microsoft platform, where
17493 // __builtin_ms_va_list and __builtin_va_list are the same.)
17494 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17495 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17496 QualType MSVaListType = Context.getBuiltinMSVaListType();
17497 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17498 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17499 return ExprError();
17500 VAKind = VAArgExpr::VA_MS;
17501 }
17502 }
17503
17504 // Get the va_list type
17505 QualType VaListType = Context.getBuiltinVaListType();
17506
17507 // It might be a __builtin_zos_va_list!
17508 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17509 // E->getType() can be:
17510 // - va_list: equal to array (char*)[2] (inside function)
17511 // - char **: decayed array (va_list passed as parameter)
17512 // We need to check for both cases.
17513 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17514 assert(ZOSVaListType->isArrayType() &&
17515 "__builtin_zos_va_list must be an array type");
17516 QualType DecayedType = Context.getArrayDecayedType(T: ZOSVaListType);
17517 if (Context.hasSameType(T1: ZOSVaListType, T2: E->getType()) ||
17518 Context.hasSameType(T1: DecayedType, T2: E->getType())) {
17519 VAKind = VAArgExpr::VA_ZOS;
17520 VaListType = ZOSVaListType;
17521 }
17522 }
17523
17524 if (VAKind != VAArgExpr::VA_MS) {
17525 if (VaListType->isArrayType()) {
17526 // Deal with implicit array decay; for example, on x86-64,
17527 // va_list is an array, but it's supposed to decay to
17528 // a pointer for va_arg.
17529 VaListType = Context.getArrayDecayedType(T: VaListType);
17530 // Make sure the input expression also decays appropriately.
17531 ExprResult Result = UsualUnaryConversions(E);
17532 if (Result.isInvalid())
17533 return ExprError();
17534 E = Result.get();
17535 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17536 // If va_list is a record type and we are compiling in C++ mode,
17537 // check the argument using reference binding.
17538 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17539 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17540 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17541 if (Init.isInvalid())
17542 return ExprError();
17543 E = Init.getAs<Expr>();
17544 } else {
17545 // Otherwise, the va_list argument must be an l-value because
17546 // it is modified by va_arg.
17547 if (!E->isTypeDependent() &&
17548 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17549 return ExprError();
17550 }
17551 }
17552
17553 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17554 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17555 return ExprError(
17556 Diag(Loc: E->getBeginLoc(),
17557 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17558 << OrigExpr->getType() << E->getSourceRange());
17559
17560 if (!TInfo->getType()->isDependentType()) {
17561 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17562 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17563 Args: TInfo->getTypeLoc()))
17564 return ExprError();
17565
17566 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17567 T: TInfo->getType(),
17568 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17569 Args: TInfo->getTypeLoc()))
17570 return ExprError();
17571
17572 if (!TInfo->getType().isPODType(Context)) {
17573 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17574 DiagID: TInfo->getType()->isObjCLifetimeType()
17575 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17576 : diag::warn_second_parameter_to_va_arg_not_pod)
17577 << TInfo->getType()
17578 << TInfo->getTypeLoc().getSourceRange();
17579 }
17580
17581 if (TInfo->getType()->isArrayType()) {
17582 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17583 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17584 << TInfo->getType()
17585 << TInfo->getTypeLoc().getSourceRange());
17586 }
17587
17588 // Check for va_arg where arguments of the given type will be promoted
17589 // (i.e. this va_arg is guaranteed to have undefined behavior).
17590 QualType PromoteType;
17591 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17592 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17593 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17594 // and C23 7.16.1.1p2 says, in part:
17595 // If type is not compatible with the type of the actual next argument
17596 // (as promoted according to the default argument promotions), the
17597 // behavior is undefined, except for the following cases:
17598 // - both types are pointers to qualified or unqualified versions of
17599 // compatible types;
17600 // - one type is compatible with a signed integer type, the other
17601 // type is compatible with the corresponding unsigned integer type,
17602 // and the value is representable in both types;
17603 // - one type is pointer to qualified or unqualified void and the
17604 // other is a pointer to a qualified or unqualified character type;
17605 // - or, the type of the next argument is nullptr_t and type is a
17606 // pointer type that has the same representation and alignment
17607 // requirements as a pointer to a character type.
17608 // Given that type compatibility is the primary requirement (ignoring
17609 // qualifications), you would think we could call typesAreCompatible()
17610 // directly to test this. However, in C++, that checks for *same type*,
17611 // which causes false positives when passing an enumeration type to
17612 // va_arg. Instead, get the underlying type of the enumeration and pass
17613 // that.
17614 QualType UnderlyingType = TInfo->getType();
17615 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17616 UnderlyingType = ED->getIntegerType();
17617 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17618 /*CompareUnqualified*/ true))
17619 PromoteType = QualType();
17620
17621 // If the types are still not compatible, we need to test whether the
17622 // promoted type and the underlying type are the same except for
17623 // signedness. Ask the AST for the correctly corresponding type and see
17624 // if that's compatible.
17625 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17626 PromoteType->isUnsignedIntegerType() !=
17627 UnderlyingType->isUnsignedIntegerType()) {
17628 UnderlyingType =
17629 UnderlyingType->isUnsignedIntegerType()
17630 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17631 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17632 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17633 /*CompareUnqualified*/ true))
17634 PromoteType = QualType();
17635 }
17636 }
17637 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17638 PromoteType = Context.DoubleTy;
17639 if (!PromoteType.isNull())
17640 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17641 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17642 << TInfo->getType()
17643 << PromoteType
17644 << TInfo->getTypeLoc().getSourceRange());
17645 }
17646
17647 QualType T = TInfo->getType().getNonLValueExprType(Context);
17648 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17649}
17650
17651ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17652 // The type of __null will be int or long, depending on the size of
17653 // pointers on the target.
17654 QualType Ty;
17655 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17656 if (pw == Context.getTargetInfo().getIntWidth())
17657 Ty = Context.IntTy;
17658 else if (pw == Context.getTargetInfo().getLongWidth())
17659 Ty = Context.LongTy;
17660 else if (pw == Context.getTargetInfo().getLongLongWidth())
17661 Ty = Context.LongLongTy;
17662 else {
17663 llvm_unreachable("I don't know size of pointer!");
17664 }
17665
17666 return new (Context) GNUNullExpr(Ty, TokenLoc);
17667}
17668
17669static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17670 CXXRecordDecl *ImplDecl = nullptr;
17671
17672 // Fetch the std::source_location::__impl decl.
17673 if (NamespaceDecl *Std = S.getStdNamespace()) {
17674 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17675 Loc, Sema::LookupOrdinaryName);
17676 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17677 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17678 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17679 Loc, Sema::LookupOrdinaryName);
17680 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17681 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17682 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17683 }
17684 }
17685 }
17686 }
17687
17688 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17689 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17690 return nullptr;
17691 }
17692
17693 // Verify that __impl is a trivial struct type, with no base classes, and with
17694 // only the four expected fields.
17695 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17696 ImplDecl->getNumBases() != 0) {
17697 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17698 return nullptr;
17699 }
17700
17701 unsigned Count = 0;
17702 for (FieldDecl *F : ImplDecl->fields()) {
17703 StringRef Name = F->getName();
17704
17705 if (Name == "_M_file_name") {
17706 if (F->getType() !=
17707 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17708 break;
17709 Count++;
17710 } else if (Name == "_M_function_name") {
17711 if (F->getType() !=
17712 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17713 break;
17714 Count++;
17715 } else if (Name == "_M_line") {
17716 if (!F->getType()->isIntegerType())
17717 break;
17718 Count++;
17719 } else if (Name == "_M_column") {
17720 if (!F->getType()->isIntegerType())
17721 break;
17722 Count++;
17723 } else {
17724 Count = 100; // invalid
17725 break;
17726 }
17727 }
17728 if (Count != 4) {
17729 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17730 return nullptr;
17731 }
17732
17733 return ImplDecl;
17734}
17735
17736ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17737 SourceLocation BuiltinLoc,
17738 SourceLocation RPLoc) {
17739 QualType ResultTy;
17740 switch (Kind) {
17741 case SourceLocIdentKind::File:
17742 case SourceLocIdentKind::FileName:
17743 case SourceLocIdentKind::Function:
17744 case SourceLocIdentKind::FuncSig: {
17745 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17746 ResultTy =
17747 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17748 break;
17749 }
17750 case SourceLocIdentKind::Line:
17751 case SourceLocIdentKind::Column:
17752 ResultTy = Context.UnsignedIntTy;
17753 break;
17754 case SourceLocIdentKind::SourceLocStruct:
17755 if (!StdSourceLocationImplDecl) {
17756 StdSourceLocationImplDecl =
17757 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17758 if (!StdSourceLocationImplDecl)
17759 return ExprError();
17760 }
17761 ResultTy = Context.getPointerType(
17762 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17763 break;
17764 }
17765
17766 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17767}
17768
17769ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17770 SourceLocation BuiltinLoc,
17771 SourceLocation RPLoc,
17772 DeclContext *ParentContext) {
17773 return new (Context)
17774 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17775}
17776
17777ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17778 StringLiteral *BinaryData, StringRef FileName) {
17779 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17780 Data->BinaryData = BinaryData;
17781 Data->FileName = FileName;
17782 return new (Context)
17783 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17784 Data->getDataElementCount());
17785}
17786
17787static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17788 const Expr *SrcExpr) {
17789 if (!DstType->isFunctionPointerType() ||
17790 !SrcExpr->getType()->isFunctionType())
17791 return false;
17792
17793 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17794 if (!DRE)
17795 return false;
17796
17797 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17798 if (!FD)
17799 return false;
17800
17801 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17802 /*Complain=*/true,
17803 Loc: SrcExpr->getBeginLoc());
17804}
17805
17806bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17807 SourceLocation Loc,
17808 QualType DstType, QualType SrcType,
17809 Expr *SrcExpr, AssignmentAction Action,
17810 bool *Complained) {
17811 if (Complained)
17812 *Complained = false;
17813
17814 // Decode the result (notice that AST's are still created for extensions).
17815 bool CheckInferredResultType = false;
17816 bool isInvalid = false;
17817 unsigned DiagKind = 0;
17818 ConversionFixItGenerator ConvHints;
17819 bool MayHaveConvFixit = false;
17820 bool MayHaveFunctionDiff = false;
17821 const ObjCInterfaceDecl *IFace = nullptr;
17822 const ObjCProtocolDecl *PDecl = nullptr;
17823
17824 switch (ConvTy) {
17825 case AssignConvertType::Compatible:
17826 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17827 return false;
17828 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17829 // Still a valid conversion, but we may want to diagnose for C++
17830 // compatibility reasons.
17831 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17832 break;
17833 case AssignConvertType::PointerToInt:
17834 if (getLangOpts().CPlusPlus) {
17835 DiagKind = diag::err_typecheck_convert_pointer_int;
17836 isInvalid = true;
17837 } else {
17838 DiagKind = diag::ext_typecheck_convert_pointer_int;
17839 }
17840 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17841 MayHaveConvFixit = true;
17842 break;
17843 case AssignConvertType::IntToPointer:
17844 if (getLangOpts().CPlusPlus) {
17845 DiagKind = diag::err_typecheck_convert_int_pointer;
17846 isInvalid = true;
17847 } else {
17848 DiagKind = diag::ext_typecheck_convert_int_pointer;
17849 }
17850 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17851 MayHaveConvFixit = true;
17852 break;
17853 case AssignConvertType::IncompatibleFunctionPointerStrict:
17854 DiagKind =
17855 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17856 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17857 MayHaveConvFixit = true;
17858 break;
17859 case AssignConvertType::IncompatibleFunctionPointer:
17860 if (getLangOpts().CPlusPlus) {
17861 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17862 isInvalid = true;
17863 } else {
17864 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17865 }
17866 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17867 MayHaveConvFixit = true;
17868 break;
17869 case AssignConvertType::IncompatiblePointer:
17870 if (Action == AssignmentAction::Passing_CFAudited) {
17871 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17872 } else if (getLangOpts().CPlusPlus) {
17873 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17874 isInvalid = true;
17875 } else {
17876 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17877 }
17878 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17879 SrcType->isObjCObjectPointerType();
17880 if (CheckInferredResultType) {
17881 SrcType = SrcType.getUnqualifiedType();
17882 DstType = DstType.getUnqualifiedType();
17883 } else {
17884 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17885 }
17886 MayHaveConvFixit = true;
17887 break;
17888 case AssignConvertType::IncompatiblePointerSign:
17889 if (getLangOpts().CPlusPlus) {
17890 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17891 isInvalid = true;
17892 } else {
17893 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17894 }
17895 break;
17896 case AssignConvertType::FunctionVoidPointer:
17897 if (getLangOpts().CPlusPlus) {
17898 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17899 isInvalid = true;
17900 } else {
17901 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17902 }
17903 break;
17904 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17905 // Perform decay if necessary.
17906 if (SrcType->canDecayToPointerType())
17907 SrcType = Context.getDecayedType(T: SrcType);
17908
17909 isInvalid = true;
17910
17911 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17912 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17913 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17914 DiagKind = diag::err_typecheck_incompatible_address_space;
17915 break;
17916 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17917 DiagKind = diag::err_typecheck_incompatible_ownership;
17918 break;
17919 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17920 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17921 break;
17922 }
17923
17924 llvm_unreachable("unknown error case for discarding qualifiers!");
17925 // fallthrough
17926 }
17927 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17928 if (SrcType->isArrayType())
17929 SrcType = Context.getArrayDecayedType(T: SrcType);
17930
17931 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17932 break;
17933 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17934 // If the qualifiers lost were because we were applying the
17935 // (deprecated) C++ conversion from a string literal to a char*
17936 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17937 // Ideally, this check would be performed in
17938 // checkPointerTypesForAssignment. However, that would require a
17939 // bit of refactoring (so that the second argument is an
17940 // expression, rather than a type), which should be done as part
17941 // of a larger effort to fix checkPointerTypesForAssignment for
17942 // C++ semantics.
17943 if (getLangOpts().CPlusPlus &&
17944 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17945 return false;
17946 if (getLangOpts().CPlusPlus) {
17947 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17948 isInvalid = true;
17949 } else {
17950 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17951 }
17952
17953 break;
17954 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17955 if (getLangOpts().CPlusPlus) {
17956 isInvalid = true;
17957 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17958 } else {
17959 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17960 }
17961 break;
17962 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17963 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17964 isInvalid = true;
17965 break;
17966 case AssignConvertType::IntToBlockPointer:
17967 DiagKind = diag::err_int_to_block_pointer;
17968 isInvalid = true;
17969 break;
17970 case AssignConvertType::IncompatibleBlockPointer:
17971 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17972 isInvalid = true;
17973 break;
17974 case AssignConvertType::IncompatibleObjCQualifiedId: {
17975 if (SrcType->isObjCQualifiedIdType()) {
17976 const ObjCObjectPointerType *srcOPT =
17977 SrcType->castAs<ObjCObjectPointerType>();
17978 for (auto *srcProto : srcOPT->quals()) {
17979 PDecl = srcProto;
17980 break;
17981 }
17982 if (const ObjCInterfaceType *IFaceT =
17983 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17984 IFace = IFaceT->getDecl();
17985 }
17986 else if (DstType->isObjCQualifiedIdType()) {
17987 const ObjCObjectPointerType *dstOPT =
17988 DstType->castAs<ObjCObjectPointerType>();
17989 for (auto *dstProto : dstOPT->quals()) {
17990 PDecl = dstProto;
17991 break;
17992 }
17993 if (const ObjCInterfaceType *IFaceT =
17994 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17995 IFace = IFaceT->getDecl();
17996 }
17997 if (getLangOpts().CPlusPlus) {
17998 DiagKind = diag::err_incompatible_qualified_id;
17999 isInvalid = true;
18000 } else {
18001 DiagKind = diag::warn_incompatible_qualified_id;
18002 }
18003 break;
18004 }
18005 case AssignConvertType::IncompatibleVectors:
18006 if (getLangOpts().CPlusPlus) {
18007 DiagKind = diag::err_incompatible_vectors;
18008 isInvalid = true;
18009 } else {
18010 DiagKind = diag::warn_incompatible_vectors;
18011 }
18012 break;
18013 case AssignConvertType::IncompatibleObjCWeakRef:
18014 DiagKind = diag::err_arc_weak_unavailable_assign;
18015 isInvalid = true;
18016 break;
18017 case AssignConvertType::CompatibleOBTDiscards:
18018 return false;
18019 case AssignConvertType::IncompatibleOBTKinds: {
18020 assert(!SrcType->isFunctionType() &&
18021 "Unexpected function type found in IncompatibleOBTKinds assignment");
18022 if (SrcType->canDecayToPointerType())
18023 SrcType = Context.getDecayedType(T: SrcType);
18024
18025 auto getOBTKindName = [](QualType Ty) -> StringRef {
18026 if (Ty->isPointerType())
18027 Ty = Ty->getPointeeType();
18028 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18029 return OBT->getBehaviorKind() ==
18030 OverflowBehaviorType::OverflowBehaviorKind::Trap
18031 ? "__ob_trap"
18032 : "__ob_wrap";
18033 }
18034 llvm_unreachable("OBT kind unhandled");
18035 };
18036
18037 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
18038 << DstType << SrcType << getOBTKindName(DstType)
18039 << getOBTKindName(SrcType);
18040 isInvalid = true;
18041 return true;
18042 }
18043 case AssignConvertType::Incompatible:
18044 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
18045 if (Complained)
18046 *Complained = true;
18047 return true;
18048 }
18049
18050 DiagKind = diag::err_typecheck_convert_incompatible;
18051 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18052 MayHaveConvFixit = true;
18053 isInvalid = true;
18054 MayHaveFunctionDiff = true;
18055 break;
18056 }
18057
18058 QualType FirstType, SecondType;
18059 switch (Action) {
18060 case AssignmentAction::Assigning:
18061 case AssignmentAction::Initializing:
18062 // The destination type comes first.
18063 FirstType = DstType;
18064 SecondType = SrcType;
18065 break;
18066
18067 case AssignmentAction::Returning:
18068 case AssignmentAction::Passing:
18069 case AssignmentAction::Passing_CFAudited:
18070 case AssignmentAction::Converting:
18071 case AssignmentAction::Sending:
18072 case AssignmentAction::Casting:
18073 // The source type comes first.
18074 FirstType = SrcType;
18075 SecondType = DstType;
18076 break;
18077 }
18078
18079 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
18080 AssignmentAction ActionForDiag = Action;
18081 if (Action == AssignmentAction::Passing_CFAudited)
18082 ActionForDiag = AssignmentAction::Passing;
18083
18084 FDiag << FirstType << SecondType << ActionForDiag
18085 << SrcExpr->getSourceRange();
18086
18087 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18088 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18089 auto isPlainChar = [](const clang::Type *Type) {
18090 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
18091 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
18092 };
18093 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18094 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18095 }
18096
18097 // If we can fix the conversion, suggest the FixIts.
18098 if (!ConvHints.isNull()) {
18099 for (FixItHint &H : ConvHints.Hints)
18100 FDiag << H;
18101 }
18102
18103 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18104
18105 if (MayHaveFunctionDiff)
18106 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
18107
18108 Diag(Loc, PD: FDiag);
18109 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18110 DiagKind == diag::err_incompatible_qualified_id) &&
18111 PDecl && IFace && !IFace->hasDefinition())
18112 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
18113 << IFace << PDecl;
18114
18115 if (SecondType == Context.OverloadTy)
18116 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
18117 DestType: FirstType, /*TakingAddress=*/true);
18118
18119 if (CheckInferredResultType)
18120 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
18121
18122 if (Action == AssignmentAction::Returning &&
18123 ConvTy == AssignConvertType::IncompatiblePointer)
18124 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
18125
18126 if (Complained)
18127 *Complained = true;
18128 return isInvalid;
18129}
18130
18131ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18132 llvm::APSInt *Result,
18133 AllowFoldKind CanFold) {
18134 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18135 public:
18136 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18137 QualType T) override {
18138 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
18139 << T << S.LangOpts.CPlusPlus;
18140 }
18141 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18142 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18143 }
18144 } Diagnoser;
18145
18146 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18147}
18148
18149ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18150 llvm::APSInt *Result,
18151 unsigned DiagID,
18152 AllowFoldKind CanFold) {
18153 class IDDiagnoser : public VerifyICEDiagnoser {
18154 unsigned DiagID;
18155
18156 public:
18157 IDDiagnoser(unsigned DiagID)
18158 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18159
18160 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18161 return S.Diag(Loc, DiagID);
18162 }
18163 } Diagnoser(DiagID);
18164
18165 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18166}
18167
18168Sema::SemaDiagnosticBuilder
18169Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
18170 QualType T) {
18171 return diagnoseNotICE(S, Loc);
18172}
18173
18174Sema::SemaDiagnosticBuilder
18175Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
18176 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18177}
18178
18179ExprResult
18180Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
18181 VerifyICEDiagnoser &Diagnoser,
18182 AllowFoldKind CanFold) {
18183 SourceLocation DiagLoc = E->getBeginLoc();
18184
18185 if (getLangOpts().CPlusPlus11) {
18186 // C++11 [expr.const]p5:
18187 // If an expression of literal class type is used in a context where an
18188 // integral constant expression is required, then that class type shall
18189 // have a single non-explicit conversion function to an integral or
18190 // unscoped enumeration type
18191 ExprResult Converted;
18192 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18193 VerifyICEDiagnoser &BaseDiagnoser;
18194 public:
18195 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18196 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18197 BaseDiagnoser.Suppress, true),
18198 BaseDiagnoser(BaseDiagnoser) {}
18199
18200 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18201 QualType T) override {
18202 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18203 }
18204
18205 SemaDiagnosticBuilder diagnoseIncomplete(
18206 Sema &S, SourceLocation Loc, QualType T) override {
18207 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
18208 }
18209
18210 SemaDiagnosticBuilder diagnoseExplicitConv(
18211 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18212 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
18213 }
18214
18215 SemaDiagnosticBuilder noteExplicitConv(
18216 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18217 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18218 << ConvTy->isEnumeralType() << ConvTy;
18219 }
18220
18221 SemaDiagnosticBuilder diagnoseAmbiguous(
18222 Sema &S, SourceLocation Loc, QualType T) override {
18223 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
18224 }
18225
18226 SemaDiagnosticBuilder noteAmbiguous(
18227 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18228 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18229 << ConvTy->isEnumeralType() << ConvTy;
18230 }
18231
18232 SemaDiagnosticBuilder diagnoseConversion(
18233 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18234 llvm_unreachable("conversion functions are permitted");
18235 }
18236 } ConvertDiagnoser(Diagnoser);
18237
18238 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18239 Converter&: ConvertDiagnoser);
18240 if (Converted.isInvalid())
18241 return Converted;
18242 E = Converted.get();
18243 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18244 // don't try to evaluate it later. We also don't want to return the
18245 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18246 // this function will attempt to use 'Value'.
18247 if (isa<RecoveryExpr>(Val: E))
18248 return ExprError();
18249 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18250 return ExprError();
18251 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18252 // An ICE must be of integral or unscoped enumeration type.
18253 if (!Diagnoser.Suppress)
18254 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18255 << E->getSourceRange();
18256 return ExprError();
18257 }
18258
18259 ExprResult RValueExpr = DefaultLvalueConversion(E);
18260 if (RValueExpr.isInvalid())
18261 return ExprError();
18262
18263 E = RValueExpr.get();
18264
18265 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18266 // in the non-ICE case.
18267 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18268 SmallVector<PartialDiagnosticAt, 8> Notes;
18269 if (Result)
18270 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18271 if (!isa<ConstantExpr>(Val: E))
18272 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18273 : ConstantExpr::Create(Context, E);
18274
18275 if (Notes.empty())
18276 return E;
18277
18278 // If our only note is the usual "invalid subexpression" note, just point
18279 // the caret at its location rather than producing an essentially
18280 // redundant note.
18281 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18282 diag::note_invalid_subexpr_in_const_expr) {
18283 DiagLoc = Notes[0].first;
18284 Notes.clear();
18285 }
18286
18287 if (getLangOpts().CPlusPlus) {
18288 if (!Diagnoser.Suppress) {
18289 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18290 for (const PartialDiagnosticAt &Note : Notes)
18291 Diag(Loc: Note.first, PD: Note.second);
18292 }
18293 return ExprError();
18294 }
18295
18296 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18297 for (const PartialDiagnosticAt &Note : Notes)
18298 Diag(Loc: Note.first, PD: Note.second);
18299
18300 return E;
18301 }
18302
18303 Expr::EvalResult EvalResult;
18304 SmallVector<PartialDiagnosticAt, 8> Notes;
18305 SmallVector<PartialDiagnosticAt> MSWarning;
18306 EvalResult.Diag = &Notes;
18307 EvalResult.ExtendedDiag = &MSWarning;
18308
18309 // Try to evaluate the expression, and produce diagnostics explaining why it's
18310 // not a constant expression as a side-effect.
18311 bool Folded =
18312 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18313 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18314 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18315
18316 if (!isa<ConstantExpr>(Val: E))
18317 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18318
18319 // For -fms-compatibility mode we relax some requirements
18320 // for constant folding in non-SFINAE contexts
18321 if (!MSWarning.empty()) {
18322 if (isSFINAEContext()) {
18323 Folded = false;
18324 } else {
18325 for (auto &Info : MSWarning)
18326 Diag(Loc: Info.first, PD: Info.second);
18327 }
18328 }
18329
18330 // In C++11, we can rely on diagnostics being produced for any expression
18331 // which is not a constant expression. If no diagnostics were produced, then
18332 // this is a constant expression.
18333 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18334 if (Result)
18335 *Result = EvalResult.Val.getInt();
18336 return E;
18337 }
18338
18339 // If our only note is the usual "invalid subexpression" note, just point
18340 // the caret at its location rather than producing an essentially
18341 // redundant note.
18342 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18343 diag::note_invalid_subexpr_in_const_expr) {
18344 DiagLoc = Notes[0].first;
18345 Notes.clear();
18346 }
18347
18348 if (!Folded || CanFold == AllowFoldKind::No) {
18349 if (!Diagnoser.Suppress) {
18350 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18351 for (const PartialDiagnosticAt &Note : Notes)
18352 Diag(Loc: Note.first, PD: Note.second);
18353 }
18354
18355 return ExprError();
18356 }
18357
18358 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18359 for (const PartialDiagnosticAt &Note : Notes)
18360 Diag(Loc: Note.first, PD: Note.second);
18361
18362 if (Result)
18363 *Result = EvalResult.Val.getInt();
18364 return E;
18365}
18366
18367namespace {
18368 // Handle the case where we conclude a expression which we speculatively
18369 // considered to be unevaluated is actually evaluated.
18370 class TransformToPE : public TreeTransform<TransformToPE> {
18371 typedef TreeTransform<TransformToPE> BaseTransform;
18372
18373 public:
18374 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18375
18376 // Make sure we redo semantic analysis
18377 bool AlwaysRebuild() { return true; }
18378 bool ReplacingOriginal() { return true; }
18379
18380 // We need to special-case DeclRefExprs referring to FieldDecls which
18381 // are not part of a member pointer formation; normal TreeTransforming
18382 // doesn't catch this case because of the way we represent them in the AST.
18383 // FIXME: This is a bit ugly; is it really the best way to handle this
18384 // case?
18385 //
18386 // Error on DeclRefExprs referring to FieldDecls.
18387 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18388 if (isa<FieldDecl>(Val: E->getDecl()) &&
18389 !SemaRef.isUnevaluatedContext())
18390 return SemaRef.Diag(Loc: E->getLocation(),
18391 DiagID: diag::err_invalid_non_static_member_use)
18392 << E->getDecl() << E->getSourceRange();
18393
18394 return BaseTransform::TransformDeclRefExpr(E);
18395 }
18396
18397 // Exception: filter out member pointer formation
18398 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18399 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18400 return E;
18401
18402 return BaseTransform::TransformUnaryOperator(E);
18403 }
18404
18405 // The body of a lambda-expression is in a separate expression evaluation
18406 // context so never needs to be transformed.
18407 // FIXME: Ideally we wouldn't transform the closure type either, and would
18408 // just recreate the capture expressions and lambda expression.
18409 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18410 return SkipLambdaBody(E, S: Body);
18411 }
18412 };
18413}
18414
18415ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18416 assert(isUnevaluatedContext() &&
18417 "Should only transform unevaluated expressions");
18418 ExprEvalContexts.back().Context =
18419 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18420 if (isUnevaluatedContext())
18421 return E;
18422 return TransformToPE(*this).TransformExpr(E);
18423}
18424
18425TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18426 assert(isUnevaluatedContext() &&
18427 "Should only transform unevaluated expressions");
18428 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18429 if (isUnevaluatedContext())
18430 return TInfo;
18431 return TransformToPE(*this).TransformType(TSI: TInfo);
18432}
18433
18434void
18435Sema::PushExpressionEvaluationContext(
18436 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18437 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18438 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18439 Args&: LambdaContextDecl, Args&: ExprContext);
18440
18441 // Discarded statements and immediate contexts nested in other
18442 // discarded statements or immediate context are themselves
18443 // a discarded statement or an immediate context, respectively.
18444 ExprEvalContexts.back().InDiscardedStatement =
18445 parentEvaluationContext().isDiscardedStatementContext();
18446
18447 // C++23 [expr.const]/p15
18448 // An expression or conversion is in an immediate function context if [...]
18449 // it is a subexpression of a manifestly constant-evaluated expression or
18450 // conversion.
18451 const auto &Prev = parentEvaluationContext();
18452 ExprEvalContexts.back().InImmediateFunctionContext =
18453 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18454
18455 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18456 Prev.InImmediateEscalatingFunctionContext;
18457
18458 Cleanup.reset();
18459 if (!MaybeODRUseExprs.empty())
18460 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18461}
18462
18463void
18464Sema::PushExpressionEvaluationContext(
18465 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18466 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18467 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18468 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18469}
18470
18471void Sema::PushExpressionEvaluationContextForFunction(
18472 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18473 // [expr.const]/p14.1
18474 // An expression or conversion is in an immediate function context if it is
18475 // potentially evaluated and either: its innermost enclosing non-block scope
18476 // is a function parameter scope of an immediate function.
18477 PushExpressionEvaluationContext(
18478 NewContext: FD && FD->isConsteval()
18479 ? ExpressionEvaluationContext::ImmediateFunctionContext
18480 : NewContext);
18481 const Sema::ExpressionEvaluationContextRecord &Parent =
18482 parentEvaluationContext();
18483 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18484
18485 Current.InDiscardedStatement = false;
18486
18487 if (FD) {
18488
18489 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18490 // context is nested in an immediate function context, so smaller contexts
18491 // that appear inside immediate functions (like variable initializers) are
18492 // considered to be inside an immediate function context even though by
18493 // themselves they are not immediate function contexts. But when a new
18494 // function is entered, we need to reset this tracking, since the entered
18495 // function might be not an immediate function.
18496
18497 Current.InImmediateEscalatingFunctionContext =
18498 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18499
18500 if (isLambdaMethod(DC: FD))
18501 Current.InImmediateFunctionContext =
18502 FD->isConsteval() ||
18503 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18504 Parent.isImmediateFunctionContext()));
18505 else
18506 Current.InImmediateFunctionContext = FD->isConsteval();
18507 }
18508}
18509
18510ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18511 TypeSourceInfo *TSI) {
18512 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18513}
18514
18515ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18516 TypeSourceInfo *TSI) {
18517 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18518}
18519
18520namespace {
18521
18522const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18523 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18524 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18525 if (E->getOpcode() == UO_Deref)
18526 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18527 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18528 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18529 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18530 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18531 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18532 QualType Inner;
18533 QualType Ty = E->getType();
18534 if (const auto *Ptr = Ty->getAs<PointerType>())
18535 Inner = Ptr->getPointeeType();
18536 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18537 Inner = Arr->getElementType();
18538 else
18539 return nullptr;
18540
18541 if (Inner->hasAttr(AK: attr::NoDeref))
18542 return E;
18543 }
18544 return nullptr;
18545}
18546
18547} // namespace
18548
18549void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18550 for (const Expr *E : Rec.PossibleDerefs) {
18551 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18552 if (DeclRef) {
18553 const ValueDecl *Decl = DeclRef->getDecl();
18554 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18555 << Decl->getName() << E->getSourceRange();
18556 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18557 } else {
18558 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18559 << E->getSourceRange();
18560 }
18561 }
18562 Rec.PossibleDerefs.clear();
18563}
18564
18565void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18566 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18567 return;
18568
18569 // Note: ignoring parens here is not justified by the standard rules, but
18570 // ignoring parentheses seems like a more reasonable approach, and this only
18571 // drives a deprecation warning so doesn't affect conformance.
18572 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18573 if (BO->getOpcode() == BO_Assign) {
18574 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18575 llvm::erase(C&: LHSs, V: BO->getLHS());
18576 }
18577 }
18578}
18579
18580void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18581 assert(getLangOpts().CPlusPlus20 &&
18582 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18583 "Cannot mark an immediate escalating expression outside of an "
18584 "immediate escalating context");
18585 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18586 Call && Call->getCallee()) {
18587 if (auto *DeclRef =
18588 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18589 DeclRef->setIsImmediateEscalating(true);
18590 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18591 Ctr->setIsImmediateEscalating(true);
18592 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18593 DeclRef->setIsImmediateEscalating(true);
18594 } else {
18595 assert(false && "expected an immediately escalating expression");
18596 }
18597 if (FunctionScopeInfo *FI = getCurFunction())
18598 FI->FoundImmediateEscalatingExpression = true;
18599}
18600
18601ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18602 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18603 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18604 isCheckingDefaultArgumentOrInitializer() ||
18605 RebuildingImmediateInvocation || isImmediateFunctionContext())
18606 return E;
18607
18608 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18609 /// It's OK if this fails; we'll also remove this in
18610 /// HandleImmediateInvocations, but catching it here allows us to avoid
18611 /// walking the AST looking for it in simple cases.
18612 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18613 if (auto *DeclRef =
18614 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18615 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18616
18617 // C++23 [expr.const]/p16
18618 // An expression or conversion is immediate-escalating if it is not initially
18619 // in an immediate function context and it is [...] an immediate invocation
18620 // that is not a constant expression and is not a subexpression of an
18621 // immediate invocation.
18622 APValue Cached;
18623 auto CheckConstantExpressionAndKeepResult = [&]() {
18624 Expr::EvalResult Eval;
18625 bool Res = E.get()->EvaluateAsConstantExpr(
18626 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18627 if (Res && !Eval.DiagEmitted) {
18628 Cached = std::move(Eval.Val);
18629 return true;
18630 }
18631 return false;
18632 };
18633
18634 if (!E.get()->isValueDependent() &&
18635 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18636 !CheckConstantExpressionAndKeepResult()) {
18637 MarkExpressionAsImmediateEscalating(E: E.get());
18638 return E;
18639 }
18640
18641 if (Cleanup.exprNeedsCleanups()) {
18642 // Since an immediate invocation is a full expression itself - it requires
18643 // an additional ExprWithCleanups node, but it can participate to a bigger
18644 // full expression which actually requires cleanups to be run after so
18645 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18646 // may discard cleanups for outer expression too early.
18647
18648 // Note that ExprWithCleanups created here must always have empty cleanup
18649 // objects:
18650 // - compound literals do not create cleanup objects in C++ and immediate
18651 // invocations are C++-only.
18652 // - blocks are not allowed inside constant expressions and compiler will
18653 // issue an error if they appear there.
18654 //
18655 // Hence, in correct code any cleanup objects created inside current
18656 // evaluation context must be outside the immediate invocation.
18657 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18658 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18659 }
18660
18661 ConstantExpr *Res = ConstantExpr::Create(
18662 Context: getASTContext(), E: E.get(),
18663 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18664 Context: getASTContext()),
18665 /*IsImmediateInvocation*/ true);
18666 if (Cached.hasValue())
18667 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18668 /// Value-dependent constant expressions should not be immediately
18669 /// evaluated until they are instantiated.
18670 if (!Res->isValueDependent())
18671 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18672 return Res;
18673}
18674
18675static void EvaluateAndDiagnoseImmediateInvocation(
18676 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18677 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18678 Expr::EvalResult Eval;
18679 Eval.Diag = &Notes;
18680 ConstantExpr *CE = Candidate.getPointer();
18681 bool Result = CE->EvaluateAsConstantExpr(
18682 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18683 if (!Result || !Notes.empty()) {
18684 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18685 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18686 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18687 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18688 FunctionDecl *FD = nullptr;
18689 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18690 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18691 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18692 FD = Call->getConstructor();
18693 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18694 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18695
18696 assert(FD && FD->isImmediateFunction() &&
18697 "could not find an immediate function in this expression");
18698 if (FD->isInvalidDecl())
18699 return;
18700 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18701 << FD << FD->isConsteval();
18702 if (auto Context =
18703 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18704 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18705 << Context->Decl;
18706 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18707 }
18708 if (!FD->isConsteval())
18709 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18710 for (auto &Note : Notes)
18711 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18712 return;
18713 }
18714 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18715}
18716
18717static void RemoveNestedImmediateInvocation(
18718 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18719 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18720 struct ComplexRemove : TreeTransform<ComplexRemove> {
18721 using Base = TreeTransform<ComplexRemove>;
18722 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18723 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18724 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18725 CurrentII;
18726 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18727 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18728 SmallVector<Sema::ImmediateInvocationCandidate,
18729 4>::reverse_iterator Current)
18730 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18731 void RemoveImmediateInvocation(ConstantExpr* E) {
18732 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18733 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18734 return Elem.getPointer() == E;
18735 });
18736 // It is possible that some subexpression of the current immediate
18737 // invocation was handled from another expression evaluation context. Do
18738 // not handle the current immediate invocation if some of its
18739 // subexpressions failed before.
18740 if (It == IISet.rend()) {
18741 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18742 CurrentII->setInt(1);
18743 } else {
18744 It->setInt(1); // Mark as deleted
18745 }
18746 }
18747 ExprResult TransformConstantExpr(ConstantExpr *E) {
18748 if (!E->isImmediateInvocation())
18749 return Base::TransformConstantExpr(E);
18750 RemoveImmediateInvocation(E);
18751 return Base::TransformExpr(E: E->getSubExpr());
18752 }
18753 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18754 /// we need to remove its DeclRefExpr from the DRSet.
18755 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18756 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18757 return Base::TransformCXXOperatorCallExpr(E);
18758 }
18759 /// Base::TransformUserDefinedLiteral doesn't preserve the
18760 /// UserDefinedLiteral node.
18761 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18762 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18763 /// here.
18764 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18765 if (!Init)
18766 return Init;
18767
18768 // We cannot use IgnoreImpCasts because we need to preserve
18769 // full expressions.
18770 while (true) {
18771 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18772 Init = ICE->getSubExpr();
18773 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18774 Init = ICE->getSubExpr();
18775 else
18776 break;
18777 }
18778 /// ConstantExprs are the first layer of implicit node to be removed so if
18779 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18780 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18781 CE && CE->isImmediateInvocation())
18782 RemoveImmediateInvocation(E: CE);
18783 return Base::TransformInitializer(Init, NotCopyInit);
18784 }
18785 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18786 DRSet.erase(Ptr: E);
18787 return E;
18788 }
18789 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18790 // Do not rebuild lambdas to avoid creating a new type.
18791 // Lambdas have already been processed inside their eval contexts.
18792 return E;
18793 }
18794
18795 // We do not have enough information to transform opaque expressions and
18796 // assume they do not contain immediate subexpressions.
18797 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18798
18799 bool AlwaysRebuild() { return false; }
18800 bool ReplacingOriginal() { return true; }
18801 bool AllowSkippingCXXConstructExpr() {
18802 bool Res = AllowSkippingFirstCXXConstructExpr;
18803 AllowSkippingFirstCXXConstructExpr = true;
18804 return Res;
18805 }
18806 bool AllowSkippingFirstCXXConstructExpr = true;
18807 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18808 Rec.ImmediateInvocationCandidates, It);
18809
18810 /// CXXConstructExpr with a single argument are getting skipped by
18811 /// TreeTransform in some situtation because they could be implicit. This
18812 /// can only occur for the top-level CXXConstructExpr because it is used
18813 /// nowhere in the expression being transformed therefore will not be rebuilt.
18814 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18815 /// skipping the first CXXConstructExpr.
18816 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18817 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18818
18819 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18820 // The result may not be usable in case of previous compilation errors.
18821 // In this case evaluation of the expression may result in crash so just
18822 // don't do anything further with the result.
18823 if (Res.isUsable()) {
18824 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18825 It->getPointer()->setSubExpr(Res.get());
18826 }
18827}
18828
18829static void
18830HandleImmediateInvocations(Sema &SemaRef,
18831 Sema::ExpressionEvaluationContextRecord &Rec) {
18832 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18833 Rec.ReferenceToConsteval.size() == 0) ||
18834 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18835 return;
18836
18837 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18838 // [...]
18839 // - the initializer of a variable that is usable in constant expressions or
18840 // has constant initialization.
18841 if (SemaRef.getLangOpts().CPlusPlus23 &&
18842 Rec.ExprContext ==
18843 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18844 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18845 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18846 VD->hasConstantInitialization())) {
18847 // An expression or conversion is in an 'immediate function context' if it
18848 // is potentially evaluated and either:
18849 // [...]
18850 // - it is a subexpression of a manifestly constant-evaluated expression
18851 // or conversion.
18852 return;
18853 }
18854 }
18855
18856 /// When we have more than 1 ImmediateInvocationCandidates or previously
18857 /// failed immediate invocations, we need to check for nested
18858 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18859 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18860 /// invocation.
18861 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18862 !SemaRef.FailedImmediateInvocations.empty()) {
18863
18864 /// Prevent sema calls during the tree transform from adding pointers that
18865 /// are already in the sets.
18866 llvm::SaveAndRestore DisableIITracking(
18867 SemaRef.RebuildingImmediateInvocation, true);
18868
18869 /// Prevent diagnostic during tree transfrom as they are duplicates
18870 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18871
18872 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18873 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18874 if (!It->getInt())
18875 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18876 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18877 Rec.ReferenceToConsteval.size()) {
18878 struct SimpleRemove : DynamicRecursiveASTVisitor {
18879 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18880 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18881 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18882 DRSet.erase(Ptr: E);
18883 return DRSet.size();
18884 }
18885 } Visitor(Rec.ReferenceToConsteval);
18886 Visitor.TraverseStmt(
18887 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18888 }
18889 for (auto CE : Rec.ImmediateInvocationCandidates)
18890 if (!CE.getInt())
18891 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18892 for (auto *DR : Rec.ReferenceToConsteval) {
18893 // If the expression is immediate escalating, it is not an error;
18894 // The outer context itself becomes immediate and further errors,
18895 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18896 if (DR->isImmediateEscalating())
18897 continue;
18898 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18899 const NamedDecl *ND = FD;
18900 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18901 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18902 ND = MD->getParent();
18903
18904 // C++23 [expr.const]/p16
18905 // An expression or conversion is immediate-escalating if it is not
18906 // initially in an immediate function context and it is [...] a
18907 // potentially-evaluated id-expression that denotes an immediate function
18908 // that is not a subexpression of an immediate invocation.
18909 bool ImmediateEscalating = false;
18910 bool IsPotentiallyEvaluated =
18911 Rec.Context ==
18912 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18913 Rec.Context ==
18914 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18915 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18916 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18917
18918 if (!Rec.InImmediateEscalatingFunctionContext ||
18919 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18920 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18921 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18922 if (!FD->getBuiltinID())
18923 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18924 if (auto Context =
18925 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18926 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18927 << Context->Decl;
18928 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18929 }
18930 if (FD->isImmediateEscalating() && !FD->isConsteval())
18931 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18932
18933 } else {
18934 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18935 }
18936 }
18937}
18938
18939void Sema::PopExpressionEvaluationContext() {
18940 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18941 if (!Rec.Lambdas.empty()) {
18942 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18943 if (!getLangOpts().CPlusPlus20 &&
18944 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18945 Rec.isUnevaluated() ||
18946 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18947 unsigned D;
18948 if (Rec.isUnevaluated()) {
18949 // C++11 [expr.prim.lambda]p2:
18950 // A lambda-expression shall not appear in an unevaluated operand
18951 // (Clause 5).
18952 D = diag::err_lambda_unevaluated_operand;
18953 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18954 // C++1y [expr.const]p2:
18955 // A conditional-expression e is a core constant expression unless the
18956 // evaluation of e, following the rules of the abstract machine, would
18957 // evaluate [...] a lambda-expression.
18958 D = diag::err_lambda_in_constant_expression;
18959 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18960 // C++17 [expr.prim.lamda]p2:
18961 // A lambda-expression shall not appear [...] in a template-argument.
18962 D = diag::err_lambda_in_invalid_context;
18963 } else
18964 llvm_unreachable("Couldn't infer lambda error message.");
18965
18966 for (const auto *L : Rec.Lambdas)
18967 Diag(Loc: L->getBeginLoc(), DiagID: D);
18968 }
18969 }
18970
18971 // Append the collected materialized temporaries into previous context before
18972 // exit if the previous also is a lifetime extending context.
18973 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18974 parentEvaluationContext().InLifetimeExtendingContext &&
18975 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18976 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18977 RHS: Rec.ForRangeLifetimeExtendTemps);
18978 }
18979
18980 WarnOnPendingNoDerefs(Rec);
18981 HandleImmediateInvocations(SemaRef&: *this, Rec);
18982
18983 // Warn on any volatile-qualified simple-assignments that are not discarded-
18984 // value expressions nor unevaluated operands (those cases get removed from
18985 // this list by CheckUnusedVolatileAssignment).
18986 for (auto *BO : Rec.VolatileAssignmentLHSs)
18987 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18988 << BO->getType();
18989
18990 // When are coming out of an unevaluated context, clear out any
18991 // temporaries that we may have created as part of the evaluation of
18992 // the expression in that context: they aren't relevant because they
18993 // will never be constructed.
18994 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18995 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18996 CE: ExprCleanupObjects.end());
18997 Cleanup = Rec.ParentCleanup;
18998 CleanupVarDeclMarking();
18999 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
19000 // Otherwise, merge the contexts together.
19001 } else {
19002 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
19003 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
19004 }
19005
19006 DiagnoseMisalignedMembers();
19007
19008 // Pop the current expression evaluation context off the stack.
19009 ExprEvalContexts.pop_back();
19010}
19011
19012void Sema::DiscardCleanupsInEvaluationContext() {
19013 ExprCleanupObjects.erase(
19014 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19015 CE: ExprCleanupObjects.end());
19016 Cleanup.reset();
19017 MaybeODRUseExprs.clear();
19018}
19019
19020ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
19021 ExprResult Result = CheckPlaceholderExpr(E);
19022 if (Result.isInvalid())
19023 return ExprError();
19024 E = Result.get();
19025 if (!E->getType()->isVariablyModifiedType())
19026 return E;
19027 return TransformToPotentiallyEvaluated(E);
19028}
19029
19030/// Are we in a context that is potentially constant evaluated per C++20
19031/// [expr.const]p12?
19032static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
19033 /// C++2a [expr.const]p12:
19034 // An expression or conversion is potentially constant evaluated if it is
19035 switch (SemaRef.ExprEvalContexts.back().Context) {
19036 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
19037 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
19038
19039 // -- a manifestly constant-evaluated expression,
19040 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
19041 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19042 case Sema::ExpressionEvaluationContext::DiscardedStatement:
19043 // -- a potentially-evaluated expression,
19044 case Sema::ExpressionEvaluationContext::UnevaluatedList:
19045 // -- an immediate subexpression of a braced-init-list,
19046
19047 // -- [FIXME] an expression of the form & cast-expression that occurs
19048 // within a templated entity
19049 // -- a subexpression of one of the above that is not a subexpression of
19050 // a nested unevaluated operand.
19051 return true;
19052
19053 case Sema::ExpressionEvaluationContext::Unevaluated:
19054 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
19055 // Expressions in this context are never evaluated.
19056 return false;
19057 }
19058 llvm_unreachable("Invalid context");
19059}
19060
19061/// Return true if this function has a calling convention that requires mangling
19062/// in the size of the parameter pack.
19063static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
19064 // These manglings are only applicable for targets whcih use Microsoft
19065 // mangling scheme for C.
19066 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
19067 return false;
19068
19069 // If this is C++ and this isn't an extern "C" function, parameters do not
19070 // need to be complete. In this case, C++ mangling will apply, which doesn't
19071 // use the size of the parameters.
19072 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19073 return false;
19074
19075 // Stdcall, fastcall, and vectorcall need this special treatment.
19076 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19077 switch (CC) {
19078 case CC_X86StdCall:
19079 case CC_X86FastCall:
19080 case CC_X86VectorCall:
19081 return true;
19082 default:
19083 break;
19084 }
19085 return false;
19086}
19087
19088/// Require that all of the parameter types of function be complete. Normally,
19089/// parameter types are only required to be complete when a function is called
19090/// or defined, but to mangle functions with certain calling conventions, the
19091/// mangler needs to know the size of the parameter list. In this situation,
19092/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19093/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19094/// result in a linker error. Clang doesn't implement this behavior, and instead
19095/// attempts to error at compile time.
19096static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
19097 SourceLocation Loc) {
19098 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19099 FunctionDecl *FD;
19100 ParmVarDecl *Param;
19101
19102 public:
19103 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19104 : FD(FD), Param(Param) {}
19105
19106 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19107 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19108 StringRef CCName;
19109 switch (CC) {
19110 case CC_X86StdCall:
19111 CCName = "stdcall";
19112 break;
19113 case CC_X86FastCall:
19114 CCName = "fastcall";
19115 break;
19116 case CC_X86VectorCall:
19117 CCName = "vectorcall";
19118 break;
19119 default:
19120 llvm_unreachable("CC does not need mangling");
19121 }
19122
19123 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
19124 << Param->getDeclName() << FD->getDeclName() << CCName;
19125 }
19126 };
19127
19128 for (ParmVarDecl *Param : FD->parameters()) {
19129 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19130 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
19131 }
19132}
19133
19134namespace {
19135enum class OdrUseContext {
19136 /// Declarations in this context are not odr-used.
19137 None,
19138 /// Declarations in this context are formally odr-used, but this is a
19139 /// dependent context.
19140 Dependent,
19141 /// Declarations in this context are odr-used but not actually used (yet).
19142 FormallyOdrUsed,
19143 /// Declarations in this context are used.
19144 Used
19145};
19146}
19147
19148/// Are we within a context in which references to resolved functions or to
19149/// variables result in odr-use?
19150static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19151 const Sema::ExpressionEvaluationContextRecord &Context =
19152 SemaRef.currentEvaluationContext();
19153
19154 if (Context.isUnevaluated())
19155 return OdrUseContext::None;
19156
19157 if (SemaRef.CurContext->isDependentContext())
19158 return OdrUseContext::Dependent;
19159
19160 if (Context.isDiscardedStatementContext())
19161 return OdrUseContext::FormallyOdrUsed;
19162
19163 else if (Context.Context ==
19164 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
19165 return OdrUseContext::FormallyOdrUsed;
19166
19167 return OdrUseContext::Used;
19168}
19169
19170static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
19171 if (!Func->isConstexpr())
19172 return false;
19173
19174 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19175 return true;
19176
19177 // Lambda conversion operators are never user provided.
19178 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
19179 return isLambdaConversionOperator(C: Conv);
19180
19181 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
19182 return CCD && CCD->getInheritedConstructor();
19183}
19184
19185void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
19186 bool MightBeOdrUse) {
19187 assert(Func && "No function?");
19188
19189 Func->setReferenced();
19190
19191 // Recursive functions aren't really used until they're used from some other
19192 // context.
19193 bool IsRecursiveCall = CurContext == Func;
19194
19195 // C++11 [basic.def.odr]p3:
19196 // A function whose name appears as a potentially-evaluated expression is
19197 // odr-used if it is the unique lookup result or the selected member of a
19198 // set of overloaded functions [...].
19199 //
19200 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19201 // can just check that here.
19202 OdrUseContext OdrUse =
19203 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
19204 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19205 OdrUse = OdrUseContext::FormallyOdrUsed;
19206
19207 // Trivial default constructors and destructors are never actually used.
19208 // FIXME: What about other special members?
19209 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19210 OdrUse == OdrUseContext::Used) {
19211 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
19212 if (Constructor->isDefaultConstructor())
19213 OdrUse = OdrUseContext::FormallyOdrUsed;
19214 if (isa<CXXDestructorDecl>(Val: Func))
19215 OdrUse = OdrUseContext::FormallyOdrUsed;
19216 }
19217
19218 // C++20 [expr.const]p12:
19219 // A function [...] is needed for constant evaluation if it is [...] a
19220 // constexpr function that is named by an expression that is potentially
19221 // constant evaluated
19222 bool NeededForConstantEvaluation =
19223 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
19224 isImplicitlyDefinableConstexprFunction(Func);
19225
19226 // Determine whether we require a function definition to exist, per
19227 // C++11 [temp.inst]p3:
19228 // Unless a function template specialization has been explicitly
19229 // instantiated or explicitly specialized, the function template
19230 // specialization is implicitly instantiated when the specialization is
19231 // referenced in a context that requires a function definition to exist.
19232 // C++20 [temp.inst]p7:
19233 // The existence of a definition of a [...] function is considered to
19234 // affect the semantics of the program if the [...] function is needed for
19235 // constant evaluation by an expression
19236 // C++20 [basic.def.odr]p10:
19237 // Every program shall contain exactly one definition of every non-inline
19238 // function or variable that is odr-used in that program outside of a
19239 // discarded statement
19240 // C++20 [special]p1:
19241 // The implementation will implicitly define [defaulted special members]
19242 // if they are odr-used or needed for constant evaluation.
19243 //
19244 // Note that we skip the implicit instantiation of templates that are only
19245 // used in unused default arguments or by recursive calls to themselves.
19246 // This is formally non-conforming, but seems reasonable in practice.
19247 bool NeedDefinition =
19248 !IsRecursiveCall &&
19249 (OdrUse == OdrUseContext::Used ||
19250 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19251
19252 // C++14 [temp.expl.spec]p6:
19253 // If a template [...] is explicitly specialized then that specialization
19254 // shall be declared before the first use of that specialization that would
19255 // cause an implicit instantiation to take place, in every translation unit
19256 // in which such a use occurs
19257 if (NeedDefinition &&
19258 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19259 Func->getMemberSpecializationInfo()))
19260 checkSpecializationReachability(Loc, Spec: Func);
19261
19262 if (getLangOpts().CUDA)
19263 CUDA().CheckCall(Loc, Callee: Func);
19264
19265 // If we need a definition, try to create one.
19266 if (NeedDefinition && !Func->getBody()) {
19267 runWithSufficientStackSpace(Loc, Fn: [&] {
19268 if (CXXConstructorDecl *Constructor =
19269 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19270 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19271 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19272 if (Constructor->isDefaultConstructor()) {
19273 if (Constructor->isTrivial() &&
19274 !Constructor->hasAttr<DLLExportAttr>())
19275 return;
19276 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19277 } else if (Constructor->isCopyConstructor()) {
19278 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19279 } else if (Constructor->isMoveConstructor()) {
19280 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19281 }
19282 } else if (Constructor->getInheritedConstructor()) {
19283 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19284 }
19285 } else if (CXXDestructorDecl *Destructor =
19286 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19287 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19288 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19289 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19290 return;
19291 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19292 }
19293 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19294 MarkVTableUsed(Loc, Class: Destructor->getParent());
19295 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19296 if (MethodDecl->isOverloadedOperator() &&
19297 MethodDecl->getOverloadedOperator() == OO_Equal) {
19298 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19299 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19300 if (MethodDecl->isCopyAssignmentOperator())
19301 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19302 else if (MethodDecl->isMoveAssignmentOperator())
19303 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19304 }
19305 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19306 MethodDecl->getParent()->isLambda()) {
19307 CXXConversionDecl *Conversion =
19308 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19309 if (Conversion->isLambdaToBlockPointerConversion())
19310 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19311 else
19312 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19313 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19314 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19315 }
19316
19317 if (Func->isDefaulted() && !Func->isDeleted()) {
19318 DefaultedComparisonKind DCK = Func->getDefaultedComparisonKind();
19319 if (DCK != DefaultedComparisonKind::None)
19320 DefineDefaultedComparison(Loc, FD: Func, DCK);
19321 }
19322
19323 // Implicit instantiation of function templates and member functions of
19324 // class templates.
19325 if (Func->isImplicitlyInstantiable()) {
19326 TemplateSpecializationKind TSK =
19327 Func->getTemplateSpecializationKindForInstantiation();
19328 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19329 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19330 if (FirstInstantiation) {
19331 PointOfInstantiation = Loc;
19332 if (auto *MSI = Func->getMemberSpecializationInfo())
19333 MSI->setPointOfInstantiation(Loc);
19334 // FIXME: Notify listener.
19335 else
19336 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19337 } else if (TSK != TSK_ImplicitInstantiation) {
19338 // Use the point of use as the point of instantiation, instead of the
19339 // point of explicit instantiation (which we track as the actual point
19340 // of instantiation). This gives better backtraces in diagnostics.
19341 PointOfInstantiation = Loc;
19342 }
19343
19344 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19345 Func->isConstexpr()) {
19346 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19347 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19348 CodeSynthesisContexts.size())
19349 PendingLocalImplicitInstantiations.push_back(
19350 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19351 else if (Func->isConstexpr())
19352 // Do not defer instantiations of constexpr functions, to avoid the
19353 // expression evaluator needing to call back into Sema if it sees a
19354 // call to such a function.
19355 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19356 else {
19357 Func->setInstantiationIsPending(true);
19358 PendingInstantiations.push_back(
19359 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19360 if (llvm::isTimeTraceVerbose()) {
19361 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19362 std::string Name;
19363 llvm::raw_string_ostream OS(Name);
19364 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19365 /*Qualified=*/true);
19366 return Name;
19367 });
19368 }
19369 // Notify the consumer that a function was implicitly instantiated.
19370 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19371 }
19372 }
19373 } else {
19374 // Walk redefinitions, as some of them may be instantiable.
19375 for (auto *i : Func->redecls()) {
19376 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19377 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19378 }
19379 }
19380 });
19381 }
19382
19383 // If a constructor was defined in the context of a default parameter
19384 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19385 // context), its initializers may not be referenced yet.
19386 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19387 EnterExpressionEvaluationContext EvalContext(
19388 *this,
19389 Constructor->isImmediateFunction()
19390 ? ExpressionEvaluationContext::ImmediateFunctionContext
19391 : ExpressionEvaluationContext::PotentiallyEvaluated,
19392 Constructor);
19393 for (CXXCtorInitializer *Init : Constructor->inits()) {
19394 if (Init->isInClassMemberInitializer())
19395 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19396 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19397 });
19398 }
19399 }
19400
19401 // C++14 [except.spec]p17:
19402 // An exception-specification is considered to be needed when:
19403 // - the function is odr-used or, if it appears in an unevaluated operand,
19404 // would be odr-used if the expression were potentially-evaluated;
19405 //
19406 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19407 // function is a pure virtual function we're calling, and in that case the
19408 // function was selected by overload resolution and we need to resolve its
19409 // exception specification for a different reason.
19410 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19411 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19412 ResolveExceptionSpec(Loc, FPT);
19413
19414 // A callee could be called by a host function then by a device function.
19415 // If we only try recording once, we will miss recording the use on device
19416 // side. Therefore keep trying until it is recorded.
19417 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19418 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19419 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19420
19421 // If this is the first "real" use, act on that.
19422 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19423 // Keep track of used but undefined functions.
19424 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19425 if (mightHaveNonExternalLinkage(FD: Func))
19426 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19427 else if (Func->getMostRecentDecl()->isInlined() &&
19428 !LangOpts.GNUInline &&
19429 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19430 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19431 else if (isExternalWithNoLinkageType(VD: Func))
19432 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19433 }
19434
19435 // Some x86 Windows calling conventions mangle the size of the parameter
19436 // pack into the name. Computing the size of the parameters requires the
19437 // parameter types to be complete. Check that now.
19438 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19439 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19440
19441 // In the MS C++ ABI, the compiler emits destructor variants where they are
19442 // used. If the destructor is used here but defined elsewhere, mark the
19443 // virtual base destructors referenced. If those virtual base destructors
19444 // are inline, this will ensure they are defined when emitting the complete
19445 // destructor variant. This checking may be redundant if the destructor is
19446 // provided later in this TU.
19447 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19448 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19449 CXXRecordDecl *Parent = Dtor->getParent();
19450 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19451 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19452 }
19453 }
19454
19455 Func->markUsed(C&: Context);
19456 }
19457}
19458
19459/// Directly mark a variable odr-used. Given a choice, prefer to use
19460/// MarkVariableReferenced since it does additional checks and then
19461/// calls MarkVarDeclODRUsed.
19462/// If the variable must be captured:
19463/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19464/// - else capture it in the DeclContext that maps to the
19465/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19466static void
19467MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19468 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19469 // Keep track of used but undefined variables.
19470 // FIXME: We shouldn't suppress this warning for static data members.
19471 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19472 assert(Var && "expected a capturable variable");
19473
19474 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19475 (!Var->isExternallyVisible() || Var->isInline() ||
19476 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19477 !(Var->isStaticDataMember() && Var->hasInit())) {
19478 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19479 if (old.isInvalid())
19480 old = Loc;
19481 }
19482 QualType CaptureType, DeclRefType;
19483 if (SemaRef.LangOpts.OpenMP)
19484 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19485 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19486 /*EllipsisLoc*/ SourceLocation(),
19487 /*BuildAndDiagnose*/ true, CaptureType,
19488 DeclRefType, FunctionScopeIndexToStopAt);
19489
19490 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19491 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19492 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19493 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19494 if (VarTarget == SemaCUDA::CVT_Host &&
19495 (UserTarget == CUDAFunctionTarget::Device ||
19496 UserTarget == CUDAFunctionTarget::HostDevice ||
19497 UserTarget == CUDAFunctionTarget::Global)) {
19498 // Diagnose ODR-use of host global variables in device functions.
19499 // Reference of device global variables in host functions is allowed
19500 // through shadow variables therefore it is not diagnosed.
19501 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19502 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19503 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19504 SemaRef.targetDiag(Loc: Var->getLocation(),
19505 DiagID: Var->getType().isConstQualified()
19506 ? diag::note_cuda_const_var_unpromoted
19507 : diag::note_cuda_host_var);
19508 }
19509 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19510 // Also capture __device__ const variables, which are classified
19511 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19512 // an explicit CUDADeviceAttr to distinguish them from plain
19513 // const variables (no __device__), which also get CVT_Both but
19514 // only have an implicit CUDADeviceAttr.
19515 (VarTarget == SemaCUDA::CVT_Both &&
19516 Var->hasAttr<CUDADeviceAttr>() &&
19517 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19518 !Var->hasAttr<CUDASharedAttr>() &&
19519 (UserTarget == CUDAFunctionTarget::Host ||
19520 UserTarget == CUDAFunctionTarget::HostDevice)) {
19521 // Record a CUDA/HIP device side variable if it is ODR-used
19522 // by host code. This is done conservatively, when the variable is
19523 // referenced in any of the following contexts:
19524 // - a non-function context
19525 // - a host function
19526 // - a host device function
19527 // This makes the ODR-use of the device side variable by host code to
19528 // be visible in the device compilation for the compiler to be able to
19529 // emit template variables instantiated by host code only and to
19530 // externalize the static device side variable ODR-used by host code.
19531 if (!Var->hasExternalStorage())
19532 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19533 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19534 (!FD || (!FD->getDescribedFunctionTemplate() &&
19535 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19536 GVA_StrongExternal)))
19537 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19538 }
19539 }
19540
19541 V->markUsed(C&: SemaRef.Context);
19542}
19543
19544void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19545 SourceLocation Loc,
19546 unsigned CapturingScopeIndex) {
19547 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19548}
19549
19550static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19551 SourceLocation loc,
19552 ValueDecl *var) {
19553 DeclContext *VarDC =
19554 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19555
19556 // If the parameter still belongs to the translation unit, then
19557 // we're actually just using one parameter in the declaration of
19558 // the next.
19559 if (isa<ParmVarDecl>(Val: var) &&
19560 isa<TranslationUnitDecl>(Val: VarDC))
19561 return;
19562
19563 // For C code, don't diagnose about capture if we're not actually in code
19564 // right now; it's impossible to write a non-constant expression outside of
19565 // function context, so we'll get other (more useful) diagnostics later.
19566 //
19567 // For C++, things get a bit more nasty... it would be nice to suppress this
19568 // diagnostic for certain cases like using a local variable in an array bound
19569 // for a member of a local class, but the correct predicate is not obvious.
19570 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19571 return;
19572
19573 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19574 unsigned ContextKind = 3; // unknown
19575 if (isa<CXXMethodDecl>(Val: VarDC) &&
19576 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19577 ContextKind = 2;
19578 } else if (isa<FunctionDecl>(Val: VarDC)) {
19579 ContextKind = 0;
19580 } else if (isa<BlockDecl>(Val: VarDC)) {
19581 ContextKind = 1;
19582 }
19583
19584 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19585 << var << ValueKind << ContextKind << VarDC;
19586 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19587 << var;
19588
19589 // FIXME: Add additional diagnostic info about class etc. which prevents
19590 // capture.
19591}
19592
19593static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19594 ValueDecl *Var,
19595 bool &SubCapturesAreNested,
19596 QualType &CaptureType,
19597 QualType &DeclRefType) {
19598 // Check whether we've already captured it.
19599 if (CSI->CaptureMap.count(Val: Var)) {
19600 // If we found a capture, any subcaptures are nested.
19601 SubCapturesAreNested = true;
19602
19603 // Retrieve the capture type for this variable.
19604 CaptureType = CSI->getCapture(Var).getCaptureType();
19605
19606 // Compute the type of an expression that refers to this variable.
19607 DeclRefType = CaptureType.getNonReferenceType();
19608
19609 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19610 // are mutable in the sense that user can change their value - they are
19611 // private instances of the captured declarations.
19612 const Capture &Cap = CSI->getCapture(Var);
19613 // C++ [expr.prim.lambda]p10:
19614 // The type of such a data member is [...] an lvalue reference to the
19615 // referenced function type if the entity is a reference to a function.
19616 // [...]
19617 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19618 !(isa<LambdaScopeInfo>(Val: CSI) &&
19619 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19620 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19621 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19622 DeclRefType.addConst();
19623 return true;
19624 }
19625 return false;
19626}
19627
19628// Only block literals, captured statements, and lambda expressions can
19629// capture; other scopes don't work.
19630static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19631 ValueDecl *Var,
19632 SourceLocation Loc,
19633 const bool Diagnose,
19634 Sema &S) {
19635 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19636 return getLambdaAwareParentOfDeclContext(DC);
19637
19638 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19639 if (Underlying) {
19640 if (Underlying->hasLocalStorage() && Diagnose)
19641 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19642 }
19643 return nullptr;
19644}
19645
19646// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19647// certain types of variables (unnamed, variably modified types etc.)
19648// so check for eligibility.
19649static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19650 SourceLocation Loc, const bool Diagnose,
19651 Sema &S) {
19652
19653 assert((isa<VarDecl, BindingDecl>(Var)) &&
19654 "Only variables and structured bindings can be captured");
19655
19656 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19657 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19658
19659 // Lambdas are not allowed to capture unnamed variables
19660 // (e.g. anonymous unions).
19661 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19662 // assuming that's the intent.
19663 if (IsLambda && !Var->getDeclName()) {
19664 if (Diagnose) {
19665 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19666 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19667 }
19668 return false;
19669 }
19670
19671 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19672 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19673 if (Diagnose) {
19674 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19675 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19676 }
19677 return false;
19678 }
19679 // Prohibit structs with flexible array members too.
19680 // We cannot capture what is in the tail end of the struct.
19681 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19682 VTD && VTD->hasFlexibleArrayMember()) {
19683 if (Diagnose) {
19684 if (IsBlock)
19685 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19686 else
19687 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19688 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19689 }
19690 return false;
19691 }
19692 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19693 // Lambdas and captured statements are not allowed to capture __block
19694 // variables; they don't support the expected semantics.
19695 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19696 if (Diagnose) {
19697 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19698 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19699 }
19700 return false;
19701 }
19702 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19703 if (S.getLangOpts().OpenCL && IsBlock &&
19704 Var->getType()->isBlockPointerType()) {
19705 if (Diagnose)
19706 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19707 return false;
19708 }
19709
19710 if (isa<BindingDecl>(Val: Var)) {
19711 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19712 if (Diagnose)
19713 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19714 return false;
19715 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19716 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19717 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19718 }
19719 }
19720
19721 return true;
19722}
19723
19724// Returns true if the capture by block was successful.
19725static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19726 SourceLocation Loc, const bool BuildAndDiagnose,
19727 QualType &CaptureType, QualType &DeclRefType,
19728 const bool Nested, Sema &S, bool Invalid) {
19729 bool ByRef = false;
19730
19731 // Blocks are not allowed to capture arrays, excepting OpenCL.
19732 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19733 // (decayed to pointers).
19734 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19735 if (BuildAndDiagnose) {
19736 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19737 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19738 Invalid = true;
19739 } else {
19740 return false;
19741 }
19742 }
19743
19744 // Forbid the block-capture of autoreleasing variables.
19745 if (!Invalid &&
19746 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19747 if (BuildAndDiagnose) {
19748 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19749 << /*block*/ 0;
19750 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19751 Invalid = true;
19752 } else {
19753 return false;
19754 }
19755 }
19756
19757 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19758 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19759 QualType PointeeTy = PT->getPointeeType();
19760
19761 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19762 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19763 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19764 if (BuildAndDiagnose) {
19765 SourceLocation VarLoc = Var->getLocation();
19766 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19767 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19768 }
19769 }
19770 }
19771
19772 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19773 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19774 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19775 // Block capture by reference does not change the capture or
19776 // declaration reference types.
19777 ByRef = true;
19778 } else {
19779 // Block capture by copy introduces 'const'.
19780 CaptureType = CaptureType.getNonReferenceType().withConst();
19781 DeclRefType = CaptureType;
19782 }
19783
19784 // Actually capture the variable.
19785 if (BuildAndDiagnose)
19786 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19787 CaptureType, Invalid);
19788
19789 return !Invalid;
19790}
19791
19792/// Capture the given variable in the captured region.
19793static bool captureInCapturedRegion(
19794 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19795 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19796 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19797 Sema &S, bool Invalid) {
19798 // By default, capture variables by reference.
19799 bool ByRef = true;
19800 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19801 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19802 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19803 // Using an LValue reference type is consistent with Lambdas (see below).
19804 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19805 bool HasConst = DeclRefType.isConstQualified();
19806 DeclRefType = DeclRefType.getUnqualifiedType();
19807 // Don't lose diagnostics about assignments to const.
19808 if (HasConst)
19809 DeclRefType.addConst();
19810 }
19811 // Do not capture firstprivates in tasks.
19812 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19813 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19814 return true;
19815 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19816 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19817 }
19818
19819 if (ByRef)
19820 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19821 else
19822 CaptureType = DeclRefType;
19823
19824 // Actually capture the variable.
19825 if (BuildAndDiagnose)
19826 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19827 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19828
19829 return !Invalid;
19830}
19831
19832/// Capture the given variable in the lambda.
19833static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19834 SourceLocation Loc, const bool BuildAndDiagnose,
19835 QualType &CaptureType, QualType &DeclRefType,
19836 const bool RefersToCapturedVariable,
19837 const TryCaptureKind Kind,
19838 SourceLocation EllipsisLoc, const bool IsTopScope,
19839 Sema &S, bool Invalid) {
19840 // Determine whether we are capturing by reference or by value.
19841 bool ByRef = false;
19842 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19843 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19844 } else {
19845 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19846 }
19847
19848 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19849 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19850 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19851 Invalid = true;
19852 }
19853
19854 // Compute the type of the field that will capture this variable.
19855 if (ByRef) {
19856 // C++11 [expr.prim.lambda]p15:
19857 // An entity is captured by reference if it is implicitly or
19858 // explicitly captured but not captured by copy. It is
19859 // unspecified whether additional unnamed non-static data
19860 // members are declared in the closure type for entities
19861 // captured by reference.
19862 //
19863 // FIXME: It is not clear whether we want to build an lvalue reference
19864 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19865 // to do the former, while EDG does the latter. Core issue 1249 will
19866 // clarify, but for now we follow GCC because it's a more permissive and
19867 // easily defensible position.
19868 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19869 } else {
19870 // C++11 [expr.prim.lambda]p14:
19871 // For each entity captured by copy, an unnamed non-static
19872 // data member is declared in the closure type. The
19873 // declaration order of these members is unspecified. The type
19874 // of such a data member is the type of the corresponding
19875 // captured entity if the entity is not a reference to an
19876 // object, or the referenced type otherwise. [Note: If the
19877 // captured entity is a reference to a function, the
19878 // corresponding data member is also a reference to a
19879 // function. - end note ]
19880 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19881 if (!RefType->getPointeeType()->isFunctionType())
19882 CaptureType = RefType->getPointeeType();
19883 }
19884
19885 // Forbid the lambda copy-capture of autoreleasing variables.
19886 if (!Invalid &&
19887 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19888 if (BuildAndDiagnose) {
19889 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19890 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19891 << Var->getDeclName();
19892 Invalid = true;
19893 } else {
19894 return false;
19895 }
19896 }
19897
19898 // Make sure that by-copy captures are of a complete and non-abstract type.
19899 if (!Invalid && BuildAndDiagnose) {
19900 if (!CaptureType->isDependentType() &&
19901 S.RequireCompleteSizedType(
19902 Loc, T: CaptureType,
19903 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19904 Args: Var->getDeclName()))
19905 Invalid = true;
19906 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19907 DiagID: diag::err_capture_of_abstract_type))
19908 Invalid = true;
19909 }
19910 }
19911
19912 // Compute the type of a reference to this captured variable.
19913 if (ByRef)
19914 DeclRefType = CaptureType.getNonReferenceType();
19915 else {
19916 // C++ [expr.prim.lambda]p5:
19917 // The closure type for a lambda-expression has a public inline
19918 // function call operator [...]. This function call operator is
19919 // declared const (9.3.1) if and only if the lambda-expression's
19920 // parameter-declaration-clause is not followed by mutable.
19921 DeclRefType = CaptureType.getNonReferenceType();
19922 bool Const = LSI->lambdaCaptureShouldBeConst();
19923 // C++ [expr.prim.lambda]p10:
19924 // The type of such a data member is [...] an lvalue reference to the
19925 // referenced function type if the entity is a reference to a function.
19926 // [...]
19927 if (Const && !CaptureType->isReferenceType() &&
19928 !DeclRefType->isFunctionType())
19929 DeclRefType.addConst();
19930 }
19931
19932 // Add the capture.
19933 if (BuildAndDiagnose)
19934 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19935 Loc, EllipsisLoc, CaptureType, Invalid);
19936
19937 return !Invalid;
19938}
19939
19940static bool canCaptureVariableByCopy(ValueDecl *Var,
19941 const ASTContext &Context) {
19942 // Offer a Copy fix even if the type is dependent.
19943 if (Var->getType()->isDependentType())
19944 return true;
19945 QualType T = Var->getType().getNonReferenceType();
19946 if (T.isTriviallyCopyableType(Context))
19947 return true;
19948 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19949
19950 if (!(RD = RD->getDefinition()))
19951 return false;
19952 if (RD->hasSimpleCopyConstructor())
19953 return true;
19954 if (RD->hasUserDeclaredCopyConstructor())
19955 for (CXXConstructorDecl *Ctor : RD->ctors())
19956 if (Ctor->isCopyConstructor())
19957 return !Ctor->isDeleted();
19958 }
19959 return false;
19960}
19961
19962/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19963/// default capture. Fixes may be omitted if they aren't allowed by the
19964/// standard, for example we can't emit a default copy capture fix-it if we
19965/// already explicitly copy capture capture another variable.
19966static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19967 ValueDecl *Var) {
19968 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19969 // Don't offer Capture by copy of default capture by copy fixes if Var is
19970 // known not to be copy constructible.
19971 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19972
19973 SmallString<32> FixBuffer;
19974 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19975 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19976 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19977 if (ShouldOfferCopyFix) {
19978 // Offer fixes to insert an explicit capture for the variable.
19979 // [] -> [VarName]
19980 // [OtherCapture] -> [OtherCapture, VarName]
19981 FixBuffer.assign(Refs: {Separator, Var->getName()});
19982 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19983 << Var << /*value*/ 0
19984 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19985 }
19986 // As above but capture by reference.
19987 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19988 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19989 << Var << /*reference*/ 1
19990 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19991 }
19992
19993 // Only try to offer default capture if there are no captures excluding this
19994 // and init captures.
19995 // [this]: OK.
19996 // [X = Y]: OK.
19997 // [&A, &B]: Don't offer.
19998 // [A, B]: Don't offer.
19999 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
20000 return !C.isThisCapture() && !C.isInitCapture();
20001 }))
20002 return;
20003
20004 // The default capture specifiers, '=' or '&', must appear first in the
20005 // capture body.
20006 SourceLocation DefaultInsertLoc =
20007 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
20008
20009 if (ShouldOfferCopyFix) {
20010 bool CanDefaultCopyCapture = true;
20011 // [=, *this] OK since c++17
20012 // [=, this] OK since c++20
20013 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20014 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20015 ? LSI->getCXXThisCapture().isCopyCapture()
20016 : false;
20017 // We can't use default capture by copy if any captures already specified
20018 // capture by copy.
20019 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20020 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20021 })) {
20022 FixBuffer.assign(Refs: {"=", Separator});
20023 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20024 << /*value*/ 0
20025 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20026 }
20027 }
20028
20029 // We can't use default capture by reference if any captures already specified
20030 // capture by reference.
20031 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20032 return !C.isInitCapture() && C.isReferenceCapture() &&
20033 !C.isThisCapture();
20034 })) {
20035 FixBuffer.assign(Refs: {"&", Separator});
20036 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20037 << /*reference*/ 1
20038 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20039 }
20040}
20041
20042bool Sema::tryCaptureVariable(
20043 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20044 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20045 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20046 // An init-capture is notionally from the context surrounding its
20047 // declaration, but its parent DC is the lambda class.
20048 DeclContext *VarDC =
20049 Var->getDeclContext()->getEnclosingNonExpansionStatementContext();
20050 DeclContext *DC = CurContext;
20051
20052 // Skip past RequiresExprBodys because they don't constitute function scopes.
20053 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20054 DC = DC->getParent();
20055
20056 // tryCaptureVariable is called every time a DeclRef is formed,
20057 // it can therefore have non-negigible impact on performances.
20058 // For local variables and when there is no capturing scope,
20059 // we can bailout early.
20060 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20061 return true;
20062
20063 // Exception: Function parameters are not tied to the function's DeclContext
20064 // until we enter the function definition. Capturing them anyway would result
20065 // in an out-of-bounds error while traversing DC and its parents.
20066 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
20067 return true;
20068
20069 const auto *VD = dyn_cast<VarDecl>(Val: Var);
20070 if (VD) {
20071 if (VD->isInitCapture())
20072 VarDC = VarDC->getParent();
20073 } else {
20074 VD = Var->getPotentiallyDecomposedVarDecl();
20075 }
20076 assert(VD && "Cannot capture a null variable");
20077
20078 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20079 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20080 // We need to sync up the Declaration Context with the
20081 // FunctionScopeIndexToStopAt
20082 if (FunctionScopeIndexToStopAt) {
20083 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20084 unsigned FSIndex = FunctionScopes.size() - 1;
20085 // When we're parsing the lambda parameter list, the current DeclContext is
20086 // NOT the lambda but its parent. So move away the current LSI before
20087 // aligning DC and FunctionScopeIndexToStopAt.
20088 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
20089 FSIndex && LSI && !LSI->AfterParameterList)
20090 --FSIndex;
20091 assert(MaxFunctionScopesIndex <= FSIndex &&
20092 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20093 "FunctionScopes.");
20094 while (FSIndex != MaxFunctionScopesIndex) {
20095 DC = getLambdaAwareParentOfDeclContext(DC);
20096 --FSIndex;
20097 }
20098 }
20099
20100 // Capture global variables if it is required to use private copy of this
20101 // variable.
20102 bool IsGlobal = !VD->hasLocalStorage();
20103 if (IsGlobal && !(LangOpts.OpenMP &&
20104 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
20105 StopAt: MaxFunctionScopesIndex)))
20106 return true;
20107
20108 if (isa<VarDecl>(Val: Var))
20109 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
20110
20111 // Walk up the stack to determine whether we can capture the variable,
20112 // performing the "simple" checks that don't depend on type. We stop when
20113 // we've either hit the declared scope of the variable or find an existing
20114 // capture of that variable. We start from the innermost capturing-entity
20115 // (the DC) and ensure that all intervening capturing-entities
20116 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20117 // declcontext can either capture the variable or have already captured
20118 // the variable.
20119 CaptureType = Var->getType();
20120 DeclRefType = CaptureType.getNonReferenceType();
20121 bool Nested = false;
20122 bool Explicit = (Kind != TryCaptureKind::Implicit);
20123 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20124 do {
20125
20126 LambdaScopeInfo *LSI = nullptr;
20127 if (!FunctionScopes.empty())
20128 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20129 Val: FunctionScopes[FunctionScopesIndex]);
20130
20131 bool IsInScopeDeclarationContext =
20132 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20133
20134 if (LSI && !LSI->AfterParameterList) {
20135 // This allows capturing parameters from a default value which does not
20136 // seems correct
20137 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
20138 return true;
20139 }
20140 // If the variable is declared in the current context, there is no need to
20141 // capture it.
20142 if (IsInScopeDeclarationContext &&
20143 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20144 return true;
20145
20146 // Only block literals, captured statements, and lambda expressions can
20147 // capture; other scopes don't work.
20148 DeclContext *ParentDC =
20149 !IsInScopeDeclarationContext
20150 ? DC->getParent()
20151 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
20152 Diagnose: BuildAndDiagnose, S&: *this);
20153 // We need to check for the parent *first* because, if we *have*
20154 // private-captured a global variable, we need to recursively capture it in
20155 // intermediate blocks, lambdas, etc.
20156 if (!ParentDC) {
20157 if (IsGlobal) {
20158 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20159 break;
20160 }
20161 return true;
20162 }
20163
20164 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20165 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
20166
20167 // Check whether we've already captured it.
20168 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
20169 DeclRefType)) {
20170 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
20171 break;
20172 }
20173
20174 // When evaluating some attributes (like enable_if) we might refer to a
20175 // function parameter appertaining to the same declaration as that
20176 // attribute.
20177 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
20178 Parm && Parm->getDeclContext() == DC)
20179 return true;
20180
20181 // If we are instantiating a generic lambda call operator body,
20182 // we do not want to capture new variables. What was captured
20183 // during either a lambdas transformation or initial parsing
20184 // should be used.
20185 if (isGenericLambdaCallOperatorSpecialization(DC)) {
20186 if (BuildAndDiagnose) {
20187 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20188 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
20189 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20190 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20191 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20192 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20193 } else
20194 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
20195 }
20196 return true;
20197 }
20198
20199 // Try to capture variable-length arrays types.
20200 if (Var->getType()->isVariablyModifiedType()) {
20201 // We're going to walk down into the type and look for VLA
20202 // expressions.
20203 QualType QTy = Var->getType();
20204 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20205 QTy = PVD->getOriginalType();
20206 captureVariablyModifiedType(Context, T: QTy, CSI);
20207 }
20208
20209 if (getLangOpts().OpenMP) {
20210 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20211 // OpenMP private variables should not be captured in outer scope, so
20212 // just break here. Similarly, global variables that are captured in a
20213 // target region should not be captured outside the scope of the region.
20214 if (RSI->CapRegionKind == CR_OpenMP) {
20215 // FIXME: We should support capturing structured bindings in OpenMP.
20216 if (isa<BindingDecl>(Val: Var)) {
20217 if (BuildAndDiagnose) {
20218 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
20219 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
20220 }
20221 return true;
20222 }
20223 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20224 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
20225 // If the variable is private (i.e. not captured) and has variably
20226 // modified type, we still need to capture the type for correct
20227 // codegen in all regions, associated with the construct. Currently,
20228 // it is captured in the innermost captured region only.
20229 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20230 Var->getType()->isVariablyModifiedType()) {
20231 QualType QTy = Var->getType();
20232 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20233 QTy = PVD->getOriginalType();
20234 for (int I = 1,
20235 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
20236 I < E; ++I) {
20237 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20238 Val: FunctionScopes[FunctionScopesIndex - I]);
20239 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20240 "Wrong number of captured regions associated with the "
20241 "OpenMP construct.");
20242 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
20243 }
20244 }
20245 bool IsTargetCap =
20246 IsOpenMPPrivateDecl != OMPC_private &&
20247 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
20248 CaptureLevel: RSI->OpenMPCaptureLevel);
20249 // Do not capture global if it is not privatized in outer regions.
20250 bool IsGlobalCap =
20251 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20252 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
20253
20254 // When we detect target captures we are looking from inside the
20255 // target region, therefore we need to propagate the capture from the
20256 // enclosing region. Therefore, the capture is not initially nested.
20257 if (IsTargetCap)
20258 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20259 Level: RSI->OpenMPLevel);
20260
20261 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20262 (IsGlobal && !IsGlobalCap)) {
20263 Nested = !IsTargetCap;
20264 bool HasConst = DeclRefType.isConstQualified();
20265 DeclRefType = DeclRefType.getUnqualifiedType();
20266 // Don't lose diagnostics about assignments to const.
20267 if (HasConst)
20268 DeclRefType.addConst();
20269 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20270 break;
20271 }
20272 }
20273 }
20274 }
20275 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20276 // No capture-default, and this is not an explicit capture
20277 // so cannot capture this variable.
20278 if (BuildAndDiagnose) {
20279 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20280 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20281 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20282 if (LSI->Lambda) {
20283 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20284 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20285 }
20286 // FIXME: If we error out because an outer lambda can not implicitly
20287 // capture a variable that an inner lambda explicitly captures, we
20288 // should have the inner lambda do the explicit capture - because
20289 // it makes for cleaner diagnostics later. This would purely be done
20290 // so that the diagnostic does not misleadingly claim that a variable
20291 // can not be captured by a lambda implicitly even though it is captured
20292 // explicitly. Suggestion:
20293 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20294 // at the function head
20295 // - cache the StartingDeclContext - this must be a lambda
20296 // - captureInLambda in the innermost lambda the variable.
20297 }
20298 return true;
20299 }
20300 Explicit = false;
20301 FunctionScopesIndex--;
20302 if (IsInScopeDeclarationContext)
20303 DC = ParentDC;
20304 } while (!VarDC->Equals(DC));
20305
20306 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20307 // computing the type of the capture at each step, checking type-specific
20308 // requirements, and adding captures if requested.
20309 // If the variable had already been captured previously, we start capturing
20310 // at the lambda nested within that one.
20311 bool Invalid = false;
20312 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20313 ++I) {
20314 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20315
20316 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20317 // certain types of variables (unnamed, variably modified types etc.)
20318 // so check for eligibility.
20319 if (!Invalid)
20320 Invalid =
20321 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20322
20323 // After encountering an error, if we're actually supposed to capture, keep
20324 // capturing in nested contexts to suppress any follow-on diagnostics.
20325 if (Invalid && !BuildAndDiagnose)
20326 return true;
20327
20328 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20329 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20330 DeclRefType, Nested, S&: *this, Invalid);
20331 Nested = true;
20332 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20333 Invalid = !captureInCapturedRegion(
20334 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20335 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20336 Nested = true;
20337 } else {
20338 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20339 Invalid =
20340 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20341 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20342 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20343 Nested = true;
20344 }
20345
20346 if (Invalid && !BuildAndDiagnose)
20347 return true;
20348 }
20349 return Invalid;
20350}
20351
20352bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20353 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20354 QualType CaptureType;
20355 QualType DeclRefType;
20356 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20357 /*BuildAndDiagnose=*/true, CaptureType,
20358 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20359}
20360
20361bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20362 QualType CaptureType;
20363 QualType DeclRefType;
20364 return !tryCaptureVariable(
20365 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20366 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20367}
20368
20369QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20370 assert(Var && "Null value cannot be captured");
20371
20372 QualType CaptureType;
20373 QualType DeclRefType;
20374
20375 // Determine whether we can capture this variable.
20376 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20377 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20378 FunctionScopeIndexToStopAt: nullptr))
20379 return QualType();
20380
20381 return DeclRefType;
20382}
20383
20384namespace {
20385// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20386// The produced TemplateArgumentListInfo* points to data stored within this
20387// object, so should only be used in contexts where the pointer will not be
20388// used after the CopiedTemplateArgs object is destroyed.
20389class CopiedTemplateArgs {
20390 bool HasArgs;
20391 TemplateArgumentListInfo TemplateArgStorage;
20392public:
20393 template<typename RefExpr>
20394 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20395 if (HasArgs)
20396 E->copyTemplateArgumentsInto(TemplateArgStorage);
20397 }
20398 operator TemplateArgumentListInfo*()
20399#ifdef __has_cpp_attribute
20400#if __has_cpp_attribute(clang::lifetimebound)
20401 [[clang::lifetimebound]]
20402#endif
20403#endif
20404 {
20405 return HasArgs ? &TemplateArgStorage : nullptr;
20406 }
20407};
20408}
20409
20410/// Walk the set of potential results of an expression and mark them all as
20411/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20412///
20413/// \return A new expression if we found any potential results, ExprEmpty() if
20414/// not, and ExprError() if we diagnosed an error.
20415static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20416 NonOdrUseReason NOUR) {
20417 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20418 // an object that satisfies the requirements for appearing in a
20419 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20420 // is immediately applied." This function handles the lvalue-to-rvalue
20421 // conversion part.
20422 //
20423 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20424 // transform it into the relevant kind of non-odr-use node and rebuild the
20425 // tree of nodes leading to it.
20426 //
20427 // This is a mini-TreeTransform that only transforms a restricted subset of
20428 // nodes (and only certain operands of them).
20429
20430 // Rebuild a subexpression.
20431 auto Rebuild = [&](Expr *Sub) {
20432 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20433 };
20434
20435 // Check whether a potential result satisfies the requirements of NOUR.
20436 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20437 // Any entity other than a VarDecl is always odr-used whenever it's named
20438 // in a potentially-evaluated expression.
20439 auto *VD = dyn_cast<VarDecl>(Val: D);
20440 if (!VD)
20441 return true;
20442
20443 // C++2a [basic.def.odr]p4:
20444 // A variable x whose name appears as a potentially-evalauted expression
20445 // e is odr-used by e unless
20446 // -- x is a reference that is usable in constant expressions, or
20447 // -- x is a variable of non-reference type that is usable in constant
20448 // expressions and has no mutable subobjects, and e is an element of
20449 // the set of potential results of an expression of
20450 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20451 // conversion is applied, or
20452 // -- x is a variable of non-reference type, and e is an element of the
20453 // set of potential results of a discarded-value expression to which
20454 // the lvalue-to-rvalue conversion is not applied
20455 //
20456 // We check the first bullet and the "potentially-evaluated" condition in
20457 // BuildDeclRefExpr. We check the type requirements in the second bullet
20458 // in CheckLValueToRValueConversionOperand below.
20459 switch (NOUR) {
20460 case NOUR_None:
20461 case NOUR_Unevaluated:
20462 llvm_unreachable("unexpected non-odr-use-reason");
20463
20464 case NOUR_Constant:
20465 // Constant references were handled when they were built.
20466 if (VD->getType()->isReferenceType())
20467 return true;
20468 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20469 if (RD->hasDefinition() && RD->hasMutableFields())
20470 return true;
20471 if (!VD->isUsableInConstantExpressions(C: S.Context))
20472 return true;
20473 break;
20474
20475 case NOUR_Discarded:
20476 if (VD->getType()->isReferenceType())
20477 return true;
20478 break;
20479 }
20480 return false;
20481 };
20482
20483 // Check whether this expression may be odr-used in CUDA/HIP.
20484 auto MaybeCUDAODRUsed = [&]() -> bool {
20485 if (!S.LangOpts.CUDA)
20486 return false;
20487 LambdaScopeInfo *LSI = S.getCurLambda();
20488 if (!LSI)
20489 return false;
20490 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20491 if (!DRE)
20492 return false;
20493 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20494 if (!VD)
20495 return false;
20496 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20497 };
20498
20499 // Mark that this expression does not constitute an odr-use.
20500 auto MarkNotOdrUsed = [&] {
20501 if (!MaybeCUDAODRUsed()) {
20502 S.MaybeODRUseExprs.remove(X: E);
20503 if (LambdaScopeInfo *LSI = S.getCurLambda())
20504 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20505 }
20506 };
20507
20508 // C++2a [basic.def.odr]p2:
20509 // The set of potential results of an expression e is defined as follows:
20510 switch (E->getStmtClass()) {
20511 // -- If e is an id-expression, ...
20512 case Expr::DeclRefExprClass: {
20513 auto *DRE = cast<DeclRefExpr>(Val: E);
20514 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20515 break;
20516
20517 // Rebuild as a non-odr-use DeclRefExpr.
20518 MarkNotOdrUsed();
20519 return DeclRefExpr::Create(
20520 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20521 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20522 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20523 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20524 }
20525
20526 case Expr::FunctionParmPackExprClass: {
20527 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20528 // If any of the declarations in the pack is odr-used, then the expression
20529 // as a whole constitutes an odr-use.
20530 for (ValueDecl *D : *FPPE)
20531 if (IsPotentialResultOdrUsed(D))
20532 return ExprEmpty();
20533
20534 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20535 // nothing cares about whether we marked this as an odr-use, but it might
20536 // be useful for non-compiler tools.
20537 MarkNotOdrUsed();
20538 break;
20539 }
20540
20541 // -- If e is a subscripting operation with an array operand...
20542 case Expr::ArraySubscriptExprClass: {
20543 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20544 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20545 if (!OldBase->getType()->isArrayType())
20546 break;
20547 ExprResult Base = Rebuild(OldBase);
20548 if (!Base.isUsable())
20549 return Base;
20550 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20551 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20552 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20553 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20554 rbLoc: ASE->getRBracketLoc());
20555 }
20556
20557 case Expr::MemberExprClass: {
20558 auto *ME = cast<MemberExpr>(Val: E);
20559 // -- If e is a class member access expression [...] naming a non-static
20560 // data member...
20561 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20562 ExprResult Base = Rebuild(ME->getBase());
20563 if (!Base.isUsable())
20564 return Base;
20565 return MemberExpr::Create(
20566 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20567 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20568 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20569 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20570 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20571 }
20572
20573 if (ME->getMemberDecl()->isCXXInstanceMember())
20574 break;
20575
20576 // -- If e is a class member access expression naming a static data member,
20577 // ...
20578 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20579 break;
20580
20581 // Rebuild as a non-odr-use MemberExpr.
20582 MarkNotOdrUsed();
20583 return MemberExpr::Create(
20584 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20585 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20586 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20587 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20588 }
20589
20590 case Expr::BinaryOperatorClass: {
20591 auto *BO = cast<BinaryOperator>(Val: E);
20592 Expr *LHS = BO->getLHS();
20593 Expr *RHS = BO->getRHS();
20594 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20595 if (BO->getOpcode() == BO_PtrMemD) {
20596 ExprResult Sub = Rebuild(LHS);
20597 if (!Sub.isUsable())
20598 return Sub;
20599 BO->setLHS(Sub.get());
20600 // -- If e is a comma expression, ...
20601 } else if (BO->getOpcode() == BO_Comma) {
20602 ExprResult Sub = Rebuild(RHS);
20603 if (!Sub.isUsable())
20604 return Sub;
20605 BO->setRHS(Sub.get());
20606 } else {
20607 break;
20608 }
20609 return ExprResult(BO);
20610 }
20611
20612 // -- If e has the form (e1)...
20613 case Expr::ParenExprClass: {
20614 auto *PE = cast<ParenExpr>(Val: E);
20615 ExprResult Sub = Rebuild(PE->getSubExpr());
20616 if (!Sub.isUsable())
20617 return Sub;
20618 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20619 }
20620
20621 // -- If e is a glvalue conditional expression, ...
20622 // We don't apply this to a binary conditional operator. FIXME: Should we?
20623 case Expr::ConditionalOperatorClass: {
20624 auto *CO = cast<ConditionalOperator>(Val: E);
20625 ExprResult LHS = Rebuild(CO->getLHS());
20626 if (LHS.isInvalid())
20627 return ExprError();
20628 ExprResult RHS = Rebuild(CO->getRHS());
20629 if (RHS.isInvalid())
20630 return ExprError();
20631 if (!LHS.isUsable() && !RHS.isUsable())
20632 return ExprEmpty();
20633 if (!LHS.isUsable())
20634 LHS = CO->getLHS();
20635 if (!RHS.isUsable())
20636 RHS = CO->getRHS();
20637 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20638 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20639 }
20640
20641 // [Clang extension]
20642 // -- If e has the form __extension__ e1...
20643 case Expr::UnaryOperatorClass: {
20644 auto *UO = cast<UnaryOperator>(Val: E);
20645 if (UO->getOpcode() != UO_Extension)
20646 break;
20647 ExprResult Sub = Rebuild(UO->getSubExpr());
20648 if (!Sub.isUsable())
20649 return Sub;
20650 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20651 Input: Sub.get());
20652 }
20653
20654 // [Clang extension]
20655 // -- If e has the form _Generic(...), the set of potential results is the
20656 // union of the sets of potential results of the associated expressions.
20657 case Expr::GenericSelectionExprClass: {
20658 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20659
20660 SmallVector<Expr *, 4> AssocExprs;
20661 bool AnyChanged = false;
20662 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20663 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20664 if (AssocExpr.isInvalid())
20665 return ExprError();
20666 if (AssocExpr.isUsable()) {
20667 AssocExprs.push_back(Elt: AssocExpr.get());
20668 AnyChanged = true;
20669 } else {
20670 AssocExprs.push_back(Elt: OrigAssocExpr);
20671 }
20672 }
20673
20674 void *ExOrTy = nullptr;
20675 bool IsExpr = GSE->isExprPredicate();
20676 if (IsExpr)
20677 ExOrTy = GSE->getControllingExpr();
20678 else
20679 ExOrTy = GSE->getControllingType();
20680 return AnyChanged ? S.CreateGenericSelectionExpr(
20681 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20682 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20683 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20684 : ExprEmpty();
20685 }
20686
20687 // [Clang extension]
20688 // -- If e has the form __builtin_choose_expr(...), the set of potential
20689 // results is the union of the sets of potential results of the
20690 // second and third subexpressions.
20691 case Expr::ChooseExprClass: {
20692 auto *CE = cast<ChooseExpr>(Val: E);
20693
20694 ExprResult LHS = Rebuild(CE->getLHS());
20695 if (LHS.isInvalid())
20696 return ExprError();
20697
20698 ExprResult RHS = Rebuild(CE->getLHS());
20699 if (RHS.isInvalid())
20700 return ExprError();
20701
20702 if (!LHS.get() && !RHS.get())
20703 return ExprEmpty();
20704 if (!LHS.isUsable())
20705 LHS = CE->getLHS();
20706 if (!RHS.isUsable())
20707 RHS = CE->getRHS();
20708
20709 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20710 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20711 }
20712
20713 // Step through non-syntactic nodes.
20714 case Expr::ConstantExprClass: {
20715 auto *CE = cast<ConstantExpr>(Val: E);
20716 ExprResult Sub = Rebuild(CE->getSubExpr());
20717 if (!Sub.isUsable())
20718 return Sub;
20719 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20720 }
20721
20722 // We could mostly rely on the recursive rebuilding to rebuild implicit
20723 // casts, but not at the top level, so rebuild them here.
20724 case Expr::ImplicitCastExprClass: {
20725 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20726 // Only step through the narrow set of cast kinds we expect to encounter.
20727 // Anything else suggests we've left the region in which potential results
20728 // can be found.
20729 switch (ICE->getCastKind()) {
20730 case CK_NoOp:
20731 case CK_DerivedToBase:
20732 case CK_UncheckedDerivedToBase: {
20733 ExprResult Sub = Rebuild(ICE->getSubExpr());
20734 if (!Sub.isUsable())
20735 return Sub;
20736 CXXCastPath Path(ICE->path());
20737 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20738 VK: ICE->getValueKind(), BasePath: &Path);
20739 }
20740
20741 default:
20742 break;
20743 }
20744 break;
20745 }
20746
20747 default:
20748 break;
20749 }
20750
20751 // Can't traverse through this node. Nothing to do.
20752 return ExprEmpty();
20753}
20754
20755ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20756 // Check whether the operand is or contains an object of non-trivial C union
20757 // type.
20758 if (E->getType().isVolatileQualified() &&
20759 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20760 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20761 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20762 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20763 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20764
20765 // C++2a [basic.def.odr]p4:
20766 // [...] an expression of non-volatile-qualified non-class type to which
20767 // the lvalue-to-rvalue conversion is applied [...]
20768 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20769 return E;
20770
20771 ExprResult Result =
20772 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20773 if (Result.isInvalid())
20774 return ExprError();
20775 return Result.get() ? Result : E;
20776}
20777
20778ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20779 if (!Res.isUsable())
20780 return Res;
20781
20782 // If a constant-expression is a reference to a variable where we delay
20783 // deciding whether it is an odr-use, just assume we will apply the
20784 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20785 // (a non-type template argument), we have special handling anyway.
20786 return CheckLValueToRValueConversionOperand(E: Res.get());
20787}
20788
20789void Sema::CleanupVarDeclMarking() {
20790 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20791 // call.
20792 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20793 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20794
20795 for (Expr *E : LocalMaybeODRUseExprs) {
20796 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20797 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20798 Loc: DRE->getLocation(), SemaRef&: *this);
20799 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20800 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20801 SemaRef&: *this);
20802 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20803 for (ValueDecl *VD : *FP)
20804 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20805 } else {
20806 llvm_unreachable("Unexpected expression");
20807 }
20808 }
20809
20810 assert(MaybeODRUseExprs.empty() &&
20811 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20812}
20813
20814static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20815 ValueDecl *Var, Expr *E) {
20816 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20817 if (!VD)
20818 return;
20819
20820 const bool RefersToEnclosingScope =
20821 (SemaRef.CurContext != VD->getDeclContext() &&
20822 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20823 if (RefersToEnclosingScope) {
20824 LambdaScopeInfo *const LSI =
20825 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20826 if (LSI && (!LSI->CallOperator ||
20827 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20828 // If a variable could potentially be odr-used, defer marking it so
20829 // until we finish analyzing the full expression for any
20830 // lvalue-to-rvalue
20831 // or discarded value conversions that would obviate odr-use.
20832 // Add it to the list of potential captures that will be analyzed
20833 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20834 // unless the variable is a reference that was initialized by a constant
20835 // expression (this will never need to be captured or odr-used).
20836 //
20837 // FIXME: We can simplify this a lot after implementing P0588R1.
20838 assert(E && "Capture variable should be used in an expression.");
20839 if (!Var->getType()->isReferenceType() ||
20840 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20841 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20842 }
20843 }
20844}
20845
20846static void DoMarkVarDeclReferenced(
20847 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20848 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20849 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20850 isa<FunctionParmPackExpr>(E)) &&
20851 "Invalid Expr argument to DoMarkVarDeclReferenced");
20852 Var->setReferenced();
20853
20854 if (Var->isInvalidDecl())
20855 return;
20856
20857 auto *MSI = Var->getMemberSpecializationInfo();
20858 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20859 : Var->getTemplateSpecializationKind();
20860
20861 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20862 bool UsableInConstantExpr =
20863 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20864
20865 // Only track variables with internal linkage or local scope.
20866 // Use canonical decl so in-class declarations and out-of-class definitions
20867 // of static data members in anonymous namespaces are tracked as a single
20868 // entry.
20869 const VarDecl *CanonVar = Var->getCanonicalDecl();
20870 if ((CanonVar->isLocalVarDeclOrParm() ||
20871 CanonVar->isInternalLinkageFileVar()) &&
20872 !CanonVar->hasExternalStorage()) {
20873 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20874 }
20875
20876 // C++20 [expr.const]p12:
20877 // A variable [...] is needed for constant evaluation if it is [...] a
20878 // variable whose name appears as a potentially constant evaluated
20879 // expression that is either a contexpr variable or is of non-volatile
20880 // const-qualified integral type or of reference type
20881 bool NeededForConstantEvaluation =
20882 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20883
20884 bool NeedDefinition =
20885 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20886 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20887 Var->getType()->isUndeducedType());
20888
20889 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20890 "Can't instantiate a partial template specialization.");
20891
20892 // If this might be a member specialization of a static data member, check
20893 // the specialization is visible. We already did the checks for variable
20894 // template specializations when we created them.
20895 if (NeedDefinition && TSK != TSK_Undeclared &&
20896 !isa<VarTemplateSpecializationDecl>(Val: Var))
20897 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20898
20899 // Perform implicit instantiation of static data members, static data member
20900 // templates of class templates, and variable template specializations. Delay
20901 // instantiations of variable templates, except for those that could be used
20902 // in a constant expression.
20903 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20904 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20905 // instantiation declaration if a variable is usable in a constant
20906 // expression (among other cases).
20907 bool TryInstantiating =
20908 TSK == TSK_ImplicitInstantiation ||
20909 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20910
20911 if (TryInstantiating) {
20912 SourceLocation PointOfInstantiation =
20913 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20914 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20915 if (FirstInstantiation) {
20916 PointOfInstantiation = Loc;
20917 if (MSI)
20918 MSI->setPointOfInstantiation(PointOfInstantiation);
20919 // FIXME: Notify listener.
20920 else
20921 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20922 }
20923
20924 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20925 // Do not defer instantiations of variables that could be used in a
20926 // constant expression.
20927 // The type deduction also needs a complete initializer.
20928 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20929 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20930 });
20931
20932 // The size of an incomplete array type can be updated by
20933 // instantiating the initializer. The DeclRefExpr's type should be
20934 // updated accordingly too, or users of it would be confused!
20935 if (E)
20936 SemaRef.getCompletedType(E);
20937
20938 // Re-set the member to trigger a recomputation of the dependence bits
20939 // for the expression.
20940 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20941 DRE->setDecl(DRE->getDecl());
20942 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20943 ME->setMemberDecl(ME->getMemberDecl());
20944 } else if (FirstInstantiation) {
20945 SemaRef.PendingInstantiations
20946 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20947 } else {
20948 bool Inserted = false;
20949 for (auto &I : SemaRef.SavedPendingInstantiations) {
20950 auto Iter = llvm::find_if(
20951 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20952 return P.first == Var;
20953 });
20954 if (Iter != I.end()) {
20955 SemaRef.PendingInstantiations.push_back(x: *Iter);
20956 I.erase(position: Iter);
20957 Inserted = true;
20958 break;
20959 }
20960 }
20961
20962 // FIXME: For a specialization of a variable template, we don't
20963 // distinguish between "declaration and type implicitly instantiated"
20964 // and "implicit instantiation of definition requested", so we have
20965 // no direct way to avoid enqueueing the pending instantiation
20966 // multiple times.
20967 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20968 SemaRef.PendingInstantiations
20969 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20970 }
20971 }
20972 }
20973
20974 // C++2a [basic.def.odr]p4:
20975 // A variable x whose name appears as a potentially-evaluated expression e
20976 // is odr-used by e unless
20977 // -- x is a reference that is usable in constant expressions
20978 // -- x is a variable of non-reference type that is usable in constant
20979 // expressions and has no mutable subobjects [FIXME], and e is an
20980 // element of the set of potential results of an expression of
20981 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20982 // conversion is applied
20983 // -- x is a variable of non-reference type, and e is an element of the set
20984 // of potential results of a discarded-value expression to which the
20985 // lvalue-to-rvalue conversion is not applied [FIXME]
20986 //
20987 // We check the first part of the second bullet here, and
20988 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20989 // FIXME: To get the third bullet right, we need to delay this even for
20990 // variables that are not usable in constant expressions.
20991
20992 // If we already know this isn't an odr-use, there's nothing more to do.
20993 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20994 if (DRE->isNonOdrUse())
20995 return;
20996 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20997 if (ME->isNonOdrUse())
20998 return;
20999
21000 switch (OdrUse) {
21001 case OdrUseContext::None:
21002 // In some cases, a variable may not have been marked unevaluated, if it
21003 // appears in a defaukt initializer.
21004 assert((!E || isa<FunctionParmPackExpr>(E) ||
21005 SemaRef.isUnevaluatedContext()) &&
21006 "missing non-odr-use marking for unevaluated decl ref");
21007 break;
21008
21009 case OdrUseContext::FormallyOdrUsed:
21010 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21011 // behavior.
21012 break;
21013
21014 case OdrUseContext::Used:
21015 // If we might later find that this expression isn't actually an odr-use,
21016 // delay the marking.
21017 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
21018 SemaRef.MaybeODRUseExprs.insert(X: E);
21019 else
21020 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
21021 break;
21022
21023 case OdrUseContext::Dependent:
21024 // If this is a dependent context, we don't need to mark variables as
21025 // odr-used, but we may still need to track them for lambda capture.
21026 // FIXME: Do we also need to do this inside dependent typeid expressions
21027 // (which are modeled as unevaluated at this point)?
21028 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21029 break;
21030 }
21031}
21032
21033static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
21034 BindingDecl *BD, Expr *E) {
21035 BD->setReferenced();
21036
21037 if (BD->isInvalidDecl())
21038 return;
21039
21040 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21041 if (OdrUse == OdrUseContext::Used) {
21042 QualType CaptureType, DeclRefType;
21043 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
21044 /*EllipsisLoc*/ SourceLocation(),
21045 /*BuildAndDiagnose*/ true, CaptureType,
21046 DeclRefType,
21047 /*FunctionScopeIndexToStopAt*/ nullptr);
21048 } else if (OdrUse == OdrUseContext::Dependent) {
21049 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
21050 }
21051}
21052
21053void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
21054 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
21055}
21056
21057// C++ [temp.dep.expr]p3:
21058// An id-expression is type-dependent if it contains:
21059// - an identifier associated by name lookup with an entity captured by copy
21060// in a lambda-expression that has an explicit object parameter whose type
21061// is dependent ([dcl.fct]),
21062static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
21063 Sema &SemaRef, ValueDecl *D, Expr *E) {
21064 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
21065 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21066 return;
21067
21068 // If any enclosing lambda with a dependent explicit object parameter either
21069 // explicitly captures the variable by value, or has a capture default of '='
21070 // and does not capture the variable by reference, then the type of the DRE
21071 // is dependent on the type of that lambda's explicit object parameter.
21072 auto IsDependent = [&]() {
21073 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
21074 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
21075 if (!LSI)
21076 continue;
21077
21078 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
21079 LSI->AfterParameterList)
21080 return false;
21081
21082 const auto *MD = LSI->CallOperator;
21083 if (MD->getType().isNull())
21084 continue;
21085
21086 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21087 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21088 !Ty->getParamType(i: 0)->isDependentType())
21089 continue;
21090
21091 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
21092 if (C->isCopyCapture())
21093 return true;
21094 continue;
21095 }
21096
21097 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21098 return true;
21099 }
21100 return false;
21101 }();
21102
21103 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21104 Set: IsDependent, Context: SemaRef.getASTContext());
21105}
21106
21107static void
21108MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
21109 bool MightBeOdrUse,
21110 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21111 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
21112 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
21113
21114 if (SemaRef.getLangOpts().OpenACC)
21115 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21116
21117 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
21118 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
21119 if (SemaRef.getLangOpts().CPlusPlus)
21120 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21121 D: Var, E);
21122 return;
21123 }
21124
21125 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
21126 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
21127 if (SemaRef.getLangOpts().CPlusPlus)
21128 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21129 D: Decl, E);
21130 return;
21131 }
21132 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21133
21134 // If this is a call to a method via a cast, also mark the method in the
21135 // derived class used in case codegen can devirtualize the call.
21136 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
21137 if (!ME)
21138 return;
21139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
21140 if (!MD)
21141 return;
21142 // Only attempt to devirtualize if this is truly a virtual call.
21143 bool IsVirtualCall = MD->isVirtual() &&
21144 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
21145 if (!IsVirtualCall)
21146 return;
21147
21148 // If it's possible to devirtualize the call, mark the called function
21149 // referenced.
21150 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
21151 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
21152 if (DM)
21153 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
21154}
21155
21156void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
21157 // [basic.def.odr] (CWG 1614)
21158 // A function is named by an expression or conversion [...]
21159 // unless it is a pure virtual function and either the expression is not an
21160 // id-expression naming the function with an explicitly qualified name or
21161 // the expression forms a pointer to member
21162 bool OdrUse = true;
21163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
21164 if (Method->isVirtual() &&
21165 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
21166 OdrUse = false;
21167
21168 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
21169 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
21170 !isImmediateFunctionContext() &&
21171 !isCheckingDefaultArgumentOrInitializer() &&
21172 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21173 !FD->isDependentContext())
21174 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
21175 }
21176 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
21177 RefsMinusAssignments);
21178}
21179
21180void Sema::MarkMemberReferenced(MemberExpr *E) {
21181 // C++11 [basic.def.odr]p2:
21182 // A non-overloaded function whose name appears as a potentially-evaluated
21183 // expression or a member of a set of candidate functions, if selected by
21184 // overload resolution when referred to from a potentially-evaluated
21185 // expression, is odr-used, unless it is a pure virtual function and its
21186 // name is not explicitly qualified.
21187 bool MightBeOdrUse = true;
21188 if (E->performsVirtualDispatch(LO: getLangOpts())) {
21189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
21190 if (Method->isPureVirtual())
21191 MightBeOdrUse = false;
21192 }
21193 SourceLocation Loc =
21194 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21195 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
21196 RefsMinusAssignments);
21197}
21198
21199void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
21200 for (ValueDecl *VD : *E)
21201 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
21202 RefsMinusAssignments);
21203}
21204
21205/// Perform marking for a reference to an arbitrary declaration. It
21206/// marks the declaration referenced, and performs odr-use checking for
21207/// functions and variables. This method should not be used when building a
21208/// normal expression which refers to a variable.
21209void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
21210 bool MightBeOdrUse) {
21211 if (MightBeOdrUse) {
21212 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
21213 MarkVariableReferenced(Loc, Var: VD);
21214 return;
21215 }
21216 }
21217 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
21218 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
21219 return;
21220 }
21221 D->setReferenced();
21222}
21223
21224namespace {
21225 // Mark all of the declarations used by a type as referenced.
21226 // FIXME: Not fully implemented yet! We need to have a better understanding
21227 // of when we're entering a context we should not recurse into.
21228 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21229 // TreeTransforms rebuilding the type in a new context. Rather than
21230 // duplicating the TreeTransform logic, we should consider reusing it here.
21231 // Currently that causes problems when rebuilding LambdaExprs.
21232class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21233 Sema &S;
21234 SourceLocation Loc;
21235
21236public:
21237 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21238
21239 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21240};
21241}
21242
21243bool MarkReferencedDecls::TraverseTemplateArgument(
21244 const TemplateArgument &Arg) {
21245 {
21246 // A non-type template argument is a constant-evaluated context.
21247 EnterExpressionEvaluationContext Evaluated(
21248 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
21249 if (Arg.getKind() == TemplateArgument::Declaration) {
21250 if (Decl *D = Arg.getAsDecl())
21251 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
21252 } else if (Arg.getKind() == TemplateArgument::Expression) {
21253 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
21254 }
21255 }
21256
21257 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
21258}
21259
21260void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
21261 MarkReferencedDecls Marker(*this, Loc);
21262 Marker.TraverseType(T);
21263}
21264
21265namespace {
21266/// Helper class that marks all of the declarations referenced by
21267/// potentially-evaluated subexpressions as "referenced".
21268class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21269public:
21270 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21271 bool SkipLocalVariables;
21272 ArrayRef<const Expr *> StopAt;
21273
21274 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21275 ArrayRef<const Expr *> StopAt)
21276 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21277
21278 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21279 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21280 }
21281
21282 void Visit(Expr *E) {
21283 if (llvm::is_contained(Range&: StopAt, Element: E))
21284 return;
21285 Inherited::Visit(S: E);
21286 }
21287
21288 void VisitConstantExpr(ConstantExpr *E) {
21289 // Don't mark declarations within a ConstantExpression, as this expression
21290 // will be evaluated and folded to a value.
21291 }
21292
21293 void VisitDeclRefExpr(DeclRefExpr *E) {
21294 // If we were asked not to visit local variables, don't.
21295 if (SkipLocalVariables) {
21296 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21297 if (VD->hasLocalStorage())
21298 return;
21299 }
21300
21301 // FIXME: This can trigger the instantiation of the initializer of a
21302 // variable, which can cause the expression to become value-dependent
21303 // or error-dependent. Do we need to propagate the new dependence bits?
21304 S.MarkDeclRefReferenced(E);
21305 }
21306
21307 void VisitMemberExpr(MemberExpr *E) {
21308 S.MarkMemberReferenced(E);
21309 Visit(E: E->getBase());
21310 }
21311};
21312} // namespace
21313
21314void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21315 bool SkipLocalVariables,
21316 ArrayRef<const Expr*> StopAt) {
21317 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21318}
21319
21320/// Emit a diagnostic when statements are reachable.
21321bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21322 const PartialDiagnostic &PD) {
21323 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21324 // The initializer of a constexpr variable or of the first declaration of a
21325 // static data member is not syntactically a constant evaluated constant,
21326 // but nonetheless is always required to be a constant expression, so we
21327 // can skip diagnosing.
21328 if (Decl &&
21329 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21330 Decl->isFirstDecl() && !Decl->isInline())))
21331 return false;
21332
21333 if (Stmts.empty()) {
21334 Diag(Loc, PD);
21335 return true;
21336 }
21337
21338 if (getCurFunction()) {
21339 // This queue flushes after the function is analyzed, by which time an
21340 // ignore-all-warnings region live here is gone, so sample it now. A note
21341 // is not error-class either, so this also drops the notes that accompany a
21342 // skipped warning. They arrive on their own call, out of reach of the
21343 // engine's rule that drops a note whose warning was ignored.
21344 if (Diags.getIgnoreAllWarnings() &&
21345 Diags.getDiagnosticIDs()->isWarningOrExtension(DiagID: PD.getDiagID()))
21346 return false;
21347 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21348 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21349 return true;
21350 }
21351
21352 // For non-constexpr file-scope variables with reachability context (non-empty
21353 // Stmts), build a CFG for the initializer and check whether the context in
21354 // question is reachable.
21355 if (Decl && Decl->isFileVarDecl()) {
21356 AnalysisWarnings.registerVarDeclWarning(
21357 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21358 return true;
21359 }
21360
21361 Diag(Loc, PD);
21362 return true;
21363}
21364
21365/// Emit a diagnostic that describes an effect on the run-time behavior
21366/// of the program being compiled.
21367///
21368/// This routine emits the given diagnostic when the code currently being
21369/// type-checked is "potentially evaluated", meaning that there is a
21370/// possibility that the code will actually be executable. Code in sizeof()
21371/// expressions, code used only during overload resolution, etc., are not
21372/// potentially evaluated. This routine will suppress such diagnostics or,
21373/// in the absolutely nutty case of potentially potentially evaluated
21374/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21375/// later.
21376///
21377/// This routine should be used for all diagnostics that describe the run-time
21378/// behavior of a program, such as passing a non-POD value through an ellipsis.
21379/// Failure to do so will likely result in spurious diagnostics or failures
21380/// during overload resolution or within sizeof/alignof/typeof/typeid.
21381bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21382 const PartialDiagnostic &PD) {
21383
21384 if (ExprEvalContexts.back().isDiscardedStatementContext())
21385 return false;
21386
21387 switch (ExprEvalContexts.back().Context) {
21388 case ExpressionEvaluationContext::Unevaluated:
21389 case ExpressionEvaluationContext::UnevaluatedList:
21390 case ExpressionEvaluationContext::UnevaluatedAbstract:
21391 case ExpressionEvaluationContext::DiscardedStatement:
21392 // The argument will never be evaluated, so don't complain.
21393 break;
21394
21395 case ExpressionEvaluationContext::ConstantEvaluated:
21396 case ExpressionEvaluationContext::ImmediateFunctionContext:
21397 // Relevant diagnostics should be produced by constant evaluation.
21398 break;
21399
21400 case ExpressionEvaluationContext::PotentiallyEvaluated:
21401 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21402 return DiagIfReachable(Loc, Stmts, PD);
21403 }
21404
21405 return false;
21406}
21407
21408bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21409 const PartialDiagnostic &PD) {
21410 return DiagRuntimeBehavior(
21411 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21412 PD);
21413}
21414
21415bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21416 CallExpr *CE, FunctionDecl *FD) {
21417 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21418 return false;
21419
21420 // If we're inside a decltype's expression, don't check for a valid return
21421 // type or construct temporaries until we know whether this is the last call.
21422 if (ExprEvalContexts.back().ExprContext ==
21423 ExpressionEvaluationContextRecord::EK_Decltype) {
21424 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21425 return false;
21426 }
21427
21428 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21429 FunctionDecl *FD;
21430 CallExpr *CE;
21431
21432 public:
21433 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21434 : FD(FD), CE(CE) { }
21435
21436 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21437 if (!FD) {
21438 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21439 << T << CE->getSourceRange();
21440 return;
21441 }
21442
21443 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21444 << CE->getSourceRange() << FD << T;
21445 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21446 << FD->getDeclName();
21447 }
21448 } Diagnoser(FD, CE);
21449
21450 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21451 return true;
21452
21453 return false;
21454}
21455
21456// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21457// will prevent this condition from triggering, which is what we want.
21458void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21459 SourceLocation Loc;
21460
21461 unsigned diagnostic = diag::warn_condition_is_assignment;
21462 bool IsOrAssign = false;
21463
21464 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21465 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21466 return;
21467
21468 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21469
21470 // Greylist some idioms by putting them into a warning subcategory.
21471 if (ObjCMessageExpr *ME
21472 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21473 Selector Sel = ME->getSelector();
21474
21475 // self = [<foo> init...]
21476 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21477 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21478
21479 // <foo> = [<bar> nextObject]
21480 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21481 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21482 }
21483
21484 Loc = Op->getOperatorLoc();
21485 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21486 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21487 return;
21488
21489 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21490 Loc = Op->getOperatorLoc();
21491 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21492 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21493 else {
21494 // Not an assignment.
21495 return;
21496 }
21497
21498 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21499
21500 SourceLocation Open = E->getBeginLoc();
21501 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21502 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21503 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21504 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21505
21506 if (IsOrAssign)
21507 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21508 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21509 else
21510 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21511 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21512}
21513
21514void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21515 // Don't warn if the parens came from a macro.
21516 SourceLocation parenLoc = ParenE->getBeginLoc();
21517 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21518 return;
21519 // Don't warn for dependent expressions.
21520 if (ParenE->isTypeDependent())
21521 return;
21522
21523 Expr *E = ParenE->IgnoreParens();
21524 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21525 return;
21526
21527 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21528 if (opE->getOpcode() == BO_EQ &&
21529 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21530 == Expr::MLV_Valid) {
21531 SourceLocation Loc = opE->getOperatorLoc();
21532
21533 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21534 SourceRange ParenERange = ParenE->getSourceRange();
21535 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21536 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21537 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21538 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21539 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21540 }
21541}
21542
21543ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21544 bool IsConstexpr) {
21545 DiagnoseAssignmentAsCondition(E);
21546 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21547 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21548
21549 ExprResult result = CheckPlaceholderExpr(E);
21550 if (result.isInvalid()) return ExprError();
21551 E = result.get();
21552
21553 if (!E->isTypeDependent()) {
21554 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21555 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21556
21557 if (getLangOpts().CPlusPlus)
21558 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21559
21560 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21561 if (ERes.isInvalid())
21562 return ExprError();
21563 E = ERes.get();
21564
21565 QualType T = E->getType();
21566 if (!T->isScalarType()) { // C99 6.8.4.1p1
21567 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21568 << T << E->getSourceRange();
21569 return ExprError();
21570 }
21571 CheckBoolLikeConversion(E, CC: Loc);
21572 }
21573
21574 return E;
21575}
21576
21577Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21578 Expr *SubExpr, ConditionKind CK,
21579 bool MissingOK) {
21580 // MissingOK indicates whether having no condition expression is valid
21581 // (for loop) or invalid (e.g. while loop).
21582 if (!SubExpr)
21583 return MissingOK ? ConditionResult() : ConditionError();
21584
21585 ExprResult Cond;
21586 switch (CK) {
21587 case ConditionKind::Boolean:
21588 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21589 break;
21590
21591 case ConditionKind::ConstexprIf:
21592 // Note: this might produce a FullExpr
21593 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21594 break;
21595
21596 case ConditionKind::Switch:
21597 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21598 break;
21599 }
21600 if (Cond.isInvalid()) {
21601 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21602 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21603 if (!Cond.get())
21604 return ConditionError();
21605 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21606 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21607
21608 if (!Cond.isUsable())
21609 return ConditionError();
21610
21611 return ConditionResult(*this, nullptr, Cond,
21612 CK == ConditionKind::ConstexprIf);
21613}
21614
21615namespace {
21616 /// A visitor for rebuilding a call to an __unknown_any expression
21617 /// to have an appropriate type.
21618 struct RebuildUnknownAnyFunction
21619 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21620
21621 Sema &S;
21622
21623 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21624
21625 ExprResult VisitStmt(Stmt *S) {
21626 llvm_unreachable("unexpected statement!");
21627 }
21628
21629 ExprResult VisitExpr(Expr *E) {
21630 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21631 << E->getSourceRange();
21632 return ExprError();
21633 }
21634
21635 /// Rebuild an expression which simply semantically wraps another
21636 /// expression which it shares the type and value kind of.
21637 template <class T> ExprResult rebuildSugarExpr(T *E) {
21638 ExprResult SubResult = Visit(S: E->getSubExpr());
21639 if (SubResult.isInvalid()) return ExprError();
21640
21641 Expr *SubExpr = SubResult.get();
21642 E->setSubExpr(SubExpr);
21643 E->setType(SubExpr->getType());
21644 E->setValueKind(SubExpr->getValueKind());
21645 assert(E->getObjectKind() == OK_Ordinary);
21646 return E;
21647 }
21648
21649 ExprResult VisitParenExpr(ParenExpr *E) {
21650 return rebuildSugarExpr(E);
21651 }
21652
21653 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21654 return rebuildSugarExpr(E);
21655 }
21656
21657 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21658 ExprResult SubResult = Visit(S: E->getSubExpr());
21659 if (SubResult.isInvalid()) return ExprError();
21660
21661 Expr *SubExpr = SubResult.get();
21662 E->setSubExpr(SubExpr);
21663 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21664 assert(E->isPRValue());
21665 assert(E->getObjectKind() == OK_Ordinary);
21666 return E;
21667 }
21668
21669 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21670 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21671
21672 E->setType(VD->getType());
21673
21674 assert(E->isPRValue());
21675 if (S.getLangOpts().CPlusPlus &&
21676 !(isa<CXXMethodDecl>(Val: VD) &&
21677 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21678 E->setValueKind(VK_LValue);
21679
21680 return E;
21681 }
21682
21683 ExprResult VisitMemberExpr(MemberExpr *E) {
21684 return resolveDecl(E, VD: E->getMemberDecl());
21685 }
21686
21687 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21688 return resolveDecl(E, VD: E->getDecl());
21689 }
21690 };
21691}
21692
21693/// Given a function expression of unknown-any type, try to rebuild it
21694/// to have a function type.
21695static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21696 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21697 if (Result.isInvalid()) return ExprError();
21698 return S.DefaultFunctionArrayConversion(E: Result.get());
21699}
21700
21701namespace {
21702 /// A visitor for rebuilding an expression of type __unknown_anytype
21703 /// into one which resolves the type directly on the referring
21704 /// expression. Strict preservation of the original source
21705 /// structure is not a goal.
21706 struct RebuildUnknownAnyExpr
21707 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21708
21709 Sema &S;
21710
21711 /// The current destination type.
21712 QualType DestType;
21713
21714 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21715 : S(S), DestType(CastType) {}
21716
21717 ExprResult VisitStmt(Stmt *S) {
21718 llvm_unreachable("unexpected statement!");
21719 }
21720
21721 ExprResult VisitExpr(Expr *E) {
21722 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21723 << E->getSourceRange();
21724 return ExprError();
21725 }
21726
21727 ExprResult VisitCallExpr(CallExpr *E);
21728 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21729
21730 /// Rebuild an expression which simply semantically wraps another
21731 /// expression which it shares the type and value kind of.
21732 template <class T> ExprResult rebuildSugarExpr(T *E) {
21733 ExprResult SubResult = Visit(S: E->getSubExpr());
21734 if (SubResult.isInvalid()) return ExprError();
21735 Expr *SubExpr = SubResult.get();
21736 E->setSubExpr(SubExpr);
21737 E->setType(SubExpr->getType());
21738 E->setValueKind(SubExpr->getValueKind());
21739 assert(E->getObjectKind() == OK_Ordinary);
21740 return E;
21741 }
21742
21743 ExprResult VisitParenExpr(ParenExpr *E) {
21744 return rebuildSugarExpr(E);
21745 }
21746
21747 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21748 return rebuildSugarExpr(E);
21749 }
21750
21751 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21752 const PointerType *Ptr = DestType->getAs<PointerType>();
21753 if (!Ptr) {
21754 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21755 << E->getSourceRange();
21756 return ExprError();
21757 }
21758
21759 if (isa<CallExpr>(Val: E->getSubExpr())) {
21760 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21761 << E->getSourceRange();
21762 return ExprError();
21763 }
21764
21765 assert(E->isPRValue());
21766 assert(E->getObjectKind() == OK_Ordinary);
21767 E->setType(DestType);
21768
21769 // Build the sub-expression as if it were an object of the pointee type.
21770 DestType = Ptr->getPointeeType();
21771 ExprResult SubResult = Visit(S: E->getSubExpr());
21772 if (SubResult.isInvalid()) return ExprError();
21773 E->setSubExpr(SubResult.get());
21774 return E;
21775 }
21776
21777 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21778
21779 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21780
21781 ExprResult VisitMemberExpr(MemberExpr *E) {
21782 return resolveDecl(E, VD: E->getMemberDecl());
21783 }
21784
21785 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21786 return resolveDecl(E, VD: E->getDecl());
21787 }
21788 };
21789}
21790
21791/// Rebuilds a call expression which yielded __unknown_anytype.
21792ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21793 Expr *CalleeExpr = E->getCallee();
21794
21795 enum FnKind {
21796 FK_MemberFunction,
21797 FK_FunctionPointer,
21798 FK_BlockPointer
21799 };
21800
21801 FnKind Kind;
21802 QualType CalleeType = CalleeExpr->getType();
21803 if (CalleeType == S.Context.BoundMemberTy) {
21804 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21805 Kind = FK_MemberFunction;
21806 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21807 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21808 CalleeType = Ptr->getPointeeType();
21809 Kind = FK_FunctionPointer;
21810 } else {
21811 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21812 Kind = FK_BlockPointer;
21813 }
21814 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21815
21816 // Verify that this is a legal result type of a function.
21817 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21818 DestType->isFunctionType()) {
21819 unsigned diagID = diag::err_func_returning_array_function;
21820 if (Kind == FK_BlockPointer)
21821 diagID = diag::err_block_returning_array_function;
21822
21823 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21824 << DestType->isFunctionType() << DestType;
21825 return ExprError();
21826 }
21827
21828 // Otherwise, go ahead and set DestType as the call's result.
21829 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21830 E->setValueKind(Expr::getValueKindForType(T: DestType));
21831 assert(E->getObjectKind() == OK_Ordinary);
21832
21833 // Rebuild the function type, replacing the result type with DestType.
21834 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21835 if (Proto) {
21836 // __unknown_anytype(...) is a special case used by the debugger when
21837 // it has no idea what a function's signature is.
21838 //
21839 // We want to build this call essentially under the K&R
21840 // unprototyped rules, but making a FunctionNoProtoType in C++
21841 // would foul up all sorts of assumptions. However, we cannot
21842 // simply pass all arguments as variadic arguments, nor can we
21843 // portably just call the function under a non-variadic type; see
21844 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21845 // However, it turns out that in practice it is generally safe to
21846 // call a function declared as "A foo(B,C,D);" under the prototype
21847 // "A foo(B,C,D,...);". The only known exception is with the
21848 // Windows ABI, where any variadic function is implicitly cdecl
21849 // regardless of its normal CC. Therefore we change the parameter
21850 // types to match the types of the arguments.
21851 //
21852 // This is a hack, but it is far superior to moving the
21853 // corresponding target-specific code from IR-gen to Sema/AST.
21854
21855 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21856 SmallVector<QualType, 8> ArgTypes;
21857 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21858 ArgTypes.reserve(N: E->getNumArgs());
21859 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21860 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21861 }
21862 ParamTypes = ArgTypes;
21863 }
21864 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21865 EPI: Proto->getExtProtoInfo());
21866 } else {
21867 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21868 Info: FnType->getExtInfo());
21869 }
21870
21871 // Rebuild the appropriate pointer-to-function type.
21872 switch (Kind) {
21873 case FK_MemberFunction:
21874 // Nothing to do.
21875 break;
21876
21877 case FK_FunctionPointer:
21878 DestType = S.Context.getPointerType(T: DestType);
21879 break;
21880
21881 case FK_BlockPointer:
21882 DestType = S.Context.getBlockPointerType(T: DestType);
21883 break;
21884 }
21885
21886 // Finally, we can recurse.
21887 ExprResult CalleeResult = Visit(S: CalleeExpr);
21888 if (!CalleeResult.isUsable()) return ExprError();
21889 E->setCallee(CalleeResult.get());
21890
21891 // Bind a temporary if necessary.
21892 return S.MaybeBindToTemporary(E);
21893}
21894
21895ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21896 // Verify that this is a legal result type of a call.
21897 if (DestType->isArrayType() || DestType->isFunctionType()) {
21898 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21899 << DestType->isFunctionType() << DestType;
21900 return ExprError();
21901 }
21902
21903 // Rewrite the method result type if available.
21904 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21905 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21906 Method->setReturnType(DestType);
21907 }
21908
21909 // Change the type of the message.
21910 E->setType(DestType.getNonReferenceType());
21911 E->setValueKind(Expr::getValueKindForType(T: DestType));
21912
21913 return S.MaybeBindToTemporary(E);
21914}
21915
21916ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21917 // The only case we should ever see here is a function-to-pointer decay.
21918 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21919 assert(E->isPRValue());
21920 assert(E->getObjectKind() == OK_Ordinary);
21921
21922 E->setType(DestType);
21923
21924 // Rebuild the sub-expression as the pointee (function) type.
21925 DestType = DestType->castAs<PointerType>()->getPointeeType();
21926
21927 ExprResult Result = Visit(S: E->getSubExpr());
21928 if (!Result.isUsable()) return ExprError();
21929
21930 E->setSubExpr(Result.get());
21931 return E;
21932 } else if (E->getCastKind() == CK_LValueToRValue) {
21933 assert(E->isPRValue());
21934 assert(E->getObjectKind() == OK_Ordinary);
21935
21936 assert(isa<BlockPointerType>(E->getType()));
21937
21938 E->setType(DestType);
21939
21940 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21941 DestType = S.Context.getLValueReferenceType(T: DestType);
21942
21943 ExprResult Result = Visit(S: E->getSubExpr());
21944 if (!Result.isUsable()) return ExprError();
21945
21946 E->setSubExpr(Result.get());
21947 return E;
21948 } else {
21949 llvm_unreachable("Unhandled cast type!");
21950 }
21951}
21952
21953ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21954 ExprValueKind ValueKind = VK_LValue;
21955 QualType Type = DestType;
21956
21957 // We know how to make this work for certain kinds of decls:
21958
21959 // - functions
21960 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21961 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21962 DestType = Ptr->getPointeeType();
21963 ExprResult Result = resolveDecl(E, VD);
21964 if (Result.isInvalid()) return ExprError();
21965 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21966 VK: VK_PRValue);
21967 }
21968
21969 if (!Type->isFunctionType()) {
21970 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21971 << VD << E->getSourceRange();
21972 return ExprError();
21973 }
21974 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21975 // We must match the FunctionDecl's type to the hack introduced in
21976 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21977 // type. See the lengthy commentary in that routine.
21978 QualType FDT = FD->getType();
21979 const FunctionType *FnType = FDT->castAs<FunctionType>();
21980 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21981 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21982 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21983 SourceLocation Loc = FD->getLocation();
21984 FunctionDecl *NewFD = FunctionDecl::Create(
21985 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21986 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21987 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21988 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21989 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21990
21991 if (FD->getQualifier())
21992 NewFD->setQualifierInfo(FD->getQualifierLoc());
21993
21994 SmallVector<ParmVarDecl*, 16> Params;
21995 for (const auto &AI : FT->param_types()) {
21996 ParmVarDecl *Param =
21997 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21998 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21999 Params.push_back(Elt: Param);
22000 }
22001 NewFD->setParams(Params);
22002 DRE->setDecl(NewFD);
22003 VD = DRE->getDecl();
22004 }
22005 }
22006
22007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
22008 if (MD->isInstance()) {
22009 ValueKind = VK_PRValue;
22010 Type = S.Context.BoundMemberTy;
22011 }
22012
22013 // Function references aren't l-values in C.
22014 if (!S.getLangOpts().CPlusPlus)
22015 ValueKind = VK_PRValue;
22016
22017 // - variables
22018 } else if (isa<VarDecl>(Val: VD)) {
22019 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22020 Type = RefTy->getPointeeType();
22021 } else if (Type->isFunctionType()) {
22022 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
22023 << VD << E->getSourceRange();
22024 return ExprError();
22025 }
22026
22027 // - nothing else
22028 } else {
22029 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
22030 << VD << E->getSourceRange();
22031 return ExprError();
22032 }
22033
22034 // Modifying the declaration like this is friendly to IR-gen but
22035 // also really dangerous.
22036 VD->setType(DestType);
22037 E->setType(Type);
22038 E->setValueKind(ValueKind);
22039 return E;
22040}
22041
22042ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
22043 Expr *CastExpr, CastKind &CastKind,
22044 ExprValueKind &VK, CXXCastPath &Path) {
22045 // The type we're casting to must be either void or complete.
22046 if (!CastType->isVoidType() &&
22047 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
22048 DiagID: diag::err_typecheck_cast_to_incomplete))
22049 return ExprError();
22050
22051 // Rewrite the casted expression from scratch.
22052 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
22053 if (!result.isUsable()) return ExprError();
22054
22055 CastExpr = result.get();
22056 VK = CastExpr->getValueKind();
22057 CastKind = CK_NoOp;
22058
22059 return CastExpr;
22060}
22061
22062ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
22063 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
22064}
22065
22066ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
22067 Expr *arg, QualType &paramType) {
22068 // If the syntactic form of the argument is not an explicit cast of
22069 // any sort, just do default argument promotion.
22070 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
22071 if (!castArg) {
22072 ExprResult result = DefaultArgumentPromotion(E: arg);
22073 if (result.isInvalid()) return ExprError();
22074 paramType = result.get()->getType();
22075 return result;
22076 }
22077
22078 // Otherwise, use the type that was written in the explicit cast.
22079 assert(!arg->hasPlaceholderType());
22080 paramType = castArg->getTypeAsWritten();
22081
22082 // Copy-initialize a parameter of that type.
22083 InitializedEntity entity =
22084 InitializedEntity::InitializeParameter(Context, Type: paramType,
22085 /*consumed*/ Consumed: false);
22086 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
22087}
22088
22089static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
22090 Expr *orig = E;
22091 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22092 while (true) {
22093 E = E->IgnoreParenImpCasts();
22094 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
22095 E = call->getCallee();
22096 diagID = diag::err_uncasted_call_of_unknown_any;
22097 } else {
22098 break;
22099 }
22100 }
22101
22102 SourceLocation loc;
22103 NamedDecl *d;
22104 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
22105 loc = ref->getLocation();
22106 d = ref->getDecl();
22107 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
22108 loc = mem->getMemberLoc();
22109 d = mem->getMemberDecl();
22110 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
22111 diagID = diag::err_uncasted_call_of_unknown_any;
22112 loc = msg->getSelectorStartLoc();
22113 d = msg->getMethodDecl();
22114 if (!d) {
22115 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
22116 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22117 << orig->getSourceRange();
22118 return ExprError();
22119 }
22120 } else {
22121 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
22122 << E->getSourceRange();
22123 return ExprError();
22124 }
22125
22126 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
22127
22128 // Never recoverable.
22129 return ExprError();
22130}
22131
22132ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
22133 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22134 if (!placeholderType) return E;
22135
22136 switch (placeholderType->getKind()) {
22137 case BuiltinType::UnresolvedTemplate: {
22138 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
22139 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22140 // There's only one FoundDecl for UnresolvedTemplate type. See
22141 // BuildTemplateIdExpr.
22142 NamedDecl *Temp = *ULE->decls_begin();
22143 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
22144
22145 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22146 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22147 // as it models only the unqualified-id case, where this case can clearly be
22148 // qualified. Thus we can't just qualify an assumed template.
22149 TemplateName TN;
22150 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
22151 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
22152 Template: TemplateName(TD));
22153 else
22154 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
22155
22156 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
22157 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22158 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
22159 << IsTypeAliasTemplateDecl;
22160
22161 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22162 bool HasAnyDependentTA = false;
22163 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22164 HasAnyDependentTA |= Arg.getArgument().isDependent();
22165 TAL.addArgument(Loc: Arg);
22166 }
22167
22168 QualType TST;
22169 {
22170 SFINAETrap Trap(*this);
22171 TST = CheckTemplateIdType(
22172 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
22173 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22174 }
22175 if (TST.isNull())
22176 TST = Context.getTemplateSpecializationType(
22177 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
22178 /*CanonicalArgs=*/{},
22179 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22180 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
22181 T: TST);
22182 }
22183
22184 // Overloaded expressions.
22185 case BuiltinType::Overload: {
22186 // Try to resolve a single function template specialization.
22187 // This is obligatory.
22188 ExprResult Result = E;
22189 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
22190 return Result;
22191
22192 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22193 // leaves Result unchanged on failure.
22194 Result = E;
22195 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
22196 return Result;
22197
22198 // If that failed, try to recover with a call.
22199 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
22200 /*complain*/ ForceComplain: true);
22201 return Result;
22202 }
22203
22204 // Bound member functions.
22205 case BuiltinType::BoundMember: {
22206 ExprResult result = E;
22207 const Expr *BME = E->IgnoreParens();
22208 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
22209 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22210 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
22211 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22212 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
22213 if (ME->getMemberNameInfo().getName().getNameKind() ==
22214 DeclarationName::CXXDestructorName)
22215 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22216 }
22217 tryToRecoverWithCall(E&: result, PD,
22218 /*complain*/ ForceComplain: true);
22219 return result;
22220 }
22221
22222 // ARC unbridged casts.
22223 case BuiltinType::ARCUnbridgedCast: {
22224 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
22225 ObjC().diagnoseARCUnbridgedCast(e: realCast);
22226 return realCast;
22227 }
22228
22229 // Expressions of unknown type.
22230 case BuiltinType::UnknownAny:
22231 return diagnoseUnknownAnyExpr(S&: *this, E);
22232
22233 // Pseudo-objects.
22234 case BuiltinType::PseudoObject:
22235 return PseudoObject().checkRValue(E);
22236
22237 case BuiltinType::BuiltinFn: {
22238 // Accept __noop without parens by implicitly converting it to a call expr.
22239 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
22240 if (DRE) {
22241 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
22242 unsigned BuiltinID = FD->getBuiltinID();
22243 if (BuiltinID == Builtin::BI__noop) {
22244 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
22245 CK: CK_BuiltinFnToFnPtr)
22246 .get();
22247 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
22248 VK: VK_PRValue, RParenLoc: SourceLocation(),
22249 FPFeatures: FPOptionsOverride());
22250 }
22251
22252 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
22253 // Any use of these other than a direct call is ill-formed as of C++20,
22254 // because they are not addressable functions. In earlier language
22255 // modes, warn and force an instantiation of the real body.
22256 Diag(Loc: E->getBeginLoc(),
22257 DiagID: getLangOpts().CPlusPlus20
22258 ? diag::err_use_of_unaddressable_function
22259 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22260 if (FD->isImplicitlyInstantiable()) {
22261 // Require a definition here because a normal attempt at
22262 // instantiation for a builtin will be ignored, and we won't try
22263 // again later. We assume that the definition of the template
22264 // precedes this use.
22265 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
22266 /*Recursive=*/false,
22267 /*DefinitionRequired=*/true,
22268 /*AtEndOfTU=*/false);
22269 }
22270 // Produce a properly-typed reference to the function.
22271 CXXScopeSpec SS;
22272 SS.Adopt(Other: DRE->getQualifierLoc());
22273 TemplateArgumentListInfo TemplateArgs;
22274 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22275 return BuildDeclRefExpr(
22276 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22277 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22278 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22279 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22280 }
22281 }
22282
22283 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22284 return ExprError();
22285 }
22286
22287 case BuiltinType::IncompleteMatrixIdx: {
22288 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22289 // At this point, we know there was no second [] to complete the operator.
22290 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22291 if (getLangOpts().HLSL) {
22292 return CreateBuiltinMatrixSingleSubscriptExpr(
22293 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22294 }
22295 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22296 return ExprError();
22297 }
22298
22299 // Expressions of unknown type.
22300 case BuiltinType::ArraySection:
22301 // If we've already diagnosed something on the array section type, we
22302 // shouldn't need to do any further diagnostic here.
22303 if (!E->containsErrors())
22304 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22305 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22306 return ExprError();
22307
22308 // Expressions of unknown type.
22309 case BuiltinType::OMPArrayShaping:
22310 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22311
22312 case BuiltinType::OMPIterator:
22313 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22314
22315 // Everything else should be impossible.
22316#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22317 case BuiltinType::Id:
22318#include "clang/Basic/OpenCLImageTypes.def"
22319#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22320 case BuiltinType::Id:
22321#include "clang/Basic/OpenCLExtensionTypes.def"
22322#define SVE_TYPE(Name, Id, SingletonId) \
22323 case BuiltinType::Id:
22324#include "clang/Basic/AArch64ACLETypes.def"
22325#define PPC_VECTOR_TYPE(Name, Id, Size) \
22326 case BuiltinType::Id:
22327#include "clang/Basic/PPCTypes.def"
22328#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22329#include "clang/Basic/RISCVVTypes.def"
22330#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22331#include "clang/Basic/WebAssemblyReferenceTypes.def"
22332#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22333#include "clang/Basic/AMDGPUTypes.def"
22334#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22335#include "clang/Basic/HLSLIntangibleTypes.def"
22336#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22337#include "clang/Basic/SPIRVTypes.def"
22338#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22339#define PLACEHOLDER_TYPE(Id, SingletonId)
22340#include "clang/AST/BuiltinTypes.def"
22341 break;
22342 }
22343
22344 llvm_unreachable("invalid placeholder type!");
22345}
22346
22347bool Sema::CheckCaseExpression(Expr *E) {
22348 if (E->isTypeDependent())
22349 return true;
22350 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22351 return E->getType()->isIntegralOrEnumerationType();
22352 return false;
22353}
22354
22355ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22356 ArrayRef<Expr *> SubExprs, QualType T) {
22357 if (!Context.getLangOpts().RecoveryAST)
22358 return ExprError();
22359
22360 if (isSFINAEContext())
22361 return ExprError();
22362
22363 if (T.isNull() || T->isUndeducedType() ||
22364 !Context.getLangOpts().RecoveryASTType)
22365 // We don't know the concrete type, fallback to dependent type.
22366 T = Context.DependentTy;
22367
22368 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22369}
22370