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 if (getLangOpts().HLSL)
726 if (const auto *MT = T->getAs<ConstantMatrixType>(); MT && MT->getLayout())
727 T = Context.getCanonicalType(T);
728
729 // Under the MS ABI, lock down the inheritance model now.
730 if (T->isMemberPointerType() &&
731 Context.getTargetInfo().getCXXABI().isMicrosoft())
732 (void)isCompleteType(Loc: E->getExprLoc(), T);
733
734 ExprResult Res = CheckLValueToRValueConversionOperand(E);
735 if (Res.isInvalid())
736 return Res;
737 E = Res.get();
738
739 // Loading a __weak object implicitly retains the value, so we need a cleanup to
740 // balance that.
741 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
742 Cleanup.setExprNeedsCleanups(true);
743
744 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
745 Cleanup.setExprNeedsCleanups(true);
746
747 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
748 return ExprError();
749
750 // C++ [conv.lval]p3:
751 // If T is cv std::nullptr_t, the result is a null pointer constant.
752 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
753 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
754 FPO: CurFPFeatureOverrides());
755
756 // C11 6.3.2.1p2:
757 // ... if the lvalue has atomic type, the value has the non-atomic version
758 // of the type of the lvalue ...
759 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
760 T = Atomic->getValueType().getUnqualifiedType();
761 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
762 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
763 }
764
765 return Res;
766}
767
768ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
769 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
770 if (Res.isInvalid())
771 return ExprError();
772 Res = DefaultLvalueConversion(E: Res.get());
773 if (Res.isInvalid())
774 return ExprError();
775 return Res;
776}
777
778ExprResult Sema::CallExprUnaryConversions(Expr *E) {
779 QualType Ty = E->getType();
780 ExprResult Res = E;
781 // Only do implicit cast for a function type, but not for a pointer
782 // to function type.
783 if (Ty->isFunctionType()) {
784 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
785 CK: CK_FunctionToPointerDecay);
786 if (Res.isInvalid())
787 return ExprError();
788 }
789 Res = DefaultLvalueConversion(E: Res.get());
790 if (Res.isInvalid())
791 return ExprError();
792 return Res.get();
793}
794
795/// UsualUnaryFPConversions - Promotes floating-point types according to the
796/// current language semantics.
797ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
800
801 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
802 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
803 (getLangOpts().getFPEvalMethod() !=
804 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
805 PP.getLastFPEvalPragmaLocation().isValid())) {
806 switch (EvalMethod) {
807 default:
808 llvm_unreachable("Unrecognized float evaluation method");
809 break;
810 case LangOptions::FEM_UnsetOnCommandLine:
811 llvm_unreachable("Float evaluation method should be set by now");
812 break;
813 case LangOptions::FEM_Double:
814 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
815 // Widen the expression to double.
816 return Ty->isComplexType()
817 ? ImpCastExprToType(E,
818 Type: Context.getComplexType(T: Context.DoubleTy),
819 CK: CK_FloatingComplexCast)
820 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
821 break;
822 case LangOptions::FEM_Extended:
823 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
824 // Widen the expression to long double.
825 return Ty->isComplexType()
826 ? ImpCastExprToType(
827 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
828 CK: CK_FloatingComplexCast)
829 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
830 CK: CK_FloatingCast);
831 break;
832 }
833 }
834
835 // Half FP have to be promoted to float unless it is natively supported
836 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
837 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
838
839 return E;
840}
841
842/// UsualUnaryConversions - Performs various conversions that are common to most
843/// operators (C99 6.3). The conversions of array and function types are
844/// sometimes suppressed. For example, the array->pointer conversion doesn't
845/// apply if the array is an argument to the sizeof or address (&) operators.
846/// In these instances, this routine should *not* be called.
847ExprResult Sema::UsualUnaryConversions(Expr *E) {
848 // First, convert to an r-value.
849 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
850 if (Res.isInvalid())
851 return ExprError();
852
853 // Promote floating-point types.
854 Res = UsualUnaryFPConversions(E: Res.get());
855 if (Res.isInvalid())
856 return ExprError();
857 E = Res.get();
858
859 QualType Ty = E->getType();
860 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
861
862 // Try to perform integral promotions if the object has a theoretically
863 // promotable type.
864 if (Ty->isIntegralOrUnscopedEnumerationType()) {
865 // C99 6.3.1.1p2:
866 //
867 // The following may be used in an expression wherever an int or
868 // unsigned int may be used:
869 // - an object or expression with an integer type whose integer
870 // conversion rank is less than or equal to the rank of int
871 // and unsigned int.
872 // - A bit-field of type _Bool, int, signed int, or unsigned int.
873 //
874 // If an int can represent all values of the original type, the
875 // value is converted to an int; otherwise, it is converted to an
876 // unsigned int. These are called the integer promotions. All
877 // other types are unchanged by the integer promotions.
878
879 QualType PTy = Context.isPromotableBitField(E);
880 if (!PTy.isNull()) {
881 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
882 return E;
883 }
884 if (Context.isPromotableIntegerType(T: Ty)) {
885 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
886 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
887 return E;
888 }
889 }
890 return E;
891}
892
893/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
894/// do not have a prototype. Arguments that have type float or __fp16
895/// are promoted to double. All other argument types are converted by
896/// UsualUnaryConversions().
897ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
898 QualType Ty = E->getType();
899 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
900
901 ExprResult Res = UsualUnaryConversions(E);
902 if (Res.isInvalid())
903 return ExprError();
904 E = Res.get();
905
906 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
907 // promote to double.
908 // Note that default argument promotion applies only to float (and
909 // half/fp16); it does not apply to _Float16.
910 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
911 if (BTy && (BTy->getKind() == BuiltinType::Half ||
912 BTy->getKind() == BuiltinType::Float)) {
913 if (getLangOpts().OpenCL &&
914 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
915 if (BTy->getKind() == BuiltinType::Half) {
916 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
917 }
918 } else {
919 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
920 }
921 }
922 if (BTy &&
923 getLangOpts().getExtendIntArgs() ==
924 LangOptions::ExtendArgsKind::ExtendTo64 &&
925 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
926 Context.getTypeSizeInChars(T: BTy) <
927 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
928 E = (Ty->isUnsignedIntegerType())
929 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
930 .get()
931 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
932 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
933 "Unexpected typesize for LongLongTy");
934 }
935
936 // C++ performs lvalue-to-rvalue conversion as a default argument
937 // promotion, even on class types, but note:
938 // C++11 [conv.lval]p2:
939 // When an lvalue-to-rvalue conversion occurs in an unevaluated
940 // operand or a subexpression thereof the value contained in the
941 // referenced object is not accessed. Otherwise, if the glvalue
942 // has a class type, the conversion copy-initializes a temporary
943 // of type T from the glvalue and the result of the conversion
944 // is a prvalue for the temporary.
945 // FIXME: add some way to gate this entire thing for correctness in
946 // potentially potentially evaluated contexts.
947 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
948 ExprResult Temp = PerformCopyInitialization(
949 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
950 EqualLoc: E->getExprLoc(), Init: E);
951 if (Temp.isInvalid())
952 return ExprError();
953 E = Temp.get();
954 }
955
956 // C++ [expr.call]p7, per CWG722:
957 // An argument that has (possibly cv-qualified) type std::nullptr_t is
958 // converted to void* ([conv.ptr]).
959 // (This does not apply to C23 nullptr)
960 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
961 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
962
963 return E;
964}
965
966VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
967 if (Ty->isIncompleteType()) {
968 // C++11 [expr.call]p7:
969 // After these conversions, if the argument does not have arithmetic,
970 // enumeration, pointer, pointer to member, or class type, the program
971 // is ill-formed.
972 //
973 // Since we've already performed null pointer conversion, array-to-pointer
974 // decay and function-to-pointer decay, the only such type in C++ is cv
975 // void. This also handles initializer lists as variadic arguments.
976 if (Ty->isVoidType())
977 return VarArgKind::Invalid;
978
979 if (Ty->isObjCObjectType())
980 return VarArgKind::Invalid;
981 return VarArgKind::Valid;
982 }
983
984 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
985 return VarArgKind::Invalid;
986
987 if (Context.getTargetInfo().getTriple().isWasm() &&
988 Ty.isWebAssemblyReferenceType()) {
989 return VarArgKind::Invalid;
990 }
991
992 if (Ty.isCXX98PODType(Context))
993 return VarArgKind::Valid;
994
995 // C++11 [expr.call]p7:
996 // Passing a potentially-evaluated argument of class type (Clause 9)
997 // having a non-trivial copy constructor, a non-trivial move constructor,
998 // or a non-trivial destructor, with no corresponding parameter,
999 // is conditionally-supported with implementation-defined semantics.
1000 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
1001 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
1002 if (!Record->hasNonTrivialCopyConstructor() &&
1003 !Record->hasNonTrivialMoveConstructor() &&
1004 !Record->hasNonTrivialDestructor())
1005 return VarArgKind::ValidInCXX11;
1006
1007 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1008 return VarArgKind::Valid;
1009
1010 if (Ty->isObjCObjectType())
1011 return VarArgKind::Invalid;
1012
1013 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1014 return VarArgKind::Valid;
1015
1016 if (getLangOpts().MSVCCompat)
1017 return VarArgKind::MSVCUndefined;
1018
1019 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1020 return VarArgKind::Valid;
1021
1022 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1023 // permitted to reject them. We should consider doing so.
1024 return VarArgKind::Undefined;
1025}
1026
1027void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1028 // Don't allow one to pass an Objective-C interface to a vararg.
1029 const QualType &Ty = E->getType();
1030 VarArgKind VAK = isValidVarArgType(Ty);
1031
1032 // Complain about passing non-POD types through varargs.
1033 switch (VAK) {
1034 case VarArgKind::ValidInCXX11:
1035 DiagRuntimeBehavior(
1036 Loc: E->getBeginLoc(), Statement: nullptr,
1037 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1038 [[fallthrough]];
1039 case VarArgKind::Valid:
1040 if (Ty->isRecordType()) {
1041 // This is unlikely to be what the user intended. If the class has a
1042 // 'c_str' member function, the user probably meant to call that.
1043 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1044 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1045 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1046 }
1047 break;
1048
1049 case VarArgKind::Undefined:
1050 case VarArgKind::MSVCUndefined:
1051 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1052 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1053 << getLangOpts().CPlusPlus11 << Ty << CT);
1054 break;
1055
1056 case VarArgKind::Invalid:
1057 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1058 Diag(Loc: E->getBeginLoc(),
1059 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1060 << Ty << CT;
1061 else if (Ty->isObjCObjectType())
1062 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1063 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1064 << Ty << CT);
1065 else
1066 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1067 << isa<InitListExpr>(Val: E) << Ty << CT;
1068 break;
1069 }
1070}
1071
1072ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1073 FunctionDecl *FDecl) {
1074 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1075 // Strip the unbridged-cast placeholder expression off, if applicable.
1076 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1077 (CT == VariadicCallType::Method ||
1078 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1079 E = ObjC().stripARCUnbridgedCast(e: E);
1080
1081 // Otherwise, do normal placeholder checking.
1082 } else {
1083 ExprResult ExprRes = CheckPlaceholderExpr(E);
1084 if (ExprRes.isInvalid())
1085 return ExprError();
1086 E = ExprRes.get();
1087 }
1088 }
1089
1090 ExprResult ExprRes = DefaultArgumentPromotion(E);
1091 if (ExprRes.isInvalid())
1092 return ExprError();
1093
1094 // Copy blocks to the heap.
1095 if (ExprRes.get()->getType()->isBlockPointerType())
1096 maybeExtendBlockObject(E&: ExprRes);
1097
1098 E = ExprRes.get();
1099
1100 // Diagnostics regarding non-POD argument types are
1101 // emitted along with format string checking in Sema::CheckFunctionCall().
1102 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1103 // Turn this into a trap.
1104 CXXScopeSpec SS;
1105 SourceLocation TemplateKWLoc;
1106 UnqualifiedId Name;
1107 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1108 IdLoc: E->getBeginLoc());
1109 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1110 /*HasTrailingLParen=*/true,
1111 /*IsAddressOfOperand=*/false);
1112 if (TrapFn.isInvalid())
1113 return ExprError();
1114
1115 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1116 RParenLoc: E->getEndLoc());
1117 if (Call.isInvalid())
1118 return ExprError();
1119
1120 ExprResult Comma =
1121 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1122 if (Comma.isInvalid())
1123 return ExprError();
1124 return Comma.get();
1125 }
1126
1127 if (!getLangOpts().CPlusPlus &&
1128 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1129 DiagID: diag::err_call_incomplete_argument))
1130 return ExprError();
1131
1132 return E;
1133}
1134
1135/// Convert complex integers to complex floats and real integers to
1136/// real floats as required for complex arithmetic. Helper function of
1137/// UsualArithmeticConversions()
1138///
1139/// \return false if the integer expression is an integer type and is
1140/// successfully converted to the (complex) float type.
1141static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1142 ExprResult &ComplexExpr,
1143 QualType IntTy,
1144 QualType ComplexTy,
1145 bool SkipCast) {
1146 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1147 if (SkipCast) return false;
1148 if (IntTy->isIntegerType()) {
1149 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1150 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1151 } else {
1152 assert(IntTy->isComplexIntegerType());
1153 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1154 CK: CK_IntegralComplexToFloatingComplex);
1155 }
1156 return false;
1157}
1158
1159// This handles complex/complex, complex/float, or float/complex.
1160// When both operands are complex, the shorter operand is converted to the
1161// type of the longer, and that is the type of the result. This corresponds
1162// to what is done when combining two real floating-point operands.
1163// The fun begins when size promotion occur across type domains.
1164// From H&S 6.3.4: When one operand is complex and the other is a real
1165// floating-point type, the less precise type is converted, within it's
1166// real or complex domain, to the precision of the other type. For example,
1167// when combining a "long double" with a "double _Complex", the
1168// "double _Complex" is promoted to "long double _Complex".
1169static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1170 QualType ShorterType,
1171 QualType LongerType,
1172 bool PromotePrecision) {
1173 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1174 QualType Result =
1175 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1176
1177 if (PromotePrecision) {
1178 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1179 Shorter =
1180 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1181 } else {
1182 if (LongerIsComplex)
1183 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1184 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1185 }
1186 }
1187 return Result;
1188}
1189
1190/// Handle arithmetic conversion with complex types. Helper function of
1191/// UsualArithmeticConversions()
1192static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1193 ExprResult &RHS, QualType LHSType,
1194 QualType RHSType, bool IsCompAssign) {
1195 // Handle (complex) integer types.
1196 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1197 /*SkipCast=*/false))
1198 return LHSType;
1199 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1200 /*SkipCast=*/IsCompAssign))
1201 return RHSType;
1202
1203 // Compute the rank of the two types, regardless of whether they are complex.
1204 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1205 if (Order < 0)
1206 // Promote the precision of the LHS if not an assignment.
1207 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1208 /*PromotePrecision=*/!IsCompAssign);
1209 // Promote the precision of the RHS unless it is already the same as the LHS.
1210 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1211 /*PromotePrecision=*/Order > 0);
1212}
1213
1214/// Handle arithmetic conversion from integer to float. Helper function
1215/// of UsualArithmeticConversions()
1216static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1217 ExprResult &IntExpr,
1218 QualType FloatTy, QualType IntTy,
1219 bool ConvertFloat, bool ConvertInt) {
1220 if (IntTy->isIntegerType()) {
1221 if (ConvertInt)
1222 // Convert intExpr to the lhs floating point type.
1223 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1224 CK: CK_IntegralToFloating);
1225 return FloatTy;
1226 }
1227
1228 // Convert both sides to the appropriate complex float.
1229 assert(IntTy->isComplexIntegerType());
1230 QualType result = S.Context.getComplexType(T: FloatTy);
1231
1232 // _Complex int -> _Complex float
1233 if (ConvertInt)
1234 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1235 CK: CK_IntegralComplexToFloatingComplex);
1236
1237 // float -> _Complex float
1238 if (ConvertFloat)
1239 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1240 CK: CK_FloatingRealToComplex);
1241
1242 return result;
1243}
1244
1245/// Handle arithmethic conversion with floating point types. Helper
1246/// function of UsualArithmeticConversions()
1247static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1248 ExprResult &RHS, QualType LHSType,
1249 QualType RHSType, bool IsCompAssign) {
1250 bool LHSFloat = LHSType->isRealFloatingType();
1251 bool RHSFloat = RHSType->isRealFloatingType();
1252
1253 // N1169 4.1.4: If one of the operands has a floating type and the other
1254 // operand has a fixed-point type, the fixed-point operand
1255 // is converted to the floating type [...]
1256 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1257 if (LHSFloat)
1258 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1259 else if (!IsCompAssign)
1260 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1261 return LHSFloat ? LHSType : RHSType;
1262 }
1263
1264 // If we have two real floating types, convert the smaller operand
1265 // to the bigger result.
1266 if (LHSFloat && RHSFloat) {
1267 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1268 if (order > 0) {
1269 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1270 return LHSType;
1271 }
1272
1273 assert(order < 0 && "illegal float comparison");
1274 if (!IsCompAssign)
1275 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1276 return RHSType;
1277 }
1278
1279 if (LHSFloat) {
1280 // Half FP has to be promoted to float unless it is natively supported
1281 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1282 LHSType = S.Context.FloatTy;
1283
1284 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1285 /*ConvertFloat=*/!IsCompAssign,
1286 /*ConvertInt=*/ true);
1287 }
1288 assert(RHSFloat);
1289 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1290 /*ConvertFloat=*/ true,
1291 /*ConvertInt=*/!IsCompAssign);
1292}
1293
1294/// Diagnose attempts to convert between __float128, __ibm128 and
1295/// long double if there is no support for such conversion.
1296/// Helper function of UsualArithmeticConversions().
1297static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1298 QualType RHSType) {
1299 // No issue if either is not a floating point type.
1300 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1301 return false;
1302
1303 // No issue if both have the same 128-bit float semantics.
1304 auto *LHSComplex = LHSType->getAs<ComplexType>();
1305 auto *RHSComplex = RHSType->getAs<ComplexType>();
1306
1307 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1308 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1309
1310 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1311 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1312
1313 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1314 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1315 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1316 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1317 return false;
1318
1319 return true;
1320}
1321
1322typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1323
1324namespace {
1325/// These helper callbacks are placed in an anonymous namespace to
1326/// permit their use as function template parameters.
1327ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1328 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1329}
1330
1331ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1332 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1333 CK: CK_IntegralComplexCast);
1334}
1335}
1336
1337/// Handle integer arithmetic conversions. Helper function of
1338/// UsualArithmeticConversions()
1339template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1340static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1341 ExprResult &RHS, QualType LHSType,
1342 QualType RHSType, bool IsCompAssign) {
1343 // The rules for this case are in C99 6.3.1.8
1344 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1345 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1346 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1347 if (LHSSigned == RHSSigned) {
1348 // Same signedness; use the higher-ranked type
1349 if (order >= 0) {
1350 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1351 return LHSType;
1352 } else if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1354 return RHSType;
1355 } else if (order != (LHSSigned ? 1 : -1)) {
1356 // The unsigned type has greater than or equal rank to the
1357 // signed type, so use the unsigned type
1358 if (RHSSigned) {
1359 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1360 return LHSType;
1361 } else if (!IsCompAssign)
1362 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1363 return RHSType;
1364 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1365 // The two types are different widths; if we are here, that
1366 // means the signed type is larger than the unsigned type, so
1367 // use the signed type.
1368 if (LHSSigned) {
1369 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1370 return LHSType;
1371 } else if (!IsCompAssign)
1372 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1373 return RHSType;
1374 } else {
1375 // The signed type is higher-ranked than the unsigned type,
1376 // but isn't actually any bigger (like unsigned int and long
1377 // on most 32-bit systems). Use the unsigned type corresponding
1378 // to the signed type.
1379 QualType result =
1380 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1381 RHS = (*doRHSCast)(S, RHS.get(), result);
1382 if (!IsCompAssign)
1383 LHS = (*doLHSCast)(S, LHS.get(), result);
1384 return result;
1385 }
1386}
1387
1388/// Handle conversions with GCC complex int extension. Helper function
1389/// of UsualArithmeticConversions()
1390static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1391 ExprResult &RHS, QualType LHSType,
1392 QualType RHSType,
1393 bool IsCompAssign) {
1394 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1395 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1396
1397 if (LHSComplexInt && RHSComplexInt) {
1398 QualType LHSEltType = LHSComplexInt->getElementType();
1399 QualType RHSEltType = RHSComplexInt->getElementType();
1400 QualType ScalarType =
1401 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1402 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1403
1404 return S.Context.getComplexType(T: ScalarType);
1405 }
1406
1407 if (LHSComplexInt) {
1408 QualType LHSEltType = LHSComplexInt->getElementType();
1409 QualType ScalarType =
1410 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1411 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1412 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1413 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1414 CK: CK_IntegralRealToComplex);
1415
1416 return ComplexType;
1417 }
1418
1419 assert(RHSComplexInt);
1420
1421 QualType RHSEltType = RHSComplexInt->getElementType();
1422 QualType ScalarType =
1423 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1424 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1425 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1426
1427 if (!IsCompAssign)
1428 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1429 CK: CK_IntegralRealToComplex);
1430 return ComplexType;
1431}
1432
1433static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1434 ExprResult &RHS,
1435 QualType LHSType,
1436 QualType RHSType,
1437 bool IsCompAssign) {
1438
1439 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1440 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1441
1442 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1443 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1444
1445 bool LHSHasTrap =
1446 LhsOBT && LhsOBT->getBehaviorKind() ==
1447 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1448 bool RHSHasTrap =
1449 RhsOBT && RhsOBT->getBehaviorKind() ==
1450 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1451 bool LHSHasWrap =
1452 LhsOBT && LhsOBT->getBehaviorKind() ==
1453 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1454 bool RHSHasWrap =
1455 RhsOBT && RhsOBT->getBehaviorKind() ==
1456 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457
1458 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1459 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1460
1461 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1462 if (LHSHasTrap || RHSHasTrap)
1463 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1464 else if (LHSHasWrap || RHSHasWrap)
1465 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1466
1467 QualType LHSConvType = LHSUnderlyingType;
1468 QualType RHSConvType = RHSUnderlyingType;
1469 if (DominantBehavior) {
1470 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1471 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1472 Wrapped: LHSUnderlyingType);
1473 else
1474 LHSConvType = LHSType;
1475
1476 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1477 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1478 Wrapped: RHSUnderlyingType);
1479 else
1480 RHSConvType = RHSType;
1481 }
1482
1483 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1484 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1485}
1486
1487/// Return the rank of a given fixed point or integer type. The value itself
1488/// doesn't matter, but the values must be increasing with proper increasing
1489/// rank as described in N1169 4.1.1.
1490static unsigned GetFixedPointRank(QualType Ty) {
1491 const auto *BTy = Ty->getAs<BuiltinType>();
1492 assert(BTy && "Expected a builtin type.");
1493
1494 switch (BTy->getKind()) {
1495 case BuiltinType::ShortFract:
1496 case BuiltinType::UShortFract:
1497 case BuiltinType::SatShortFract:
1498 case BuiltinType::SatUShortFract:
1499 return 1;
1500 case BuiltinType::Fract:
1501 case BuiltinType::UFract:
1502 case BuiltinType::SatFract:
1503 case BuiltinType::SatUFract:
1504 return 2;
1505 case BuiltinType::LongFract:
1506 case BuiltinType::ULongFract:
1507 case BuiltinType::SatLongFract:
1508 case BuiltinType::SatULongFract:
1509 return 3;
1510 case BuiltinType::ShortAccum:
1511 case BuiltinType::UShortAccum:
1512 case BuiltinType::SatShortAccum:
1513 case BuiltinType::SatUShortAccum:
1514 return 4;
1515 case BuiltinType::Accum:
1516 case BuiltinType::UAccum:
1517 case BuiltinType::SatAccum:
1518 case BuiltinType::SatUAccum:
1519 return 5;
1520 case BuiltinType::LongAccum:
1521 case BuiltinType::ULongAccum:
1522 case BuiltinType::SatLongAccum:
1523 case BuiltinType::SatULongAccum:
1524 return 6;
1525 default:
1526 if (BTy->isInteger())
1527 return 0;
1528 llvm_unreachable("Unexpected fixed point or integer type");
1529 }
1530}
1531
1532/// handleFixedPointConversion - Fixed point operations between fixed
1533/// point types and integers or other fixed point types do not fall under
1534/// usual arithmetic conversion since these conversions could result in loss
1535/// of precsision (N1169 4.1.4). These operations should be calculated with
1536/// the full precision of their result type (N1169 4.1.6.2.1).
1537static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1538 QualType RHSTy) {
1539 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1540 "Expected at least one of the operands to be a fixed point type");
1541 assert((LHSTy->isFixedPointOrIntegerType() ||
1542 RHSTy->isFixedPointOrIntegerType()) &&
1543 "Special fixed point arithmetic operation conversions are only "
1544 "applied to ints or other fixed point types");
1545
1546 // If one operand has signed fixed-point type and the other operand has
1547 // unsigned fixed-point type, then the unsigned fixed-point operand is
1548 // converted to its corresponding signed fixed-point type and the resulting
1549 // type is the type of the converted operand.
1550 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1551 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1552 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1553 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1554
1555 // The result type is the type with the highest rank, whereby a fixed-point
1556 // conversion rank is always greater than an integer conversion rank; if the
1557 // type of either of the operands is a saturating fixedpoint type, the result
1558 // type shall be the saturating fixed-point type corresponding to the type
1559 // with the highest rank; the resulting value is converted (taking into
1560 // account rounding and overflow) to the precision of the resulting type.
1561 // Same ranks between signed and unsigned types are resolved earlier, so both
1562 // types are either signed or both unsigned at this point.
1563 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1564 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1565
1566 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1567
1568 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1569 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1570
1571 return ResultTy;
1572}
1573
1574/// Check that the usual arithmetic conversions can be performed on this pair of
1575/// expressions that might be of enumeration type.
1576void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1577 SourceLocation Loc,
1578 ArithConvKind ACK) {
1579 // C++2a [expr.arith.conv]p1:
1580 // If one operand is of enumeration type and the other operand is of a
1581 // different enumeration type or a floating-point type, this behavior is
1582 // deprecated ([depr.arith.conv.enum]).
1583 //
1584 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1585 // Eventually we will presumably reject these cases (in C++23 onwards?).
1586 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1587 R = RHS->getEnumCoercedType(Ctx: Context);
1588 bool LEnum = L->isUnscopedEnumerationType(),
1589 REnum = R->isUnscopedEnumerationType();
1590 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1591 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1592 (REnum && L->isFloatingType())) {
1593 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1594 : getLangOpts().CPlusPlus20
1595 ? diag::warn_arith_conv_enum_float_cxx20
1596 : diag::warn_arith_conv_enum_float)
1597 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1598 << L << R;
1599 } else if (!IsCompAssign && LEnum && REnum &&
1600 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1601 unsigned DiagID;
1602 // In C++ 26, usual arithmetic conversions between 2 different enum types
1603 // are ill-formed.
1604 if (getLangOpts().CPlusPlus26)
1605 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1606 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1607 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1608 // If either enumeration type is unnamed, it's less likely that the
1609 // user cares about this, but this situation is still deprecated in
1610 // C++2a. Use a different warning group.
1611 DiagID = getLangOpts().CPlusPlus20
1612 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1613 : diag::warn_arith_conv_mixed_anon_enum_types;
1614 } else if (ACK == ArithConvKind::Conditional) {
1615 // Conditional expressions are separated out because they have
1616 // historically had a different warning flag.
1617 DiagID = getLangOpts().CPlusPlus20
1618 ? diag::warn_conditional_mixed_enum_types_cxx20
1619 : diag::warn_conditional_mixed_enum_types;
1620 } else if (ACK == ArithConvKind::Comparison) {
1621 // Comparison expressions are separated out because they have
1622 // historically had a different warning flag.
1623 DiagID = getLangOpts().CPlusPlus20
1624 ? diag::warn_comparison_mixed_enum_types_cxx20
1625 : diag::warn_comparison_mixed_enum_types;
1626 } else {
1627 DiagID = getLangOpts().CPlusPlus20
1628 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1629 : diag::warn_arith_conv_mixed_enum_types;
1630 }
1631 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1632 << (int)ACK << L << R;
1633 }
1634}
1635
1636static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1637 Expr *RHS, SourceLocation Loc,
1638 ArithConvKind ACK) {
1639 QualType LHSType = LHS->getType().getUnqualifiedType();
1640 QualType RHSType = RHS->getType().getUnqualifiedType();
1641
1642 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1643 !RHSType->isUnicodeCharacterType())
1644 return;
1645
1646 if (ACK == ArithConvKind::Comparison) {
1647 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1648 return;
1649
1650 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1651 if (T->isChar8Type())
1652 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1653 if (T->isChar16Type())
1654 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1655 assert(T->isChar32Type());
1656 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1657 };
1658
1659 Expr::EvalResult LHSRes, RHSRes;
1660 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1661 AllowSideEffects: Expr::SE_AllowSideEffects,
1662 InConstantContext: SemaRef.isConstantEvaluatedContext());
1663 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1664 AllowSideEffects: Expr::SE_AllowSideEffects,
1665 InConstantContext: SemaRef.isConstantEvaluatedContext());
1666
1667 // Don't warn if the one known value is a representable
1668 // in the type of both expressions.
1669 if (LHSSuccess != RHSuccess) {
1670 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1671 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1672 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1673 return;
1674 }
1675
1676 if (!LHSSuccess || !RHSuccess) {
1677 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1678 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1679 << RHSType;
1680 return;
1681 }
1682
1683 llvm::APSInt LHSValue(32);
1684 LHSValue = LHSRes.Val.getInt();
1685 llvm::APSInt RHSValue(32);
1686 RHSValue = RHSRes.Val.getInt();
1687
1688 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1689 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1690 if (LHSSafe && RHSSafe)
1691 return;
1692
1693 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1694 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1695 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1696 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1697 return;
1698 }
1699
1700 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1701 return;
1702
1703 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1704 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1705 << RHSType;
1706}
1707
1708/// UsualArithmeticConversions - Performs various conversions that are common to
1709/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1710/// routine returns the first non-arithmetic type found. The client is
1711/// responsible for emitting appropriate error diagnostics.
1712QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1713 SourceLocation Loc,
1714 ArithConvKind ACK) {
1715
1716 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1717
1718 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1719
1720 if (ACK != ArithConvKind::CompAssign) {
1721 LHS = UsualUnaryConversions(E: LHS.get());
1722 if (LHS.isInvalid())
1723 return QualType();
1724 }
1725
1726 RHS = UsualUnaryConversions(E: RHS.get());
1727 if (RHS.isInvalid())
1728 return QualType();
1729
1730 // For conversion purposes, we ignore any qualifiers.
1731 // For example, "const float" and "float" are equivalent.
1732 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1733 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1734
1735 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1736 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1737 LHSType = AtomicLHS->getValueType();
1738
1739 // If both types are identical, no conversion is needed.
1740 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1741 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1742
1743 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1744 // The caller can deal with this (e.g. pointer + int).
1745 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1746 return QualType();
1747
1748 // Apply unary and bitfield promotions to the LHS's type.
1749 QualType LHSUnpromotedType = LHSType;
1750 if (Context.isPromotableIntegerType(T: LHSType))
1751 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1752 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1753 if (!LHSBitfieldPromoteTy.isNull())
1754 LHSType = LHSBitfieldPromoteTy;
1755 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1756 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1757
1758 // If both types are identical, no conversion is needed.
1759 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1760 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1761
1762 // At this point, we have two different arithmetic types.
1763
1764 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1765 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1766 return QualType();
1767
1768 // Diagnose attempts to convert between __ibm128, __float128 and long double
1769 // where such conversions currently can't be handled.
1770 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1771 return QualType();
1772
1773 // Handle complex types first (C99 6.3.1.8p1).
1774 if (LHSType->isComplexType() || RHSType->isComplexType())
1775 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1776 IsCompAssign: ACK == ArithConvKind::CompAssign);
1777
1778 // Now handle "real" floating types (i.e. float, double, long double).
1779 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1780 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1781 IsCompAssign: ACK == ArithConvKind::CompAssign);
1782
1783 // Handle GCC complex int extension.
1784 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1785 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1786 IsCompAssign: ACK == ArithConvKind::CompAssign);
1787
1788 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1789 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1790
1791 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1792 return handleOverflowBehaviorTypeConversion(
1793 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1794
1795 // Finally, we have two differing integer types.
1796 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1797 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1798}
1799
1800//===----------------------------------------------------------------------===//
1801// Semantic Analysis for various Expression Types
1802//===----------------------------------------------------------------------===//
1803
1804
1805ExprResult Sema::ActOnGenericSelectionExpr(
1806 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1807 bool PredicateIsExpr, void *ControllingExprOrType,
1808 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1809 unsigned NumAssocs = ArgTypes.size();
1810 assert(NumAssocs == ArgExprs.size());
1811
1812 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1813 for (unsigned i = 0; i < NumAssocs; ++i) {
1814 if (ArgTypes[i])
1815 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1816 else
1817 Types[i] = nullptr;
1818 }
1819
1820 // If we have a controlling type, we need to convert it from a parsed type
1821 // into a semantic type and then pass that along.
1822 if (!PredicateIsExpr) {
1823 TypeSourceInfo *ControllingType;
1824 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1825 TInfo: &ControllingType);
1826 assert(ControllingType && "couldn't get the type out of the parser");
1827 ControllingExprOrType = ControllingType;
1828 }
1829
1830 ExprResult ER = CreateGenericSelectionExpr(
1831 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1832 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1833 delete [] Types;
1834 return ER;
1835}
1836
1837// Helper function to determine type compatibility for C _Generic expressions.
1838// Multiple compatible types within the same _Generic expression is ambiguous
1839// and not valid.
1840static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1841 QualType U) {
1842 // Try to handle special types like OverflowBehaviorTypes
1843 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1844 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1845
1846 if (TOBT || UOBT) {
1847 if (TOBT && UOBT) {
1848 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1849 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1850 T2: UOBT->getUnderlyingType());
1851 return false;
1852 }
1853 return false;
1854 }
1855
1856 // We're dealing with types that don't require special handling.
1857 return Ctx.typesAreCompatible(T1: T, T2: U);
1858}
1859
1860ExprResult Sema::CreateGenericSelectionExpr(
1861 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1862 bool PredicateIsExpr, void *ControllingExprOrType,
1863 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1864 unsigned NumAssocs = Types.size();
1865 assert(NumAssocs == Exprs.size());
1866 assert(ControllingExprOrType &&
1867 "Must have either a controlling expression or a controlling type");
1868
1869 Expr *ControllingExpr = nullptr;
1870 TypeSourceInfo *ControllingType = nullptr;
1871 if (PredicateIsExpr) {
1872 // Decay and strip qualifiers for the controlling expression type, and
1873 // handle placeholder type replacement. See committee discussion from WG14
1874 // DR423.
1875 EnterExpressionEvaluationContext Unevaluated(
1876 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1877 ExprResult R = DefaultFunctionArrayLvalueConversion(
1878 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1879 if (R.isInvalid())
1880 return ExprError();
1881 ControllingExpr = R.get();
1882 } else {
1883 // The extension form uses the type directly rather than converting it.
1884 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1885 if (!ControllingType)
1886 return ExprError();
1887 }
1888
1889 bool TypeErrorFound = false,
1890 IsResultDependent = ControllingExpr
1891 ? ControllingExpr->isTypeDependent()
1892 : ControllingType->getType()->isDependentType(),
1893 ContainsUnexpandedParameterPack =
1894 ControllingExpr
1895 ? ControllingExpr->containsUnexpandedParameterPack()
1896 : ControllingType->getType()->containsUnexpandedParameterPack();
1897
1898 // The controlling expression is an unevaluated operand, so side effects are
1899 // likely unintended.
1900 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1901 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1902 Diag(Loc: ControllingExpr->getExprLoc(),
1903 DiagID: diag::warn_side_effects_unevaluated_context);
1904
1905 for (unsigned i = 0; i < NumAssocs; ++i) {
1906 if (Exprs[i]->containsUnexpandedParameterPack())
1907 ContainsUnexpandedParameterPack = true;
1908
1909 if (Types[i]) {
1910 if (Types[i]->getType()->containsUnexpandedParameterPack())
1911 ContainsUnexpandedParameterPack = true;
1912
1913 if (Types[i]->getType()->isDependentType()) {
1914 IsResultDependent = true;
1915 } else {
1916 // We relax the restriction on use of incomplete types and non-object
1917 // types with the type-based extension of _Generic. Allowing incomplete
1918 // objects means those can be used as "tags" for a type-safe way to map
1919 // to a value. Similarly, matching on function types rather than
1920 // function pointer types can be useful. However, the restriction on VM
1921 // types makes sense to retain as there are open questions about how
1922 // the selection can be made at compile time.
1923 //
1924 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1925 // complete object type other than a variably modified type."
1926 // C2y removed the requirement that an expression form must
1927 // use a complete type, though it's still as-if the type has undergone
1928 // lvalue conversion. We support this as an extension in C23 and
1929 // earlier because GCC does so.
1930 unsigned D = 0;
1931 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1932 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1933 : diag::compat_pre_c2y_assoc_type_incomplete;
1934 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1935 D = diag::err_assoc_type_nonobject;
1936 else if (Types[i]->getType()->isVariablyModifiedType())
1937 D = diag::err_assoc_type_variably_modified;
1938 else if (ControllingExpr) {
1939 // Because the controlling expression undergoes lvalue conversion,
1940 // array conversion, and function conversion, an association which is
1941 // of array type, function type, or is qualified can never be
1942 // reached. We will warn about this so users are less surprised by
1943 // the unreachable association. However, we don't have to handle
1944 // function types; that's not an object type, so it's handled above.
1945 //
1946 // The logic is somewhat different for C++ because C++ has different
1947 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1948 // If T is a non-class type, the type of the prvalue is the cv-
1949 // unqualified version of T. Otherwise, the type of the prvalue is T.
1950 // The result of these rules is that all qualified types in an
1951 // association in C are unreachable, and in C++, only qualified non-
1952 // class types are unreachable.
1953 //
1954 // NB: this does not apply when the first operand is a type rather
1955 // than an expression, because the type form does not undergo
1956 // conversion.
1957 unsigned Reason = 0;
1958 QualType QT = Types[i]->getType();
1959 if (QT->isArrayType())
1960 Reason = 1;
1961 else if (QT.hasQualifiers() &&
1962 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1963 Reason = 2;
1964
1965 if (Reason)
1966 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1967 DiagID: diag::warn_unreachable_association)
1968 << QT << (Reason - 1);
1969 }
1970
1971 if (D != 0) {
1972 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1973 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1974 if (getDiagnostics().getDiagnosticLevel(
1975 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1976 DiagnosticsEngine::Error)
1977 TypeErrorFound = true;
1978 }
1979
1980 // C11 6.5.1.1p2 "No two generic associations in the same generic
1981 // selection shall specify compatible types."
1982 for (unsigned j = i+1; j < NumAssocs; ++j)
1983 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1984 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1985 U: Types[j]->getType())) {
1986 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1987 DiagID: diag::err_assoc_compatible_types)
1988 << Types[j]->getTypeLoc().getSourceRange()
1989 << Types[j]->getType()
1990 << Types[i]->getType();
1991 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1992 DiagID: diag::note_compat_assoc)
1993 << Types[i]->getTypeLoc().getSourceRange()
1994 << Types[i]->getType();
1995 TypeErrorFound = true;
1996 }
1997 }
1998 }
1999 }
2000 if (TypeErrorFound)
2001 return ExprError();
2002
2003 // If we determined that the generic selection is result-dependent, don't
2004 // try to compute the result expression.
2005 if (IsResultDependent) {
2006 if (ControllingExpr)
2007 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
2008 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2009 ContainsUnexpandedParameterPack);
2010 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
2011 AssocExprs: Exprs, DefaultLoc, RParenLoc,
2012 ContainsUnexpandedParameterPack);
2013 }
2014
2015 SmallVector<unsigned, 1> CompatIndices;
2016 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2017 // Look at the canonical type of the controlling expression in case it was a
2018 // deduced type like __auto_type. However, when issuing diagnostics, use the
2019 // type the user wrote in source rather than the canonical one.
2020 for (unsigned i = 0; i < NumAssocs; ++i) {
2021 if (!Types[i])
2022 DefaultIndex = i;
2023 else {
2024 bool Compatible;
2025 QualType ControllingQT =
2026 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2027 : ControllingType->getType().getCanonicalType();
2028 QualType AssocQT = Types[i]->getType();
2029
2030 Compatible =
2031 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2032
2033 if (Compatible)
2034 CompatIndices.push_back(Elt: i);
2035 }
2036 }
2037
2038 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2039 TypeSourceInfo *ControllingType) {
2040 // We strip parens here because the controlling expression is typically
2041 // parenthesized in macro definitions.
2042 if (ControllingExpr)
2043 ControllingExpr = ControllingExpr->IgnoreParens();
2044
2045 SourceRange SR = ControllingExpr
2046 ? ControllingExpr->getSourceRange()
2047 : ControllingType->getTypeLoc().getSourceRange();
2048 QualType QT = ControllingExpr ? ControllingExpr->getType()
2049 : ControllingType->getType();
2050
2051 return std::make_pair(x&: SR, y&: QT);
2052 };
2053
2054 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2055 // type compatible with at most one of the types named in its generic
2056 // association list."
2057 if (CompatIndices.size() > 1) {
2058 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2059 SourceRange SR = P.first;
2060 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2061 << SR << P.second << (unsigned)CompatIndices.size();
2062 for (unsigned I : CompatIndices) {
2063 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2064 DiagID: diag::note_compat_assoc)
2065 << Types[I]->getTypeLoc().getSourceRange()
2066 << Types[I]->getType();
2067 }
2068 return ExprError();
2069 }
2070
2071 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2072 // its controlling expression shall have type compatible with exactly one of
2073 // the types named in its generic association list."
2074 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2075 CompatIndices.size() == 0) {
2076 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2077 SourceRange SR = P.first;
2078 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2079 return ExprError();
2080 }
2081
2082 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2083 // type name that is compatible with the type of the controlling expression,
2084 // then the result expression of the generic selection is the expression
2085 // in that generic association. Otherwise, the result expression of the
2086 // generic selection is the expression in the default generic association."
2087 unsigned ResultIndex =
2088 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2089
2090 if (ControllingExpr) {
2091 return GenericSelectionExpr::Create(
2092 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2093 ContainsUnexpandedParameterPack, ResultIndex);
2094 }
2095 return GenericSelectionExpr::Create(
2096 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2097 ContainsUnexpandedParameterPack, ResultIndex);
2098}
2099
2100static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2101 switch (Kind) {
2102 default:
2103 llvm_unreachable("unexpected TokenKind");
2104 case tok::kw___func__:
2105 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2106 case tok::kw___FUNCTION__:
2107 return PredefinedIdentKind::Function;
2108 case tok::kw___FUNCDNAME__:
2109 return PredefinedIdentKind::FuncDName; // [MS]
2110 case tok::kw___FUNCSIG__:
2111 return PredefinedIdentKind::FuncSig; // [MS]
2112 case tok::kw_L__FUNCTION__:
2113 return PredefinedIdentKind::LFunction; // [MS]
2114 case tok::kw_L__FUNCSIG__:
2115 return PredefinedIdentKind::LFuncSig; // [MS]
2116 case tok::kw___PRETTY_FUNCTION__:
2117 return PredefinedIdentKind::PrettyFunction; // [GNU]
2118 }
2119}
2120
2121/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2122/// to determine the value of a PredefinedExpr. This can be either a
2123/// block, lambda, captured statement, function, otherwise a nullptr.
2124static Decl *getPredefinedExprDecl(Sema &S, DeclContext *DC) {
2125 auto LSI = S.FunctionScopes.rbegin();
2126
2127 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2128 if (isLambdaCallOperator(DC)) {
2129 auto E = S.FunctionScopes.rend();
2130 while (LSI != E && !isa<LambdaScopeInfo>(Val: *LSI))
2131 ++LSI;
2132 assert(LSI != E && "Should be in a lambda scope info");
2133 if (dyn_cast<LambdaScopeInfo>(Val: *LSI)->BeforeCompoundStatement)
2134 DC = DC->getParent();
2135 ++LSI;
2136 }
2137 };
2138
2139 tryAdjustLambdaContext(DC);
2140 while (DC &&
2141 !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) {
2142 DC = DC->getParent();
2143 tryAdjustLambdaContext(DC);
2144 }
2145
2146 return cast_or_null<Decl>(Val: DC);
2147}
2148
2149/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2150/// location of the token and the offset of the ud-suffix within it.
2151static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2152 unsigned Offset) {
2153 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2154 LangOpts: S.getLangOpts());
2155}
2156
2157/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2158/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2159static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2160 IdentifierInfo *UDSuffix,
2161 SourceLocation UDSuffixLoc,
2162 ArrayRef<Expr*> Args,
2163 SourceLocation LitEndLoc) {
2164 assert(Args.size() <= 2 && "too many arguments for literal operator");
2165
2166 QualType ArgTy[2];
2167 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2168 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2169 if (ArgTy[ArgIdx]->isArrayType())
2170 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2171 }
2172
2173 DeclarationName OpName =
2174 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2175 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2176 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2177
2178 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2179 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2180 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2181 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2182 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2183 return ExprError();
2184
2185 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2186}
2187
2188ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2189 // StringToks needs backing storage as it doesn't hold array elements itself
2190 std::vector<Token> ExpandedToks;
2191 if (getLangOpts().MicrosoftExt)
2192 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2193
2194 StringLiteralParser Literal(StringToks, PP,
2195 StringLiteralEvalMethod::Unevaluated);
2196 if (Literal.hadError)
2197 return ExprError();
2198
2199 SmallVector<SourceLocation, 4> StringTokLocs;
2200 for (const Token &Tok : StringToks)
2201 StringTokLocs.push_back(Elt: Tok.getLocation());
2202
2203 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2204 Kind: StringLiteralKind::Unevaluated,
2205 Pascal: false, Ty: {}, Locs: StringTokLocs);
2206
2207 if (!Literal.getUDSuffix().empty()) {
2208 SourceLocation UDSuffixLoc =
2209 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2210 Offset: Literal.getUDSuffixOffset());
2211 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2212 }
2213
2214 return Lit;
2215}
2216
2217std::vector<Token>
2218Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2219 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2220 // local macros that expand to string literals that may be concatenated.
2221 // These macros are expanded here (in Sema), because StringLiteralParser
2222 // (in Lex) doesn't know the enclosing function (because it hasn't been
2223 // parsed yet).
2224 assert(getLangOpts().MicrosoftExt);
2225
2226 // Note: Although function local macros are defined only inside functions,
2227 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2228 // expansion of macros into empty string literals without additional checks.
2229 Decl *CurrentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
2230 if (!CurrentDecl)
2231 CurrentDecl = Context.getTranslationUnitDecl();
2232
2233 std::vector<Token> ExpandedToks;
2234 ExpandedToks.reserve(n: Toks.size());
2235 for (const Token &Tok : Toks) {
2236 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2237 assert(tok::isStringLiteral(Tok.getKind()));
2238 ExpandedToks.emplace_back(args: Tok);
2239 continue;
2240 }
2241 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2242 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2243 // Stringify predefined expression
2244 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2245 << Tok.getKind();
2246 SmallString<64> Str;
2247 llvm::raw_svector_ostream OS(Str);
2248 Token &Exp = ExpandedToks.emplace_back();
2249 Exp.startToken();
2250 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2251 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2252 OS << 'L';
2253 Exp.setKind(tok::wide_string_literal);
2254 } else {
2255 Exp.setKind(tok::string_literal);
2256 }
2257 OS << '"'
2258 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2259 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2260 << '"';
2261 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2262 }
2263 return ExpandedToks;
2264}
2265
2266ExprResult
2267Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2268 assert(!StringToks.empty() && "Must have at least one string!");
2269
2270 // StringToks needs backing storage as it doesn't hold array elements itself
2271 std::vector<Token> ExpandedToks;
2272 if (getLangOpts().MicrosoftExt)
2273 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2274
2275 StringLiteralParser Literal(
2276 StringToks, PP, StringLiteralEvalMethod::Evaluated, CA_ToLiteralEncoding);
2277 if (Literal.hadError)
2278 return ExprError();
2279
2280 SmallVector<SourceLocation, 4> StringTokLocs;
2281 for (const Token &Tok : StringToks)
2282 StringTokLocs.push_back(Elt: Tok.getLocation());
2283
2284 QualType CharTy = Context.CharTy;
2285 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2286 if (Literal.isWide()) {
2287 CharTy = Context.getWideCharType();
2288 Kind = StringLiteralKind::Wide;
2289 } else if (Literal.isUTF8()) {
2290 if (getLangOpts().Char8)
2291 CharTy = Context.Char8Ty;
2292 else if (getLangOpts().C23)
2293 CharTy = Context.UnsignedCharTy;
2294 Kind = StringLiteralKind::UTF8;
2295 } else if (Literal.isUTF16()) {
2296 CharTy = Context.Char16Ty;
2297 Kind = StringLiteralKind::UTF16;
2298 } else if (Literal.isUTF32()) {
2299 CharTy = Context.Char32Ty;
2300 Kind = StringLiteralKind::UTF32;
2301 } else if (Literal.isPascal()) {
2302 CharTy = Context.UnsignedCharTy;
2303 }
2304
2305 // Warn on u8 string literals before C++20 and C23, whose type
2306 // was an array of char before but becomes an array of char8_t.
2307 // In C++20, it cannot be used where a pointer to char is expected.
2308 // In C23, it might have an unexpected value if char was signed.
2309 if (Kind == StringLiteralKind::UTF8 &&
2310 (getLangOpts().CPlusPlus
2311 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2312 : !getLangOpts().C23)) {
2313 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2314 ? diag::warn_cxx20_compat_utf8_string
2315 : diag::warn_c23_compat_utf8_string);
2316
2317 // Create removals for all 'u8' prefixes in the string literal(s). This
2318 // ensures C++20/C23 compatibility (but may change the program behavior when
2319 // built by non-Clang compilers for which the execution character set is
2320 // not always UTF-8).
2321 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2322 SourceLocation RemovalDiagLoc;
2323 for (const Token &Tok : StringToks) {
2324 if (Tok.getKind() == tok::utf8_string_literal) {
2325 if (RemovalDiagLoc.isInvalid())
2326 RemovalDiagLoc = Tok.getLocation();
2327 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2328 B: Tok.getLocation(),
2329 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2330 SM: getSourceManager(), LangOpts: getLangOpts())));
2331 }
2332 }
2333 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2334 }
2335
2336 QualType StrTy =
2337 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2338
2339 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2340 StringLiteral *Lit = StringLiteral::Create(
2341 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2342 if (Literal.getUDSuffix().empty())
2343 return Lit;
2344
2345 // We're building a user-defined literal.
2346 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2347 SourceLocation UDSuffixLoc =
2348 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2349 Offset: Literal.getUDSuffixOffset());
2350
2351 // Make sure we're allowed user-defined literals here.
2352 if (!UDLScope)
2353 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2354
2355 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2356 // operator "" X (str, len)
2357 QualType SizeType = Context.getSizeType();
2358
2359 DeclarationName OpName =
2360 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2361 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2362 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2363
2364 QualType ArgTy[] = {
2365 Context.getArrayDecayedType(T: StrTy), SizeType
2366 };
2367
2368 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2369 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2370 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2371 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2372 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2373
2374 case LOLR_Cooked: {
2375 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2376 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2377 l: StringTokLocs[0]);
2378 Expr *Args[] = { Lit, LenArg };
2379
2380 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2381 }
2382
2383 case LOLR_Template: {
2384 TemplateArgumentListInfo ExplicitArgs;
2385 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2386 TemplateArgumentLocInfo ArgInfo(Lit);
2387 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2388 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2389 ExplicitTemplateArgs: &ExplicitArgs);
2390 }
2391
2392 case LOLR_StringTemplatePack: {
2393 TemplateArgumentListInfo ExplicitArgs;
2394
2395 unsigned CharBits = Context.getIntWidth(T: CharTy);
2396 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2397 llvm::APSInt Value(CharBits, CharIsUnsigned);
2398
2399 TemplateArgument TypeArg(CharTy);
2400 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2401 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2402
2403 SourceLocation Loc = StringTokLocs.back();
2404 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2405 Value = Lit->getCodeUnit(I);
2406 TemplateArgument Arg(Context, Value, CharTy);
2407 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2408 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2409 }
2410 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2411 }
2412 case LOLR_Raw:
2413 case LOLR_ErrorNoDiagnostic:
2414 llvm_unreachable("unexpected literal operator lookup result");
2415 case LOLR_Error:
2416 return ExprError();
2417 }
2418 llvm_unreachable("unexpected literal operator lookup result");
2419}
2420
2421DeclRefExpr *
2422Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2423 SourceLocation Loc,
2424 const CXXScopeSpec *SS) {
2425 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2426 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2427}
2428
2429DeclRefExpr *
2430Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2431 const DeclarationNameInfo &NameInfo,
2432 const CXXScopeSpec *SS, NamedDecl *FoundD,
2433 SourceLocation TemplateKWLoc,
2434 const TemplateArgumentListInfo *TemplateArgs) {
2435 NestedNameSpecifierLoc NNS =
2436 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2437 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2438 TemplateArgs);
2439}
2440
2441// CUDA/HIP: Check whether a captured reference variable is referencing a
2442// host variable in a device or host device lambda.
2443static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2444 VarDecl *VD) {
2445 if (!S.getLangOpts().CUDA || !VD->hasInit())
2446 return false;
2447 assert(VD->getType()->isReferenceType());
2448
2449 // Check whether the reference variable is referencing a host variable.
2450 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2451 if (!DRE)
2452 return false;
2453 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2454 if (!Referee || !Referee->hasGlobalStorage() ||
2455 Referee->hasAttr<CUDADeviceAttr>())
2456 return false;
2457
2458 // Check whether the current function is a device or host device lambda.
2459 // Check whether the reference variable is a capture by getDeclContext()
2460 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2461 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2462 if (MD && MD->getParent()->isLambda() &&
2463 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2464 VD->getDeclContext() != MD)
2465 return true;
2466
2467 return false;
2468}
2469
2470NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2471 // A declaration named in an unevaluated operand never constitutes an odr-use.
2472 if (isUnevaluatedContext())
2473 return NOUR_Unevaluated;
2474
2475 // C++2a [basic.def.odr]p4:
2476 // A variable x whose name appears as a potentially-evaluated expression e
2477 // is odr-used by e unless [...] x is a reference that is usable in
2478 // constant expressions.
2479 // CUDA/HIP:
2480 // If a reference variable referencing a host variable is captured in a
2481 // device or host device lambda, the value of the referee must be copied
2482 // to the capture and the reference variable must be treated as odr-use
2483 // since the value of the referee is not known at compile time and must
2484 // be loaded from the captured.
2485 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2486 if (VD->getType()->isReferenceType() &&
2487 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2488 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2489 VD->isUsableInConstantExpressions(C: Context))
2490 return NOUR_Constant;
2491 }
2492
2493 // All remaining non-variable cases constitute an odr-use. For variables, we
2494 // need to wait and see how the expression is used.
2495 return NOUR_None;
2496}
2497
2498DeclRefExpr *
2499Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2500 const DeclarationNameInfo &NameInfo,
2501 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2502 SourceLocation TemplateKWLoc,
2503 const TemplateArgumentListInfo *TemplateArgs) {
2504 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2505 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2506
2507 DeclRefExpr *E = DeclRefExpr::Create(
2508 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2509 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2510 MarkDeclRefReferenced(E);
2511
2512 // C++ [except.spec]p17:
2513 // An exception-specification is considered to be needed when:
2514 // - in an expression, the function is the unique lookup result or
2515 // the selected member of a set of overloaded functions.
2516 //
2517 // We delay doing this until after we've built the function reference and
2518 // marked it as used so that:
2519 // a) if the function is defaulted, we get errors from defining it before /
2520 // instead of errors from computing its exception specification, and
2521 // b) if the function is a defaulted comparison, we can use the body we
2522 // build when defining it as input to the exception specification
2523 // computation rather than computing a new body.
2524 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2525 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2526 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2527 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2528 }
2529 }
2530
2531 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2532 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2533 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2534 getCurFunction()->recordUseOfWeak(E);
2535
2536 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2537 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2538 FD = IFD->getAnonField();
2539 if (FD) {
2540 UnusedPrivateFields.remove(X: FD);
2541 // Just in case we're building an illegal pointer-to-member.
2542 if (FD->isBitField())
2543 E->setObjectKind(OK_BitField);
2544 }
2545
2546 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2547 // designates a bit-field.
2548 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2549 if (const auto *BE = BD->getBinding())
2550 E->setObjectKind(BE->getObjectKind());
2551
2552 return E;
2553}
2554
2555// Diagnose when a macro cannot be expanded because it's a function-like macro
2556// being used as a function-like macro. Returns true if a diagnostic is emitted.
2557static bool diagnoseFunctionLikeMacro(Sema &SemaRef, DeclarationName Name,
2558 SourceLocation TypoLoc) {
2559
2560 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2561 if (II->hasMacroDefinition()) {
2562 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2563 if (MI && MI->isFunctionLike()) {
2564 // If the identifier is immediately followed by '(', the user did
2565 // attempt to invoke it as a function-like macro; the failure is
2566 // for some other reason (e.g. wrong argument count), which the
2567 // preprocessor already diagnosed separately. Don't suggest adding
2568 // parens in that case, since they're already there.
2569 SourceManager &SM = SemaRef.getSourceManager();
2570 const LangOptions &LangOpts = SemaRef.getLangOpts();
2571 std::optional<Token> NextTok =
2572 Lexer::findNextToken(Loc: TypoLoc, SM, LangOpts);
2573 if (NextTok && NextTok->is(K: tok::l_paren))
2574 return false;
2575 SemaRef.Diag(Loc: TypoLoc,
2576 DiagID: diag::err_undeclared_var_use_suggest_func_like_macro)
2577 << II->getName();
2578 SemaRef.Diag(Loc: MI->getDefinitionLoc(),
2579 DiagID: diag::note_function_like_macro_requires_parens)
2580 << II->getName();
2581 return true;
2582 }
2583 }
2584 }
2585 return false;
2586}
2587
2588void
2589Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2590 TemplateArgumentListInfo &Buffer,
2591 DeclarationNameInfo &NameInfo,
2592 const TemplateArgumentListInfo *&TemplateArgs) {
2593 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2594 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2595 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2596
2597 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2598 Id.TemplateId->NumArgs);
2599 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2600
2601 TemplateName TName = Id.TemplateId->Template.get();
2602 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2603 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2604 TemplateArgs = &Buffer;
2605 } else {
2606 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2607 TemplateArgs = nullptr;
2608 }
2609}
2610
2611bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2612 // During a default argument instantiation the CurContext points
2613 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2614 // function parameter list, hence add an explicit check.
2615 bool isDefaultArgument =
2616 !CodeSynthesisContexts.empty() &&
2617 CodeSynthesisContexts.back().Kind ==
2618 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2619 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2620 bool isInstance = CurMethod && CurMethod->isInstance() &&
2621 R.getNamingClass() == CurMethod->getParent() &&
2622 !isDefaultArgument;
2623
2624 // There are two ways we can find a class-scope declaration during template
2625 // instantiation that we did not find in the template definition: if it is a
2626 // member of a dependent base class, or if it is declared after the point of
2627 // use in the same class. Distinguish these by comparing the class in which
2628 // the member was found to the naming class of the lookup.
2629 unsigned DiagID = diag::err_found_in_dependent_base;
2630 unsigned NoteID = diag::note_member_declared_at;
2631 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2632 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2633 : diag::err_found_later_in_class;
2634 } else if (getLangOpts().MSVCCompat) {
2635 DiagID = diag::ext_found_in_dependent_base;
2636 NoteID = diag::note_dependent_member_use;
2637 }
2638
2639 if (isInstance) {
2640 // Give a code modification hint to insert 'this->'.
2641 Diag(Loc: R.getNameLoc(), DiagID)
2642 << R.getLookupName()
2643 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2644 CheckCXXThisCapture(Loc: R.getNameLoc());
2645 } else {
2646 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2647 // they're not shadowed).
2648 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2649 }
2650
2651 for (const NamedDecl *D : R)
2652 Diag(Loc: D->getLocation(), DiagID: NoteID);
2653
2654 // Return true if we are inside a default argument instantiation
2655 // and the found name refers to an instance member function, otherwise
2656 // the caller will try to create an implicit member call and this is wrong
2657 // for default arguments.
2658 //
2659 // FIXME: Is this special case necessary? We could allow the caller to
2660 // diagnose this.
2661 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2662 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2663 return true;
2664 }
2665
2666 // Tell the callee to try to recover.
2667 return false;
2668}
2669
2670bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2671 CorrectionCandidateCallback &CCC,
2672 TemplateArgumentListInfo *ExplicitTemplateArgs,
2673 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2674 DeclarationName Name = R.getLookupName();
2675 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2676
2677 unsigned diagnostic = diag::err_undeclared_var_use;
2678 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2679 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2680 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2681 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2682 diagnostic = diag::err_undeclared_use;
2683 diagnostic_suggest = diag::err_undeclared_use_suggest;
2684 }
2685
2686 // If the original lookup was an unqualified lookup, fake an
2687 // unqualified lookup. This is useful when (for example) the
2688 // original lookup would not have found something because it was a
2689 // dependent name.
2690 DeclContext *DC =
2691 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2692 while (DC) {
2693 if (isa<CXXRecordDecl>(Val: DC)) {
2694 if (ExplicitTemplateArgs) {
2695 if (LookupTemplateName(
2696 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2697 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2698 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2699 return true;
2700 } else {
2701 LookupQualifiedName(R, LookupCtx: DC);
2702 }
2703
2704 if (!R.empty()) {
2705 // Don't give errors about ambiguities in this lookup.
2706 R.suppressDiagnostics();
2707
2708 // If there's a best viable function among the results, only mention
2709 // that one in the notes.
2710 OverloadCandidateSet Candidates(R.getNameLoc(),
2711 OverloadCandidateSet::CSK_Normal);
2712 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2713 OverloadCandidateSet::iterator Best;
2714 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2715 OR_Success) {
2716 R.clear();
2717 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2718 R.resolveKind();
2719 }
2720
2721 return DiagnoseDependentMemberLookup(R);
2722 }
2723
2724 R.clear();
2725 }
2726
2727 DC = DC->getLookupParent();
2728 }
2729
2730 // We didn't find anything, so try to correct for a typo.
2731 TypoCorrection Corrected;
2732 if (S && (Corrected =
2733 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2734 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2735 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2736 bool DroppedSpecifier =
2737 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2738 R.setLookupName(Corrected.getCorrection());
2739
2740 bool AcceptableWithRecovery = false;
2741 bool AcceptableWithoutRecovery = false;
2742 NamedDecl *ND = Corrected.getFoundDecl();
2743 if (ND) {
2744 if (Corrected.isOverloaded()) {
2745 OverloadCandidateSet OCS(R.getNameLoc(),
2746 OverloadCandidateSet::CSK_Normal);
2747 OverloadCandidateSet::iterator Best;
2748 for (NamedDecl *CD : Corrected) {
2749 if (FunctionTemplateDecl *FTD =
2750 dyn_cast<FunctionTemplateDecl>(Val: CD))
2751 AddTemplateOverloadCandidate(
2752 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2753 Args, CandidateSet&: OCS);
2754 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2755 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2756 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2757 Args, CandidateSet&: OCS);
2758 }
2759 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2760 case OR_Success:
2761 ND = Best->FoundDecl;
2762 Corrected.setCorrectionDecl(ND);
2763 break;
2764 default:
2765 // FIXME: Arbitrarily pick the first declaration for the note.
2766 Corrected.setCorrectionDecl(ND);
2767 break;
2768 }
2769 }
2770 R.addDecl(D: ND);
2771 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2772 CXXRecordDecl *Record =
2773 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2774 if (!Record)
2775 Record = cast<CXXRecordDecl>(
2776 Val: ND->getDeclContext()->getRedeclContext());
2777 R.setNamingClass(Record);
2778 }
2779
2780 auto *UnderlyingND = ND->getUnderlyingDecl();
2781 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2782 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2783 // FIXME: If we ended up with a typo for a type name or
2784 // Objective-C class name, we're in trouble because the parser
2785 // is in the wrong place to recover. Suggest the typo
2786 // correction, but don't make it a fix-it since we're not going
2787 // to recover well anyway.
2788 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2789 getAsTypeTemplateDecl(D: UnderlyingND) ||
2790 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2791 } else {
2792 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2793 // because we aren't able to recover.
2794 AcceptableWithoutRecovery = true;
2795 }
2796
2797 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2798 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2799 ? diag::note_implicit_param_decl
2800 : diag::note_previous_decl;
2801 if (SS.isEmpty())
2802 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2803 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2804 else
2805 diagnoseTypo(Correction: Corrected,
2806 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2807 << Name << computeDeclContext(SS, EnteringContext: false)
2808 << DroppedSpecifier << NameRange,
2809 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2810
2811 if (Corrected.WillReplaceSpecifier()) {
2812 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2813 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2814 SS.MakeTrivial(Context, Qualifier: NNS,
2815 R: NNS ? NameRange.getBegin() : SourceRange());
2816 }
2817
2818 // Tell the callee whether to try to recover.
2819 return !AcceptableWithRecovery;
2820 }
2821 }
2822 R.clear();
2823
2824 if (diagnoseFunctionLikeMacro(SemaRef, Name, TypoLoc: R.getNameLoc()))
2825 return true;
2826
2827 // Emit a special diagnostic for failed member lookups.
2828 // FIXME: computing the declaration context might fail here (?)
2829 if (!SS.isEmpty()) {
2830 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2831 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2832 return true;
2833 }
2834
2835 // Give up, we can't recover.
2836 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2837 return true;
2838}
2839
2840/// In Microsoft mode, if we are inside a template class whose parent class has
2841/// dependent base classes, and we can't resolve an unqualified identifier, then
2842/// assume the identifier is a member of a dependent base class. We can only
2843/// recover successfully in static methods, instance methods, and other contexts
2844/// where 'this' is available. This doesn't precisely match MSVC's
2845/// instantiation model, but it's close enough.
2846static Expr *
2847recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2848 DeclarationNameInfo &NameInfo,
2849 SourceLocation TemplateKWLoc,
2850 const TemplateArgumentListInfo *TemplateArgs) {
2851 // Only try to recover from lookup into dependent bases in static methods or
2852 // contexts where 'this' is available.
2853 QualType ThisType = S.getCurrentThisType();
2854 const CXXRecordDecl *RD = nullptr;
2855 if (!ThisType.isNull())
2856 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2857 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2858 RD = MD->getParent();
2859 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2860 return nullptr;
2861
2862 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2863 // is available, suggest inserting 'this->' as a fixit.
2864 SourceLocation Loc = NameInfo.getLoc();
2865 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2866 DB << NameInfo.getName() << RD;
2867
2868 if (!ThisType.isNull()) {
2869 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2870 return CXXDependentScopeMemberExpr::Create(
2871 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2872 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2873 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2874 }
2875
2876 // Synthesize a fake NNS that points to the derived class. This will
2877 // perform name lookup during template instantiation.
2878 CXXScopeSpec SS;
2879 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2880 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2881 return DependentScopeDeclRefExpr::Create(
2882 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2883 TemplateArgs);
2884}
2885
2886ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2887 SourceLocation TemplateKWLoc,
2888 UnqualifiedId &Id, bool HasTrailingLParen,
2889 bool IsAddressOfOperand,
2890 CorrectionCandidateCallback *CCC,
2891 bool IsInlineAsmIdentifier) {
2892 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2893 "cannot be direct & operand and have a trailing lparen");
2894 if (SS.isInvalid())
2895 return ExprError();
2896
2897 TemplateArgumentListInfo TemplateArgsBuffer;
2898
2899 // Decompose the UnqualifiedId into the following data.
2900 DeclarationNameInfo NameInfo;
2901 const TemplateArgumentListInfo *TemplateArgs;
2902 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2903
2904 DeclarationName Name = NameInfo.getName();
2905 IdentifierInfo *II = Name.getAsIdentifierInfo();
2906 SourceLocation NameLoc = NameInfo.getLoc();
2907
2908 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId &&
2909 Id.TemplateId->Template)
2910 if (TemplateName TN = Id.TemplateId->Template.get();
2911 TN.getAsPackIndexingTemplate())
2912 return CheckVarOrConceptTemplateTemplateId(NameInfo, Template: TN, TemplateArgs);
2913
2914 if (II && II->isEditorPlaceholder()) {
2915 // FIXME: When typed placeholders are supported we can create a typed
2916 // placeholder expression node.
2917 return ExprError();
2918 }
2919
2920 // This specially handles arguments of attributes appertains to a type of C
2921 // struct field such that the name lookup within a struct finds the member
2922 // name, which is not the case for other contexts in C.
2923 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2924 // See if this is reference to a field of struct.
2925 LookupResult R(*this, NameInfo, LookupMemberName);
2926 // LookupName handles a name lookup from within anonymous struct.
2927 if (LookupName(R, S)) {
2928 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2929 QualType type = VD->getType().getNonReferenceType();
2930 // This will eventually be translated into MemberExpr upon
2931 // the use of instantiated struct fields.
2932 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2933 }
2934 }
2935 }
2936
2937 // Perform the required lookup.
2938 LookupResult R(*this, NameInfo,
2939 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2940 ? LookupObjCImplicitSelfParam
2941 : LookupOrdinaryName);
2942 if (TemplateKWLoc.isValid() || TemplateArgs) {
2943 // Lookup the template name again to correctly establish the context in
2944 // which it was found. This is really unfortunate as we already did the
2945 // lookup to determine that it was a template name in the first place. If
2946 // this becomes a performance hit, we can work harder to preserve those
2947 // results until we get here but it's likely not worth it.
2948 AssumedTemplateKind AssumedTemplate;
2949 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2950 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2951 ATK: &AssumedTemplate))
2952 return ExprError();
2953
2954 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2955 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2956 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2957 } else {
2958 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2959 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2960 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2961
2962 // If the result might be in a dependent base class, this is a dependent
2963 // id-expression.
2964 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2965 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2966 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2967
2968 // If this reference is in an Objective-C method, then we need to do
2969 // some special Objective-C lookup, too.
2970 if (IvarLookupFollowUp) {
2971 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2972 if (E.isInvalid())
2973 return ExprError();
2974
2975 if (Expr *Ex = E.getAs<Expr>())
2976 return Ex;
2977 }
2978 }
2979
2980 if (R.isAmbiguous())
2981 return ExprError();
2982
2983 // This could be an implicitly declared function reference if the language
2984 // mode allows it as a feature.
2985 if (R.empty() && HasTrailingLParen && II &&
2986 getLangOpts().implicitFunctionsAllowed()) {
2987 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2988 if (D) R.addDecl(D);
2989 }
2990
2991 // Determine whether this name might be a candidate for
2992 // argument-dependent lookup.
2993 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2994
2995 if (R.empty() && !ADL) {
2996 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2997 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2998 TemplateKWLoc, TemplateArgs))
2999 return E;
3000 }
3001
3002 // Don't diagnose an empty lookup for inline assembly.
3003 if (IsInlineAsmIdentifier)
3004 return ExprError();
3005
3006 // If this name wasn't predeclared and if this is not a function
3007 // call, diagnose the problem.
3008 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3009 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3010 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3011 "Typo correction callback misconfigured");
3012 if (CCC) {
3013 // Make sure the callback knows what the typo being diagnosed is.
3014 CCC->setTypoName(II);
3015 if (SS.isValid())
3016 CCC->setTypoNNS(SS.getScopeRep());
3017 }
3018 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3019 // a template name, but we happen to have always already looked up the name
3020 // before we get here if it must be a template name.
3021 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
3022 Args: {}, LookupCtx: nullptr))
3023 return ExprError();
3024
3025 assert(!R.empty() &&
3026 "DiagnoseEmptyLookup returned false but added no results");
3027
3028 // If we found an Objective-C instance variable, let
3029 // LookupInObjCMethod build the appropriate expression to
3030 // reference the ivar.
3031 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3032 R.clear();
3033 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
3034 // In a hopelessly buggy code, Objective-C instance variable
3035 // lookup fails and no expression will be built to reference it.
3036 if (!E.isInvalid() && !E.get())
3037 return ExprError();
3038 return E;
3039 }
3040 }
3041
3042 // This is guaranteed from this point on.
3043 assert(!R.empty() || ADL);
3044
3045 // Check whether this might be a C++ implicit instance member access.
3046 // C++ [class.mfct.non-static]p3:
3047 // When an id-expression that is not part of a class member access
3048 // syntax and not used to form a pointer to member is used in the
3049 // body of a non-static member function of class X, if name lookup
3050 // resolves the name in the id-expression to a non-static non-type
3051 // member of some class C, the id-expression is transformed into a
3052 // class member access expression using (*this) as the
3053 // postfix-expression to the left of the . operator.
3054 //
3055 // But we don't actually need to do this for '&' operands if R
3056 // resolved to a function or overloaded function set, because the
3057 // expression is ill-formed if it actually works out to be a
3058 // non-static member function:
3059 //
3060 // C++ [expr.ref]p4:
3061 // Otherwise, if E1.E2 refers to a non-static member function. . .
3062 // [t]he expression can be used only as the left-hand operand of a
3063 // member function call.
3064 //
3065 // There are other safeguards against such uses, but it's important
3066 // to get this right here so that we don't end up making a
3067 // spuriously dependent expression if we're inside a dependent
3068 // instance method.
3069 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3070 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3071 S);
3072
3073 if (TemplateArgs || TemplateKWLoc.isValid()) {
3074
3075 // In C++1y, if this is a variable template id, then check it
3076 // in BuildTemplateIdExpr().
3077 // The single lookup result must be a variable template declaration.
3078 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3079 (Id.TemplateId->Kind == TNK_Var_template ||
3080 Id.TemplateId->Kind == TNK_Concept_template)) {
3081 assert(R.getAsSingle<TemplateDecl>() &&
3082 "There should only be one declaration found.");
3083 }
3084
3085 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3086 }
3087
3088 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3089}
3090
3091ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3092 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3093 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3094 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3095 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3096
3097 if (R.isAmbiguous())
3098 return ExprError();
3099
3100 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3101 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3102 NameInfo, /*TemplateArgs=*/nullptr);
3103
3104 if (R.empty()) {
3105 // Don't diagnose problems with invalid record decl, the secondary no_member
3106 // diagnostic during template instantiation is likely bogus, e.g. if a class
3107 // is invalid because it's derived from an invalid base class, then missing
3108 // members were likely supposed to be inherited.
3109 DeclContext *DC = computeDeclContext(SS);
3110 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3111 if (CD->isInvalidDecl() || CD->isBeingDefined())
3112 return ExprError();
3113 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3114 << NameInfo.getName() << DC << SS.getRange();
3115 return ExprError();
3116 }
3117
3118 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3119 QualType ET;
3120 TypeLocBuilder TLB;
3121 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3122 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3123 Qualifier: SS.getScopeRep(), TD: TagD,
3124 /*OwnsTag=*/false);
3125 auto TL = TLB.push<TagTypeLoc>(T: ET);
3126 TL.setElaboratedKeywordLoc(SourceLocation());
3127 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3128 TL.setNameLoc(NameInfo.getLoc());
3129 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3130 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3131 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3132 TLB.push<TypedefTypeLoc>(T: ET).set(
3133 /*ElaboratedKeywordLoc=*/SourceLocation(),
3134 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3135 } else {
3136 // FIXME: What else can appear here?
3137 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3138 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3139 assert(SS.isEmpty());
3140 }
3141
3142 // Diagnose a missing typename if this resolved unambiguously to a type in
3143 // a dependent context. If we can recover with a type, downgrade this to
3144 // a warning in Microsoft compatibility mode.
3145 unsigned DiagID = diag::err_typename_missing;
3146 if (RecoveryTSI && getLangOpts().MSVCCompat)
3147 DiagID = diag::ext_typename_missing;
3148 SourceLocation Loc = SS.getBeginLoc();
3149 auto D = Diag(Loc, DiagID);
3150 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3151
3152 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3153 // context.
3154 if (!RecoveryTSI)
3155 return ExprError();
3156
3157 // Only issue the fixit if we're prepared to recover.
3158 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3159
3160 // Recover by pretending this was an elaborated type.
3161 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3162
3163 return ExprEmpty();
3164 }
3165
3166 // If necessary, build an implicit class member access.
3167 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3168 return BuildPossibleImplicitMemberExpr(SS,
3169 /*TemplateKWLoc=*/SourceLocation(),
3170 R, /*TemplateArgs=*/nullptr,
3171 /*S=*/nullptr);
3172
3173 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3174}
3175
3176ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3177 NestedNameSpecifier Qualifier,
3178 NamedDecl *FoundDecl,
3179 NamedDecl *Member) {
3180 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3181 if (!RD)
3182 return From;
3183
3184 QualType DestRecordType;
3185 QualType DestType;
3186 QualType FromRecordType;
3187 QualType FromType = From->getType();
3188 bool PointerConversions = false;
3189 if (isa<FieldDecl>(Val: Member)) {
3190 DestRecordType = Context.getCanonicalTagType(TD: RD);
3191 auto FromPtrType = FromType->getAs<PointerType>();
3192 DestRecordType = Context.getAddrSpaceQualType(
3193 T: DestRecordType, AddressSpace: FromPtrType
3194 ? FromType->getPointeeType().getAddressSpace()
3195 : FromType.getAddressSpace());
3196
3197 if (FromPtrType) {
3198 DestType = Context.getPointerType(T: DestRecordType);
3199 FromRecordType = FromPtrType->getPointeeType();
3200 PointerConversions = true;
3201 } else {
3202 DestType = DestRecordType;
3203 FromRecordType = FromType;
3204 }
3205 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3206 if (!Method->isImplicitObjectMemberFunction())
3207 return From;
3208
3209 DestType = Method->getThisType().getNonReferenceType();
3210 DestRecordType = Method->getFunctionObjectParameterType();
3211
3212 if (FromType->getAs<PointerType>()) {
3213 FromRecordType = FromType->getPointeeType();
3214 PointerConversions = true;
3215 } else {
3216 FromRecordType = FromType;
3217 DestType = DestRecordType;
3218 }
3219
3220 LangAS FromAS = FromRecordType.getAddressSpace();
3221 LangAS DestAS = DestRecordType.getAddressSpace();
3222 if (FromAS != DestAS) {
3223 QualType FromRecordTypeWithoutAS =
3224 Context.removeAddrSpaceQualType(T: FromRecordType);
3225 QualType FromTypeWithDestAS =
3226 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3227 if (PointerConversions)
3228 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3229 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3230 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3231 .get();
3232 }
3233 } else {
3234 // No conversion necessary.
3235 return From;
3236 }
3237
3238 if (DestType->isDependentType() || FromType->isDependentType())
3239 return From;
3240
3241 // If the unqualified types are the same, no conversion is necessary.
3242 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3243 return From;
3244
3245 SourceRange FromRange = From->getSourceRange();
3246 SourceLocation FromLoc = FromRange.getBegin();
3247
3248 ExprValueKind VK = From->getValueKind();
3249
3250 // C++ [class.member.lookup]p8:
3251 // [...] Ambiguities can often be resolved by qualifying a name with its
3252 // class name.
3253 //
3254 // If the member was a qualified name and the qualified referred to a
3255 // specific base subobject type, we'll cast to that intermediate type
3256 // first and then to the object in which the member is declared. That allows
3257 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3258 //
3259 // class Base { public: int x; };
3260 // class Derived1 : public Base { };
3261 // class Derived2 : public Base { };
3262 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3263 //
3264 // void VeryDerived::f() {
3265 // x = 17; // error: ambiguous base subobjects
3266 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3267 // }
3268 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3269 QualType QType = QualType(Qualifier.getAsType(), 0);
3270 assert(QType->isRecordType() && "lookup done with non-record type");
3271
3272 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3273
3274 // In C++98, the qualifier type doesn't actually have to be a base
3275 // type of the object type, in which case we just ignore it.
3276 // Otherwise build the appropriate casts.
3277 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3278 CXXCastPath BasePath;
3279 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3280 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3281 return ExprError();
3282
3283 if (PointerConversions)
3284 QType = Context.getPointerType(T: QType);
3285 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3286 VK, BasePath: &BasePath).get();
3287
3288 FromType = QType;
3289 FromRecordType = QRecordType;
3290
3291 // If the qualifier type was the same as the destination type,
3292 // we're done.
3293 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3294 return From;
3295 }
3296 }
3297
3298 CXXCastPath BasePath;
3299 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3300 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3301 /*IgnoreAccess=*/true))
3302 return ExprError();
3303
3304 // Propagate qualifiers to base subobjects as per:
3305 // C++ [basic.type.qualifier]p1.2:
3306 // A volatile object is [...] a subobject of a volatile object.
3307 Qualifiers FromTypeQuals = FromType.getQualifiers();
3308 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3309 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3310
3311 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3312 BasePath: &BasePath);
3313}
3314
3315bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3316 const LookupResult &R,
3317 bool HasTrailingLParen) {
3318 // Only when used directly as the postfix-expression of a call.
3319 if (!HasTrailingLParen)
3320 return false;
3321
3322 // Never if a scope specifier was provided.
3323 if (SS.isNotEmpty())
3324 return false;
3325
3326 // Only in C++ or ObjC++.
3327 if (!getLangOpts().CPlusPlus)
3328 return false;
3329
3330 // Turn off ADL when we find certain kinds of declarations during
3331 // normal lookup:
3332 for (const NamedDecl *D : R) {
3333 // C++0x [basic.lookup.argdep]p3:
3334 // -- a declaration of a class member
3335 // Since using decls preserve this property, we check this on the
3336 // original decl.
3337 if (D->isCXXClassMember())
3338 return false;
3339
3340 // C++0x [basic.lookup.argdep]p3:
3341 // -- a block-scope function declaration that is not a
3342 // using-declaration
3343 // NOTE: we also trigger this for function templates (in fact, we
3344 // don't check the decl type at all, since all other decl types
3345 // turn off ADL anyway).
3346 if (isa<UsingShadowDecl>(Val: D))
3347 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3348 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3349 return false;
3350
3351 // C++0x [basic.lookup.argdep]p3:
3352 // -- a declaration that is neither a function or a function
3353 // template
3354 // And also for builtin functions.
3355 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3356 // But also builtin functions.
3357 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3358 return false;
3359 } else if (!isa<FunctionTemplateDecl>(Val: D))
3360 return false;
3361 }
3362
3363 return true;
3364}
3365
3366
3367/// Diagnoses obvious problems with the use of the given declaration
3368/// as an expression. This is only actually called for lookups that
3369/// were not overloaded, and it doesn't promise that the declaration
3370/// will in fact be used.
3371static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3372 bool AcceptInvalid) {
3373 if (D->isInvalidDecl() && !AcceptInvalid)
3374 return true;
3375
3376 if (isa<TypedefNameDecl>(Val: D)) {
3377 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3378 return true;
3379 }
3380
3381 if (isa<ObjCInterfaceDecl>(Val: D)) {
3382 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3383 return true;
3384 }
3385
3386 if (isa<NamespaceDecl>(Val: D)) {
3387 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3388 return true;
3389 }
3390
3391 return false;
3392}
3393
3394// Certain multiversion types should be treated as overloaded even when there is
3395// only one result.
3396static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3397 assert(R.isSingleResult() && "Expected only a single result");
3398 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3399 return FD &&
3400 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3401}
3402
3403ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3404 LookupResult &R, bool NeedsADL,
3405 bool AcceptInvalidDecl) {
3406 // If this is a single, fully-resolved result and we don't need ADL,
3407 // just build an ordinary singleton decl ref.
3408 if (!NeedsADL && R.isSingleResult() &&
3409 !R.getAsSingle<FunctionTemplateDecl>() &&
3410 !ShouldLookupResultBeMultiVersionOverload(R))
3411 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3412 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3413 AcceptInvalidDecl);
3414
3415 // We only need to check the declaration if there's exactly one
3416 // result, because in the overloaded case the results can only be
3417 // functions and function templates.
3418 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3419 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3420 AcceptInvalid: AcceptInvalidDecl))
3421 return ExprError();
3422
3423 // Otherwise, just build an unresolved lookup expression. Suppress
3424 // any lookup-related diagnostics; we'll hash these out later, when
3425 // we've picked a target.
3426 R.suppressDiagnostics();
3427
3428 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3429 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3430 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3431 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3432
3433 return ULE;
3434}
3435
3436ExprResult Sema::BuildDeclarationNameExpr(
3437 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3438 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3439 bool AcceptInvalidDecl) {
3440 assert(D && "Cannot refer to a NULL declaration");
3441 assert(!isa<FunctionTemplateDecl>(D) &&
3442 "Cannot refer unambiguously to a function template");
3443
3444 SourceLocation Loc = NameInfo.getLoc();
3445 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3446 // Recovery from invalid cases (e.g. D is an invalid Decl).
3447 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3448 // diagnostics, as invalid decls use int as a fallback type.
3449 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3450 }
3451
3452 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3453 // Specifically diagnose references to class templates that are missing
3454 // a template argument list.
3455 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3456 return ExprError();
3457 }
3458
3459 // Make sure that we're referring to a value.
3460 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3461 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3462 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3463 return ExprError();
3464 }
3465
3466 // Check whether this declaration can be used. Note that we suppress
3467 // this check when we're going to perform argument-dependent lookup
3468 // on this function name, because this might not be the function
3469 // that overload resolution actually selects.
3470 if (DiagnoseUseOfDecl(D, Locs: Loc))
3471 return ExprError();
3472
3473 auto *VD = cast<ValueDecl>(Val: D);
3474
3475 // Only create DeclRefExpr's for valid Decl's.
3476 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3477 return ExprError();
3478
3479 // Handle members of anonymous structs and unions. If we got here,
3480 // and the reference is to a class member indirect field, then this
3481 // must be the subject of a pointer-to-member expression.
3482 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3483 IndirectField && !IndirectField->isCXXClassMember())
3484 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3485 indirectField: IndirectField);
3486
3487 QualType type = VD->getType();
3488 if (type.isNull())
3489 return ExprError();
3490 ExprValueKind valueKind = VK_PRValue;
3491
3492 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3493 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3494 // is expanded by some outer '...' in the context of the use.
3495 type = type.getNonPackExpansionType();
3496
3497 switch (D->getKind()) {
3498 // Ignore all the non-ValueDecl kinds.
3499#define ABSTRACT_DECL(kind)
3500#define VALUE(type, base)
3501#define DECL(type, base) case Decl::type:
3502#include "clang/AST/DeclNodes.inc"
3503 llvm_unreachable("invalid value decl kind");
3504
3505 // These shouldn't make it here.
3506 case Decl::ObjCAtDefsField:
3507 llvm_unreachable("forming non-member reference to ivar?");
3508
3509 // Enum constants are always r-values and never references.
3510 // Unresolved using declarations are dependent.
3511 case Decl::EnumConstant:
3512 case Decl::UnresolvedUsingValue:
3513 case Decl::OMPDeclareReduction:
3514 case Decl::OMPDeclareMapper:
3515 valueKind = VK_PRValue;
3516 break;
3517
3518 // Fields and indirect fields that got here must be for
3519 // pointer-to-member expressions; we just call them l-values for
3520 // internal consistency, because this subexpression doesn't really
3521 // exist in the high-level semantics.
3522 case Decl::Field:
3523 case Decl::IndirectField:
3524 case Decl::ObjCIvar:
3525 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3526 "building reference to field in C?");
3527
3528 // These can't have reference type in well-formed programs, but
3529 // for internal consistency we do this anyway.
3530 type = type.getNonReferenceType();
3531 valueKind = VK_LValue;
3532 break;
3533
3534 // Non-type template parameters are either l-values or r-values
3535 // depending on the type.
3536 case Decl::NonTypeTemplateParm: {
3537 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3538 type = reftype->getPointeeType();
3539 valueKind = VK_LValue; // even if the parameter is an r-value reference
3540 break;
3541 }
3542
3543 // [expr.prim.id.unqual]p2:
3544 // If the entity is a template parameter object for a template
3545 // parameter of type T, the type of the expression is const T.
3546 // [...] The expression is an lvalue if the entity is a [...] template
3547 // parameter object.
3548 if (type->isRecordType()) {
3549 type = type.getUnqualifiedType().withConst();
3550 valueKind = VK_LValue;
3551 break;
3552 }
3553
3554 // For non-references, we need to strip qualifiers just in case
3555 // the template parameter was declared as 'const int' or whatever.
3556 valueKind = VK_PRValue;
3557 type = type.getUnqualifiedType();
3558 break;
3559 }
3560
3561 case Decl::Var:
3562 case Decl::VarTemplateSpecialization:
3563 case Decl::VarTemplatePartialSpecialization:
3564 case Decl::Decomposition:
3565 case Decl::Binding:
3566 case Decl::OMPCapturedExpr:
3567 // In C, "extern void blah;" is valid and is an r-value.
3568 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3569 type->isVoidType()) {
3570 valueKind = VK_PRValue;
3571 break;
3572 }
3573 [[fallthrough]];
3574
3575 case Decl::ImplicitParam:
3576 case Decl::ParmVar: {
3577 // These are always l-values.
3578 valueKind = VK_LValue;
3579 type = type.getNonReferenceType();
3580
3581 // FIXME: Does the addition of const really only apply in
3582 // potentially-evaluated contexts? Since the variable isn't actually
3583 // captured in an unevaluated context, it seems that the answer is no.
3584 if (!isUnevaluatedContext()) {
3585 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3586 if (!CapturedType.isNull())
3587 type = CapturedType;
3588 }
3589 break;
3590 }
3591
3592 case Decl::Function: {
3593 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3594 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3595 type = Context.BuiltinFnTy;
3596 valueKind = VK_PRValue;
3597 break;
3598 }
3599 }
3600
3601 const FunctionType *fty = type->castAs<FunctionType>();
3602
3603 // If we're referring to a function with an __unknown_anytype
3604 // result type, make the entire expression __unknown_anytype.
3605 if (fty->getReturnType() == Context.UnknownAnyTy) {
3606 type = Context.UnknownAnyTy;
3607 valueKind = VK_PRValue;
3608 break;
3609 }
3610
3611 // Functions are l-values in C++.
3612 if (getLangOpts().CPlusPlus) {
3613 valueKind = VK_LValue;
3614 break;
3615 }
3616
3617 // C99 DR 316 says that, if a function type comes from a
3618 // function definition (without a prototype), that type is only
3619 // used for checking compatibility. Therefore, when referencing
3620 // the function, we pretend that we don't have the full function
3621 // type.
3622 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3623 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3624 Info: fty->getExtInfo());
3625
3626 // Functions are r-values in C.
3627 valueKind = VK_PRValue;
3628 break;
3629 }
3630
3631 case Decl::CXXDeductionGuide:
3632 llvm_unreachable("building reference to deduction guide");
3633
3634 case Decl::MSProperty:
3635 case Decl::MSGuid:
3636 case Decl::TemplateParamObject:
3637 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3638 // capture in OpenMP, or duplicated between host and device?
3639 valueKind = VK_LValue;
3640 break;
3641
3642 case Decl::UnnamedGlobalConstant:
3643 valueKind = VK_LValue;
3644 break;
3645
3646 case Decl::CXXMethod:
3647 // If we're referring to a method with an __unknown_anytype
3648 // result type, make the entire expression __unknown_anytype.
3649 // This should only be possible with a type written directly.
3650 if (const FunctionProtoType *proto =
3651 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3652 if (proto->getReturnType() == Context.UnknownAnyTy) {
3653 type = Context.UnknownAnyTy;
3654 valueKind = VK_PRValue;
3655 break;
3656 }
3657
3658 // C++ methods are l-values if static, r-values if non-static.
3659 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3660 valueKind = VK_LValue;
3661 break;
3662 }
3663 [[fallthrough]];
3664
3665 case Decl::CXXConversion:
3666 case Decl::CXXDestructor:
3667 case Decl::CXXConstructor:
3668 valueKind = VK_PRValue;
3669 break;
3670 }
3671
3672 auto *E =
3673 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3674 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3675 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3676 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3677 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3678 // diagnostics).
3679 if (VD->isInvalidDecl() && E)
3680 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3681 return E;
3682}
3683
3684static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3685 SmallString<32> &Target) {
3686 Target.resize(N: CharByteWidth * (Source.size() + 1));
3687 char *ResultPtr = &Target[0];
3688 const llvm::UTF8 *ErrorPtr;
3689 bool success =
3690 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3691 (void)success;
3692 assert(success);
3693 Target.resize(N: ResultPtr - &Target[0]);
3694}
3695
3696ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3697 PredefinedIdentKind IK) {
3698 Decl *currentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
3699 if (!currentDecl) {
3700 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3701 currentDecl = Context.getTranslationUnitDecl();
3702 }
3703
3704 QualType ResTy;
3705 StringLiteral *SL = nullptr;
3706 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3707 ResTy = Context.DependentTy;
3708 else {
3709 // Pre-defined identifiers are of type char[x], where x is the length of
3710 // the string.
3711 bool ForceElaboratedPrinting =
3712 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3713 auto Str =
3714 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3715 unsigned Length = Str.length();
3716
3717 llvm::APInt LengthI(32, Length + 1);
3718 if (IK == PredefinedIdentKind::LFunction ||
3719 IK == PredefinedIdentKind::LFuncSig) {
3720 ResTy =
3721 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3722 SmallString<32> RawChars;
3723 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3724 Source: Str, Target&: RawChars);
3725 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3726 ASM: ArraySizeModifier::Normal,
3727 /*IndexTypeQuals*/ 0);
3728 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3729 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3730 } else {
3731 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3732 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3733 ASM: ArraySizeModifier::Normal,
3734 /*IndexTypeQuals*/ 0);
3735 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3736 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3737 }
3738 }
3739
3740 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3741 SL);
3742}
3743
3744ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3745 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3746}
3747
3748ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3749 SmallString<16> CharBuffer;
3750 bool Invalid = false;
3751 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3752 if (Invalid)
3753 return ExprError();
3754
3755 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3756 PP, Tok.getKind());
3757 if (Literal.hadError())
3758 return ExprError();
3759
3760 QualType Ty;
3761 if (Literal.isWide())
3762 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3763 else if (Literal.isUTF8() && getLangOpts().C23)
3764 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3765 else if (Literal.isUTF8() && getLangOpts().Char8)
3766 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3767 else if (Literal.isUTF16())
3768 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3769 else if (Literal.isUTF32())
3770 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3771 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3772 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3773 else
3774 Ty = Context.CharTy; // 'x' -> char in C++;
3775 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3776
3777 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3778 if (Literal.isWide())
3779 Kind = CharacterLiteralKind::Wide;
3780 else if (Literal.isUTF16())
3781 Kind = CharacterLiteralKind::UTF16;
3782 else if (Literal.isUTF32())
3783 Kind = CharacterLiteralKind::UTF32;
3784 else if (Literal.isUTF8())
3785 Kind = CharacterLiteralKind::UTF8;
3786
3787 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3788 Tok.getLocation());
3789
3790 if (Literal.getUDSuffix().empty())
3791 return Lit;
3792
3793 // We're building a user-defined literal.
3794 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3795 SourceLocation UDSuffixLoc =
3796 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3797
3798 // Make sure we're allowed user-defined literals here.
3799 if (!UDLScope)
3800 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3801
3802 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3803 // operator "" X (ch)
3804 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3805 Args: Lit, LitEndLoc: Tok.getLocation());
3806}
3807
3808ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3809 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3810 return IntegerLiteral::Create(C: Context,
3811 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3812 type: Context.IntTy, l: Loc);
3813}
3814
3815ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3816 ExprResult Inner;
3817 if (getLangOpts().CPlusPlus) {
3818 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3819 } else {
3820 // C doesn't actually have a way to represent literal values of type
3821 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3822 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3823 Inner =
3824 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3825 }
3826 return Inner;
3827}
3828
3829static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3830 QualType Ty, SourceLocation Loc) {
3831 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3832
3833 using llvm::APFloat;
3834 APFloat Val(Format);
3835
3836 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3837 if (RM == llvm::RoundingMode::Dynamic)
3838 RM = llvm::RoundingMode::NearestTiesToEven;
3839 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3840
3841 // Overflow is always an error, but underflow is only an error if
3842 // we underflowed to zero (APFloat reports denormals as underflow).
3843 if ((result & APFloat::opOverflow) ||
3844 ((result & APFloat::opUnderflow) && Val.isZero())) {
3845 unsigned diagnostic;
3846 SmallString<20> buffer;
3847 if (result & APFloat::opOverflow) {
3848 diagnostic = diag::warn_float_overflow;
3849 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3850 } else {
3851 diagnostic = diag::warn_float_underflow;
3852 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3853 }
3854
3855 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3856 }
3857
3858 bool isExact = (result == APFloat::opOK);
3859 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3860}
3861
3862bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3863 assert(E && "Invalid expression");
3864
3865 if (E->isValueDependent())
3866 return false;
3867
3868 QualType QT = E->getType();
3869 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3870 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3871 return true;
3872 }
3873
3874 llvm::APSInt ValueAPS;
3875 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3876
3877 if (R.isInvalid())
3878 return true;
3879
3880 // GCC allows the value of unroll count to be 0.
3881 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3882 // "The values of 0 and 1 block any unrolling of the loop."
3883 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3884 // '#pragma unroll' cases.
3885 bool ValueIsPositive =
3886 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3887 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3888 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3889 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3890 return true;
3891 }
3892
3893 return false;
3894}
3895
3896ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3897 // Fast path for a single digit (which is quite common). A single digit
3898 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3899 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3900 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3901 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3902 }
3903
3904 SmallString<128> SpellingBuffer;
3905 // NumericLiteralParser wants to overread by one character. Add padding to
3906 // the buffer in case the token is copied to the buffer. If getSpelling()
3907 // returns a StringRef to the memory buffer, it should have a null char at
3908 // the EOF, so it is also safe.
3909 SpellingBuffer.resize(N: Tok.getLength() + 1);
3910
3911 // Get the spelling of the token, which eliminates trigraphs, etc.
3912 bool Invalid = false;
3913 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3914 if (Invalid)
3915 return ExprError();
3916
3917 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3918 PP.getSourceManager(), PP.getLangOpts(),
3919 PP.getTargetInfo(), PP.getDiagnostics());
3920 if (Literal.hadError)
3921 return ExprError();
3922
3923 if (Literal.hasUDSuffix()) {
3924 // We're building a user-defined literal.
3925 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3926 SourceLocation UDSuffixLoc =
3927 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3928
3929 // Make sure we're allowed user-defined literals here.
3930 if (!UDLScope)
3931 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3932
3933 QualType CookedTy;
3934 if (Literal.isFloatingLiteral()) {
3935 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3936 // long double, the literal is treated as a call of the form
3937 // operator "" X (f L)
3938 CookedTy = Context.LongDoubleTy;
3939 } else {
3940 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3941 // unsigned long long, the literal is treated as a call of the form
3942 // operator "" X (n ULL)
3943 CookedTy = Context.UnsignedLongLongTy;
3944 }
3945
3946 DeclarationName OpName =
3947 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3948 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3949 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3950
3951 SourceLocation TokLoc = Tok.getLocation();
3952
3953 // Perform literal operator lookup to determine if we're building a raw
3954 // literal or a cooked one.
3955 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3956 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3957 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3958 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3959 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3960 case LOLR_ErrorNoDiagnostic:
3961 // Lookup failure for imaginary constants isn't fatal, there's still the
3962 // GNU extension producing _Complex types.
3963 break;
3964 case LOLR_Error:
3965 return ExprError();
3966 case LOLR_Cooked: {
3967 Expr *Lit;
3968 if (Literal.isFloatingLiteral()) {
3969 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3970 } else {
3971 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3972 if (Literal.GetIntegerValue(Val&: ResultVal))
3973 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3974 << /* Unsigned */ 1;
3975 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3976 l: Tok.getLocation());
3977 }
3978 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3979 }
3980
3981 case LOLR_Raw: {
3982 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3983 // literal is treated as a call of the form
3984 // operator "" X ("n")
3985 unsigned Length = Literal.getUDSuffixOffset();
3986 QualType StrTy = Context.getConstantArrayType(
3987 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3988 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3989 Expr *Lit =
3990 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3991 Kind: StringLiteralKind::Ordinary,
3992 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3993 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3994 }
3995
3996 case LOLR_Template: {
3997 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3998 // template), L is treated as a call fo the form
3999 // operator "" X <'c1', 'c2', ... 'ck'>()
4000 // where n is the source character sequence c1 c2 ... ck.
4001 TemplateArgumentListInfo ExplicitArgs;
4002 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
4003 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4004 llvm::APSInt Value(CharBits, CharIsUnsigned);
4005 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4006 Value = TokSpelling[I];
4007 TemplateArgument Arg(Context, Value, Context.CharTy);
4008 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
4009 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
4010 }
4011 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
4012 }
4013 case LOLR_StringTemplatePack:
4014 llvm_unreachable("unexpected literal operator lookup result");
4015 }
4016 }
4017
4018 Expr *Res;
4019
4020 if (Literal.isFixedPointLiteral()) {
4021 QualType Ty;
4022
4023 if (Literal.isAccum) {
4024 if (Literal.isHalf) {
4025 Ty = Context.ShortAccumTy;
4026 } else if (Literal.isLong) {
4027 Ty = Context.LongAccumTy;
4028 } else {
4029 Ty = Context.AccumTy;
4030 }
4031 } else if (Literal.isFract) {
4032 if (Literal.isHalf) {
4033 Ty = Context.ShortFractTy;
4034 } else if (Literal.isLong) {
4035 Ty = Context.LongFractTy;
4036 } else {
4037 Ty = Context.FractTy;
4038 }
4039 }
4040
4041 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
4042
4043 bool isSigned = !Literal.isUnsigned;
4044 unsigned scale = Context.getFixedPointScale(Ty);
4045 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4046
4047 llvm::APInt Val(bit_width, 0, isSigned);
4048 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
4049 bool ValIsZero = Val.isZero() && !Overflowed;
4050
4051 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4052 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4053 // Clause 6.4.4 - The value of a constant shall be in the range of
4054 // representable values for its type, with exception for constants of a
4055 // fract type with a value of exactly 1; such a constant shall denote
4056 // the maximal value for the type.
4057 --Val;
4058 else if (Val.ugt(RHS: MaxVal) || Overflowed)
4059 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
4060
4061 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4062 l: Tok.getLocation(), Scale: scale);
4063 } else if (Literal.isFloatingLiteral()) {
4064 QualType Ty;
4065 if (Literal.isHalf){
4066 if (getLangOpts().HLSL ||
4067 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4068 Ty = Context.HalfTy;
4069 else {
4070 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4071 return ExprError();
4072 }
4073 } else if (Literal.isFloat)
4074 Ty = Context.FloatTy;
4075 else if (Literal.isLong)
4076 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4077 else if (Literal.isFloat16)
4078 Ty = Context.Float16Ty;
4079 else if (Literal.isFloat128)
4080 Ty = Context.Float128Ty;
4081 else if (getLangOpts().HLSL)
4082 Ty = Context.FloatTy;
4083 else
4084 Ty = Context.DoubleTy;
4085
4086 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4087
4088 if (Ty == Context.DoubleTy) {
4089 if (getLangOpts().SinglePrecisionConstants) {
4090 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4091 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4092 }
4093 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4094 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4095 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4096 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4097 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4098 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4099 }
4100 }
4101 } else if (!Literal.isIntegerLiteral()) {
4102 return ExprError();
4103 } else {
4104 QualType Ty;
4105
4106 // 'z/uz' literals are a C++23 feature.
4107 if (Literal.isSizeT) {
4108 if (getLangOpts().CPlusPlus)
4109 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::size_t_suffix);
4110 else
4111 Diag(Loc: Tok.getLocation(), DiagID: diag::err_cxx23_size_t_suffix);
4112 }
4113
4114 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4115 // but we do not currently support the suffix in C++ mode because it's not
4116 // entirely clear whether WG21 will prefer this suffix to return a library
4117 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4118 // literals are a C++ extension.
4119 if (Literal.isBitInt)
4120 PP.Diag(Loc: Tok.getLocation(),
4121 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4122 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4123 : diag::ext_c23_bitint_suffix);
4124
4125 // Get the value in the widest-possible width. What is "widest" depends on
4126 // whether the literal is a bit-precise integer or not. For a bit-precise
4127 // integer type, try to scan the source to determine how many bits are
4128 // needed to represent the value. This may seem a bit expensive, but trying
4129 // to get the integer value from an overly-wide APInt is *extremely*
4130 // expensive, so the naive approach of assuming
4131 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4132 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4133 if (Literal.isBitInt)
4134 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4135 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4136 if (Literal.MicrosoftInteger) {
4137 if (Literal.MicrosoftInteger == 128 &&
4138 !Context.getTargetInfo().hasInt128Type())
4139 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4140 << Literal.isUnsigned;
4141 BitsNeeded = std::max<unsigned>(a: BitsNeeded, b: Literal.MicrosoftInteger);
4142 }
4143
4144 llvm::APInt ResultVal(BitsNeeded, 0);
4145
4146 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4147 // If this value didn't fit into uintmax_t, error and force to ull.
4148 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4149 << /* Unsigned */ 1;
4150 Ty = Context.UnsignedLongLongTy;
4151 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4152 "long long is not intmax_t?");
4153 } else {
4154 // If this value fits into a ULL, try to figure out what else it fits into
4155 // according to the rules of C99 6.4.4.1p5.
4156
4157 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4158 // be an unsigned int.
4159 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4160
4161 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4162 // suffix for portability of code with C++, but both `l` and `ll` are
4163 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4164 // same.
4165 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4166 Literal.isLong = true;
4167 Literal.isLongLong = false;
4168 }
4169
4170 // Check from smallest to largest, picking the smallest type we can.
4171 unsigned Width = 0;
4172
4173 // Microsoft specific integer suffixes are explicitly sized.
4174 if (Literal.MicrosoftInteger) {
4175 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4176 Width = 8;
4177 Ty = Context.CharTy;
4178 } else {
4179 Width = Literal.MicrosoftInteger;
4180 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4181 /*Signed=*/!Literal.isUnsigned);
4182 }
4183 // To maintain consistency with MSVC, we chose to truncate directly
4184 // without issuing any warnings.
4185 ResultVal = ResultVal.zextOrTrunc(width: Width);
4186 }
4187
4188 // Bit-precise integer literals are automagically-sized based on the
4189 // width required by the literal.
4190 if (Literal.isBitInt) {
4191 // The signed version has one more bit for the sign value. There are no
4192 // zero-width bit-precise integers, even if the literal value is 0.
4193 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4194 (Literal.isUnsigned ? 0u : 1u);
4195
4196 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4197 // and reset the type to the largest supported width.
4198 unsigned int MaxBitIntWidth =
4199 Context.getTargetInfo().getMaxBitIntWidth();
4200 if (Width > MaxBitIntWidth) {
4201 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4202 << Literal.isUnsigned;
4203 Width = MaxBitIntWidth;
4204 }
4205
4206 // Reset the result value to the smaller APInt and select the correct
4207 // type to be used. Note, we zext even for signed values because the
4208 // literal itself is always an unsigned value (a preceeding - is a
4209 // unary operator, not part of the literal).
4210 ResultVal = ResultVal.zextOrTrunc(width: Width);
4211 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4212 }
4213
4214 // Check C++23 size_t literals.
4215 if (Literal.isSizeT) {
4216 assert(!Literal.MicrosoftInteger &&
4217 "size_t literals can't be Microsoft literals");
4218 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4219 T: Context.getTargetInfo().getSizeType());
4220
4221 // Does it fit in size_t?
4222 if (ResultVal.isIntN(N: SizeTSize)) {
4223 // Does it fit in ssize_t?
4224 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4225 Ty = Context.getSignedSizeType();
4226 else if (AllowUnsigned)
4227 Ty = Context.getSizeType();
4228 Width = SizeTSize;
4229 }
4230 }
4231
4232 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4233 !Literal.isSizeT) {
4234 // Are int/unsigned possibilities?
4235 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4236
4237 // Does it fit in a unsigned int?
4238 if (ResultVal.isIntN(N: IntSize)) {
4239 // Does it fit in a signed int?
4240 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4241 Ty = Context.IntTy;
4242 else if (AllowUnsigned)
4243 Ty = Context.UnsignedIntTy;
4244 Width = IntSize;
4245 }
4246 }
4247
4248 // Are long/unsigned long possibilities?
4249 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4250 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4251
4252 // Does it fit in a unsigned long?
4253 if (ResultVal.isIntN(N: LongSize)) {
4254 // Does it fit in a signed long?
4255 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4256 Ty = Context.LongTy;
4257 else if (AllowUnsigned)
4258 Ty = Context.UnsignedLongTy;
4259 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4260 // is compatible.
4261 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4262 const unsigned LongLongSize =
4263 Context.getTargetInfo().getLongLongWidth();
4264 Diag(Loc: Tok.getLocation(),
4265 DiagID: getLangOpts().CPlusPlus
4266 ? Literal.isLong
4267 ? diag::warn_old_implicitly_unsigned_long_cxx
4268 : /*C++98 UB*/ diag::
4269 ext_old_implicitly_unsigned_long_cxx
4270 : diag::warn_old_implicitly_unsigned_long)
4271 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4272 : /*will be ill-formed*/ 1);
4273 Ty = Context.UnsignedLongTy;
4274 }
4275 Width = LongSize;
4276 }
4277 }
4278
4279 // Check long long if needed.
4280 if (Ty.isNull() && !Literal.isSizeT) {
4281 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4282
4283 // Does it fit in a unsigned long long?
4284 if (ResultVal.isIntN(N: LongLongSize)) {
4285 // Does it fit in a signed long long?
4286 // To be compatible with MSVC, hex integer literals ending with the
4287 // LL or i64 suffix are always signed in Microsoft mode.
4288 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4289 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4290 Ty = Context.LongLongTy;
4291 else if (AllowUnsigned)
4292 Ty = Context.UnsignedLongLongTy;
4293 Width = LongLongSize;
4294
4295 // 'long long' is a C99 or C++11 feature, whether the literal
4296 // explicitly specified 'long long' or we needed the extra width.
4297 if (getLangOpts().CPlusPlus)
4298 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4299 ? diag::warn_cxx98_compat_longlong
4300 : diag::ext_cxx11_longlong);
4301 else if (!getLangOpts().C99)
4302 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4303 }
4304 }
4305
4306 // If we still couldn't decide a type, we either have 'size_t' literal
4307 // that is out of range, or a decimal literal that does not fit in a
4308 // signed long long and has no U suffix.
4309 if (Ty.isNull()) {
4310 if (Literal.isSizeT)
4311 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4312 << Literal.isUnsigned;
4313 else
4314 Diag(Loc: Tok.getLocation(),
4315 DiagID: diag::ext_integer_literal_too_large_for_signed);
4316 Ty = Context.UnsignedLongLongTy;
4317 Width = Context.getTargetInfo().getLongLongWidth();
4318 }
4319
4320 if (ResultVal.getBitWidth() != Width)
4321 ResultVal = ResultVal.trunc(width: Width);
4322 }
4323 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4324 }
4325
4326 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4327 if (Literal.isImaginary) {
4328 Res = new (Context) ImaginaryLiteral(Res,
4329 Context.getComplexType(T: Res->getType()));
4330
4331 // In C++, this is a GNU extension. In C, it's a C2y extension.
4332 if (getLangOpts().CPlusPlus)
4333 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_gnu_imaginary_constant);
4334 else
4335 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::imaginary_constant);
4336 }
4337 return Res;
4338}
4339
4340ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4341 assert(E && "ActOnParenExpr() missing expr");
4342 QualType ExprTy = E->getType();
4343 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4344 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4345 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4346 return new (Context) ParenExpr(L, R, E);
4347}
4348
4349static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4350 SourceLocation Loc,
4351 SourceRange ArgRange) {
4352 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4353 // scalar or vector data type argument..."
4354 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4355 // type (C99 6.2.5p18) or void.
4356 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4357 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4358 << T << ArgRange;
4359 return true;
4360 }
4361
4362 assert((T->isVoidType() || !T->isIncompleteType()) &&
4363 "Scalar types should always be complete");
4364 return false;
4365}
4366
4367static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4368 SourceLocation Loc,
4369 SourceRange ArgRange) {
4370 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4371 if (!T->isVectorType() && !T->isSizelessVectorType())
4372 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4373 << ""
4374 << "__builtin_vectorelements" << T << ArgRange;
4375
4376 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4377 if (T->isSVESizelessBuiltinType()) {
4378 llvm::StringMap<bool> CallerFeatureMap;
4379 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4380 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4381 }
4382 }
4383
4384 return false;
4385}
4386
4387static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4388 SourceLocation Loc,
4389 SourceRange ArgRange) {
4390 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4391 return true;
4392
4393 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4394 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4395 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4396 return true;
4397 }
4398
4399 return false;
4400}
4401
4402static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4403 SourceLocation Loc,
4404 SourceRange ArgRange,
4405 UnaryExprOrTypeTrait TraitKind) {
4406 // Invalid types must be hard errors for SFINAE in C++.
4407 if (S.LangOpts.CPlusPlus)
4408 return true;
4409
4410 // C99 6.5.3.4p1:
4411 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4412 TraitKind == UETT_PreferredAlignOf) {
4413
4414 // sizeof(function)/alignof(function) is allowed as an extension.
4415 if (T->isFunctionType()) {
4416 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4417 << getTraitSpelling(T: TraitKind) << ArgRange;
4418 return false;
4419 }
4420
4421 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4422 // this is an error (OpenCL v1.1 s6.3.k)
4423 if (T->isVoidType()) {
4424 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4425 : diag::ext_sizeof_alignof_void_type;
4426 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4427 return false;
4428 }
4429 }
4430 return true;
4431}
4432
4433static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4434 SourceLocation Loc,
4435 SourceRange ArgRange,
4436 UnaryExprOrTypeTrait TraitKind) {
4437 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4438 // runtime doesn't allow it.
4439 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4440 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4441 << T << (TraitKind == UETT_SizeOf)
4442 << ArgRange;
4443 return true;
4444 }
4445
4446 return false;
4447}
4448
4449/// Check whether E is a pointer from a decayed array type (the decayed
4450/// pointer type is equal to T) and emit a warning if it is.
4451static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4452 const Expr *E) {
4453 // Don't warn if the operation changed the type.
4454 if (T != E->getType())
4455 return;
4456
4457 // Now look for array decays.
4458 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4459 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4460 return;
4461
4462 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4463 << ICE->getType()
4464 << ICE->getSubExpr()->getType();
4465}
4466
4467bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4468 UnaryExprOrTypeTrait ExprKind) {
4469 QualType ExprTy = E->getType();
4470 assert(!ExprTy->isReferenceType());
4471
4472 bool IsUnevaluatedOperand =
4473 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4474 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4475 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4476 if (IsUnevaluatedOperand) {
4477 ExprResult Result = CheckUnevaluatedOperand(E);
4478 if (Result.isInvalid())
4479 return true;
4480 E = Result.get();
4481 }
4482
4483 // The operand for sizeof and alignof is in an unevaluated expression context,
4484 // so side effects could result in unintended consequences.
4485 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4486 // used to build SFINAE gadgets.
4487 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4488 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4489 !E->isInstantiationDependent() &&
4490 !E->getType()->isVariableArrayType() &&
4491 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4492 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4493
4494 if (ExprKind == UETT_VecStep)
4495 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4496 ArgRange: E->getSourceRange());
4497
4498 if (ExprKind == UETT_VectorElements)
4499 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4500 ArgRange: E->getSourceRange());
4501
4502 // Explicitly list some types as extensions.
4503 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4504 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4505 return false;
4506
4507 // WebAssembly tables are always illegal operands to unary expressions and
4508 // type traits.
4509 if (Context.getTargetInfo().getTriple().isWasm() &&
4510 E->getType()->isWebAssemblyTableType()) {
4511 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4512 << getTraitSpelling(T: ExprKind);
4513 return true;
4514 }
4515
4516 // 'alignof' applied to an expression only requires the base element type of
4517 // the expression to be complete. 'sizeof' requires the expression's type to
4518 // be complete (and will attempt to complete it if it's an array of unknown
4519 // bound).
4520 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4521 if (RequireCompleteSizedType(
4522 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4523 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4524 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4525 return true;
4526 } else {
4527 if (RequireCompleteSizedExprType(
4528 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4529 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4530 return true;
4531 }
4532
4533 // Completing the expression's type may have changed it.
4534 ExprTy = E->getType();
4535 assert(!ExprTy->isReferenceType());
4536
4537 if (ExprTy->isFunctionType()) {
4538 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4539 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4540 return true;
4541 }
4542
4543 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4544 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4545 return true;
4546
4547 if (ExprKind == UETT_CountOf) {
4548 // The type has to be an array type. We already checked for incomplete
4549 // types above.
4550 QualType ExprType = E->IgnoreParens()->getType();
4551 if (!ExprType->isArrayType()) {
4552 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4553 return true;
4554 }
4555 // FIXME: warn on _Countof on an array parameter. Not warning on it
4556 // currently because there are papers in WG14 about array types which do
4557 // not decay that could impact this behavior, so we want to see if anything
4558 // changes here before coming up with a warning group for _Countof-related
4559 // diagnostics.
4560 }
4561
4562 if (ExprKind == UETT_SizeOf) {
4563 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4564 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4565 QualType OType = PVD->getOriginalType();
4566 QualType Type = PVD->getType();
4567 if (Type->isPointerType() && OType->isArrayType()) {
4568 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4569 << Type << OType;
4570 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4571 }
4572 }
4573 }
4574
4575 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4576 // decays into a pointer and returns an unintended result. This is most
4577 // likely a typo for "sizeof(array) op x".
4578 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4579 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4580 E: BO->getLHS());
4581 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4582 E: BO->getRHS());
4583 }
4584 }
4585
4586 return false;
4587}
4588
4589static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4590 // Cannot know anything else if the expression is dependent.
4591 if (E->isTypeDependent())
4592 return false;
4593
4594 if (E->getObjectKind() == OK_BitField) {
4595 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4596 << 1 << E->getSourceRange();
4597 return true;
4598 }
4599
4600 ValueDecl *D = nullptr;
4601 Expr *Inner = E->IgnoreParens();
4602 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4603 D = DRE->getDecl();
4604 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4605 D = ME->getMemberDecl();
4606 }
4607
4608 // If it's a field, require the containing struct to have a
4609 // complete definition so that we can compute the layout.
4610 //
4611 // This can happen in C++11 onwards, either by naming the member
4612 // in a way that is not transformed into a member access expression
4613 // (in an unevaluated operand, for instance), or by naming the member
4614 // in a trailing-return-type.
4615 //
4616 // For the record, since __alignof__ on expressions is a GCC
4617 // extension, GCC seems to permit this but always gives the
4618 // nonsensical answer 0.
4619 //
4620 // We don't really need the layout here --- we could instead just
4621 // directly check for all the appropriate alignment-lowing
4622 // attributes --- but that would require duplicating a lot of
4623 // logic that just isn't worth duplicating for such a marginal
4624 // use-case.
4625 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4626 // Fast path this check, since we at least know the record has a
4627 // definition if we can find a member of it.
4628 if (!FD->getParent()->isCompleteDefinition()) {
4629 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4630 << E->getSourceRange();
4631 return true;
4632 }
4633
4634 // Otherwise, if it's a field, and the field doesn't have
4635 // reference type, then it must have a complete type (or be a
4636 // flexible array member, which we explicitly want to
4637 // white-list anyway), which makes the following checks trivial.
4638 if (!FD->getType()->isReferenceType())
4639 return false;
4640 }
4641
4642 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4643}
4644
4645bool Sema::CheckVecStepExpr(Expr *E) {
4646 E = E->IgnoreParens();
4647
4648 // Cannot know anything else if the expression is dependent.
4649 if (E->isTypeDependent())
4650 return false;
4651
4652 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4653}
4654
4655static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4656 CapturingScopeInfo *CSI) {
4657 assert(T->isVariablyModifiedType());
4658 assert(CSI != nullptr);
4659
4660 // We're going to walk down into the type and look for VLA expressions.
4661 do {
4662 const Type *Ty = T.getTypePtr();
4663 switch (Ty->getTypeClass()) {
4664#define TYPE(Class, Base)
4665#define ABSTRACT_TYPE(Class, Base)
4666#define NON_CANONICAL_TYPE(Class, Base)
4667#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4668#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4669#include "clang/AST/TypeNodes.inc"
4670 T = QualType();
4671 break;
4672 // These types are never variably-modified.
4673 case Type::Builtin:
4674 case Type::Complex:
4675 case Type::Vector:
4676 case Type::ExtVector:
4677 case Type::ConstantMatrix:
4678 case Type::Record:
4679 case Type::Enum:
4680 case Type::TemplateSpecialization:
4681 case Type::ObjCObject:
4682 case Type::ObjCInterface:
4683 case Type::ObjCObjectPointer:
4684 case Type::ObjCTypeParam:
4685 case Type::Pipe:
4686 case Type::BitInt:
4687 case Type::HLSLInlineSpirv:
4688 llvm_unreachable("type class is never variably-modified!");
4689 case Type::Adjusted:
4690 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4691 break;
4692 case Type::Decayed:
4693 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4694 break;
4695 case Type::ArrayParameter:
4696 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4697 break;
4698 case Type::Pointer:
4699 T = cast<PointerType>(Val: Ty)->getPointeeType();
4700 break;
4701 case Type::BlockPointer:
4702 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4703 break;
4704 case Type::LValueReference:
4705 case Type::RValueReference:
4706 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4707 break;
4708 case Type::MemberPointer:
4709 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4710 break;
4711 case Type::ConstantArray:
4712 case Type::IncompleteArray:
4713 // Losing element qualification here is fine.
4714 T = cast<ArrayType>(Val: Ty)->getElementType();
4715 break;
4716 case Type::VariableArray: {
4717 // Losing element qualification here is fine.
4718 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4719
4720 // Unknown size indication requires no size computation.
4721 // Otherwise, evaluate and record it.
4722 auto Size = VAT->getSizeExpr();
4723 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4724 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4725 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4726
4727 T = VAT->getElementType();
4728 break;
4729 }
4730 case Type::FunctionProto:
4731 case Type::FunctionNoProto:
4732 T = cast<FunctionType>(Val: Ty)->getReturnType();
4733 break;
4734 case Type::Paren:
4735 case Type::TypeOf:
4736 case Type::UnaryTransform:
4737 case Type::Attributed:
4738 case Type::BTFTagAttributed:
4739 case Type::OverflowBehavior:
4740 case Type::HLSLAttributedResource:
4741 case Type::SubstTemplateTypeParm:
4742 case Type::MacroQualified:
4743 case Type::CountAttributed:
4744 case Type::LateParsedAttr:
4745 // Keep walking after single level desugaring.
4746 T = T.getSingleStepDesugaredType(Context);
4747 break;
4748 case Type::Typedef:
4749 T = cast<TypedefType>(Val: Ty)->desugar();
4750 break;
4751 case Type::Decltype:
4752 T = cast<DecltypeType>(Val: Ty)->desugar();
4753 break;
4754 case Type::PackIndexing:
4755 T = cast<PackIndexingType>(Val: Ty)->desugar();
4756 break;
4757 case Type::Using:
4758 T = cast<UsingType>(Val: Ty)->desugar();
4759 break;
4760 case Type::Auto:
4761 case Type::DeducedTemplateSpecialization:
4762 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4763 break;
4764 case Type::TypeOfExpr:
4765 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4766 break;
4767 case Type::Atomic:
4768 T = cast<AtomicType>(Val: Ty)->getValueType();
4769 break;
4770 case Type::PredefinedSugar:
4771 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4772 break;
4773 }
4774 } while (!T.isNull() && T->isVariablyModifiedType());
4775}
4776
4777bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4778 SourceLocation OpLoc,
4779 SourceRange ExprRange,
4780 UnaryExprOrTypeTrait ExprKind,
4781 StringRef KWName) {
4782 if (ExprType->isDependentType())
4783 return false;
4784
4785 // These builtins evaluate with the operand type as written; a reference is
4786 // not looked through.
4787 if (ExprKind == UETT_VectorElements)
4788 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4789 ArgRange: ExprRange);
4790 if (ExprKind == UETT_VecStep)
4791 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4792 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4793 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4794 ArgRange: ExprRange);
4795
4796 // C++ [expr.sizeof]p2:
4797 // When applied to a reference or a reference type, the result
4798 // is the size of the referenced type.
4799 // C++11 [expr.alignof]p3:
4800 // When alignof is applied to a reference type, the result
4801 // shall be the alignment of the referenced type.
4802 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4803 ExprType = Ref->getPointeeType();
4804
4805 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4806 // When alignof or _Alignof is applied to an array type, the result
4807 // is the alignment of the element type.
4808 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4809 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4810 // If the trait is 'alignof' in C before C2y, the ability to apply the
4811 // trait to an incomplete array is an extension.
4812 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4813 ExprType->isIncompleteArrayType())
4814 DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::alignof_incomplete_array);
4815 ExprType = Context.getBaseElementType(QT: ExprType);
4816 }
4817
4818 // Explicitly list some types as extensions.
4819 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4820 TraitKind: ExprKind))
4821 return false;
4822
4823 if (RequireCompleteSizedType(
4824 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4825 Args: KWName, Args: ExprRange))
4826 return true;
4827
4828 if (ExprType->isFunctionType()) {
4829 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4830 return true;
4831 }
4832
4833 if (ExprKind == UETT_CountOf) {
4834 // The type has to be an array type. We already checked for incomplete
4835 // types above.
4836 if (!ExprType->isArrayType()) {
4837 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4838 return true;
4839 }
4840 }
4841
4842 // WebAssembly tables are always illegal operands to unary expressions and
4843 // type traits.
4844 if (Context.getTargetInfo().getTriple().isWasm() &&
4845 ExprType->isWebAssemblyTableType()) {
4846 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4847 << getTraitSpelling(T: ExprKind);
4848 return true;
4849 }
4850
4851 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4852 TraitKind: ExprKind))
4853 return true;
4854
4855 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4856 if (auto *TT = ExprType->getAs<TypedefType>()) {
4857 for (auto I = FunctionScopes.rbegin(),
4858 E = std::prev(x: FunctionScopes.rend());
4859 I != E; ++I) {
4860 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4861 if (CSI == nullptr)
4862 break;
4863 DeclContext *DC = nullptr;
4864 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4865 DC = LSI->CallOperator;
4866 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4867 DC = CRSI->TheCapturedDecl;
4868 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4869 DC = BSI->TheDecl;
4870 if (DC) {
4871 if (DC->containsDecl(D: TT->getDecl()))
4872 break;
4873 captureVariablyModifiedType(Context, T: ExprType, CSI);
4874 }
4875 }
4876 }
4877 }
4878
4879 return false;
4880}
4881
4882ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4883 SourceLocation OpLoc,
4884 UnaryExprOrTypeTrait ExprKind,
4885 SourceRange R) {
4886 if (!TInfo)
4887 return ExprError();
4888
4889 QualType T = TInfo->getType();
4890
4891 if (!T->isDependentType() &&
4892 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4893 KWName: getTraitSpelling(T: ExprKind)))
4894 return ExprError();
4895
4896 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4897 // properly deal with VLAs in nested calls of sizeof and typeof.
4898 if (currentEvaluationContext().isUnevaluated() &&
4899 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4900 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4901 TInfo->getType()->isVariablyModifiedType())
4902 TInfo = TransformToPotentiallyEvaluated(TInfo);
4903
4904 // It's possible that the transformation above failed.
4905 if (!TInfo)
4906 return ExprError();
4907
4908 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4909 return new (Context) UnaryExprOrTypeTraitExpr(
4910 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4911}
4912
4913ExprResult
4914Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4915 UnaryExprOrTypeTrait ExprKind) {
4916 ExprResult PE = CheckPlaceholderExpr(E);
4917 if (PE.isInvalid())
4918 return ExprError();
4919
4920 E = PE.get();
4921
4922 // Verify that the operand is valid.
4923 bool isInvalid = false;
4924 if (E->isTypeDependent()) {
4925 // Delay type-checking for type-dependent expressions.
4926 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4927 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4928 } else if (ExprKind == UETT_VecStep) {
4929 isInvalid = CheckVecStepExpr(E);
4930 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4931 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4932 isInvalid = true;
4933 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4934 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4935 isInvalid = true;
4936 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4937 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4938 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4939 }
4940
4941 if (isInvalid)
4942 return ExprError();
4943
4944 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4945 E->getType()->isVariableArrayType()) {
4946 PE = TransformToPotentiallyEvaluated(E);
4947 if (PE.isInvalid()) return ExprError();
4948 E = PE.get();
4949 }
4950
4951 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4952 return new (Context) UnaryExprOrTypeTraitExpr(
4953 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4954}
4955
4956ExprResult
4957Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4958 UnaryExprOrTypeTrait ExprKind, bool IsType,
4959 void *TyOrEx, SourceRange ArgRange) {
4960 // If error parsing type, ignore.
4961 if (!TyOrEx) return ExprError();
4962
4963 if (IsType) {
4964 TypeSourceInfo *TInfo;
4965 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4966 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4967 }
4968
4969 Expr *ArgEx = (Expr *)TyOrEx;
4970 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4971 return Result;
4972}
4973
4974bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4975 SourceLocation OpLoc, SourceRange R) {
4976 if (!TInfo)
4977 return true;
4978 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4979 ExprKind: UETT_AlignOf, KWName);
4980}
4981
4982bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4983 SourceLocation OpLoc, SourceRange R) {
4984 TypeSourceInfo *TInfo;
4985 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4986 TInfo: &TInfo);
4987 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4988}
4989
4990static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4991 bool IsReal) {
4992 if (V.get()->isTypeDependent())
4993 return S.Context.DependentTy;
4994
4995 // _Real and _Imag are only l-values for normal l-values.
4996 if (V.get()->getObjectKind() != OK_Ordinary) {
4997 V = S.DefaultLvalueConversion(E: V.get());
4998 if (V.isInvalid())
4999 return QualType();
5000 }
5001
5002 // These operators return the element type of a complex type.
5003 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5004 return CT->getElementType();
5005
5006 // Otherwise they pass through real integer and floating point types here.
5007 if (V.get()->getType()->isArithmeticType())
5008 return V.get()->getType();
5009
5010 // Test for placeholders.
5011 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
5012 if (PR.isInvalid()) return QualType();
5013 if (PR.get() != V.get()) {
5014 V = PR;
5015 return CheckRealImagOperand(S, V, Loc, IsReal);
5016 }
5017
5018 // Reject anything else.
5019 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
5020 << (IsReal ? "__real" : "__imag");
5021 return QualType();
5022}
5023
5024
5025
5026ExprResult
5027Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5028 tok::TokenKind Kind, Expr *Input) {
5029 UnaryOperatorKind Opc;
5030 switch (Kind) {
5031 default: llvm_unreachable("Unknown unary op!");
5032 case tok::plusplus: Opc = UO_PostInc; break;
5033 case tok::minusminus: Opc = UO_PostDec; break;
5034 }
5035
5036 // Since this might is a postfix expression, get rid of ParenListExprs.
5037 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
5038 if (Result.isInvalid()) return ExprError();
5039 Input = Result.get();
5040
5041 return BuildUnaryOp(S, OpLoc, Opc, Input);
5042}
5043
5044/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5045///
5046/// \return true on error
5047static bool checkArithmeticOnObjCPointer(Sema &S,
5048 SourceLocation opLoc,
5049 Expr *op) {
5050 assert(op->getType()->isObjCObjectPointerType());
5051 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5052 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5053 return false;
5054
5055 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
5056 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5057 << op->getSourceRange();
5058 return true;
5059}
5060
5061static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5062 auto *BaseNoParens = Base->IgnoreParens();
5063 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5064 return MSProp->getPropertyDecl()->getType()->isArrayType();
5065 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
5066}
5067
5068// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5069// Typically this is DependentTy, but can sometimes be more precise.
5070//
5071// There are cases when we could determine a non-dependent type:
5072// - LHS and RHS may have non-dependent types despite being type-dependent
5073// (e.g. unbounded array static members of the current instantiation)
5074// - one may be a dependent-sized array with known element type
5075// - one may be a dependent-typed valid index (enum in current instantiation)
5076//
5077// We *always* return a dependent type, in such cases it is DependentTy.
5078// This avoids creating type-dependent expressions with non-dependent types.
5079// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5080static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5081 const ASTContext &Ctx) {
5082 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5083 QualType LTy = LHS->getType(), RTy = RHS->getType();
5084 QualType Result = Ctx.DependentTy;
5085 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5086 if (const PointerType *PT = LTy->getAs<PointerType>())
5087 Result = PT->getPointeeType();
5088 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5089 Result = AT->getElementType();
5090 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5091 if (const PointerType *PT = RTy->getAs<PointerType>())
5092 Result = PT->getPointeeType();
5093 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5094 Result = AT->getElementType();
5095 }
5096 // Ensure we return a dependent type.
5097 return Result->isDependentType() ? Result : Ctx.DependentTy;
5098}
5099
5100ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5101 SourceLocation lbLoc,
5102 MultiExprArg ArgExprs,
5103 SourceLocation rbLoc) {
5104
5105 if (base && !base->getType().isNull() &&
5106 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5107 auto *AS = cast<ArraySectionExpr>(Val: base);
5108 if (AS->isOMPArraySection())
5109 return OpenMP().ActOnOMPArraySectionExpr(
5110 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5111 /*Length*/ nullptr,
5112 /*Stride=*/nullptr, RBLoc: rbLoc);
5113
5114 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5115 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5116 RBLoc: rbLoc);
5117 }
5118
5119 // Since this might be a postfix expression, get rid of ParenListExprs.
5120 if (isa<ParenListExpr>(Val: base)) {
5121 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5122 if (result.isInvalid())
5123 return ExprError();
5124 base = result.get();
5125 }
5126
5127 // Check if base and idx form a MatrixSubscriptExpr.
5128 //
5129 // Helper to check for comma expressions, which are not allowed as indices for
5130 // matrix subscript expressions.
5131 //
5132 // In C++23, we get multiple arguments instead of a comma expression.
5133 auto CheckAndReportCommaError = [&](Expr *E) {
5134 if (ArgExprs.size() > 1 ||
5135 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5136 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5137 << SourceRange(base->getBeginLoc(), rbLoc);
5138 return true;
5139 }
5140 return false;
5141 };
5142 // The matrix subscript operator ([][])is considered a single operator.
5143 // Separating the index expressions by parenthesis is not allowed.
5144 if (base && !base->getType().isNull() &&
5145 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5146 !isa<MatrixSubscriptExpr>(Val: base)) {
5147 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5148 << SourceRange(base->getBeginLoc(), rbLoc);
5149 return ExprError();
5150 }
5151 // If the base is a MatrixSubscriptExpr, try to create a new
5152 // MatrixSubscriptExpr.
5153 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5154 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5155 if (CheckAndReportCommaError(ArgExprs.front()))
5156 return ExprError();
5157
5158 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5159 RowIdx: matSubscriptE->getRowIdx(),
5160 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5161 }
5162 if (base->getType()->isWebAssemblyTableType()) {
5163 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5164 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5165 return ExprError();
5166 }
5167
5168 CheckInvalidBuiltinCountedByRef(E: base,
5169 K: BuiltinCountedByRefKind::ArraySubscript);
5170
5171 // Handle any non-overload placeholder types in the base and index
5172 // expressions. We can't handle overloads here because the other
5173 // operand might be an overloadable type, in which case the overload
5174 // resolution for the operator overload should get the first crack
5175 // at the overload.
5176 bool IsMSPropertySubscript = false;
5177 if (base->getType()->isNonOverloadPlaceholderType()) {
5178 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5179 if (!IsMSPropertySubscript) {
5180 ExprResult result = CheckPlaceholderExpr(E: base);
5181 if (result.isInvalid())
5182 return ExprError();
5183 base = result.get();
5184 }
5185 }
5186
5187 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5188 if (base->getType()->isMatrixType()) {
5189 if (CheckAndReportCommaError(ArgExprs.front()))
5190 return ExprError();
5191
5192 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5193 RBLoc: rbLoc);
5194 }
5195
5196 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5197 Expr *idx = ArgExprs[0];
5198 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5199 (isa<CXXOperatorCallExpr>(Val: idx) &&
5200 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5201 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5202 << SourceRange(base->getBeginLoc(), rbLoc);
5203 }
5204 }
5205
5206 if (ArgExprs.size() == 1 &&
5207 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5208 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5209 if (result.isInvalid())
5210 return ExprError();
5211 ArgExprs[0] = result.get();
5212 } else {
5213 if (CheckArgsForPlaceholders(args: ArgExprs))
5214 return ExprError();
5215 }
5216
5217 // Build an unanalyzed expression if either operand is type-dependent.
5218 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5219 (base->isTypeDependent() ||
5220 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5221 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5222 return new (Context) ArraySubscriptExpr(
5223 base, ArgExprs.front(),
5224 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5225 VK_LValue, OK_Ordinary, rbLoc);
5226 }
5227
5228 // MSDN, property (C++)
5229 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5230 // This attribute can also be used in the declaration of an empty array in a
5231 // class or structure definition. For example:
5232 // __declspec(property(get=GetX, put=PutX)) int x[];
5233 // The above statement indicates that x[] can be used with one or more array
5234 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5235 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5236 if (IsMSPropertySubscript) {
5237 if (ArgExprs.size() > 1) {
5238 Diag(Loc: base->getExprLoc(),
5239 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5240 return ExprError();
5241 }
5242
5243 // Build MS property subscript expression if base is MS property reference
5244 // or MS property subscript.
5245 return new (Context)
5246 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5247 VK_LValue, OK_Ordinary, rbLoc);
5248 }
5249
5250 // Use C++ overloaded-operator rules if either operand has record
5251 // type. The spec says to do this if either type is *overloadable*,
5252 // but enum types can't declare subscript operators or conversion
5253 // operators, so there's nothing interesting for overload resolution
5254 // to do if there aren't any record types involved.
5255 //
5256 // ObjC pointers have their own subscripting logic that is not tied
5257 // to overload resolution and so should not take this path.
5258 //
5259 // Issue a better diagnostic if we tried to pass multiple arguments to
5260 // a builtin subscript operator rather than diagnosing this as a generic
5261 // overload resolution failure.
5262 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5263 !base->getType()->isRecordType() &&
5264 !base->getType()->isObjCObjectPointerType()) {
5265 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5266 << base->getType() << base->getSourceRange();
5267 return ExprError();
5268 }
5269
5270 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5271 ((base->getType()->isRecordType() ||
5272 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5273 ArgExprs[0]->getType()->isRecordType())))) {
5274 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5275 }
5276
5277 ExprResult Res =
5278 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5279
5280 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5281 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5282
5283 return Res;
5284}
5285
5286ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5287 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5288 InitializationKind Kind =
5289 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5290 InitializationSequence InitSeq(*this, Entity, Kind, E);
5291 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5292}
5293
5294ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5295 Expr *RowIdx,
5296 SourceLocation RBLoc) {
5297 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5298 if (BaseR.isInvalid())
5299 return BaseR;
5300 Base = BaseR.get();
5301
5302 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5303 if (RowR.isInvalid())
5304 return RowR;
5305 RowIdx = RowR.get();
5306
5307 // Build an unanalyzed expression if any of the operands is type-dependent.
5308 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5309 return new (Context)
5310 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5311
5312 // Check that IndexExpr is an integer expression. If it is a constant
5313 // expression, check that it is less than Dim (= the number of elements in the
5314 // corresponding dimension).
5315 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5316 bool IsColumnIdx) -> Expr * {
5317 if (!IndexExpr->getType()->isIntegerType() &&
5318 !IndexExpr->isTypeDependent()) {
5319 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5320 << IsColumnIdx;
5321 return nullptr;
5322 }
5323
5324 if (std::optional<llvm::APSInt> Idx =
5325 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5326 if ((*Idx < 0 || *Idx >= Dim)) {
5327 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5328 << IsColumnIdx << Dim;
5329 return nullptr;
5330 }
5331 }
5332
5333 ExprResult ConvExpr = IndexExpr;
5334 assert(!ConvExpr.isInvalid() &&
5335 "should be able to convert any integer type to size type");
5336 return ConvExpr.get();
5337 };
5338
5339 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5340 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5341 if (!RowIdx)
5342 return ExprError();
5343
5344 QualType RowVecQT =
5345 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5346
5347 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5348}
5349
5350ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5351 Expr *ColumnIdx,
5352 SourceLocation RBLoc) {
5353 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5354 if (BaseR.isInvalid())
5355 return BaseR;
5356 Base = BaseR.get();
5357
5358 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5359 if (RowR.isInvalid())
5360 return RowR;
5361 RowIdx = RowR.get();
5362
5363 if (!ColumnIdx)
5364 return new (Context) MatrixSubscriptExpr(
5365 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5366
5367 // Build an unanalyzed expression if any of the operands is type-dependent.
5368 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5369 ColumnIdx->isTypeDependent())
5370 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5371 Context.DependentTy, RBLoc);
5372
5373 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5374 if (ColumnR.isInvalid())
5375 return ColumnR;
5376 ColumnIdx = ColumnR.get();
5377
5378 // Check that IndexExpr is an integer expression. If it is a constant
5379 // expression, check that it is less than Dim (= the number of elements in the
5380 // corresponding dimension).
5381 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5382 bool IsColumnIdx) -> Expr * {
5383 if (!IndexExpr->getType()->isIntegerType() &&
5384 !IndexExpr->isTypeDependent()) {
5385 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5386 << IsColumnIdx;
5387 return nullptr;
5388 }
5389
5390 if (std::optional<llvm::APSInt> Idx =
5391 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5392 if ((*Idx < 0 || *Idx >= Dim)) {
5393 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5394 << IsColumnIdx << Dim;
5395 return nullptr;
5396 }
5397 }
5398
5399 ExprResult ConvExpr = IndexExpr;
5400 assert(!ConvExpr.isInvalid() &&
5401 "should be able to convert any integer type to size type");
5402 return ConvExpr.get();
5403 };
5404
5405 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5406 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5407 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5408 if (!RowIdx || !ColumnIdx)
5409 return ExprError();
5410
5411 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5412 MTy->getElementType(), RBLoc);
5413}
5414
5415void Sema::CheckAddressOfNoDeref(const Expr *E) {
5416 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5417 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5418
5419 // For expressions like `&(*s).b`, the base is recorded and what should be
5420 // checked.
5421 const MemberExpr *Member = nullptr;
5422 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5423 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5424
5425 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5426}
5427
5428void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5429 if (isUnevaluatedContext())
5430 return;
5431
5432 QualType ResultTy = E->getType();
5433 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5434
5435 // Bail if the element is an array since it is not memory access.
5436 if (isa<ArrayType>(Val: ResultTy))
5437 return;
5438
5439 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5440 LastRecord.PossibleDerefs.insert(Ptr: E);
5441 return;
5442 }
5443
5444 // Check if the base type is a pointer to a member access of a struct
5445 // marked with noderef.
5446 const Expr *Base = E->getBase();
5447 QualType BaseTy = Base->getType();
5448 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5449 // Not a pointer access
5450 return;
5451
5452 const MemberExpr *Member = nullptr;
5453 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5454 Member->isArrow())
5455 Base = Member->getBase();
5456
5457 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5458 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5459 LastRecord.PossibleDerefs.insert(Ptr: E);
5460 }
5461}
5462
5463ExprResult
5464Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5465 Expr *Idx, SourceLocation RLoc) {
5466 Expr *LHSExp = Base;
5467 Expr *RHSExp = Idx;
5468
5469 ExprValueKind VK = VK_LValue;
5470 ExprObjectKind OK = OK_Ordinary;
5471
5472 // Per C++ core issue 1213, the result is an xvalue if either operand is
5473 // a non-lvalue array, and an lvalue otherwise.
5474 if (getLangOpts().CPlusPlus11) {
5475 for (auto *Op : {LHSExp, RHSExp}) {
5476 Op = Op->IgnoreImplicit();
5477 if (Op->getType()->isArrayType() && !Op->isLValue())
5478 VK = VK_XValue;
5479 }
5480 }
5481
5482 // Perform default conversions.
5483 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5484 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5485 if (Result.isInvalid())
5486 return ExprError();
5487 LHSExp = Result.get();
5488 }
5489 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5490 if (Result.isInvalid())
5491 return ExprError();
5492 RHSExp = Result.get();
5493
5494 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5495
5496 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5497 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5498 // in the subscript position. As a result, we need to derive the array base
5499 // and index from the expression types.
5500 Expr *BaseExpr, *IndexExpr;
5501 QualType ResultType;
5502 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5503 BaseExpr = LHSExp;
5504 IndexExpr = RHSExp;
5505 ResultType =
5506 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5507 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5508 BaseExpr = LHSExp;
5509 IndexExpr = RHSExp;
5510 ResultType = PTy->getPointeeType();
5511 } else if (const ObjCObjectPointerType *PTy =
5512 LHSTy->getAs<ObjCObjectPointerType>()) {
5513 BaseExpr = LHSExp;
5514 IndexExpr = RHSExp;
5515
5516 // Use custom logic if this should be the pseudo-object subscript
5517 // expression.
5518 if (!LangOpts.isSubscriptPointerArithmetic())
5519 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5520 getterMethod: nullptr, setterMethod: nullptr);
5521
5522 ResultType = PTy->getPointeeType();
5523 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5524 // Handle the uncommon case of "123[Ptr]".
5525 BaseExpr = RHSExp;
5526 IndexExpr = LHSExp;
5527 ResultType = PTy->getPointeeType();
5528 } else if (const ObjCObjectPointerType *PTy =
5529 RHSTy->getAs<ObjCObjectPointerType>()) {
5530 // Handle the uncommon case of "123[Ptr]".
5531 BaseExpr = RHSExp;
5532 IndexExpr = LHSExp;
5533 ResultType = PTy->getPointeeType();
5534 if (!LangOpts.isSubscriptPointerArithmetic()) {
5535 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5536 << ResultType << BaseExpr->getSourceRange();
5537 return ExprError();
5538 }
5539 } else if (LHSTy->isSubscriptableVectorType()) {
5540 if (LHSTy->isBuiltinType() &&
5541 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5542 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5543 if (BTy->isSVEBool())
5544 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5545 << LHSExp->getSourceRange()
5546 << RHSExp->getSourceRange());
5547 ResultType = BTy->getSveEltType(Ctx: Context);
5548 } else {
5549 const VectorType *VTy = LHSTy->getAs<VectorType>();
5550 ResultType = VTy->getElementType();
5551 }
5552 BaseExpr = LHSExp; // vectors: V[123]
5553 IndexExpr = RHSExp;
5554 // We apply C++ DR1213 to vector subscripting too.
5555 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5556 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5557 if (Materialized.isInvalid())
5558 return ExprError();
5559 LHSExp = Materialized.get();
5560 }
5561 VK = LHSExp->getValueKind();
5562 if (VK != VK_PRValue)
5563 OK = OK_VectorComponent;
5564
5565 QualType BaseType = BaseExpr->getType();
5566 Qualifiers BaseQuals = BaseType.getQualifiers();
5567 Qualifiers MemberQuals = ResultType.getQualifiers();
5568 Qualifiers Combined = BaseQuals + MemberQuals;
5569 if (Combined != MemberQuals)
5570 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5571 } else if (LHSTy->isArrayType()) {
5572 // If we see an array that wasn't promoted by
5573 // DefaultFunctionArrayLvalueConversion, it must be an array that
5574 // wasn't promoted because of the C90 rule that doesn't
5575 // allow promoting non-lvalue arrays. Warn, then
5576 // force the promotion here.
5577 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5578 << LHSExp->getSourceRange();
5579 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5580 CK: CK_ArrayToPointerDecay).get();
5581 LHSTy = LHSExp->getType();
5582
5583 BaseExpr = LHSExp;
5584 IndexExpr = RHSExp;
5585 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5586 } else if (RHSTy->isArrayType()) {
5587 // Same as previous, except for 123[f().a] case
5588 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5589 << RHSExp->getSourceRange();
5590 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5591 CK: CK_ArrayToPointerDecay).get();
5592 RHSTy = RHSExp->getType();
5593
5594 BaseExpr = RHSExp;
5595 IndexExpr = LHSExp;
5596 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5597 } else {
5598 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5599 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5600 }
5601 // C99 6.5.2.1p1
5602 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5603 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5604 << IndexExpr->getSourceRange());
5605
5606 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5607 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5608 !IndexExpr->isTypeDependent()) {
5609 std::optional<llvm::APSInt> IntegerContantExpr =
5610 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5611 if (!IntegerContantExpr.has_value() ||
5612 IntegerContantExpr.value().isNegative())
5613 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5614 }
5615
5616 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5617 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5618 // type. Note that Functions are not objects, and that (in C99 parlance)
5619 // incomplete types are not object types.
5620 if (ResultType->isFunctionType()) {
5621 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5622 << ResultType << BaseExpr->getSourceRange();
5623 return ExprError();
5624 }
5625
5626 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5627 // GNU extension: subscripting on pointer to void
5628 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5629 << BaseExpr->getSourceRange();
5630
5631 // C forbids expressions of unqualified void type from being l-values.
5632 // See IsCForbiddenLValueType.
5633 if (!ResultType.hasQualifiers())
5634 VK = VK_PRValue;
5635 } else if (!ResultType->isDependentType() &&
5636 !ResultType.isWebAssemblyReferenceType() &&
5637 RequireCompleteSizedType(
5638 Loc: LLoc, T: ResultType,
5639 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5640 return ExprError();
5641
5642 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5643 !ResultType.isCForbiddenLValueType());
5644
5645 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5646 FunctionScopes.size() > 1) {
5647 if (auto *TT =
5648 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5649 for (auto I = FunctionScopes.rbegin(),
5650 E = std::prev(x: FunctionScopes.rend());
5651 I != E; ++I) {
5652 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5653 if (CSI == nullptr)
5654 break;
5655 DeclContext *DC = nullptr;
5656 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5657 DC = LSI->CallOperator;
5658 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5659 DC = CRSI->TheCapturedDecl;
5660 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5661 DC = BSI->TheDecl;
5662 if (DC) {
5663 if (DC->containsDecl(D: TT->getDecl()))
5664 break;
5665 captureVariablyModifiedType(
5666 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5667 }
5668 }
5669 }
5670 }
5671
5672 return new (Context)
5673 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5674}
5675
5676bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5677 ParmVarDecl *Param, Expr *RewrittenInit,
5678 bool SkipImmediateInvocations) {
5679 if (Param->hasUnparsedDefaultArg()) {
5680 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5681 // If we've already cleared out the location for the default argument,
5682 // that means we're parsing it right now.
5683 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5684 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5685 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5686 Param->setInvalidDecl();
5687 return true;
5688 }
5689
5690 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5691 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5692 Diag(Loc: UnparsedDefaultArgLocs[Param],
5693 DiagID: diag::note_default_argument_declared_here);
5694 return true;
5695 }
5696
5697 if (Param->hasUninstantiatedDefaultArg()) {
5698 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5699 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5700 return true;
5701 }
5702
5703 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5704 assert(Init && "default argument but no initializer?");
5705
5706 // If the default expression creates temporaries, we need to
5707 // push them to the current stack of expression temporaries so they'll
5708 // be properly destroyed.
5709 // FIXME: We should really be rebuilding the default argument with new
5710 // bound temporaries; see the comment in PR5810.
5711 // We don't need to do that with block decls, though, because
5712 // blocks in default argument expression can never capture anything.
5713 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5714 // Set the "needs cleanups" bit regardless of whether there are
5715 // any explicit objects.
5716 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5717 // Append all the objects to the cleanup list. Right now, this
5718 // should always be a no-op, because blocks in default argument
5719 // expressions should never be able to capture anything.
5720 assert(!InitWithCleanup->getNumObjects() &&
5721 "default argument expression has capturing blocks?");
5722 }
5723 // C++ [expr.const]p15.1:
5724 // An expression or conversion is in an immediate function context if it is
5725 // potentially evaluated and [...] its innermost enclosing non-block scope
5726 // is a function parameter scope of an immediate function.
5727 EnterExpressionEvaluationContext EvalContext(
5728 *this,
5729 FD->isImmediateFunction()
5730 ? ExpressionEvaluationContext::ImmediateFunctionContext
5731 : ExpressionEvaluationContext::PotentiallyEvaluated,
5732 Param);
5733 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5734 SkipImmediateInvocations;
5735 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5736 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5737 });
5738 return false;
5739}
5740
5741struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5742 const ASTContext &Context;
5743 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5744 ShouldVisitImplicitCode = true;
5745 }
5746
5747 bool HasImmediateCalls = false;
5748
5749 bool VisitCallExpr(CallExpr *E) override {
5750 if (const FunctionDecl *FD = E->getDirectCallee())
5751 HasImmediateCalls |= FD->isImmediateFunction();
5752 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5753 }
5754
5755 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5756 if (const FunctionDecl *FD = E->getConstructor())
5757 HasImmediateCalls |= FD->isImmediateFunction();
5758 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5759 }
5760
5761 // SourceLocExpr are not immediate invocations
5762 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5763 // need to be rebuilt so that they refer to the correct SourceLocation and
5764 // DeclContext.
5765 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5766 HasImmediateCalls = true;
5767 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5768 }
5769
5770 // A nested lambda might have parameters with immediate invocations
5771 // in their default arguments.
5772 // The compound statement is not visited (as it does not constitute a
5773 // subexpression).
5774 // FIXME: We should consider visiting and transforming captures
5775 // with init expressions.
5776 bool VisitLambdaExpr(LambdaExpr *E) override {
5777 return VisitCXXMethodDecl(D: E->getCallOperator());
5778 }
5779
5780 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5781 return TraverseStmt(S: E->getExpr());
5782 }
5783
5784 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5785 return TraverseStmt(S: E->getExpr());
5786 }
5787};
5788
5789struct EnsureImmediateInvocationInDefaultArgs
5790 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5791 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5792 : TreeTransform(SemaRef) {}
5793
5794 bool AlwaysRebuild() { return true; }
5795
5796 // Lambda can only have immediate invocations in the default
5797 // args of their parameters, which is transformed upon calling the closure.
5798 // The body is not a subexpression, so we have nothing to do.
5799 // FIXME: Immediate calls in capture initializers should be transformed.
5800 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5801 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5802
5803 // Make sure we don't rebuild the this pointer as it would
5804 // cause it to incorrectly point it to the outermost class
5805 // in the case of nested struct initialization.
5806 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5807
5808 // Rewrite to source location to refer to the context in which they are used.
5809 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5810 DeclContext *DC = E->getParentContext();
5811 if (DC == SemaRef.CurContext)
5812 return E;
5813
5814 // FIXME: During instantiation, because the rebuild of defaults arguments
5815 // is not always done in the context of the template instantiator,
5816 // we run the risk of producing a dependent source location
5817 // that would never be rebuilt.
5818 // This usually happens during overload resolution, or in contexts
5819 // where the value of the source location does not matter.
5820 // However, we should find a better way to deal with source location
5821 // of function templates.
5822 if (!SemaRef.CurrentInstantiationScope ||
5823 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5824 DC = SemaRef.CurContext;
5825
5826 return getDerived().RebuildSourceLocExpr(
5827 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5828 }
5829};
5830
5831ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5832 FunctionDecl *FD, ParmVarDecl *Param,
5833 Expr *Init) {
5834 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5835
5836 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5837 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5838 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5839 InitializationContext =
5840 OutermostDeclarationWithDelayedImmediateInvocations();
5841 if (!InitializationContext.has_value())
5842 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5843
5844 if (!Init && !Param->hasUnparsedDefaultArg()) {
5845 // Mark that we are replacing a default argument first.
5846 // If we are instantiating a template we won't have to
5847 // retransform immediate calls.
5848 // C++ [expr.const]p15.1:
5849 // An expression or conversion is in an immediate function context if it
5850 // is potentially evaluated and [...] its innermost enclosing non-block
5851 // scope is a function parameter scope of an immediate function.
5852 EnterExpressionEvaluationContext EvalContext(
5853 *this,
5854 FD->isImmediateFunction()
5855 ? ExpressionEvaluationContext::ImmediateFunctionContext
5856 : ExpressionEvaluationContext::PotentiallyEvaluated,
5857 Param);
5858
5859 if (Param->hasUninstantiatedDefaultArg()) {
5860 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5861 return ExprError();
5862 }
5863 // CWG2631
5864 // An immediate invocation that is not evaluated where it appears is
5865 // evaluated and checked for whether it is a constant expression at the
5866 // point where the enclosing initializer is used in a function call.
5867 ImmediateCallVisitor V(getASTContext());
5868 if (!NestedDefaultChecking)
5869 V.TraverseDecl(D: Param);
5870
5871 // Rewrite the call argument that was created from the corresponding
5872 // parameter's default argument.
5873 if (V.HasImmediateCalls ||
5874 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5875 if (V.HasImmediateCalls)
5876 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5877 CallLoc, Param, CurContext};
5878 // Pass down lifetime extending flag, and collect temporaries in
5879 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5880 currentEvaluationContext().InLifetimeExtendingContext =
5881 parentEvaluationContext().InLifetimeExtendingContext;
5882 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5883 ExprResult Res;
5884 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5885 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5886 /*NotCopy=*/NotCopyInit: false);
5887 });
5888 if (Res.isInvalid())
5889 return ExprError();
5890 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5891 EqualLoc: Res.get()->getBeginLoc());
5892 if (Res.isInvalid())
5893 return ExprError();
5894 Init = Res.get();
5895 }
5896 }
5897
5898 if (CheckCXXDefaultArgExpr(
5899 CallLoc, FD, Param, RewrittenInit: Init,
5900 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5901 return ExprError();
5902
5903 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5904 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5905}
5906
5907static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5908 FieldDecl *Field) {
5909 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5910 return Pattern;
5911 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5912 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5913 DeclContext::lookup_result Lookup =
5914 ClassPattern->lookup(Name: Field->getDeclName());
5915 auto Rng = llvm::make_filter_range(
5916 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5917 if (Rng.empty())
5918 return nullptr;
5919 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5920 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5921 // && "Duplicated instantiation pattern for field decl");
5922 return cast<FieldDecl>(Val: *Rng.begin());
5923}
5924
5925ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
5926 FieldDecl *Field,
5927 const InitializedEntity &Entity,
5928 bool NestedDefaultChecking,
5929 bool NeedRebuild) {
5930 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5931
5932 if (!Field->getInClassInitializer() &&
5933 isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5934 // Maybe we haven't instantiated the in-class initializer. Go check the
5935 // pattern FieldDecl to see if it has one.
5936 FieldDecl *Pattern =
5937 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5938 assert(Pattern && "We must have set the Pattern!");
5939 if (!Pattern->hasInClassInitializer() ||
5940 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5941 TemplateArgs: getTemplateInstantiationArgs(D: Field)))
5942 return ExprError();
5943 }
5944
5945 Expr *InClassInit = Field->getInClassInitializer();
5946 if (!InClassInit) {
5947 // DR1351:
5948 // If the brace-or-equal-initializer of a non-static data member
5949 // invokes a defaulted default constructor of its class or of an
5950 // enclosing class in a potentially evaluated subexpression, the
5951 // program is ill-formed.
5952 //
5953 // This resolution is unworkable: the exception specification of the
5954 // default constructor can be needed in an unevaluated context, in
5955 // particular, in the operand of a noexcept-expression, and we can be
5956 // unable to compute an exception specification for an enclosed class.
5957 //
5958 // Any attempt to resolve the exception specification of a defaulted default
5959 // constructor before the initializer is lexically complete will ultimately
5960 // come here at which point we can diagnose it.
5961 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5962 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5963 << OutermostClass << Field;
5964 Diag(Loc: Field->getEndLoc(),
5965 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5966 // Recover by marking the field invalid, unless we're in a SFINAE context.
5967 if (!isSFINAEContext())
5968 Field->setInvalidDecl();
5969 return ExprError();
5970 }
5971
5972 // CWG2631
5973 // An immediate invocation that is not evaluated where it appears is
5974 // evaluated and checked for whether it is a constant expression at the
5975 // point where the enclosing initializer is used in a [...] a constructor
5976 // definition, or an aggregate initialization.
5977 ImmediateCallVisitor V(getASTContext());
5978 if (!NestedDefaultChecking)
5979 V.TraverseDecl(D: Field);
5980
5981 // CWG1815
5982 // Support lifetime extension of temporary created by aggregate
5983 // initialization using a default member initializer. We should rebuild
5984 // the initializer in a lifetime extension context if the initializer
5985 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5986 // extension code recurses into the default initializer and does lifetime
5987 // extension when warranted.
5988 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(Val: InClassInit);
5989 Expr *Init = InClassInit;
5990 if (!InClassInit->containsErrors() &&
5991 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5992 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5993 CurContext};
5994 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5995 NestedDefaultChecking;
5996 // Pass down lifetime extending flag, and collect temporaries in
5997 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
5998 currentEvaluationContext().InLifetimeExtendingContext =
5999 parentEvaluationContext().InLifetimeExtendingContext;
6000
6001 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6002 ExprResult Res;
6003 runWithSufficientStackSpace(Loc, Fn: [&] {
6004 Res = Immediate.TransformInitializer(Init: InClassInit,
6005 /*CXXDirectInit=*/NotCopyInit: false);
6006 });
6007 if (!Res.isInvalid())
6008 Res = ConvertMemberDefaultInitExpression(FD: Field, Entity, InitExpr: Res.get(), InitLoc: Loc);
6009 if (Res.isInvalid()) {
6010 Field->setInvalidDecl();
6011 return ExprError();
6012 }
6013 Init = Res.get();
6014 }
6015
6016 if (!NestedDefaultChecking)
6017 runWithSufficientStackSpace(Loc, Fn: [&] {
6018 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/false);
6019 });
6020 return Init;
6021}
6022
6023ExprResult Sema::BuildCXXCtorDefaultInitExpr(SourceLocation Loc,
6024 FieldDecl *Field) {
6025 assert(Field->hasInClassInitializer());
6026
6027 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6028
6029 // C++11 [class.base.init]p7:
6030 // The initialization of each base and member constitutes a
6031 // full-expression.
6032 // So this initializer gets an evaluation context of its own, and is finished
6033 // as a full-expression below.
6034 EnterExpressionEvaluationContext EvalContext(
6035 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6036 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6037
6038 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6039 if (!InitContext)
6040 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6041
6042 // [class.temporary]/p7:
6043 // If such a temporary object would otherwise be destroyed at the end of the
6044 // for-range-initializer full-expression, the object persists for the lifetime
6045 // of the reference initialized by the for-range-initializer.
6046 //
6047 // A default member initializer used by a constructor is a separate
6048 // full-expression, we don't need extend temporaries lifetime in this
6049 // situation, the NeedRebuild will always false.
6050 ExprResult Init = BuildCXXDefaultInitInternal(
6051 Loc, Field,
6052 Entity: InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: Field),
6053 NestedDefaultChecking, /*NeedRebuild=*/false);
6054 if (Init.isInvalid())
6055 return ExprError();
6056
6057 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscardedValue=*/false);
6058 if (Init.isInvalid()) {
6059 Field->setInvalidDecl();
6060 return ExprError();
6061 }
6062
6063 return CXXDefaultInitExpr::Create(
6064 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6065 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6066}
6067
6068ExprResult
6069Sema::BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
6070 const InitializedEntity &MemberEntity) {
6071 assert(Field->hasInClassInitializer());
6072
6073 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6074
6075 // Unlike a mem-initializer, this initializer is a subexpression of the
6076 // full-expression containing the aggregate initialization. It is evaluated
6077 // exactly as that full-expression is, so inherit the enclosing context kind
6078 // rather than forcing a potentially evaluated one.
6079 EnterExpressionEvaluationContext EvalContext(
6080 *this, currentEvaluationContext().Context, Field);
6081 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6082
6083 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6084 if (!InitContext)
6085 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6086
6087 // [class.temporary]/p7:
6088 // If such a temporary object would otherwise be destroyed at the end of the
6089 // for-range-initializer full-expression, the object persists for the lifetime
6090 // of the reference initialized by the for-range-initializer.
6091 //
6092 // A default member initializer used by an aggregate initialization belongs to
6093 // the full-expression containing the aggregate initialization. we need extend
6094 // temporaries lifetime in this situation, the NeedRebuild will always true.
6095
6096 // CWG1815: always rebuild, never share the AST built when the field was
6097 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6098 // collected in this context, which is what lets the aggregate initialization
6099 // lifetime-extend them; sharing one AST would also make several uses of the
6100 // same field fight over its extension. A mem-initializer has no such need,
6101 // as its temporaries die at the end of the initializer itself.
6102 ExprResult Init = BuildCXXDefaultInitInternal(
6103 Loc, Field, Entity: MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6104 if (Init.isInvalid())
6105 return ExprError();
6106
6107 // Deliberately not finished as a full-expression: leaving the temporaries it
6108 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6109 // them into the enclosing context, which eventually wraps them all in a
6110 // single ExprWithCleanups. They are then destroyed at the end of the
6111 // containing full-expression, in reverse construction order.
6112
6113 return CXXDefaultInitExpr::Create(
6114 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6115 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6116}
6117
6118VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
6119 const FunctionProtoType *Proto,
6120 Expr *Fn) {
6121 if (Proto && Proto->isVariadic()) {
6122 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6123 return VariadicCallType::Constructor;
6124 else if (Fn && Fn->getType()->isBlockPointerType())
6125 return VariadicCallType::Block;
6126 else if (FDecl) {
6127 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6128 if (Method->isInstance())
6129 return VariadicCallType::Method;
6130 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6131 return VariadicCallType::Method;
6132 return VariadicCallType::Function;
6133 }
6134 return VariadicCallType::DoesNotApply;
6135}
6136
6137namespace {
6138class FunctionCallCCC final : public FunctionCallFilterCCC {
6139public:
6140 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6141 unsigned NumArgs, MemberExpr *ME)
6142 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6143 FunctionName(FuncName) {}
6144
6145 bool ValidateCandidate(const TypoCorrection &candidate) override {
6146 if (!candidate.getCorrectionSpecifier() ||
6147 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6148 return false;
6149 }
6150
6151 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6152 }
6153
6154 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6155 return std::make_unique<FunctionCallCCC>(args&: *this);
6156 }
6157
6158private:
6159 const IdentifierInfo *const FunctionName;
6160};
6161}
6162
6163static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6164 FunctionDecl *FDecl,
6165 ArrayRef<Expr *> Args) {
6166 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6167 DeclarationName FuncName = FDecl->getDeclName();
6168 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6169
6170 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6171 if (TypoCorrection Corrected = S.CorrectTypo(
6172 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6173 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6174 Mode: CorrectTypoKind::ErrorRecovery)) {
6175 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6176 if (Corrected.isOverloaded()) {
6177 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6178 OverloadCandidateSet::iterator Best;
6179 for (NamedDecl *CD : Corrected) {
6180 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6181 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6182 CandidateSet&: OCS);
6183 }
6184 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6185 case OR_Success:
6186 ND = Best->FoundDecl;
6187 Corrected.setCorrectionDecl(ND);
6188 break;
6189 default:
6190 break;
6191 }
6192 }
6193 ND = ND->getUnderlyingDecl();
6194 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6195 return Corrected;
6196 }
6197 }
6198 return TypoCorrection();
6199}
6200
6201// [C++26][[expr.unary.op]/p4
6202// A pointer to member is only formed when an explicit &
6203// is used and its operand is a qualified-id not enclosed in parentheses.
6204static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6205 if (!isa<ParenExpr>(Val: Fn))
6206 return false;
6207
6208 Fn = Fn->IgnoreParens();
6209
6210 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6211 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6212 return false;
6213 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6214 return DRE->hasQualifier();
6215 }
6216 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6217 return bool(OVL->getQualifier());
6218 return false;
6219}
6220
6221bool
6222Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6223 FunctionDecl *FDecl,
6224 const FunctionProtoType *Proto,
6225 ArrayRef<Expr *> Args,
6226 SourceLocation RParenLoc,
6227 bool IsExecConfig) {
6228 // Bail out early if calling a builtin with custom typechecking.
6229 // For HLSL builtin aliases, argument conversion is still needed because
6230 // overload resolution may have selected a conversion sequence (e.g.,
6231 // vector-to-scalar truncation) that must be applied before the custom
6232 // type checker runs.
6233 if (FDecl)
6234 if (unsigned ID = FDecl->getBuiltinID())
6235 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6236 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6237 return false;
6238
6239 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6240 // assignment, to the types of the corresponding parameter, ...
6241
6242 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6243 bool HasExplicitObjectParameter =
6244 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6245 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6246 unsigned NumParams = Proto->getNumParams();
6247 bool Invalid = false;
6248 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6249 unsigned FnKind = Fn->getType()->isBlockPointerType()
6250 ? 1 /* block */
6251 : (IsExecConfig ? 3 /* kernel function (exec config) */
6252 : 0 /* function */);
6253
6254 // If too few arguments are available (and we don't have default
6255 // arguments for the remaining parameters), don't make the call.
6256 if (Args.size() < NumParams) {
6257 if (Args.size() < MinArgs) {
6258 TypoCorrection TC;
6259 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6260 unsigned diag_id =
6261 MinArgs == NumParams && !Proto->isVariadic()
6262 ? diag::err_typecheck_call_too_few_args_suggest
6263 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6264 diagnoseTypo(
6265 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6266 << FnKind << MinArgs - ExplicitObjectParameterOffset
6267 << static_cast<unsigned>(Args.size()) -
6268 ExplicitObjectParameterOffset
6269 << HasExplicitObjectParameter << TC.getCorrectionRange());
6270 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6271 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6272 ->getDeclName())
6273 Diag(Loc: RParenLoc,
6274 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6275 ? diag::err_typecheck_call_too_few_args_one
6276 : diag::err_typecheck_call_too_few_args_at_least_one)
6277 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6278 << HasExplicitObjectParameter << Fn->getSourceRange();
6279 else
6280 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6281 ? diag::err_typecheck_call_too_few_args
6282 : diag::err_typecheck_call_too_few_args_at_least)
6283 << FnKind << MinArgs - ExplicitObjectParameterOffset
6284 << static_cast<unsigned>(Args.size()) -
6285 ExplicitObjectParameterOffset
6286 << HasExplicitObjectParameter << Fn->getSourceRange();
6287
6288 // Emit the location of the prototype.
6289 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6290 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6291 << FDecl << FDecl->getParametersSourceRange();
6292
6293 return true;
6294 }
6295 // We reserve space for the default arguments when we create
6296 // the call expression, before calling ConvertArgumentsForCall.
6297 assert((Call->getNumArgs() == NumParams) &&
6298 "We should have reserved space for the default arguments before!");
6299 }
6300
6301 // If too many are passed and not variadic, error on the extras and drop
6302 // them.
6303 if (Args.size() > NumParams) {
6304 if (!Proto->isVariadic()) {
6305 TypoCorrection TC;
6306 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6307 unsigned diag_id =
6308 MinArgs == NumParams && !Proto->isVariadic()
6309 ? diag::err_typecheck_call_too_many_args_suggest
6310 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6311 diagnoseTypo(
6312 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6313 << FnKind << NumParams - ExplicitObjectParameterOffset
6314 << static_cast<unsigned>(Args.size()) -
6315 ExplicitObjectParameterOffset
6316 << HasExplicitObjectParameter << TC.getCorrectionRange());
6317 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6318 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6319 ->getDeclName())
6320 Diag(Loc: Args[NumParams]->getBeginLoc(),
6321 DiagID: MinArgs == NumParams
6322 ? diag::err_typecheck_call_too_many_args_one
6323 : diag::err_typecheck_call_too_many_args_at_most_one)
6324 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6325 << static_cast<unsigned>(Args.size()) -
6326 ExplicitObjectParameterOffset
6327 << HasExplicitObjectParameter << Fn->getSourceRange()
6328 << SourceRange(Args[NumParams]->getBeginLoc(),
6329 Args.back()->getEndLoc());
6330 else
6331 Diag(Loc: Args[NumParams]->getBeginLoc(),
6332 DiagID: MinArgs == NumParams
6333 ? diag::err_typecheck_call_too_many_args
6334 : diag::err_typecheck_call_too_many_args_at_most)
6335 << FnKind << NumParams - ExplicitObjectParameterOffset
6336 << static_cast<unsigned>(Args.size()) -
6337 ExplicitObjectParameterOffset
6338 << HasExplicitObjectParameter << Fn->getSourceRange()
6339 << SourceRange(Args[NumParams]->getBeginLoc(),
6340 Args.back()->getEndLoc());
6341
6342 // Emit the location of the prototype.
6343 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6344 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6345 << FDecl << FDecl->getParametersSourceRange();
6346
6347 // This deletes the extra arguments.
6348 Call->shrinkNumArgs(NewNumArgs: NumParams);
6349 return true;
6350 }
6351 }
6352 SmallVector<Expr *, 8> AllArgs;
6353 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6354
6355 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6356 AllArgs, CallType);
6357 if (Invalid)
6358 return true;
6359 unsigned TotalNumArgs = AllArgs.size();
6360 for (unsigned i = 0; i < TotalNumArgs; ++i)
6361 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6362
6363 Call->computeDependence();
6364 return false;
6365}
6366
6367bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6368 const FunctionProtoType *Proto,
6369 unsigned FirstParam, ArrayRef<Expr *> Args,
6370 SmallVectorImpl<Expr *> &AllArgs,
6371 VariadicCallType CallType, bool AllowExplicit,
6372 bool IsListInitialization) {
6373 unsigned NumParams = Proto->getNumParams();
6374 bool Invalid = false;
6375 size_t ArgIx = 0;
6376 // Continue to check argument types (even if we have too few/many args).
6377 for (unsigned i = FirstParam; i < NumParams; i++) {
6378 QualType ProtoArgType = Proto->getParamType(i);
6379
6380 Expr *Arg;
6381 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6382 if (ArgIx < Args.size()) {
6383 Arg = Args[ArgIx++];
6384
6385 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6386 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6387 return true;
6388
6389 // Strip the unbridged-cast placeholder expression off, if applicable.
6390 bool CFAudited = false;
6391 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6392 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6393 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6394 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6395 else if (getLangOpts().ObjCAutoRefCount &&
6396 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6397 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6398 CFAudited = true;
6399
6400 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6401 ProtoArgType->isBlockPointerType())
6402 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6403 BE->getBlockDecl()->setDoesNotEscape();
6404 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6405 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6406 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6407 if (ArgExpr.isInvalid())
6408 return true;
6409 Arg = ArgExpr.getAs<Expr>();
6410 }
6411
6412 InitializedEntity Entity =
6413 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6414 Type: ProtoArgType)
6415 : InitializedEntity::InitializeParameter(
6416 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6417
6418 // Remember that parameter belongs to a CF audited API.
6419 if (CFAudited)
6420 Entity.setParameterCFAudited();
6421
6422 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6423 // function boundaries is a common oversight.
6424 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6425 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6426 bool isPedantic =
6427 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6428 Diag(Loc: Arg->getExprLoc(),
6429 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6430 : diag::warn_obt_discarded_at_function_boundary)
6431 << Arg->getType() << ProtoArgType;
6432 }
6433
6434 ExprResult ArgE = PerformCopyInitialization(
6435 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6436 if (ArgE.isInvalid())
6437 return true;
6438
6439 Arg = ArgE.getAs<Expr>();
6440 } else {
6441 assert(Param && "can't use default arguments without a known callee");
6442
6443 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6444 if (ArgExpr.isInvalid())
6445 return true;
6446
6447 Arg = ArgExpr.getAs<Expr>();
6448 }
6449
6450 // Check for array bounds violations for each argument to the call. This
6451 // check only triggers warnings when the argument isn't a more complex Expr
6452 // with its own checking, such as a BinaryOperator.
6453 CheckArrayAccess(E: Arg);
6454
6455 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6456 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6457
6458 AllArgs.push_back(Elt: Arg);
6459 }
6460
6461 // If this is a variadic call, handle args passed through "...".
6462 if (CallType != VariadicCallType::DoesNotApply) {
6463 // Assume that extern "C" functions with variadic arguments that
6464 // return __unknown_anytype aren't *really* variadic.
6465 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6466 FDecl->isExternC()) {
6467 for (Expr *A : Args.slice(N: ArgIx)) {
6468 QualType paramType; // ignored
6469 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6470 Invalid |= arg.isInvalid();
6471 AllArgs.push_back(Elt: arg.get());
6472 }
6473
6474 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6475 } else {
6476 for (Expr *A : Args.slice(N: ArgIx)) {
6477 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6478 Invalid |= Arg.isInvalid();
6479 AllArgs.push_back(Elt: Arg.get());
6480 }
6481 }
6482
6483 // Check for array bounds violations.
6484 for (Expr *A : Args.slice(N: ArgIx))
6485 CheckArrayAccess(E: A);
6486 }
6487 return Invalid;
6488}
6489
6490static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6491 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6492 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6493 TL = DTL.getOriginalLoc();
6494 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6495 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6496 << ATL.getLocalSourceRange();
6497}
6498
6499void
6500Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6501 ParmVarDecl *Param,
6502 const Expr *ArgExpr) {
6503 // Static array parameters are not supported in C++.
6504 if (!Param || getLangOpts().CPlusPlus)
6505 return;
6506
6507 QualType OrigTy = Param->getOriginalType();
6508
6509 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6510 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6511 return;
6512
6513 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6514 NPC: Expr::NPC_NeverValueDependent)) {
6515 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6516 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6517 return;
6518 }
6519
6520 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6521 if (!CAT)
6522 return;
6523
6524 const ConstantArrayType *ArgCAT =
6525 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6526 if (!ArgCAT)
6527 return;
6528
6529 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6530 T2: ArgCAT->getElementType())) {
6531 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6532 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6533 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6534 << (unsigned)CAT->getZExtSize() << 0;
6535 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6536 }
6537 return;
6538 }
6539
6540 std::optional<CharUnits> ArgSize =
6541 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6542 std::optional<CharUnits> ParmSize =
6543 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6544 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6545 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6546 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6547 << (unsigned)ParmSize->getQuantity() << 1;
6548 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6549 }
6550}
6551
6552/// Given a function expression of unknown-any type, try to rebuild it
6553/// to have a function type.
6554static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6555
6556/// Is the given type a placeholder that we need to lower out
6557/// immediately during argument processing?
6558static bool isPlaceholderToRemoveAsArg(QualType type) {
6559 // Placeholders are never sugared.
6560 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6561 if (!placeholder) return false;
6562
6563 switch (placeholder->getKind()) {
6564 // Ignore all the non-placeholder types.
6565#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6566 case BuiltinType::Id:
6567#include "clang/Basic/OpenCLImageTypes.def"
6568#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6569 case BuiltinType::Id:
6570#include "clang/Basic/OpenCLExtensionTypes.def"
6571 // In practice we'll never use this, since all SVE types are sugared
6572 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6573#define SVE_TYPE(Name, Id, SingletonId) \
6574 case BuiltinType::Id:
6575#include "clang/Basic/AArch64ACLETypes.def"
6576#define PPC_VECTOR_TYPE(Name, Id, Size) \
6577 case BuiltinType::Id:
6578#include "clang/Basic/PPCTypes.def"
6579#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6580#include "clang/Basic/RISCVVTypes.def"
6581#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6582#include "clang/Basic/WebAssemblyReferenceTypes.def"
6583#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6584#include "clang/Basic/AMDGPUTypes.def"
6585#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6586#include "clang/Basic/HLSLIntangibleTypes.def"
6587#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6588#include "clang/Basic/HLSLPackedTypes.def"
6589#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6590#include "clang/Basic/SPIRVTypes.def"
6591#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6592#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6593#include "clang/AST/BuiltinTypes.def"
6594 return false;
6595
6596 case BuiltinType::UnresolvedTemplate:
6597 // We cannot lower out overload sets; they might validly be resolved
6598 // by the call machinery.
6599 case BuiltinType::Overload:
6600 return false;
6601
6602 // Unbridged casts in ARC can be handled in some call positions and
6603 // should be left in place.
6604 case BuiltinType::ARCUnbridgedCast:
6605 return false;
6606
6607 // Pseudo-objects should be converted as soon as possible.
6608 case BuiltinType::PseudoObject:
6609 return true;
6610
6611 // The debugger mode could theoretically but currently does not try
6612 // to resolve unknown-typed arguments based on known parameter types.
6613 case BuiltinType::UnknownAny:
6614 return true;
6615
6616 // These are always invalid as call arguments and should be reported.
6617 case BuiltinType::BoundMember:
6618 case BuiltinType::BuiltinFn:
6619 case BuiltinType::IncompleteMatrixIdx:
6620 case BuiltinType::ArraySection:
6621 case BuiltinType::OMPArrayShaping:
6622 case BuiltinType::OMPIterator:
6623 return true;
6624
6625 }
6626 llvm_unreachable("bad builtin type kind");
6627}
6628
6629bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6630 // Apply this processing to all the arguments at once instead of
6631 // dying at the first failure.
6632 bool hasInvalid = false;
6633 for (size_t i = 0, e = args.size(); i != e; i++) {
6634 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6635 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6636 if (result.isInvalid()) hasInvalid = true;
6637 else args[i] = result.get();
6638 }
6639 }
6640 return hasInvalid;
6641}
6642
6643/// If a builtin function has a pointer argument with no explicit address
6644/// space, then it should be able to accept a pointer to any address
6645/// space as input. In order to do this, we need to replace the
6646/// standard builtin declaration with one that uses the same address space
6647/// as the call.
6648///
6649/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6650/// it does not contain any pointer arguments without
6651/// an address space qualifer. Otherwise the rewritten
6652/// FunctionDecl is returned.
6653/// TODO: Handle pointer return types.
6654static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6655 FunctionDecl *FDecl,
6656 MultiExprArg ArgExprs) {
6657
6658 QualType DeclType = FDecl->getType();
6659 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6660
6661 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6662 ArgExprs.size() < FT->getNumParams())
6663 return nullptr;
6664
6665 bool NeedsNewDecl = false;
6666 unsigned i = 0;
6667 SmallVector<QualType, 8> OverloadParams;
6668
6669 {
6670 // The lvalue conversions in this loop are only for type resolution and
6671 // don't actually occur.
6672 EnterExpressionEvaluationContext Unevaluated(
6673 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6674 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6675
6676 for (QualType ParamType : FT->param_types()) {
6677
6678 // Convert array arguments to pointer to simplify type lookup.
6679 ExprResult ArgRes =
6680 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6681 if (ArgRes.isInvalid())
6682 return nullptr;
6683 Expr *Arg = ArgRes.get();
6684 QualType ArgType = Arg->getType();
6685 if (!ParamType->isPointerType() ||
6686 ParamType->getPointeeType().hasAddressSpace() ||
6687 !ArgType->isPointerType() ||
6688 !ArgType->getPointeeType().hasAddressSpace() ||
6689 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6690 OverloadParams.push_back(Elt: ParamType);
6691 continue;
6692 }
6693
6694 QualType PointeeType = ParamType->getPointeeType();
6695 NeedsNewDecl = true;
6696 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6697
6698 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6699 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6700 }
6701 }
6702
6703 if (!NeedsNewDecl)
6704 return nullptr;
6705
6706 FunctionProtoType::ExtProtoInfo EPI;
6707 EPI.Variadic = FT->isVariadic();
6708 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6709 Args: OverloadParams, EPI);
6710 DeclContext *Parent = FDecl->getParent();
6711 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6712 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6713 N: FDecl->getIdentifier(), T: OverloadTy,
6714 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6715 isInlineSpecified: false,
6716 /*hasPrototype=*/hasWrittenPrototype: true);
6717 SmallVector<ParmVarDecl*, 16> Params;
6718 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6719 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6720 QualType ParamType = FT->getParamType(i);
6721 ParmVarDecl *Parm =
6722 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6723 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6724 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6725 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6726 Params.push_back(Elt: Parm);
6727 }
6728 OverloadDecl->setParams(Params);
6729 // We cannot merge host/device attributes of redeclarations. They have to
6730 // be consistent when created.
6731 if (Sema->LangOpts.CUDA) {
6732 if (FDecl->hasAttr<CUDAHostAttr>())
6733 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6734 if (FDecl->hasAttr<CUDADeviceAttr>())
6735 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6736 }
6737 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6738 return OverloadDecl;
6739}
6740
6741static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6742 FunctionDecl *Callee,
6743 MultiExprArg ArgExprs) {
6744 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6745 // similar attributes) really don't like it when functions are called with an
6746 // invalid number of args.
6747 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6748 /*PartialOverloading=*/false) &&
6749 !Callee->isVariadic())
6750 return;
6751 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6752 return;
6753
6754 if (const EnableIfAttr *Attr =
6755 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6756 S.Diag(Loc: Fn->getBeginLoc(),
6757 DiagID: isa<CXXMethodDecl>(Val: Callee)
6758 ? diag::err_ovl_no_viable_member_function_in_call
6759 : diag::err_ovl_no_viable_function_in_call)
6760 << Callee << Callee->getSourceRange();
6761 S.Diag(Loc: Callee->getLocation(),
6762 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6763 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6764 return;
6765 }
6766}
6767
6768static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6769 const UnresolvedMemberExpr *const UME, Sema &S) {
6770
6771 const auto GetFunctionLevelDCIfCXXClass =
6772 [](Sema &S) -> const CXXRecordDecl * {
6773 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6774 if (!DC || !DC->getParent())
6775 return nullptr;
6776
6777 // If the call to some member function was made from within a member
6778 // function body 'M' return return 'M's parent.
6779 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6780 return MD->getParent()->getCanonicalDecl();
6781 // else the call was made from within a default member initializer of a
6782 // class, so return the class.
6783 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6784 return RD->getCanonicalDecl();
6785 return nullptr;
6786 };
6787 // If our DeclContext is neither a member function nor a class (in the
6788 // case of a lambda in a default member initializer), we can't have an
6789 // enclosing 'this'.
6790
6791 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6792 if (!CurParentClass)
6793 return false;
6794
6795 // The naming class for implicit member functions call is the class in which
6796 // name lookup starts.
6797 const CXXRecordDecl *const NamingClass =
6798 UME->getNamingClass()->getCanonicalDecl();
6799 assert(NamingClass && "Must have naming class even for implicit access");
6800
6801 // If the unresolved member functions were found in a 'naming class' that is
6802 // related (either the same or derived from) to the class that contains the
6803 // member function that itself contained the implicit member access.
6804
6805 return CurParentClass == NamingClass ||
6806 CurParentClass->isDerivedFrom(Base: NamingClass);
6807}
6808
6809static void
6810tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6811 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6812
6813 if (!UME)
6814 return;
6815
6816 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6817 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6818 // already been captured, or if this is an implicit member function call (if
6819 // it isn't, an attempt to capture 'this' should already have been made).
6820 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6821 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6822 return;
6823
6824 // Check if the naming class in which the unresolved members were found is
6825 // related (same as or is a base of) to the enclosing class.
6826
6827 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6828 return;
6829
6830
6831 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6832 // If the enclosing function is not dependent, then this lambda is
6833 // capture ready, so if we can capture this, do so.
6834 if (!EnclosingFunctionCtx->isDependentContext()) {
6835 // If the current lambda and all enclosing lambdas can capture 'this' -
6836 // then go ahead and capture 'this' (since our unresolved overload set
6837 // contains at least one non-static member function).
6838 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6839 S.CheckCXXThisCapture(Loc: CallLoc);
6840 } else if (S.CurContext->isDependentContext()) {
6841 // ... since this is an implicit member reference, that might potentially
6842 // involve a 'this' capture, mark 'this' for potential capture in
6843 // enclosing lambdas.
6844 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6845 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6846 }
6847}
6848
6849// Once a call is fully resolved, warn for unqualified calls to specific
6850// C++ standard functions, like move and forward.
6851static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6852 const CallExpr *Call) {
6853 // We are only checking unary move and forward so exit early here.
6854 if (Call->getNumArgs() != 1)
6855 return;
6856
6857 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6858 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6859 return;
6860 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6861 if (!DRE || !DRE->getLocation().isValid())
6862 return;
6863
6864 if (DRE->getQualifier())
6865 return;
6866
6867 const FunctionDecl *FD = Call->getDirectCallee();
6868 if (!FD)
6869 return;
6870
6871 // Only warn for some functions deemed more frequent or problematic.
6872 unsigned BuiltinID = FD->getBuiltinID();
6873 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6874 return;
6875
6876 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6877 << FD->getQualifiedNameAsString()
6878 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6879}
6880
6881ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6882 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6883 Expr *ExecConfig) {
6884 ExprResult Call =
6885 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6886 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6887 if (Call.isInvalid())
6888 return Call;
6889
6890 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6891 // language modes.
6892 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6893 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6894 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6895 << ULE->getName();
6896 }
6897
6898 if (LangOpts.OpenMP)
6899 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6900 ExecConfig);
6901 if (LangOpts.CPlusPlus) {
6902 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6903 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6904
6905 // If we previously found that the id-expression of this call refers to a
6906 // consteval function but the call is dependent, we should not treat is an
6907 // an invalid immediate call.
6908 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6909 DRE && Call.get()->isValueDependent()) {
6910 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6911 }
6912 }
6913 return Call;
6914}
6915
6916// Any type that could be used to form a callable expression
6917static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6918 QualType T = E->getType();
6919 if (T->isDependentType())
6920 return true;
6921
6922 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6923 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6924 T->isFunctionType() || T->isFunctionReferenceType() ||
6925 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6926 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6927 return true;
6928
6929 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6930 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6931}
6932
6933ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6934 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6935 Expr *ExecConfig, bool IsExecConfig,
6936 bool AllowRecovery) {
6937 // Since this might be a postfix expression, get rid of ParenListExprs.
6938 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6939 if (Result.isInvalid()) return ExprError();
6940 Fn = Result.get();
6941
6942 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6943 // later, when we check boolean conditions, for now we merely forward it
6944 // without any additional checking.
6945 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6946 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6947 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6948
6949 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6950 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6951 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6952 return CallExpr::Create(
6953 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6954 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6955 }
6956 }
6957
6958 if (CheckArgsForPlaceholders(args: ArgExprs))
6959 return ExprError();
6960
6961 // The result of __builtin_counted_by_ref cannot be used as a function
6962 // argument. It allows leaking and modification of bounds safety information.
6963 for (const Expr *Arg : ArgExprs)
6964 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6965 K: BuiltinCountedByRefKind::FunctionArg))
6966 return ExprError();
6967
6968 if (getLangOpts().CPlusPlus) {
6969 // If this is a pseudo-destructor expression, build the call immediately.
6970 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6971 if (!ArgExprs.empty()) {
6972 // Pseudo-destructor calls should not have any arguments.
6973 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6974 << FixItHint::CreateRemoval(
6975 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6976 ArgExprs.back()->getEndLoc()));
6977 }
6978
6979 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6980 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6981 }
6982 if (Fn->getType() == Context.PseudoObjectTy) {
6983 ExprResult result = CheckPlaceholderExpr(E: Fn);
6984 if (result.isInvalid()) return ExprError();
6985 Fn = result.get();
6986 }
6987
6988 // Determine whether this is a dependent call inside a C++ template,
6989 // in which case we won't do any semantic analysis now.
6990 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6991 if (ExecConfig) {
6992 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6993 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6994 Ty: Context.DependentTy, VK: VK_PRValue,
6995 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6996 } else {
6997
6998 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6999 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
7000 CallLoc: Fn->getBeginLoc());
7001
7002 // If the type of the function itself is not dependent
7003 // check that it is a reasonable as a function, as type deduction
7004 // later assume the CallExpr has a sensible TYPE.
7005 if (!MayBeFunctionType(Context, E: Fn))
7006 return ExprError(
7007 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7008 << Fn->getType() << Fn->getSourceRange());
7009
7010 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7011 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7012 }
7013 }
7014
7015 // Determine whether this is a call to an object (C++ [over.call.object]).
7016 if (Fn->getType()->isRecordType())
7017 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
7018 RParenLoc);
7019
7020 if (Fn->getType() == Context.UnknownAnyTy) {
7021 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7022 if (result.isInvalid()) return ExprError();
7023 Fn = result.get();
7024 }
7025
7026 if (Fn->getType() == Context.BoundMemberTy) {
7027 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7028 RParenLoc, ExecConfig, IsExecConfig,
7029 AllowRecovery);
7030 }
7031 }
7032
7033 // Check for overloaded calls. This can happen even in C due to extensions.
7034 if (Fn->getType() == Context.OverloadTy) {
7035 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
7036
7037 // We aren't supposed to apply this logic if there's an '&' involved.
7038 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
7039 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
7040 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7041 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7042 OverloadExpr *ovl = find.Expression;
7043 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
7044 return BuildOverloadedCallExpr(
7045 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
7046 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
7047 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7048 RParenLoc, ExecConfig, IsExecConfig,
7049 AllowRecovery);
7050 }
7051 }
7052
7053 // If we're directly calling a function, get the appropriate declaration.
7054 if (Fn->getType() == Context.UnknownAnyTy) {
7055 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7056 if (result.isInvalid()) return ExprError();
7057 Fn = result.get();
7058 }
7059
7060 Expr *NakedFn = Fn->IgnoreParens();
7061
7062 bool CallingNDeclIndirectly = false;
7063 NamedDecl *NDecl = nullptr;
7064 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
7065 if (UnOp->getOpcode() == UO_AddrOf) {
7066 CallingNDeclIndirectly = true;
7067 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7068 }
7069 }
7070
7071 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
7072 NDecl = DRE->getDecl();
7073
7074 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
7075 if (FDecl && FDecl->getBuiltinID()) {
7076 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7077 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7078 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
7079 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
7080 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
7081 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7082 }
7083 }
7084
7085 // Rewrite the function decl for this builtin by replacing parameters
7086 // with no explicit address space with the address space of the arguments
7087 // in ArgExprs.
7088 if ((FDecl =
7089 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
7090 NDecl = FDecl;
7091 Fn = DeclRefExpr::Create(
7092 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
7093 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
7094 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
7095 }
7096 }
7097 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
7098 NDecl = ME->getMemberDecl();
7099
7100 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
7101 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7102 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
7103 return ExprError();
7104
7105 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
7106
7107 // If this expression is a call to a builtin function in HIP compilation,
7108 // allow a pointer-type argument to default address space to be passed as a
7109 // pointer-type parameter to a non-default address space. If Arg is declared
7110 // in the default address space and Param is declared in a non-default
7111 // address space, perform an implicit address space cast to the parameter
7112 // type.
7113 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7114 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7115 ++Idx) {
7116 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7117 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7118 !ArgExprs[Idx]->getType()->isPointerType())
7119 continue;
7120
7121 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7122 auto ArgTy = ArgExprs[Idx]->getType();
7123 auto ArgPtTy = ArgTy->getPointeeType();
7124 auto ArgAS = ArgPtTy.getAddressSpace();
7125
7126 // Add address space cast if target address spaces are different
7127 bool NeedImplicitASC =
7128 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7129 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7130 // or from specific AS which has target AS matching that of Param.
7131 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7132 if (!NeedImplicitASC)
7133 continue;
7134
7135 // First, ensure that the Arg is an RValue.
7136 if (ArgExprs[Idx]->isGLValue()) {
7137 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7138 if (Res.isInvalid())
7139 return ExprError();
7140 ArgExprs[Idx] = Res.get();
7141 }
7142
7143 // Construct a new arg type with address space of Param
7144 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7145 ArgPtQuals.setAddressSpace(ParamAS);
7146 auto NewArgPtTy =
7147 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7148 auto NewArgTy =
7149 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7150 Qs: ArgTy.getQualifiers());
7151
7152 // Finally perform an implicit address space cast
7153 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7154 CK: CK_AddressSpaceConversion)
7155 .get();
7156 }
7157 }
7158 }
7159
7160 if (Context.isDependenceAllowed() &&
7161 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7162 assert(!getLangOpts().CPlusPlus);
7163 assert((Fn->containsErrors() ||
7164 llvm::any_of(ArgExprs,
7165 [](clang::Expr *E) { return E->containsErrors(); })) &&
7166 "should only occur in error-recovery path.");
7167 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7168 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7169 }
7170 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7171 Config: ExecConfig, IsExecConfig);
7172}
7173
7174Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7175 MultiExprArg CallArgs) {
7176 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7177 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7178 Sema::LookupOrdinaryName);
7179 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7180
7181 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7182 assert(BuiltInDecl && "failed to find builtin declaration");
7183
7184 ExprResult DeclRef =
7185 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7186 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7187
7188 ExprResult Call =
7189 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7190
7191 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7192 return Call.get();
7193}
7194
7195ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7196 SourceLocation BuiltinLoc,
7197 SourceLocation RParenLoc) {
7198 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7199 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7200}
7201
7202ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7203 SourceLocation BuiltinLoc,
7204 SourceLocation RParenLoc) {
7205 ExprValueKind VK = VK_PRValue;
7206 ExprObjectKind OK = OK_Ordinary;
7207 QualType SrcTy = E->getType();
7208 if (!SrcTy->isDependentType() &&
7209 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7210 return ExprError(
7211 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7212 << DestTy << SrcTy << E->getSourceRange());
7213 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7214}
7215
7216ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7217 SourceLocation BuiltinLoc,
7218 SourceLocation RParenLoc) {
7219 TypeSourceInfo *TInfo;
7220 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7221 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7222}
7223
7224ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7225 SourceLocation LParenLoc,
7226 ArrayRef<Expr *> Args,
7227 SourceLocation RParenLoc, Expr *Config,
7228 bool IsExecConfig, ADLCallKind UsesADL) {
7229 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7230 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7231
7232 auto IsSJLJ = [&] {
7233 switch (BuiltinID) {
7234 case Builtin::BI__builtin_longjmp:
7235 case Builtin::BI__builtin_setjmp:
7236 case Builtin::BI__sigsetjmp:
7237 case Builtin::BI_longjmp:
7238 case Builtin::BI_setjmp:
7239 case Builtin::BIlongjmp:
7240 case Builtin::BIsetjmp:
7241 case Builtin::BIsiglongjmp:
7242 case Builtin::BIsigsetjmp:
7243 return true;
7244 default:
7245 return false;
7246 }
7247 };
7248
7249 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7250 if (!CurrentDefer.empty() && IsSJLJ()) {
7251 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7252 // for more than just blocks (e.g. lambdas, nested classes...).
7253 Scope *DeferParent = CurrentDefer.back().first;
7254 Scope *Block = CurScope->getBlockParent();
7255 if (DeferParent->Contains(rhs: *CurScope) &&
7256 (!Block || !DeferParent->Contains(rhs: *Block)))
7257 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7258 }
7259
7260 // Functions with 'interrupt' attribute cannot be called directly.
7261 if (FDecl) {
7262 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7263 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7264 return ExprError();
7265 }
7266 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7267 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7268 return ExprError();
7269 }
7270 }
7271
7272 // X86 interrupt handlers may only call routines with attribute
7273 // no_caller_saved_registers since there is no efficient way to
7274 // save and restore the non-GPR state.
7275 if (auto *Caller = getCurFunctionDecl()) {
7276 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7277 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7278 const TargetInfo &TI = Context.getTargetInfo();
7279 bool HasNonGPRRegisters =
7280 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7281 if (HasNonGPRRegisters &&
7282 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7283 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7284 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7285 if (FDecl)
7286 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7287 }
7288 }
7289 }
7290
7291 // Extract the return type from the builtin function pointer type.
7292 QualType ResultTy;
7293 if (BuiltinID)
7294 ResultTy = FDecl->getCallResultType();
7295 else
7296 ResultTy = Context.BoolTy;
7297
7298 // Promote the function operand.
7299 // We special-case function promotion here because we only allow promoting
7300 // builtin functions to function pointers in the callee of a call.
7301 ExprResult Result;
7302 if (BuiltinID &&
7303 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7304 // FIXME Several builtins still have setType in
7305 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7306 // Builtins.td to ensure they are correct before removing setType calls.
7307 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7308 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7309 } else
7310 Result = CallExprUnaryConversions(E: Fn);
7311 if (Result.isInvalid())
7312 return ExprError();
7313 Fn = Result.get();
7314
7315 // Check for a valid function type, but only if it is not a builtin which
7316 // requires custom type checking. These will be handled by
7317 // CheckBuiltinFunctionCall below just after creation of the call expression.
7318 const FunctionType *FuncT = nullptr;
7319 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7320 retry:
7321 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7322 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7323 // have type pointer to function".
7324 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7325 if (!FuncT)
7326 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7327 << Fn->getType() << Fn->getSourceRange());
7328 } else if (const BlockPointerType *BPT =
7329 Fn->getType()->getAs<BlockPointerType>()) {
7330 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7331 } else {
7332 // Handle calls to expressions of unknown-any type.
7333 if (Fn->getType() == Context.UnknownAnyTy) {
7334 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7335 if (rewrite.isInvalid())
7336 return ExprError();
7337 Fn = rewrite.get();
7338 goto retry;
7339 }
7340
7341 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7342 << Fn->getType() << Fn->getSourceRange());
7343 }
7344 }
7345
7346 // Get the number of parameters in the function prototype, if any.
7347 // We will allocate space for max(Args.size(), NumParams) arguments
7348 // in the call expression.
7349 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7350 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7351
7352 CallExpr *TheCall;
7353 if (Config) {
7354 assert(UsesADL == ADLCallKind::NotADL &&
7355 "CUDAKernelCallExpr should not use ADL");
7356 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7357 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7358 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7359 } else {
7360 TheCall =
7361 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7362 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7363 }
7364
7365 // Bail out early if calling a builtin with custom type checking.
7366 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7367 // For HLSL builtin aliases, the call was resolved via overload resolution
7368 // which may have selected a conversion sequence (e.g., vector-to-scalar
7369 // truncation). Convert arguments to match the declared prototype before
7370 // the custom type checker runs, otherwise the builtin will operate on
7371 // the unconverted argument types.
7372 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7373 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7374 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7375 IsExecConfig))
7376 return ExprError();
7377 }
7378 }
7379 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7380 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7381 E = CheckForImmediateInvocation(E, Decl: FDecl);
7382 return E;
7383 }
7384
7385 if (getLangOpts().CUDA) {
7386 if (Config) {
7387 // CUDA: Kernel calls must be to global functions
7388 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7389 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7390 << FDecl << Fn->getSourceRange());
7391
7392 // CUDA: Kernel function must have 'void' return type
7393 if (!FuncT->getReturnType()->isVoidType() &&
7394 !FuncT->getReturnType()->getAs<AutoType>() &&
7395 !FuncT->getReturnType()->isInstantiationDependentType())
7396 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7397 << Fn->getType() << Fn->getSourceRange());
7398 } else {
7399 // CUDA: Calls to global functions must be configured
7400 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7401 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7402 << FDecl << Fn->getSourceRange());
7403 }
7404 }
7405
7406 // Check for a valid return type
7407 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7408 FD: FDecl))
7409 return ExprError();
7410
7411 // We know the result type of the call, set it.
7412 TheCall->setType(FuncT->getCallResultType(Context));
7413 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7414
7415 // WebAssembly tables can't be used as arguments.
7416 if (Context.getTargetInfo().getTriple().isWasm()) {
7417 for (const Expr *Arg : Args) {
7418 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7419 return ExprError(Diag(Loc: Arg->getExprLoc(),
7420 DiagID: diag::err_wasm_table_as_function_parameter));
7421 }
7422 }
7423 }
7424
7425 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7426 // replaces sampler DeclRefExprs with their integer initializers.
7427 if (getLangOpts().OpenCL && FDecl) {
7428 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7429 }
7430
7431 if (Proto) {
7432 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7433 IsExecConfig))
7434 return ExprError();
7435 } else {
7436 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7437
7438 if (FDecl) {
7439 // Check if we have too few/too many template arguments, based
7440 // on our knowledge of the function definition.
7441 const FunctionDecl *Def = nullptr;
7442 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7443 Proto = Def->getType()->getAs<FunctionProtoType>();
7444 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7445 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7446 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7447 }
7448
7449 // If the function we're calling isn't a function prototype, but we have
7450 // a function prototype from a prior declaratiom, use that prototype.
7451 if (!FDecl->hasPrototype())
7452 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7453 }
7454
7455 // If we still haven't found a prototype to use but there are arguments to
7456 // the call, diagnose this as calling a function without a prototype.
7457 // However, if we found a function declaration, check to see if
7458 // -Wdeprecated-non-prototype was disabled where the function was declared.
7459 // If so, we will silence the diagnostic here on the assumption that this
7460 // interface is intentional and the user knows what they're doing. We will
7461 // also silence the diagnostic if there is a function declaration but it
7462 // was implicitly defined (the user already gets diagnostics about the
7463 // creation of the implicit function declaration, so the additional warning
7464 // is not helpful).
7465 if (!Proto && !Args.empty() &&
7466 (!FDecl || (!FDecl->isImplicit() &&
7467 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7468 Loc: FDecl->getLocation()))))
7469 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7470 << (FDecl != nullptr) << FDecl;
7471
7472 // Promote the arguments (C99 6.5.2.2p6).
7473 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7474 Expr *Arg = Args[i];
7475
7476 if (Proto && i < Proto->getNumParams()) {
7477 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7478 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7479 ExprResult ArgE =
7480 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7481 if (ArgE.isInvalid())
7482 return true;
7483
7484 Arg = ArgE.getAs<Expr>();
7485
7486 } else {
7487 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7488
7489 if (ArgE.isInvalid())
7490 return true;
7491
7492 Arg = ArgE.getAs<Expr>();
7493 }
7494
7495 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7496 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7497 return ExprError();
7498
7499 TheCall->setArg(Arg: i, ArgExpr: Arg);
7500 }
7501 TheCall->computeDependence();
7502 }
7503
7504 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7505 if (Method->isImplicitObjectMemberFunction())
7506 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7507 << Fn->getSourceRange() << 0);
7508
7509 // Check for sentinels
7510 if (NDecl)
7511 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7512
7513 // Warn for unions passing across security boundary (CMSE).
7514 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7515 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7516 if (const auto *RT =
7517 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7518 if (RT->getDecl()->isOrContainsUnion())
7519 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7520 << 0 << i;
7521 }
7522 }
7523 }
7524
7525 // Do special checking on direct calls to functions.
7526 if (FDecl) {
7527 if (CheckFunctionCall(FDecl, TheCall, Proto))
7528 return ExprError();
7529
7530 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7531 checkFortifiedLibcArgument(FD: FDecl, TheCall);
7532
7533 if (BuiltinID)
7534 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7535 } else if (NDecl) {
7536 if (CheckPointerCall(NDecl, TheCall, Proto))
7537 return ExprError();
7538 } else {
7539 if (CheckOtherCall(TheCall, Proto))
7540 return ExprError();
7541 }
7542
7543 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7544}
7545
7546ExprResult
7547Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7548 SourceLocation RParenLoc, Expr *InitExpr) {
7549 assert(Ty && "ActOnCompoundLiteral(): missing type");
7550 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7551
7552 TypeSourceInfo *TInfo;
7553 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7554 if (!TInfo)
7555 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7556
7557 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7558}
7559
7560ExprResult
7561Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7562 SourceLocation RParenLoc, Expr *LiteralExpr) {
7563 QualType literalType = TInfo->getType();
7564
7565 if (literalType->isArrayType()) {
7566 if (RequireCompleteSizedType(
7567 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7568 DiagID: diag::err_array_incomplete_or_sizeless_type,
7569 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7570 return ExprError();
7571 if (literalType->isVariableArrayType()) {
7572 // C23 6.7.10p4: An entity of variable length array type shall not be
7573 // initialized except by an empty initializer.
7574 //
7575 // The C extension warnings are issued from ParseBraceInitializer() and
7576 // do not need to be issued here. However, we continue to issue an error
7577 // in the case there are initializers or we are compiling C++. We allow
7578 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7579 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7580 // FIXME: should we allow this construct in C++ when it makes sense to do
7581 // so?
7582 //
7583 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7584 // shall specify an object type or an array of unknown size, but not a
7585 // variable length array type. This seems odd, as it allows 'int a[size] =
7586 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7587 // says, this is what's implemented here for C (except for the extension
7588 // that permits constant foldable size arrays)
7589
7590 auto diagID = LangOpts.CPlusPlus
7591 ? diag::err_variable_object_no_init
7592 : diag::err_compound_literal_with_vla_type;
7593 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7594 FailedFoldDiagID: diagID))
7595 return ExprError();
7596 }
7597 } else if (!literalType->isDependentType() &&
7598 RequireCompleteType(Loc: LParenLoc, T: literalType,
7599 DiagID: diag::err_typecheck_decl_incomplete_type,
7600 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7601 return ExprError();
7602
7603 InitializedEntity Entity
7604 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7605 InitializationKind Kind
7606 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7607 TypeRange: SourceRange(LParenLoc, RParenLoc),
7608 /*InitList=*/true);
7609 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7610 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7611 ResultType: &literalType);
7612 if (Result.isInvalid())
7613 return ExprError();
7614 LiteralExpr = Result.get();
7615
7616 // We treat the compound literal as being at file scope if it's not in a
7617 // function or method body, or within the function's prototype scope. This
7618 // means the following compound literal is not at file scope:
7619 // void func(char *para[(int [1]){ 0 }[0]);
7620 const Scope *S = getCurScope();
7621 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7622 !S->isInCFunctionScope() &&
7623 (!S || !S->isFunctionPrototypeScope());
7624
7625 // In C, compound literals are l-values for some reason.
7626 // For GCC compatibility, in C++, file-scope array compound literals with
7627 // constant initializers are also l-values, and compound literals are
7628 // otherwise prvalues.
7629 //
7630 // (GCC also treats C++ list-initialized file-scope array prvalues with
7631 // constant initializers as l-values, but that's non-conforming, so we don't
7632 // follow it there.)
7633 //
7634 // FIXME: It would be better to handle the lvalue cases as materializing and
7635 // lifetime-extending a temporary object, but our materialized temporaries
7636 // representation only supports lifetime extension from a variable, not "out
7637 // of thin air".
7638 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7639 // is bound to the result of applying array-to-pointer decay to the compound
7640 // literal.
7641 // FIXME: GCC supports compound literals of reference type, which should
7642 // obviously have a value kind derived from the kind of reference involved.
7643 ExprValueKind VK =
7644 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7645 ? VK_PRValue
7646 : VK_LValue;
7647
7648 // C99 6.5.2.5
7649 // "If the compound literal occurs outside the body of a function, the
7650 // initializer list shall consist of constant expressions."
7651 if (IsFileScope) {
7652 // An element with an immediate call or source_location is left for the
7653 // use site, and for its rebuild too when the rebuilt default arguments
7654 // could not be given the use-site location.
7655 bool DeferImmediate =
7656 isCheckingDefaultArgumentOrInitializer() ||
7657 (currentEvaluationContext().DelayedDefaultInitializationContext &&
7658 !OutermostDeclarationWithDelayedImmediateInvocations());
7659 // Store the element's value so CodeGen does not re-evaluate it outside a
7660 // constant context.
7661 auto CheckElement = [&](Expr *Init) -> Expr * {
7662 if (Init->isTypeDependent() || Init->isValueDependent())
7663 return ConstantExpr::Create(Context, E: Init);
7664 if (DeferImmediate) {
7665 ImmediateCallVisitor V(Context);
7666 V.TraverseStmt(S: Init);
7667 if (V.HasImmediateCalls)
7668 return ConstantExpr::Create(Context, E: Init);
7669 }
7670 Expr::EvalResult Eval;
7671 if (!Init->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context,
7672 Kind: ConstantExprKind::Initializer)) {
7673 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7674 << Init->getSourceBitField();
7675 return nullptr;
7676 }
7677 // An immediate invocation already is a ConstantExpr.
7678 if (isa<ConstantExpr>(Val: Init))
7679 return Init;
7680 return ConstantExpr::Create(Context, E: Init, Result: Eval.Val);
7681 };
7682 if (auto *ILE = dyn_cast<InitListExpr>(Val: LiteralExpr)) {
7683 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7684 Expr *Init = CheckElement(ILE->getInit(Init: i));
7685 if (!Init)
7686 return ExprError();
7687 ILE->setInit(Init: i, expr: Init);
7688 }
7689 } else {
7690 LiteralExpr = CheckElement(LiteralExpr);
7691 if (!LiteralExpr)
7692 return ExprError();
7693 }
7694 }
7695
7696 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7697 LiteralExpr, IsFileScope);
7698 if (!IsFileScope && literalType.getAddressSpace() != LangAS::opencl_private &&
7699 literalType.getAddressSpace() != LangAS::Default) {
7700 // Embedded-C extensions to C99 6.5.2.5:
7701 // "If the compound literal occurs inside the body of a function, the
7702 // type name shall not be qualified by an address-space qualifier."
7703 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7704 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7705 return ExprError();
7706 }
7707
7708 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7709 // Compound literals that have automatic storage duration are destroyed at
7710 // the end of the scope in C; in C++, they're just temporaries.
7711
7712 // Emit diagnostics if it is or contains a C union type that is non-trivial
7713 // to destruct.
7714 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7715 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7716 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7717 NonTrivialKind: NTCUK_Destruct);
7718
7719 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7720 Cleanup.setExprNeedsCleanups(true);
7721 ExprCleanupObjects.push_back(Elt: E);
7722 if (literalType.isDestructedType()) {
7723 getCurFunction()->setHasBranchProtectedScope();
7724 }
7725 }
7726
7727 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7728 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7729 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7730 Loc: E->getInitializer()->getExprLoc());
7731
7732 return MaybeBindToTemporary(E);
7733}
7734
7735ExprResult
7736Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7737 SourceLocation RBraceLoc) {
7738 // Only produce each kind of designated initialization diagnostic once.
7739 SourceLocation FirstDesignator;
7740 bool DiagnosedArrayDesignator = false;
7741 bool DiagnosedNestedDesignator = false;
7742 bool DiagnosedMixedDesignator = false;
7743
7744 // Check that any designated initializers are syntactically valid in the
7745 // current language mode.
7746 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7747 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7748 if (FirstDesignator.isInvalid())
7749 FirstDesignator = DIE->getBeginLoc();
7750
7751 if (!getLangOpts().CPlusPlus)
7752 break;
7753
7754 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7755 DiagnosedNestedDesignator = true;
7756 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7757 << DIE->getDesignatorsSourceRange();
7758 }
7759
7760 for (auto &Desig : DIE->designators()) {
7761 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7762 DiagnosedArrayDesignator = true;
7763 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7764 << Desig.getSourceRange();
7765 }
7766 }
7767
7768 if (!DiagnosedMixedDesignator &&
7769 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7770 DiagnosedMixedDesignator = true;
7771 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7772 << DIE->getSourceRange();
7773 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7774 << InitArgList[0]->getSourceRange();
7775 }
7776 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7777 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7778 DiagnosedMixedDesignator = true;
7779 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7780 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7781 << DIE->getSourceRange();
7782 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7783 << InitArgList[I]->getSourceRange();
7784 }
7785 }
7786
7787 if (FirstDesignator.isValid()) {
7788 // Only diagnose designated initiaization as a C++20 extension if we didn't
7789 // already diagnose use of (non-C++20) C99 designator syntax.
7790 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7791 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7792 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7793 ? diag::warn_cxx17_compat_designated_init
7794 : diag::ext_cxx_designated_init);
7795 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7796 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7797 }
7798 }
7799
7800 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7801}
7802
7803ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7804 MultiExprArg InitArgList,
7805 SourceLocation RBraceLoc, bool IsExplicit) {
7806 // Semantic analysis for initializers is done by ActOnDeclarator() and
7807 // CheckInitializer() - it requires knowledge of the object being initialized.
7808
7809 // Immediately handle non-overload placeholders. Overloads can be
7810 // resolved contextually, but everything else here can't.
7811 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7812 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7813 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7814
7815 // Ignore failures; dropping the entire initializer list because
7816 // of one failure would be terrible for indexing/etc.
7817 if (result.isInvalid()) continue;
7818
7819 InitArgList[I] = result.get();
7820 }
7821 }
7822
7823 InitListExpr *E = new (Context)
7824 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7825 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7826 return E;
7827}
7828
7829void Sema::maybeExtendBlockObject(ExprResult &E) {
7830 assert(E.get()->getType()->isBlockPointerType());
7831 assert(E.get()->isPRValue());
7832
7833 // Only do this in an r-value context.
7834 if (!getLangOpts().ObjCAutoRefCount) return;
7835
7836 E = ImplicitCastExpr::Create(
7837 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7838 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7839 Cleanup.setExprNeedsCleanups(true);
7840}
7841
7842CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7843 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7844 // Also, callers should have filtered out the invalid cases with
7845 // pointers. Everything else should be possible.
7846
7847 QualType SrcTy = Src.get()->getType();
7848 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7849 return CK_NoOp;
7850
7851 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7852 case Type::STK_MemberPointer:
7853 llvm_unreachable("member pointer type in C");
7854
7855 case Type::STK_CPointer:
7856 case Type::STK_BlockPointer:
7857 case Type::STK_ObjCObjectPointer:
7858 switch (DestTy->getScalarTypeKind()) {
7859 case Type::STK_CPointer: {
7860 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7861 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7862 if (SrcAS != DestAS)
7863 return CK_AddressSpaceConversion;
7864 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7865 return CK_NoOp;
7866 return CK_BitCast;
7867 }
7868 case Type::STK_BlockPointer:
7869 return (SrcKind == Type::STK_BlockPointer
7870 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7871 case Type::STK_ObjCObjectPointer:
7872 if (SrcKind == Type::STK_ObjCObjectPointer)
7873 return CK_BitCast;
7874 if (SrcKind == Type::STK_CPointer)
7875 return CK_CPointerToObjCPointerCast;
7876 maybeExtendBlockObject(E&: Src);
7877 return CK_BlockPointerToObjCPointerCast;
7878 case Type::STK_Bool:
7879 return CK_PointerToBoolean;
7880 case Type::STK_Integral:
7881 return CK_PointerToIntegral;
7882 case Type::STK_Floating:
7883 case Type::STK_FloatingComplex:
7884 case Type::STK_IntegralComplex:
7885 case Type::STK_MemberPointer:
7886 case Type::STK_FixedPoint:
7887 llvm_unreachable("illegal cast from pointer");
7888 }
7889 llvm_unreachable("Should have returned before this");
7890
7891 case Type::STK_FixedPoint:
7892 switch (DestTy->getScalarTypeKind()) {
7893 case Type::STK_FixedPoint:
7894 return CK_FixedPointCast;
7895 case Type::STK_Bool:
7896 return CK_FixedPointToBoolean;
7897 case Type::STK_Integral:
7898 return CK_FixedPointToIntegral;
7899 case Type::STK_Floating:
7900 return CK_FixedPointToFloating;
7901 case Type::STK_IntegralComplex:
7902 case Type::STK_FloatingComplex:
7903 Diag(Loc: Src.get()->getExprLoc(),
7904 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7905 << DestTy;
7906 return CK_IntegralCast;
7907 case Type::STK_CPointer:
7908 case Type::STK_ObjCObjectPointer:
7909 case Type::STK_BlockPointer:
7910 case Type::STK_MemberPointer:
7911 llvm_unreachable("illegal cast to pointer type");
7912 }
7913 llvm_unreachable("Should have returned before this");
7914
7915 case Type::STK_Bool: // casting from bool is like casting from an integer
7916 case Type::STK_Integral:
7917 switch (DestTy->getScalarTypeKind()) {
7918 case Type::STK_CPointer:
7919 case Type::STK_ObjCObjectPointer:
7920 case Type::STK_BlockPointer:
7921 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7922 NPC: Expr::NPC_ValueDependentIsNull))
7923 return CK_NullToPointer;
7924 return CK_IntegralToPointer;
7925 case Type::STK_Bool:
7926 return CK_IntegralToBoolean;
7927 case Type::STK_Integral:
7928 return CK_IntegralCast;
7929 case Type::STK_Floating:
7930 return CK_IntegralToFloating;
7931 case Type::STK_IntegralComplex:
7932 Src = ImpCastExprToType(E: Src.get(),
7933 Type: DestTy->castAs<ComplexType>()->getElementType(),
7934 CK: CK_IntegralCast);
7935 return CK_IntegralRealToComplex;
7936 case Type::STK_FloatingComplex:
7937 Src = ImpCastExprToType(E: Src.get(),
7938 Type: DestTy->castAs<ComplexType>()->getElementType(),
7939 CK: CK_IntegralToFloating);
7940 return CK_FloatingRealToComplex;
7941 case Type::STK_MemberPointer:
7942 llvm_unreachable("member pointer type in C");
7943 case Type::STK_FixedPoint:
7944 return CK_IntegralToFixedPoint;
7945 }
7946 llvm_unreachable("Should have returned before this");
7947
7948 case Type::STK_Floating:
7949 switch (DestTy->getScalarTypeKind()) {
7950 case Type::STK_Floating:
7951 return CK_FloatingCast;
7952 case Type::STK_Bool:
7953 return CK_FloatingToBoolean;
7954 case Type::STK_Integral:
7955 return CK_FloatingToIntegral;
7956 case Type::STK_FloatingComplex:
7957 Src = ImpCastExprToType(E: Src.get(),
7958 Type: DestTy->castAs<ComplexType>()->getElementType(),
7959 CK: CK_FloatingCast);
7960 return CK_FloatingRealToComplex;
7961 case Type::STK_IntegralComplex:
7962 Src = ImpCastExprToType(E: Src.get(),
7963 Type: DestTy->castAs<ComplexType>()->getElementType(),
7964 CK: CK_FloatingToIntegral);
7965 return CK_IntegralRealToComplex;
7966 case Type::STK_CPointer:
7967 case Type::STK_ObjCObjectPointer:
7968 case Type::STK_BlockPointer:
7969 llvm_unreachable("valid float->pointer cast?");
7970 case Type::STK_MemberPointer:
7971 llvm_unreachable("member pointer type in C");
7972 case Type::STK_FixedPoint:
7973 return CK_FloatingToFixedPoint;
7974 }
7975 llvm_unreachable("Should have returned before this");
7976
7977 case Type::STK_FloatingComplex:
7978 switch (DestTy->getScalarTypeKind()) {
7979 case Type::STK_FloatingComplex:
7980 return CK_FloatingComplexCast;
7981 case Type::STK_IntegralComplex:
7982 return CK_FloatingComplexToIntegralComplex;
7983 case Type::STK_Floating: {
7984 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7985 if (Context.hasSameType(T1: ET, T2: DestTy))
7986 return CK_FloatingComplexToReal;
7987 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7988 return CK_FloatingCast;
7989 }
7990 case Type::STK_Bool:
7991 return CK_FloatingComplexToBoolean;
7992 case Type::STK_Integral:
7993 Src = ImpCastExprToType(E: Src.get(),
7994 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7995 CK: CK_FloatingComplexToReal);
7996 return CK_FloatingToIntegral;
7997 case Type::STK_CPointer:
7998 case Type::STK_ObjCObjectPointer:
7999 case Type::STK_BlockPointer:
8000 llvm_unreachable("valid complex float->pointer cast?");
8001 case Type::STK_MemberPointer:
8002 llvm_unreachable("member pointer type in C");
8003 case Type::STK_FixedPoint:
8004 Diag(Loc: Src.get()->getExprLoc(),
8005 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8006 << SrcTy;
8007 return CK_IntegralCast;
8008 }
8009 llvm_unreachable("Should have returned before this");
8010
8011 case Type::STK_IntegralComplex:
8012 switch (DestTy->getScalarTypeKind()) {
8013 case Type::STK_FloatingComplex:
8014 return CK_IntegralComplexToFloatingComplex;
8015 case Type::STK_IntegralComplex:
8016 return CK_IntegralComplexCast;
8017 case Type::STK_Integral: {
8018 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8019 if (Context.hasSameType(T1: ET, T2: DestTy))
8020 return CK_IntegralComplexToReal;
8021 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
8022 return CK_IntegralCast;
8023 }
8024 case Type::STK_Bool:
8025 return CK_IntegralComplexToBoolean;
8026 case Type::STK_Floating:
8027 Src = ImpCastExprToType(E: Src.get(),
8028 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8029 CK: CK_IntegralComplexToReal);
8030 return CK_IntegralToFloating;
8031 case Type::STK_CPointer:
8032 case Type::STK_ObjCObjectPointer:
8033 case Type::STK_BlockPointer:
8034 llvm_unreachable("valid complex int->pointer cast?");
8035 case Type::STK_MemberPointer:
8036 llvm_unreachable("member pointer type in C");
8037 case Type::STK_FixedPoint:
8038 Diag(Loc: Src.get()->getExprLoc(),
8039 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8040 << SrcTy;
8041 return CK_IntegralCast;
8042 }
8043 llvm_unreachable("Should have returned before this");
8044 }
8045
8046 llvm_unreachable("Unhandled scalar cast");
8047}
8048
8049static bool breakDownVectorType(QualType type, uint64_t &len,
8050 QualType &eltType) {
8051 // Vectors are simple.
8052 if (const VectorType *vecType = type->getAs<VectorType>()) {
8053 len = vecType->getNumElements();
8054 eltType = vecType->getElementType();
8055 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8056 return true;
8057 }
8058
8059 // We allow lax conversion to and from non-vector types, but only if
8060 // they're real types (i.e. non-complex, non-pointer scalar types).
8061 if (!type->isRealType()) return false;
8062
8063 len = 1;
8064 eltType = type;
8065 return true;
8066}
8067
8068bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8069 assert(srcTy->isVectorType() || destTy->isVectorType());
8070
8071 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8072 if (!FirstType->isSVESizelessBuiltinType())
8073 return false;
8074
8075 const auto *VecTy = SecondType->getAs<VectorType>();
8076 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8077 };
8078
8079 return ValidScalableConversion(srcTy, destTy) ||
8080 ValidScalableConversion(destTy, srcTy);
8081}
8082
8083bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8084 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8085 return false;
8086
8087 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8088 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8089
8090 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8091 matSrcType->getNumColumns() == matDestType->getNumColumns();
8092}
8093
8094bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8095 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8096
8097 uint64_t SrcLen, DestLen;
8098 QualType SrcEltTy, DestEltTy;
8099 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
8100 return false;
8101 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
8102 return false;
8103
8104 // x87 long double has padding bits, so it cannot be bitcast to another type.
8105 auto IsX87LongDouble = [&](QualType T) {
8106 return T->isRealFloatingType() && &Context.getFloatTypeSemantics(T) ==
8107 &llvm::APFloat::x87DoubleExtended();
8108 };
8109 if (IsX87LongDouble(SrcEltTy) != IsX87LongDouble(DestEltTy))
8110 return false;
8111
8112 // ASTContext::getTypeSize will return the size rounded up to a
8113 // power of 2, so instead of using that, we need to use the raw
8114 // element size multiplied by the element count.
8115 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
8116 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
8117
8118 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8119}
8120
8121bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8122 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8123 "expected at least one type to be a vector here");
8124
8125 bool IsSrcTyAltivec =
8126 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8127 VectorKind::AltiVecVector) ||
8128 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8129 VectorKind::AltiVecBool) ||
8130 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8131 VectorKind::AltiVecPixel));
8132
8133 bool IsDestTyAltivec = DestTy->isVectorType() &&
8134 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8135 VectorKind::AltiVecVector) ||
8136 (DestTy->castAs<VectorType>()->getVectorKind() ==
8137 VectorKind::AltiVecBool) ||
8138 (DestTy->castAs<VectorType>()->getVectorKind() ==
8139 VectorKind::AltiVecPixel));
8140
8141 return (IsSrcTyAltivec || IsDestTyAltivec);
8142}
8143
8144bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8145 assert(destTy->isVectorType() || srcTy->isVectorType());
8146
8147 // Disallow lax conversions between scalars and ExtVectors (these
8148 // conversions are allowed for other vector types because common headers
8149 // depend on them). Most scalar OP ExtVector cases are handled by the
8150 // splat path anyway, which does what we want (convert, not bitcast).
8151 // What this rules out for ExtVectors is crazy things like char4*float.
8152 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8153 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8154
8155 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8156}
8157
8158bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8159 assert(destTy->isVectorType() || srcTy->isVectorType());
8160
8161 switch (Context.getLangOpts().getLaxVectorConversions()) {
8162 case LangOptions::LaxVectorConversionKind::None:
8163 return false;
8164
8165 case LangOptions::LaxVectorConversionKind::Integer:
8166 if (!srcTy->isIntegralOrEnumerationType()) {
8167 auto *Vec = srcTy->getAs<VectorType>();
8168 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8169 return false;
8170 }
8171 if (!destTy->isIntegralOrEnumerationType()) {
8172 auto *Vec = destTy->getAs<VectorType>();
8173 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8174 return false;
8175 }
8176 // OK, integer (vector) -> integer (vector) bitcast.
8177 break;
8178
8179 case LangOptions::LaxVectorConversionKind::All:
8180 break;
8181 }
8182
8183 return areLaxCompatibleVectorTypes(srcTy, destTy);
8184}
8185
8186bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8187 CastKind &Kind) {
8188 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8189 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8190 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8191 << DestTy << SrcTy << R;
8192 }
8193 } else if (SrcTy->isMatrixType()) {
8194 return Diag(Loc: R.getBegin(),
8195 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8196 << SrcTy << DestTy << R;
8197 } else if (DestTy->isMatrixType()) {
8198 return Diag(Loc: R.getBegin(),
8199 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8200 << DestTy << SrcTy << R;
8201 }
8202
8203 Kind = CK_MatrixCast;
8204 return false;
8205}
8206
8207bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8208 CastKind &Kind) {
8209 assert(VectorTy->isVectorType() && "Not a vector type!");
8210
8211 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8212 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8213 return Diag(Loc: R.getBegin(),
8214 DiagID: Ty->isVectorType() ?
8215 diag::err_invalid_conversion_between_vectors :
8216 diag::err_invalid_conversion_between_vector_and_integer)
8217 << VectorTy << Ty << R;
8218 } else
8219 return Diag(Loc: R.getBegin(),
8220 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8221 << VectorTy << Ty << R;
8222
8223 Kind = CK_BitCast;
8224 return false;
8225}
8226
8227ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8228 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8229
8230 if (DestElemTy == SplattedExpr->getType())
8231 return SplattedExpr;
8232
8233 assert(DestElemTy->isFloatingType() ||
8234 DestElemTy->isIntegralOrEnumerationType());
8235
8236 CastKind CK;
8237 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8238 // OpenCL requires that we convert `true` boolean expressions to -1, but
8239 // only when splatting vectors.
8240 if (DestElemTy->isFloatingType()) {
8241 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8242 // in two steps: boolean to signed integral, then to floating.
8243 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8244 CK: CK_BooleanToSignedIntegral);
8245 SplattedExpr = CastExprRes.get();
8246 CK = CK_IntegralToFloating;
8247 } else {
8248 CK = CK_BooleanToSignedIntegral;
8249 }
8250 } else {
8251 ExprResult CastExprRes = SplattedExpr;
8252 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8253 if (CastExprRes.isInvalid())
8254 return ExprError();
8255 SplattedExpr = CastExprRes.get();
8256 }
8257 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8258}
8259
8260ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8261 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8262
8263 if (DestElemTy == SplattedExpr->getType())
8264 return SplattedExpr;
8265
8266 assert(DestElemTy->isFloatingType() ||
8267 DestElemTy->isIntegralOrEnumerationType());
8268
8269 ExprResult CastExprRes = SplattedExpr;
8270 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8271 if (CastExprRes.isInvalid())
8272 return ExprError();
8273 SplattedExpr = CastExprRes.get();
8274
8275 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8276}
8277
8278ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8279 Expr *CastExpr, CastKind &Kind) {
8280 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8281
8282 QualType SrcTy = CastExpr->getType();
8283
8284 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8285 // an ExtVectorType.
8286 // In OpenCL, casts between vectors of different types are not allowed.
8287 // (See OpenCL 6.2).
8288 if (SrcTy->isVectorType()) {
8289 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8290 (getLangOpts().OpenCL &&
8291 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8292 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8293 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8294 << DestTy << SrcTy << R;
8295 return ExprError();
8296 }
8297 Kind = CK_BitCast;
8298 return CastExpr;
8299 }
8300
8301 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8302 // conversion will take place first from scalar to elt type, and then
8303 // splat from elt type to vector.
8304 if (SrcTy->isPointerType())
8305 return Diag(Loc: R.getBegin(),
8306 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8307 << DestTy << SrcTy << R;
8308
8309 Kind = CK_VectorSplat;
8310 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8311}
8312
8313/// Check that a call to alloc_size function specifies sufficient space for the
8314/// destination type.
8315static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8316 const Expr *E) {
8317 QualType SourceType = E->getType();
8318 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8319 DestType == SourceType)
8320 return;
8321
8322 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8323 if (!CE)
8324 return;
8325
8326 // Find the total size allocated by the function call.
8327 if (!CE->getCalleeAllocSizeAttr())
8328 return;
8329 std::optional<llvm::APInt> AllocSize =
8330 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8331 // Allocations of size zero are permitted as a special case. They are usually
8332 // done intentionally.
8333 if (!AllocSize || AllocSize->isZero())
8334 return;
8335 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8336
8337 QualType TargetType = DestType->getPointeeType();
8338 // Find the destination size. As a special case function types have size of
8339 // one byte to match the sizeof operator behavior.
8340 auto LhsSize = TargetType->isFunctionType()
8341 ? CharUnits::One()
8342 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8343 if (LhsSize && Size < LhsSize)
8344 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8345 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8346}
8347
8348ExprResult
8349Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8350 Declarator &D, ParsedType &Ty,
8351 SourceLocation RParenLoc, Expr *CastExpr) {
8352 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8353 "ActOnCastExpr(): missing type or expr");
8354
8355 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8356 if (D.isInvalidType())
8357 return ExprError();
8358
8359 if (getLangOpts().CPlusPlus) {
8360 // Check that there are no default arguments (C++ only).
8361 CheckExtraCXXDefaultArguments(D);
8362 }
8363
8364 checkUnusedDeclAttributes(D);
8365
8366 QualType castType = castTInfo->getType();
8367 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8368
8369 bool isVectorLiteral = false;
8370
8371 // Check for an altivec or OpenCL literal,
8372 // i.e. all the elements are integer constants.
8373 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8374 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8375 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8376 && castType->isVectorType() && (PE || PLE)) {
8377 if (PLE && PLE->getNumExprs() == 0) {
8378 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8379 return ExprError();
8380 }
8381 if (PE || PLE->getNumExprs() == 1) {
8382 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8383 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8384 isVectorLiteral = true;
8385 }
8386 else
8387 isVectorLiteral = true;
8388 }
8389
8390 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8391 // then handle it as such.
8392 if (isVectorLiteral)
8393 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8394
8395 // If the Expr being casted is a ParenListExpr, handle it specially.
8396 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8397 // sequence of BinOp comma operators.
8398 if (isa<ParenListExpr>(Val: CastExpr)) {
8399 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8400 if (Result.isInvalid()) return ExprError();
8401 CastExpr = Result.get();
8402 }
8403
8404 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8405 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8406
8407 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8408
8409 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8410
8411 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8412
8413 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8414
8415 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8416}
8417
8418ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8419 SourceLocation RParenLoc, Expr *E,
8420 TypeSourceInfo *TInfo) {
8421 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8422 "Expected paren or paren list expression");
8423
8424 Expr **exprs;
8425 unsigned numExprs;
8426 Expr *subExpr;
8427 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8428 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8429 LiteralLParenLoc = PE->getLParenLoc();
8430 LiteralRParenLoc = PE->getRParenLoc();
8431 exprs = PE->getExprs();
8432 numExprs = PE->getNumExprs();
8433 } else { // isa<ParenExpr> by assertion at function entrance
8434 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8435 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8436 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8437 exprs = &subExpr;
8438 numExprs = 1;
8439 }
8440
8441 QualType Ty = TInfo->getType();
8442 assert(Ty->isVectorType() && "Expected vector type");
8443
8444 SmallVector<Expr *, 8> initExprs;
8445 const VectorType *VTy = Ty->castAs<VectorType>();
8446 unsigned numElems = VTy->getNumElements();
8447
8448 // '(...)' form of vector initialization in AltiVec: the number of
8449 // initializers must be one or must match the size of the vector.
8450 // If a single value is specified in the initializer then it will be
8451 // replicated to all the components of the vector
8452 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8453 SrcTy: VTy->getElementType()))
8454 return ExprError();
8455 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8456 // The number of initializers must be one or must match the size of the
8457 // vector. If a single value is specified in the initializer then it will
8458 // be replicated to all the components of the vector
8459 if (numExprs == 1) {
8460 QualType ElemTy = VTy->getElementType();
8461 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8462 if (Literal.isInvalid())
8463 return ExprError();
8464 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8465 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8466 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8467 }
8468 else if (numExprs < numElems) {
8469 Diag(Loc: E->getExprLoc(),
8470 DiagID: diag::err_incorrect_number_of_vector_initializers);
8471 return ExprError();
8472 }
8473 else
8474 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8475 }
8476 else {
8477 // For OpenCL, when the number of initializers is a single value,
8478 // it will be replicated to all components of the vector.
8479 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8480 numExprs == 1) {
8481 QualType SrcTy = exprs[0]->getType();
8482 if (!SrcTy->isArithmeticType()) {
8483 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8484 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8485 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8486 return ExprError();
8487 }
8488 QualType ElemTy = VTy->getElementType();
8489 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8490 if (Literal.isInvalid())
8491 return ExprError();
8492 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8493 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8494 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8495 }
8496
8497 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8498 }
8499 // FIXME: This means that pretty-printing the final AST will produce curly
8500 // braces instead of the original commas.
8501 InitListExpr *initE =
8502 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8503 LiteralRParenLoc, /*isExplicit=*/false);
8504 initE->setType(Ty);
8505 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8506}
8507
8508ExprResult
8509Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8510 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8511 if (!E)
8512 return OrigExpr;
8513
8514 ExprResult Result(E->getExpr(Init: 0));
8515
8516 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8517 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8518 RHSExpr: E->getExpr(Init: i));
8519
8520 if (Result.isInvalid()) return ExprError();
8521
8522 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8523}
8524
8525ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8526 SourceLocation R,
8527 MultiExprArg Val) {
8528 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8529}
8530
8531ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8532 unsigned NumUserSpecifiedExprs,
8533 SourceLocation InitLoc,
8534 SourceLocation LParenLoc,
8535 SourceLocation RParenLoc) {
8536 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8537 InitLoc, LParenLoc, RParenLoc);
8538}
8539
8540bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8541 SourceLocation QuestionLoc) {
8542 const Expr *NullExpr = LHSExpr;
8543 const Expr *NonPointerExpr = RHSExpr;
8544 Expr::NullPointerConstantKind NullKind =
8545 NullExpr->isNullPointerConstant(Ctx&: Context,
8546 NPC: Expr::NPC_ValueDependentIsNotNull);
8547
8548 if (NullKind == Expr::NPCK_NotNull) {
8549 NullExpr = RHSExpr;
8550 NonPointerExpr = LHSExpr;
8551 NullKind =
8552 NullExpr->isNullPointerConstant(Ctx&: Context,
8553 NPC: Expr::NPC_ValueDependentIsNotNull);
8554 }
8555
8556 if (NullKind == Expr::NPCK_NotNull)
8557 return false;
8558
8559 if (NullKind == Expr::NPCK_ZeroExpression)
8560 return false;
8561
8562 if (NullKind == Expr::NPCK_ZeroLiteral) {
8563 // In this case, check to make sure that we got here from a "NULL"
8564 // string in the source code.
8565 NullExpr = NullExpr->IgnoreParenImpCasts();
8566 SourceLocation loc = NullExpr->getExprLoc();
8567 if (!findMacroSpelling(loc, name: "NULL"))
8568 return false;
8569 }
8570
8571 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8572 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8573 << NonPointerExpr->getType() << DiagType
8574 << NonPointerExpr->getSourceRange();
8575 return true;
8576}
8577
8578/// Return false if the condition expression is valid, true otherwise.
8579static bool checkCondition(Sema &S, const Expr *Cond,
8580 SourceLocation QuestionLoc) {
8581 QualType CondTy = Cond->getType();
8582
8583 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8584 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8585 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8586 << CondTy << Cond->getSourceRange();
8587 return true;
8588 }
8589
8590 // C99 6.5.15p2
8591 if (CondTy->isScalarType()) return false;
8592
8593 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8594 << CondTy << Cond->getSourceRange();
8595 return true;
8596}
8597
8598/// Return false if the NullExpr can be promoted to PointerTy,
8599/// true otherwise.
8600static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8601 QualType PointerTy) {
8602 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8603 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8604 NPC: Expr::NPC_ValueDependentIsNull))
8605 return true;
8606
8607 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8608 return false;
8609}
8610
8611/// Checks compatibility between two pointers and return the resulting
8612/// type.
8613static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8614 ExprResult &RHS,
8615 SourceLocation Loc) {
8616 QualType LHSTy = LHS.get()->getType();
8617 QualType RHSTy = RHS.get()->getType();
8618
8619 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8620 // Two identical pointers types are always compatible.
8621 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8622 }
8623
8624 QualType lhptee, rhptee;
8625
8626 // Get the pointee types.
8627 bool IsBlockPointer = false;
8628 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8629 lhptee = LHSBTy->getPointeeType();
8630 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8631 IsBlockPointer = true;
8632 } else {
8633 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8634 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8635 }
8636
8637 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8638 // differently qualified versions of compatible types, the result type is
8639 // a pointer to an appropriately qualified version of the composite
8640 // type.
8641
8642 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8643 // clause doesn't make sense for our extensions. E.g. address space 2 should
8644 // be incompatible with address space 3: they may live on different devices or
8645 // anything.
8646 Qualifiers lhQual = lhptee.getQualifiers();
8647 Qualifiers rhQual = rhptee.getQualifiers();
8648
8649 LangAS ResultAddrSpace = LangAS::Default;
8650 LangAS LAddrSpace = lhQual.getAddressSpace();
8651 LangAS RAddrSpace = rhQual.getAddressSpace();
8652
8653 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8654 // spaces is disallowed.
8655 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8656 ResultAddrSpace = LAddrSpace;
8657 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8658 ResultAddrSpace = RAddrSpace;
8659 else {
8660 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8661 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8662 << RHS.get()->getSourceRange();
8663 return QualType();
8664 }
8665
8666 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8667 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8668 lhQual.removeCVRQualifiers();
8669 rhQual.removeCVRQualifiers();
8670
8671 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8672 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8673 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8674 << RHS.get()->getSourceRange();
8675 return QualType();
8676 }
8677
8678 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8679 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8680 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8681 // qual types are compatible iff
8682 // * corresponded types are compatible
8683 // * CVR qualifiers are equal
8684 // * address spaces are equal
8685 // Thus for conditional operator we merge CVR and address space unqualified
8686 // pointees and if there is a composite type we return a pointer to it with
8687 // merged qualifiers.
8688 LHSCastKind =
8689 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8690 RHSCastKind =
8691 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8692 lhQual.removeAddressSpace();
8693 rhQual.removeAddressSpace();
8694
8695 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8696 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8697
8698 QualType CompositeTy = S.Context.mergeTypes(
8699 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8700 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8701
8702 if (CompositeTy.isNull()) {
8703 // In this situation, we assume void* type. No especially good
8704 // reason, but this is what gcc does, and we do have to pick
8705 // to get a consistent AST.
8706 QualType incompatTy;
8707 incompatTy = S.Context.getPointerType(
8708 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8709 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8710 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8711
8712 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8713 // for casts between types with incompatible address space qualifiers.
8714 // For the following code the compiler produces casts between global and
8715 // local address spaces of the corresponded innermost pointees:
8716 // local int *global *a;
8717 // global int *global *b;
8718 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8719 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8720 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8721 << RHS.get()->getSourceRange();
8722
8723 return incompatTy;
8724 }
8725
8726 // The pointer types are compatible.
8727 // In case of OpenCL ResultTy should have the address space qualifier
8728 // which is a superset of address spaces of both the 2nd and the 3rd
8729 // operands of the conditional operator.
8730 QualType ResultTy = [&, ResultAddrSpace]() {
8731 if (S.getLangOpts().OpenCL) {
8732 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8733 CompositeQuals.setAddressSpace(ResultAddrSpace);
8734 return S.Context
8735 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8736 .withCVRQualifiers(CVR: MergedCVRQual);
8737 }
8738 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8739 }();
8740 if (IsBlockPointer)
8741 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8742 else
8743 ResultTy = S.Context.getPointerType(T: ResultTy);
8744
8745 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8746 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8747 return ResultTy;
8748}
8749
8750/// Return the resulting type when the operands are both block pointers.
8751static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8752 ExprResult &LHS,
8753 ExprResult &RHS,
8754 SourceLocation Loc) {
8755 QualType LHSTy = LHS.get()->getType();
8756 QualType RHSTy = RHS.get()->getType();
8757
8758 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8759 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8760 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8761 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8762 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8763 return destType;
8764 }
8765 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8766 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8767 << RHS.get()->getSourceRange();
8768 return QualType();
8769 }
8770
8771 // We have 2 block pointer types.
8772 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8773}
8774
8775/// Return the resulting type when the operands are both pointers.
8776static QualType
8777checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8778 ExprResult &RHS,
8779 SourceLocation Loc) {
8780 // get the pointer types
8781 QualType LHSTy = LHS.get()->getType();
8782 QualType RHSTy = RHS.get()->getType();
8783
8784 // get the "pointed to" types
8785 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8786 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8787
8788 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8789 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8790 // Figure out necessary qualifiers (C99 6.5.15p6)
8791 QualType destPointee
8792 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8793 QualType destType = S.Context.getPointerType(T: destPointee);
8794 // Add qualifiers if necessary.
8795 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8796 // Promote to void*.
8797 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8798 return destType;
8799 }
8800 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8801 QualType destPointee
8802 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8803 QualType destType = S.Context.getPointerType(T: destPointee);
8804 // Add qualifiers if necessary.
8805 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8806 // Promote to void*.
8807 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8808 return destType;
8809 }
8810
8811 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8812}
8813
8814/// Return false if the first expression is not an integer and the second
8815/// expression is not a pointer, true otherwise.
8816static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8817 Expr* PointerExpr, SourceLocation Loc,
8818 bool IsIntFirstExpr) {
8819 if (!PointerExpr->getType()->isPointerType() ||
8820 !Int.get()->getType()->isIntegerType())
8821 return false;
8822
8823 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8824 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8825
8826 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8827 << Expr1->getType() << Expr2->getType()
8828 << Expr1->getSourceRange() << Expr2->getSourceRange();
8829 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8830 CK: CK_IntegralToPointer);
8831 return true;
8832}
8833
8834/// Simple conversion between integer and floating point types.
8835///
8836/// Used when handling the OpenCL conditional operator where the
8837/// condition is a vector while the other operands are scalar.
8838///
8839/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8840/// types are either integer or floating type. Between the two
8841/// operands, the type with the higher rank is defined as the "result
8842/// type". The other operand needs to be promoted to the same type. No
8843/// other type promotion is allowed. We cannot use
8844/// UsualArithmeticConversions() for this purpose, since it always
8845/// promotes promotable types.
8846static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8847 ExprResult &RHS,
8848 SourceLocation QuestionLoc) {
8849 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8850 if (LHS.isInvalid())
8851 return QualType();
8852 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8853 if (RHS.isInvalid())
8854 return QualType();
8855
8856 // For conversion purposes, we ignore any qualifiers.
8857 // For example, "const float" and "float" are equivalent.
8858 QualType LHSType =
8859 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8860 QualType RHSType =
8861 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8862
8863 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8864 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8865 << LHSType << LHS.get()->getSourceRange();
8866 return QualType();
8867 }
8868
8869 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8870 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8871 << RHSType << RHS.get()->getSourceRange();
8872 return QualType();
8873 }
8874
8875 // If both types are identical, no conversion is needed.
8876 if (LHSType == RHSType)
8877 return LHSType;
8878
8879 // Now handle "real" floating types (i.e. float, double, long double).
8880 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8881 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8882 /*IsCompAssign = */ false);
8883
8884 // Finally, we have two differing integer types.
8885 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8886 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8887}
8888
8889/// Convert scalar operands to a vector that matches the
8890/// condition in length.
8891///
8892/// Used when handling the OpenCL conditional operator where the
8893/// condition is a vector while the other operands are scalar.
8894///
8895/// We first compute the "result type" for the scalar operands
8896/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8897/// into a vector of that type where the length matches the condition
8898/// vector type. s6.11.6 requires that the element types of the result
8899/// and the condition must have the same number of bits.
8900static QualType
8901OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8902 QualType CondTy, SourceLocation QuestionLoc) {
8903 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8904 if (ResTy.isNull()) return QualType();
8905
8906 const VectorType *CV = CondTy->getAs<VectorType>();
8907 assert(CV);
8908
8909 // Determine the vector result type
8910 unsigned NumElements = CV->getNumElements();
8911 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8912
8913 // Ensure that all types have the same number of bits
8914 if (S.Context.getTypeSize(T: CV->getElementType())
8915 != S.Context.getTypeSize(T: ResTy)) {
8916 // Since VectorTy is created internally, it does not pretty print
8917 // with an OpenCL name. Instead, we just print a description.
8918 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8919 SmallString<64> Str;
8920 llvm::raw_svector_ostream OS(Str);
8921 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8922 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8923 << CondTy << OS.str();
8924 return QualType();
8925 }
8926
8927 // Convert operands to the vector result type
8928 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8929 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8930
8931 return VectorTy;
8932}
8933
8934/// Return false if this is a valid OpenCL condition vector
8935static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8936 SourceLocation QuestionLoc) {
8937 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8938 // integral type.
8939 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8940 assert(CondTy);
8941 QualType EleTy = CondTy->getElementType();
8942 if (EleTy->isIntegerType()) return false;
8943
8944 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8945 << Cond->getType() << Cond->getSourceRange();
8946 return true;
8947}
8948
8949/// Return false if the vector condition type and the vector
8950/// result type are compatible.
8951///
8952/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8953/// number of elements, and their element types have the same number
8954/// of bits.
8955static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8956 SourceLocation QuestionLoc) {
8957 const VectorType *CV = CondTy->getAs<VectorType>();
8958 const VectorType *RV = VecResTy->getAs<VectorType>();
8959 assert(CV && RV);
8960
8961 if (CV->getNumElements() != RV->getNumElements()) {
8962 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8963 << CondTy << VecResTy;
8964 return true;
8965 }
8966
8967 QualType CVE = CV->getElementType();
8968 QualType RVE = RV->getElementType();
8969
8970 // Boolean vectors are permitted outside of OpenCL mode.
8971 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8972 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8973 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8974 << CondTy << VecResTy;
8975 return true;
8976 }
8977
8978 return false;
8979}
8980
8981/// Return the resulting type for the conditional operator in
8982/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8983/// s6.3.i) when the condition is a vector type.
8984static QualType
8985OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8986 ExprResult &LHS, ExprResult &RHS,
8987 SourceLocation QuestionLoc) {
8988 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8989 if (Cond.isInvalid())
8990 return QualType();
8991 QualType CondTy = Cond.get()->getType();
8992
8993 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8994 return QualType();
8995
8996 // If either operand is a vector then find the vector type of the
8997 // result as specified in OpenCL v1.1 s6.3.i.
8998 if (LHS.get()->getType()->isVectorType() ||
8999 RHS.get()->getType()->isVectorType()) {
9000 bool IsBoolVecLang =
9001 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9002 QualType VecResTy =
9003 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
9004 /*isCompAssign*/ IsCompAssign: false,
9005 /*AllowBothBool*/ true,
9006 /*AllowBoolConversions*/ AllowBoolConversion: false,
9007 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang);
9008 if (VecResTy.isNull())
9009 return QualType();
9010 // The result type must match the condition type as specified in
9011 // OpenCL v1.1 s6.11.6.
9012 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9013 return QualType();
9014 return VecResTy;
9015 }
9016
9017 // Both operands are scalar.
9018 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9019}
9020
9021/// Return true if the Expr is block type
9022static bool checkBlockType(Sema &S, const Expr *E) {
9023 if (E->getType()->isBlockPointerType()) {
9024 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
9025 return true;
9026 }
9027
9028 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
9029 QualType Ty = CE->getCallee()->getType();
9030 if (Ty->isBlockPointerType()) {
9031 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
9032 return true;
9033 }
9034 }
9035 return false;
9036}
9037
9038/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9039/// In that case, LHS = cond.
9040/// C99 6.5.15
9041QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9042 ExprResult &RHS, ExprValueKind &VK,
9043 ExprObjectKind &OK,
9044 SourceLocation QuestionLoc) {
9045
9046 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
9047 if (!LHSResult.isUsable()) return QualType();
9048 LHS = LHSResult;
9049
9050 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
9051 if (!RHSResult.isUsable()) return QualType();
9052 RHS = RHSResult;
9053
9054 // C++ is sufficiently different to merit its own checker.
9055 if (getLangOpts().CPlusPlus)
9056 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
9057
9058 VK = VK_PRValue;
9059 OK = OK_Ordinary;
9060
9061 if (Context.isDependenceAllowed() &&
9062 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9063 RHS.get()->isTypeDependent())) {
9064 assert(!getLangOpts().CPlusPlus);
9065 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9066 RHS.get()->containsErrors()) &&
9067 "should only occur in error-recovery path.");
9068 return Context.DependentTy;
9069 }
9070
9071 // The OpenCL operator with a vector condition is sufficiently
9072 // different to merit its own checker.
9073 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9074 Cond.get()->getType()->isExtVectorType())
9075 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
9076
9077 // First, check the condition.
9078 Cond = UsualUnaryConversions(E: Cond.get());
9079 if (Cond.isInvalid())
9080 return QualType();
9081 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
9082 return QualType();
9083
9084 // Handle vectors.
9085 if (LHS.get()->getType()->isVectorType() ||
9086 RHS.get()->getType()->isVectorType())
9087 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
9088 /*AllowBothBool*/ true,
9089 /*AllowBoolConversions*/ AllowBoolConversion: false,
9090 /*AllowBooleanOperation*/ AllowBoolOperation: false);
9091
9092 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
9093 ACK: ArithConvKind::Conditional);
9094 if (LHS.isInvalid() || RHS.isInvalid())
9095 return QualType();
9096
9097 // WebAssembly tables are not allowed as conditional LHS or RHS.
9098 QualType LHSTy = LHS.get()->getType();
9099 QualType RHSTy = RHS.get()->getType();
9100 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9101 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
9102 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9103 return QualType();
9104 }
9105
9106 // Diagnose attempts to convert between __ibm128, __float128 and long double
9107 // where such conversions currently can't be handled.
9108 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
9109 Diag(Loc: QuestionLoc,
9110 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9111 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9112 return QualType();
9113 }
9114
9115 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9116 // selection operator (?:).
9117 if (getLangOpts().OpenCL &&
9118 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
9119 return QualType();
9120 }
9121
9122 // If both operands have arithmetic type, do the usual arithmetic conversions
9123 // to find a common type: C99 6.5.15p3,5.
9124 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9125 // Disallow invalid arithmetic conversions, such as those between bit-
9126 // precise integers types of different sizes, or between a bit-precise
9127 // integer and another type.
9128 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9129 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9130 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9131 << RHS.get()->getSourceRange();
9132 return QualType();
9133 }
9134
9135 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
9136 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
9137
9138 return ResTy;
9139 }
9140
9141 // If both operands are the same structure or union type, the result is that
9142 // type.
9143 // FIXME: Type of conditional expression must be complete in C mode.
9144 if (LHSTy->isRecordType() &&
9145 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
9146 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9147 Y: RHSTy.getUnqualifiedType());
9148
9149 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9150 // The following || allows only one side to be void (a GCC-ism).
9151 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9152 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9153 // UsualArithmeticConversions already handled the case where both sides
9154 // are the same type.
9155 } else if (RHSTy->isVoidType()) {
9156 ResTy = RHSTy;
9157 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9158 << RHS.get()->getSourceRange();
9159 } else {
9160 ResTy = LHSTy;
9161 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9162 << LHS.get()->getSourceRange();
9163 }
9164 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9165 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9166 return ResTy;
9167 }
9168
9169 // C23 6.5.15p7:
9170 // ... if both the second and third operands have nullptr_t type, the
9171 // result also has that type.
9172 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9173 return ResTy;
9174
9175 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9176 // the type of the other operand."
9177 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9178 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9179
9180 // All objective-c pointer type analysis is done here.
9181 QualType compositeType =
9182 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9183 if (LHS.isInvalid() || RHS.isInvalid())
9184 return QualType();
9185 if (!compositeType.isNull())
9186 return compositeType;
9187
9188
9189 // Handle block pointer types.
9190 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9191 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9192 Loc: QuestionLoc);
9193
9194 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9195 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9196 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9197 Loc: QuestionLoc);
9198
9199 // GCC compatibility: soften pointer/integer mismatch. Note that
9200 // null pointers have been filtered out by this point.
9201 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9202 /*IsIntFirstExpr=*/true))
9203 return RHSTy;
9204 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9205 /*IsIntFirstExpr=*/false))
9206 return LHSTy;
9207
9208 // Emit a better diagnostic if one of the expressions is a null pointer
9209 // constant and the other is not a pointer type. In this case, the user most
9210 // likely forgot to take the address of the other expression.
9211 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9212 return QualType();
9213
9214 // Finally, if the LHS and RHS types are canonically the same type, we can
9215 // use the common sugared type.
9216 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9217 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9218
9219 // Otherwise, the operands are not compatible.
9220 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9221 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9222 << RHS.get()->getSourceRange();
9223 return QualType();
9224}
9225
9226/// SuggestParentheses - Emit a note with a fixit hint that wraps
9227/// ParenRange in parentheses.
9228static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9229 const PartialDiagnostic &Note,
9230 SourceRange ParenRange) {
9231 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9232 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9233 EndLoc.isValid()) {
9234 Self.Diag(Loc, PD: Note)
9235 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9236 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9237 } else {
9238 // We can't display the parentheses, so just show the bare note.
9239 Self.Diag(Loc, PD: Note) << ParenRange;
9240 }
9241}
9242
9243static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9244 return BinaryOperator::isAdditiveOp(Opc) ||
9245 BinaryOperator::isMultiplicativeOp(Opc) ||
9246 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9247 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9248 // not any of the logical operators. Bitwise-xor is commonly used as a
9249 // logical-xor because there is no logical-xor operator. The logical
9250 // operators, including uses of xor, have a high false positive rate for
9251 // precedence warnings.
9252}
9253
9254/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9255/// expression, either using a built-in or overloaded operator,
9256/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9257/// expression.
9258static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9259 const Expr **RHSExprs) {
9260 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9261 E = E->IgnoreImpCasts();
9262 E = E->IgnoreConversionOperatorSingleStep();
9263 E = E->IgnoreImpCasts();
9264 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9265 E = MTE->getSubExpr();
9266 E = E->IgnoreImpCasts();
9267 }
9268
9269 // Built-in binary operator.
9270 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9271 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9272 *Opcode = OP->getOpcode();
9273 *RHSExprs = OP->getRHS();
9274 return true;
9275 }
9276
9277 // Overloaded operator.
9278 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9279 if (Call->getNumArgs() != 2)
9280 return false;
9281
9282 // Make sure this is really a binary operator that is safe to pass into
9283 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9284 OverloadedOperatorKind OO = Call->getOperator();
9285 if (OO < OO_Plus || OO > OO_Arrow ||
9286 OO == OO_PlusPlus || OO == OO_MinusMinus)
9287 return false;
9288
9289 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9290 if (IsArithmeticOp(Opc: OpKind)) {
9291 *Opcode = OpKind;
9292 *RHSExprs = Call->getArg(Arg: 1);
9293 return true;
9294 }
9295 }
9296
9297 return false;
9298}
9299
9300/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9301/// or is a logical expression such as (x==y) which has int type, but is
9302/// commonly interpreted as boolean.
9303static bool ExprLooksBoolean(const Expr *E) {
9304 E = E->IgnoreParenImpCasts();
9305
9306 if (E->getType()->isBooleanType())
9307 return true;
9308 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9309 return OP->isComparisonOp() || OP->isLogicalOp();
9310 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9311 return OP->getOpcode() == UO_LNot;
9312 if (E->getType()->isPointerType())
9313 return true;
9314 // FIXME: What about overloaded operator calls returning "unspecified boolean
9315 // type"s (commonly pointer-to-members)?
9316
9317 return false;
9318}
9319
9320/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9321/// and binary operator are mixed in a way that suggests the programmer assumed
9322/// the conditional operator has higher precedence, for example:
9323/// "int x = a + someBinaryCondition ? 1 : 2".
9324static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9325 Expr *Condition, const Expr *LHSExpr,
9326 const Expr *RHSExpr) {
9327 BinaryOperatorKind CondOpcode;
9328 const Expr *CondRHS;
9329
9330 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9331 return;
9332 if (!ExprLooksBoolean(E: CondRHS))
9333 return;
9334
9335 // The condition is an arithmetic binary expression, with a right-
9336 // hand side that looks boolean, so warn.
9337
9338 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9339 ? diag::warn_precedence_bitwise_conditional
9340 : diag::warn_precedence_conditional;
9341
9342 Self.Diag(Loc: OpLoc, DiagID)
9343 << Condition->getSourceRange()
9344 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9345
9346 SuggestParentheses(
9347 Self, Loc: OpLoc,
9348 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9349 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9350 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9351
9352 SuggestParentheses(Self, Loc: OpLoc,
9353 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9354 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9355}
9356
9357/// Compute the nullability of a conditional expression.
9358static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9359 QualType LHSTy, QualType RHSTy,
9360 ASTContext &Ctx) {
9361 if (!ResTy->isAnyPointerType())
9362 return ResTy;
9363
9364 auto GetNullability = [](QualType Ty) {
9365 NullabilityKindOrNone Kind = Ty->getNullability();
9366 if (Kind) {
9367 // For our purposes, treat _Nullable_result as _Nullable.
9368 if (*Kind == NullabilityKind::NullableResult)
9369 return NullabilityKind::Nullable;
9370 return *Kind;
9371 }
9372 return NullabilityKind::Unspecified;
9373 };
9374
9375 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9376 NullabilityKind MergedKind;
9377
9378 // Compute nullability of a binary conditional expression.
9379 if (IsBin) {
9380 if (LHSKind == NullabilityKind::NonNull)
9381 MergedKind = NullabilityKind::NonNull;
9382 else
9383 MergedKind = RHSKind;
9384 // Compute nullability of a normal conditional expression.
9385 } else {
9386 if (LHSKind == NullabilityKind::Nullable ||
9387 RHSKind == NullabilityKind::Nullable)
9388 MergedKind = NullabilityKind::Nullable;
9389 else if (LHSKind == NullabilityKind::NonNull)
9390 MergedKind = RHSKind;
9391 else if (RHSKind == NullabilityKind::NonNull)
9392 MergedKind = LHSKind;
9393 else
9394 MergedKind = NullabilityKind::Unspecified;
9395 }
9396
9397 // Return if ResTy already has the correct nullability.
9398 if (GetNullability(ResTy) == MergedKind)
9399 return ResTy;
9400
9401 // Strip all nullability from ResTy.
9402 while (ResTy->getNullability())
9403 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9404
9405 // Create a new AttributedType with the new nullability kind.
9406 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9407}
9408
9409ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9410 SourceLocation ColonLoc,
9411 Expr *CondExpr, Expr *LHSExpr,
9412 Expr *RHSExpr) {
9413 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9414 // was the condition.
9415 OpaqueValueExpr *opaqueValue = nullptr;
9416 Expr *commonExpr = nullptr;
9417 if (!LHSExpr) {
9418 commonExpr = CondExpr;
9419 // Lower out placeholder types first. This is important so that we don't
9420 // try to capture a placeholder. This happens in few cases in C++; such
9421 // as Objective-C++'s dictionary subscripting syntax.
9422 if (commonExpr->hasPlaceholderType()) {
9423 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9424 if (!result.isUsable()) return ExprError();
9425 commonExpr = result.get();
9426 }
9427 // We usually want to apply unary conversions *before* saving, except
9428 // in the special case of a C++ l-value conditional.
9429 if (!(getLangOpts().CPlusPlus
9430 && !commonExpr->isTypeDependent()
9431 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9432 && commonExpr->isGLValue()
9433 && commonExpr->isOrdinaryOrBitFieldObject()
9434 && RHSExpr->isOrdinaryOrBitFieldObject()
9435 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9436 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9437 if (commonRes.isInvalid())
9438 return ExprError();
9439 commonExpr = commonRes.get();
9440 }
9441
9442 // If the common expression is a class or array prvalue, materialize it
9443 // so that we can safely refer to it multiple times.
9444 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9445 commonExpr->getType()->isArrayType())) {
9446 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9447 if (MatExpr.isInvalid())
9448 return ExprError();
9449 commonExpr = MatExpr.get();
9450 }
9451
9452 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9453 commonExpr->getType(),
9454 commonExpr->getValueKind(),
9455 commonExpr->getObjectKind(),
9456 commonExpr);
9457 LHSExpr = CondExpr = opaqueValue;
9458 }
9459
9460 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9461 ExprValueKind VK = VK_PRValue;
9462 ExprObjectKind OK = OK_Ordinary;
9463 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9464 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9465 VK, OK, QuestionLoc);
9466 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9467 RHS.isInvalid())
9468 return ExprError();
9469
9470 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9471 RHSExpr: RHS.get());
9472
9473 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9474
9475 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9476 Ctx&: Context);
9477
9478 if (!commonExpr)
9479 return new (Context)
9480 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9481 RHS.get(), result, VK, OK);
9482
9483 return new (Context) BinaryConditionalOperator(
9484 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9485 ColonLoc, result, VK, OK);
9486}
9487
9488bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9489 unsigned FromAttributes = 0, ToAttributes = 0;
9490 if (const auto *FromFn =
9491 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9492 FromAttributes =
9493 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9494 if (const auto *ToFn =
9495 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9496 ToAttributes =
9497 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9498
9499 return FromAttributes != ToAttributes;
9500}
9501
9502// checkPointerTypesForAssignment - This is a very tricky routine (despite
9503// being closely modeled after the C99 spec:-). The odd characteristic of this
9504// routine is it effectively iqnores the qualifiers on the top level pointee.
9505// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9506// FIXME: add a couple examples in this comment.
9507static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9508 QualType LHSType,
9509 QualType RHSType,
9510 SourceLocation Loc) {
9511 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9512 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9513
9514 // get the "pointed to" type (ignoring qualifiers at the top level)
9515 const Type *lhptee, *rhptee;
9516 Qualifiers lhq, rhq;
9517 std::tie(args&: lhptee, args&: lhq) =
9518 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9519 std::tie(args&: rhptee, args&: rhq) =
9520 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9521
9522 AssignConvertType ConvTy = AssignConvertType::Compatible;
9523
9524 // C99 6.5.16.1p1: This following citation is common to constraints
9525 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9526 // qualifiers of the type *pointed to* by the right;
9527
9528 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9529 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9530 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9531 // Ignore lifetime for further calculation.
9532 lhq.removeObjCLifetime();
9533 rhq.removeObjCLifetime();
9534 }
9535
9536 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9537 // Treat address-space mismatches as fatal.
9538 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9539 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9540
9541 // It's okay to add or remove GC or lifetime qualifiers when converting to
9542 // and from void*.
9543 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9544 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9545 Ctx: S.getASTContext()) &&
9546 (lhptee->isVoidType() || rhptee->isVoidType()))
9547 ; // keep old
9548
9549 // Treat lifetime mismatches as fatal.
9550 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9551 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9552
9553 // Treat pointer-auth mismatches as fatal.
9554 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9555 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9556
9557 // For GCC/MS compatibility, other qualifier mismatches are treated
9558 // as still compatible in C.
9559 else
9560 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9561 }
9562
9563 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9564 // incomplete type and the other is a pointer to a qualified or unqualified
9565 // version of void...
9566 if (lhptee->isVoidType()) {
9567 if (rhptee->isIncompleteOrObjectType())
9568 return ConvTy;
9569
9570 // As an extension, we allow cast to/from void* to function pointer.
9571 assert(rhptee->isFunctionType());
9572 return AssignConvertType::FunctionVoidPointer;
9573 }
9574
9575 if (rhptee->isVoidType()) {
9576 // In C, void * to another pointer type is compatible, but we want to note
9577 // that there will be an implicit conversion happening here.
9578 if (lhptee->isIncompleteOrObjectType())
9579 return ConvTy == AssignConvertType::Compatible &&
9580 !S.getLangOpts().CPlusPlus
9581 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9582 : ConvTy;
9583
9584 // As an extension, we allow cast to/from void* to function pointer.
9585 assert(lhptee->isFunctionType());
9586 return AssignConvertType::FunctionVoidPointer;
9587 }
9588
9589 if (!S.Diags.isIgnored(
9590 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9591 Loc) &&
9592 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9593 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9594 return AssignConvertType::IncompatibleFunctionPointerStrict;
9595
9596 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9597 // unqualified versions of compatible types, ...
9598 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9599
9600 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9601 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9602 QualType LUnderlying =
9603 ltrans->isOverflowBehaviorType()
9604 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9605 : ltrans;
9606 QualType RUnderlying =
9607 rtrans->isOverflowBehaviorType()
9608 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9609 : rtrans;
9610
9611 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9612 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9613
9614 ltrans = LUnderlying;
9615 rtrans = RUnderlying;
9616 }
9617 }
9618
9619 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9620 // Check if the pointee types are compatible ignoring the sign.
9621 // We explicitly check for char so that we catch "char" vs
9622 // "unsigned char" on systems where "char" is unsigned.
9623 if (lhptee->isCharType())
9624 ltrans = S.Context.UnsignedCharTy;
9625 else if (lhptee->hasSignedIntegerRepresentation())
9626 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9627
9628 if (rhptee->isCharType())
9629 rtrans = S.Context.UnsignedCharTy;
9630 else if (rhptee->hasSignedIntegerRepresentation())
9631 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9632
9633 if (ltrans == rtrans) {
9634 // Types are compatible ignoring the sign. Qualifier incompatibility
9635 // takes priority over sign incompatibility because the sign
9636 // warning can be disabled.
9637 if (!S.IsAssignConvertCompatible(ConvTy))
9638 return ConvTy;
9639
9640 return AssignConvertType::IncompatiblePointerSign;
9641 }
9642
9643 // If we are a multi-level pointer, it's possible that our issue is simply
9644 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9645 // the eventual target type is the same and the pointers have the same
9646 // level of indirection, this must be the issue.
9647 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9648 do {
9649 std::tie(args&: lhptee, args&: lhq) =
9650 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9651 std::tie(args&: rhptee, args&: rhq) =
9652 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9653
9654 // Inconsistent address spaces at this point is invalid, even if the
9655 // address spaces would be compatible.
9656 // FIXME: This doesn't catch address space mismatches for pointers of
9657 // different nesting levels, like:
9658 // __local int *** a;
9659 // int ** b = a;
9660 // It's not clear how to actually determine when such pointers are
9661 // invalidly incompatible.
9662 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9663 return AssignConvertType::
9664 IncompatibleNestedPointerAddressSpaceMismatch;
9665
9666 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9667
9668 if (lhptee == rhptee)
9669 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9670 }
9671
9672 // General pointer incompatibility takes priority over qualifiers.
9673 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9674 return AssignConvertType::IncompatibleFunctionPointer;
9675 return AssignConvertType::IncompatiblePointer;
9676 }
9677 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9678 // hasSameType, so we can skip further checks.
9679 const auto *LFT = ltrans->getAs<FunctionType>();
9680 const auto *RFT = rtrans->getAs<FunctionType>();
9681 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9682 // The invocation of IsFunctionConversion below will try to transform rtrans
9683 // to obtain an exact match for ltrans. This should not fail because of
9684 // mismatches in result type and parameter types, they were already checked
9685 // by typesAreCompatible above. So we will recreate rtrans (or where
9686 // appropriate ltrans) using the result type and parameter types from ltrans
9687 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9688 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9689 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9690 if (LFPT && RFPT) {
9691 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9692 Args: LFPT->getParamTypes(),
9693 EPI: RFPT->getExtProtoInfo());
9694 } else if (LFPT) {
9695 FunctionProtoType::ExtProtoInfo EPI;
9696 EPI.ExtInfo = RFT->getExtInfo();
9697 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9698 Args: LFPT->getParamTypes(), EPI);
9699 } else if (RFPT) {
9700 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9701 // all of its ExtProtoInfo. Transform ltrans instead.
9702 FunctionProtoType::ExtProtoInfo EPI;
9703 EPI.ExtInfo = LFT->getExtInfo();
9704 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9705 Args: RFPT->getParamTypes(), EPI);
9706 } else {
9707 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9708 Info: RFT->getExtInfo());
9709 }
9710 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9711 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9712 return AssignConvertType::IncompatibleFunctionPointer;
9713 }
9714 return ConvTy;
9715}
9716
9717/// checkBlockPointerTypesForAssignment - This routine determines whether two
9718/// block pointer types are compatible or whether a block and normal pointer
9719/// are compatible. It is more restrict than comparing two function pointer
9720// types.
9721static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9722 QualType LHSType,
9723 QualType RHSType) {
9724 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9725 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9726
9727 QualType lhptee, rhptee;
9728
9729 // get the "pointed to" type (ignoring qualifiers at the top level)
9730 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9731 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9732
9733 // In C++, the types have to match exactly.
9734 if (S.getLangOpts().CPlusPlus)
9735 return AssignConvertType::IncompatibleBlockPointer;
9736
9737 AssignConvertType ConvTy = AssignConvertType::Compatible;
9738
9739 // For blocks we enforce that qualifiers are identical.
9740 Qualifiers LQuals = lhptee.getLocalQualifiers();
9741 Qualifiers RQuals = rhptee.getLocalQualifiers();
9742 if (S.getLangOpts().OpenCL) {
9743 LQuals.removeAddressSpace();
9744 RQuals.removeAddressSpace();
9745 }
9746 if (LQuals != RQuals)
9747 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9748
9749 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9750 // assignment.
9751 // The current behavior is similar to C++ lambdas. A block might be
9752 // assigned to a variable iff its return type and parameters are compatible
9753 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9754 // an assignment. Presumably it should behave in way that a function pointer
9755 // assignment does in C, so for each parameter and return type:
9756 // * CVR and address space of LHS should be a superset of CVR and address
9757 // space of RHS.
9758 // * unqualified types should be compatible.
9759 if (S.getLangOpts().OpenCL) {
9760 if (!S.Context.typesAreBlockPointerCompatible(
9761 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9762 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9763 return AssignConvertType::IncompatibleBlockPointer;
9764 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9765 return AssignConvertType::IncompatibleBlockPointer;
9766
9767 return ConvTy;
9768}
9769
9770/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9771/// for assignment compatibility.
9772static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9773 QualType LHSType,
9774 QualType RHSType) {
9775 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9776 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9777
9778 if (LHSType->isObjCBuiltinType()) {
9779 // Class is not compatible with ObjC object pointers.
9780 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9781 !RHSType->isObjCQualifiedClassType())
9782 return AssignConvertType::IncompatiblePointer;
9783 return AssignConvertType::Compatible;
9784 }
9785 if (RHSType->isObjCBuiltinType()) {
9786 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9787 !LHSType->isObjCQualifiedClassType())
9788 return AssignConvertType::IncompatiblePointer;
9789 return AssignConvertType::Compatible;
9790 }
9791 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9792 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9793
9794 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9795 // make an exception for id<P>
9796 !LHSType->isObjCQualifiedIdType())
9797 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9798
9799 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9800 return AssignConvertType::Compatible;
9801 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9802 return AssignConvertType::IncompatibleObjCQualifiedId;
9803 return AssignConvertType::IncompatiblePointer;
9804}
9805
9806AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9807 QualType LHSType,
9808 QualType RHSType) {
9809 // Fake up an opaque expression. We don't actually care about what
9810 // cast operations are required, so if CheckAssignmentConstraints
9811 // adds casts to this they'll be wasted, but fortunately that doesn't
9812 // usually happen on valid code.
9813 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9814 ExprResult RHSPtr = &RHSExpr;
9815 CastKind K;
9816
9817 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9818}
9819
9820/// This helper function returns true if QT is a vector type that has element
9821/// type ElementType.
9822static bool isVector(QualType QT, QualType ElementType) {
9823 if (const VectorType *VT = QT->getAs<VectorType>())
9824 return VT->getElementType().getCanonicalType() == ElementType;
9825 return false;
9826}
9827
9828/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9829/// has code to accommodate several GCC extensions when type checking
9830/// pointers. Here are some objectionable examples that GCC considers warnings:
9831///
9832/// int a, *pint;
9833/// short *pshort;
9834/// struct foo *pfoo;
9835///
9836/// pint = pshort; // warning: assignment from incompatible pointer type
9837/// a = pint; // warning: assignment makes integer from pointer without a cast
9838/// pint = a; // warning: assignment makes pointer from integer without a cast
9839/// pint = pfoo; // warning: assignment from incompatible pointer type
9840///
9841/// As a result, the code for dealing with pointers is more complex than the
9842/// C99 spec dictates.
9843///
9844/// Sets 'Kind' for any result kind except Incompatible.
9845AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9846 ExprResult &RHS,
9847 CastKind &Kind,
9848 bool ConvertRHS) {
9849 QualType RHSType = RHS.get()->getType();
9850 QualType OrigLHSType = LHSType;
9851
9852 // Get canonical types. We're not formatting these types, just comparing
9853 // them.
9854 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9855 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9856
9857 // Common case: no conversion required.
9858 if (LHSType == RHSType) {
9859 Kind = CK_NoOp;
9860 return AssignConvertType::Compatible;
9861 }
9862
9863 // If the LHS has an __auto_type, there are no additional type constraints
9864 // to be worried about.
9865 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9866 if (AT->isGNUAutoType()) {
9867 Kind = CK_NoOp;
9868 return AssignConvertType::Compatible;
9869 }
9870 }
9871
9872 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9873 switch (OBTResult) {
9874 case ASTContext::OBTAssignResult::IncompatibleKinds:
9875 Kind = CK_NoOp;
9876 return AssignConvertType::IncompatibleOBTKinds;
9877 case ASTContext::OBTAssignResult::Discards:
9878 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9879 return AssignConvertType::CompatibleOBTDiscards;
9880 case ASTContext::OBTAssignResult::Compatible:
9881 case ASTContext::OBTAssignResult::NotApplicable:
9882 break;
9883 }
9884
9885 // Check for incompatible OBT types in pointer pointee types
9886 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9887 QualType LHSPointee = LHSType->getPointeeType();
9888 QualType RHSPointee = RHSType->getPointeeType();
9889 if ((LHSPointee->isOverflowBehaviorType() ||
9890 RHSPointee->isOverflowBehaviorType()) &&
9891 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9892 Kind = CK_NoOp;
9893 return AssignConvertType::IncompatibleOBTKinds;
9894 }
9895 }
9896
9897 // If we have an atomic type, try a non-atomic assignment, then just add an
9898 // atomic qualification step.
9899 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9900 AssignConvertType Result =
9901 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9902 if (!IsAssignConvertCompatible(ConvTy: Result))
9903 return Result;
9904 if (Kind != CK_NoOp && ConvertRHS)
9905 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9906 Kind = CK_NonAtomicToAtomic;
9907 return Result;
9908 }
9909
9910 // If the left-hand side is a reference type, then we are in a
9911 // (rare!) case where we've allowed the use of references in C,
9912 // e.g., as a parameter type in a built-in function. In this case,
9913 // just make sure that the type referenced is compatible with the
9914 // right-hand side type. The caller is responsible for adjusting
9915 // LHSType so that the resulting expression does not have reference
9916 // type.
9917 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9918 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9919 Kind = CK_LValueBitCast;
9920 return AssignConvertType::Compatible;
9921 }
9922 return AssignConvertType::Incompatible;
9923 }
9924
9925 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9926 // of an ExtVector type to the same ExtVector type.
9927 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9928 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9929 // Implicit conversions require the same number of elements.
9930 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9931 return AssignConvertType::Incompatible;
9932
9933 if (LHSType->isExtVectorBoolType() &&
9934 RHSExtType->getElementType()->isIntegerType()) {
9935 Kind = CK_IntegralToBoolean;
9936 return AssignConvertType::Compatible;
9937 }
9938 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9939 if (Context.getLangOpts().OpenCL &&
9940 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9941 Kind = CK_BitCast;
9942 return AssignConvertType::Compatible;
9943 }
9944 return AssignConvertType::Incompatible;
9945 }
9946 if (RHSType->isArithmeticType()) {
9947 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9948 if (ConvertRHS)
9949 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9950 Kind = CK_VectorSplat;
9951 return AssignConvertType::Compatible;
9952 }
9953 }
9954
9955 // Conversions to or from vector type.
9956 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9957 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9958 // Allow assignments of an AltiVec vector type to an equivalent GCC
9959 // vector type and vice versa
9960 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9961 Kind = CK_BitCast;
9962 return AssignConvertType::Compatible;
9963 }
9964
9965 // If we are allowing lax vector conversions, and LHS and RHS are both
9966 // vectors, the total size only needs to be the same. This is a bitcast;
9967 // no bits are changed but the result type is different.
9968 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9969 // The default for lax vector conversions with Altivec vectors will
9970 // change, so if we are converting between vector types where
9971 // at least one is an Altivec vector, emit a warning.
9972 if (Context.getTargetInfo().getTriple().isPPC() &&
9973 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9974 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9975 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9976 << RHSType << LHSType;
9977 Kind = CK_BitCast;
9978 return AssignConvertType::IncompatibleVectors;
9979 }
9980 }
9981
9982 // When the RHS comes from another lax conversion (e.g. binops between
9983 // scalars and vectors) the result is canonicalized as a vector. When the
9984 // LHS is also a vector, the lax is allowed by the condition above. Handle
9985 // the case where LHS is a scalar.
9986 if (LHSType->isScalarType()) {
9987 const VectorType *VecType = RHSType->getAs<VectorType>();
9988 if (VecType && VecType->getNumElements() == 1 &&
9989 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9990 if (Context.getTargetInfo().getTriple().isPPC() &&
9991 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9992 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9993 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9994 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9995 << RHSType << LHSType;
9996 ExprResult *VecExpr = &RHS;
9997 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9998 Kind = CK_BitCast;
9999 return AssignConvertType::Compatible;
10000 }
10001 }
10002
10003 // Allow assignments between fixed-length and sizeless SVE vectors.
10004 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10005 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10006 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
10007 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
10008 Kind = CK_BitCast;
10009 return AssignConvertType::Compatible;
10010 }
10011
10012 // Allow assignments between fixed-length and sizeless RVV vectors.
10013 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10014 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10015 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
10016 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
10017 Kind = CK_BitCast;
10018 return AssignConvertType::Compatible;
10019 }
10020 }
10021
10022 return AssignConvertType::Incompatible;
10023 }
10024
10025 // Diagnose attempts to convert between __ibm128, __float128 and long double
10026 // where such conversions currently can't be handled.
10027 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
10028 return AssignConvertType::Incompatible;
10029
10030 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10031 // discards the imaginary part.
10032 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10033 !LHSType->getAs<ComplexType>())
10034 return AssignConvertType::Incompatible;
10035
10036 // Arithmetic conversions.
10037 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10038 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10039 if (ConvertRHS)
10040 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
10041 return AssignConvertType::Compatible;
10042 }
10043
10044 // Conversions to normal pointers.
10045 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
10046 // U* -> T*
10047 if (isa<PointerType>(Val: RHSType)) {
10048 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10049 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10050 if (AddrSpaceL != AddrSpaceR)
10051 Kind = CK_AddressSpaceConversion;
10052 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
10053 Kind = CK_NoOp;
10054 else
10055 Kind = CK_BitCast;
10056 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
10057 Loc: RHS.get()->getBeginLoc());
10058 }
10059
10060 // int -> T*
10061 if (RHSType->isIntegerType()) {
10062 Kind = CK_IntegralToPointer; // FIXME: null?
10063 return AssignConvertType::IntToPointer;
10064 }
10065
10066 // C pointers are not compatible with ObjC object pointers,
10067 // with two exceptions:
10068 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10069 // - conversions to void*
10070 if (LHSPointer->getPointeeType()->isVoidType()) {
10071 Kind = CK_BitCast;
10072 return AssignConvertType::Compatible;
10073 }
10074
10075 // - conversions from 'Class' to the redefinition type
10076 if (RHSType->isObjCClassType() &&
10077 Context.hasSameType(T1: LHSType,
10078 T2: Context.getObjCClassRedefinitionType())) {
10079 Kind = CK_BitCast;
10080 return AssignConvertType::Compatible;
10081 }
10082
10083 Kind = CK_BitCast;
10084 return AssignConvertType::IncompatiblePointer;
10085 }
10086
10087 // U^ -> void*
10088 if (RHSType->getAs<BlockPointerType>()) {
10089 if (LHSPointer->getPointeeType()->isVoidType()) {
10090 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10091 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10092 ->getPointeeType()
10093 .getAddressSpace();
10094 Kind =
10095 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10096 return AssignConvertType::Compatible;
10097 }
10098 }
10099
10100 return AssignConvertType::Incompatible;
10101 }
10102
10103 // Conversions to block pointers.
10104 if (isa<BlockPointerType>(Val: LHSType)) {
10105 // U^ -> T^
10106 if (RHSType->isBlockPointerType()) {
10107 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10108 ->getPointeeType()
10109 .getAddressSpace();
10110 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10111 ->getPointeeType()
10112 .getAddressSpace();
10113 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10114 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10115 }
10116
10117 // int or null -> T^
10118 if (RHSType->isIntegerType()) {
10119 Kind = CK_IntegralToPointer; // FIXME: null
10120 return AssignConvertType::IntToBlockPointer;
10121 }
10122
10123 // id -> T^
10124 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10125 Kind = CK_AnyPointerToBlockPointerCast;
10126 return AssignConvertType::Compatible;
10127 }
10128
10129 // void* -> T^
10130 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10131 if (RHSPT->getPointeeType()->isVoidType()) {
10132 Kind = CK_AnyPointerToBlockPointerCast;
10133 return AssignConvertType::Compatible;
10134 }
10135
10136 return AssignConvertType::Incompatible;
10137 }
10138
10139 // Conversions to Objective-C pointers.
10140 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10141 // A* -> B*
10142 if (RHSType->isObjCObjectPointerType()) {
10143 Kind = CK_BitCast;
10144 AssignConvertType result =
10145 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10146 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10147 result == AssignConvertType::Compatible &&
10148 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10149 result = AssignConvertType::IncompatibleObjCWeakRef;
10150 return result;
10151 }
10152
10153 // int or null -> A*
10154 if (RHSType->isIntegerType()) {
10155 Kind = CK_IntegralToPointer; // FIXME: null
10156 return AssignConvertType::IntToPointer;
10157 }
10158
10159 // In general, C pointers are not compatible with ObjC object pointers,
10160 // with two exceptions:
10161 if (isa<PointerType>(Val: RHSType)) {
10162 Kind = CK_CPointerToObjCPointerCast;
10163
10164 // - conversions from 'void*'
10165 if (RHSType->isVoidPointerType()) {
10166 return AssignConvertType::Compatible;
10167 }
10168
10169 // - conversions to 'Class' from its redefinition type
10170 if (LHSType->isObjCClassType() &&
10171 Context.hasSameType(T1: RHSType,
10172 T2: Context.getObjCClassRedefinitionType())) {
10173 return AssignConvertType::Compatible;
10174 }
10175
10176 return AssignConvertType::IncompatiblePointer;
10177 }
10178
10179 // Only under strict condition T^ is compatible with an Objective-C pointer.
10180 if (RHSType->isBlockPointerType() &&
10181 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10182 if (ConvertRHS)
10183 maybeExtendBlockObject(E&: RHS);
10184 Kind = CK_BlockPointerToObjCPointerCast;
10185 return AssignConvertType::Compatible;
10186 }
10187
10188 return AssignConvertType::Incompatible;
10189 }
10190
10191 // Conversion to nullptr_t (C23 only)
10192 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10193 RHS.get()->isNullPointerConstant(Ctx&: Context,
10194 NPC: Expr::NPC_ValueDependentIsNull)) {
10195 // null -> nullptr_t
10196 Kind = CK_NullToPointer;
10197 return AssignConvertType::Compatible;
10198 }
10199
10200 // Conversions from pointers that are not covered by the above.
10201 if (isa<PointerType>(Val: RHSType)) {
10202 // T* -> _Bool
10203 if (LHSType == Context.BoolTy) {
10204 Kind = CK_PointerToBoolean;
10205 return AssignConvertType::Compatible;
10206 }
10207
10208 // T* -> int
10209 if (LHSType->isIntegerType()) {
10210 Kind = CK_PointerToIntegral;
10211 return AssignConvertType::PointerToInt;
10212 }
10213
10214 return AssignConvertType::Incompatible;
10215 }
10216
10217 // Conversions from Objective-C pointers that are not covered by the above.
10218 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10219 // T* -> _Bool
10220 if (LHSType == Context.BoolTy) {
10221 Kind = CK_PointerToBoolean;
10222 return AssignConvertType::Compatible;
10223 }
10224
10225 // T* -> int
10226 if (LHSType->isIntegerType()) {
10227 Kind = CK_PointerToIntegral;
10228 return AssignConvertType::PointerToInt;
10229 }
10230
10231 return AssignConvertType::Incompatible;
10232 }
10233
10234 // struct A -> struct B
10235 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10236 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10237 Kind = CK_NoOp;
10238 return AssignConvertType::Compatible;
10239 }
10240 }
10241
10242 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10243 Kind = CK_IntToOCLSampler;
10244 return AssignConvertType::Compatible;
10245 }
10246
10247 return AssignConvertType::Incompatible;
10248}
10249
10250/// Constructs a transparent union from an expression that is
10251/// used to initialize the transparent union.
10252static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10253 ExprResult &EResult, QualType UnionType,
10254 FieldDecl *Field) {
10255 // Build an initializer list that designates the appropriate member
10256 // of the transparent union.
10257 Expr *E = EResult.get();
10258 InitListExpr *Initializer = new (C) InitListExpr(
10259 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10260 Initializer->setType(UnionType);
10261 Initializer->setInitializedFieldInUnion(Field);
10262
10263 // Build a compound literal constructing a value of the transparent
10264 // union type from this initializer list.
10265 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10266 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10267 VK_PRValue, Initializer, false);
10268}
10269
10270AssignConvertType
10271Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10272 ExprResult &RHS) {
10273 QualType RHSType = RHS.get()->getType();
10274
10275 // If the ArgType is a Union type, we want to handle a potential
10276 // transparent_union GCC extension.
10277 const RecordType *UT = ArgType->getAsUnionType();
10278 if (!UT)
10279 return AssignConvertType::Incompatible;
10280
10281 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10282 if (!UD->hasAttr<TransparentUnionAttr>())
10283 return AssignConvertType::Incompatible;
10284
10285 // The field to initialize within the transparent union.
10286 FieldDecl *InitField = nullptr;
10287 // It's compatible if the expression matches any of the fields.
10288 for (auto *it : UD->fields()) {
10289 if (it->getType()->isPointerType()) {
10290 // If the transparent union contains a pointer type, we allow:
10291 // 1) void pointer
10292 // 2) null pointer constant
10293 if (RHSType->isPointerType())
10294 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10295 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10296 InitField = it;
10297 break;
10298 }
10299
10300 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10301 NPC: Expr::NPC_ValueDependentIsNull)) {
10302 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10303 CK: CK_NullToPointer);
10304 InitField = it;
10305 break;
10306 }
10307 }
10308
10309 CastKind Kind;
10310 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10311 AssignConvertType::Compatible) {
10312 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10313 InitField = it;
10314 break;
10315 }
10316 }
10317
10318 if (!InitField)
10319 return AssignConvertType::Incompatible;
10320
10321 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10322 return AssignConvertType::Compatible;
10323}
10324
10325AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10326 ExprResult &CallerRHS,
10327 bool Diagnose,
10328 bool DiagnoseCFAudited,
10329 bool ConvertRHS) {
10330 // We need to be able to tell the caller whether we diagnosed a problem, if
10331 // they ask us to issue diagnostics.
10332 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10333
10334 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10335 // we can't avoid *all* modifications at the moment, so we need some somewhere
10336 // to put the updated value.
10337 ExprResult LocalRHS = CallerRHS;
10338 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10339
10340 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10341 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10342 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10343 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10344 Diag(Loc: RHS.get()->getExprLoc(),
10345 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10346 << RHS.get()->getSourceRange();
10347 }
10348 }
10349 }
10350
10351 if (getLangOpts().CPlusPlus) {
10352 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10353 // C++ 5.17p3: If the left operand is not of class type, the
10354 // expression is implicitly converted (C++ 4) to the
10355 // cv-unqualified type of the left operand.
10356 QualType RHSType = RHS.get()->getType();
10357 if (Diagnose) {
10358 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10359 Action: AssignmentAction::Assigning);
10360 } else {
10361 ImplicitConversionSequence ICS =
10362 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10363 /*SuppressUserConversions=*/false,
10364 AllowExplicit: AllowedExplicit::None,
10365 /*InOverloadResolution=*/false,
10366 /*CStyle=*/false,
10367 /*AllowObjCWritebackConversion=*/false);
10368 if (ICS.isFailure())
10369 return AssignConvertType::Incompatible;
10370 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10371 ICS, Action: AssignmentAction::Assigning);
10372 }
10373 if (RHS.isInvalid())
10374 return AssignConvertType::Incompatible;
10375 AssignConvertType result = AssignConvertType::Compatible;
10376 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10377 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10378 result = AssignConvertType::IncompatibleObjCWeakRef;
10379
10380 // Check if OBT is being discarded during assignment
10381 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10382 if (RHSType->isOverflowBehaviorType() &&
10383 !LHSType->isOverflowBehaviorType()) {
10384 result = AssignConvertType::CompatibleOBTDiscards;
10385 }
10386
10387 return result;
10388 }
10389
10390 // FIXME: Currently, we fall through and treat C++ classes like C
10391 // structures.
10392 // FIXME: We also fall through for atomics; not sure what should
10393 // happen there, though.
10394 } else if (RHS.get()->getType() == Context.OverloadTy) {
10395 // As a set of extensions to C, we support overloading on functions. These
10396 // functions need to be resolved here.
10397 DeclAccessPair DAP;
10398 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10399 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10400 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10401 else
10402 return AssignConvertType::Incompatible;
10403 }
10404
10405 // For HLSL records, insert derived-to-base conversion if needed.
10406 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10407 QualType RHSType = RHS.get()->getType();
10408 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10409 CXXBasePaths Paths;
10410 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10411 CXXCastPath CastPath;
10412 BuildBasePathArray(Paths, BasePath&: CastPath);
10413 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10414 BasePath: &CastPath);
10415 }
10416 }
10417 }
10418
10419 // This check seems unnatural, however it is necessary to ensure the proper
10420 // conversion of functions/arrays. If the conversion were done for all
10421 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10422 // expressions that suppress this implicit conversion (&, sizeof). This needs
10423 // to happen before we check for null pointer conversions because C does not
10424 // undergo the same implicit conversions as C++ does above (by the calls to
10425 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10426 // lvalue to rvalue cast before checking for null pointer constraints. This
10427 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10428 //
10429 // Suppress this for references: C++ 8.5.3p5.
10430 if (!LHSType->isReferenceType()) {
10431 // FIXME: We potentially allocate here even if ConvertRHS is false.
10432 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10433 if (RHS.isInvalid())
10434 return AssignConvertType::Incompatible;
10435 }
10436
10437 // The constraints are expressed in terms of the atomic, qualified, or
10438 // unqualified type of the LHS.
10439 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10440
10441 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10442 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10443 if ((LHSTypeAfterConversion->isPointerType() ||
10444 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10445 LHSTypeAfterConversion->isBlockPointerType()) &&
10446 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10447 RHS.get()->isNullPointerConstant(Ctx&: Context,
10448 NPC: Expr::NPC_ValueDependentIsNull))) {
10449 AssignConvertType Ret = AssignConvertType::Compatible;
10450 if (Diagnose || ConvertRHS) {
10451 CastKind Kind;
10452 CXXCastPath Path;
10453 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10454 /*IgnoreBaseAccess=*/false, Diagnose);
10455
10456 // If there is a conversion of some kind, check to see what kind of
10457 // pointer conversion happened so we can diagnose a C++ compatibility
10458 // diagnostic if the conversion is invalid. This only matters if the RHS
10459 // is some kind of void pointer. We have a carve-out when the RHS is from
10460 // a macro expansion because the use of a macro may indicate different
10461 // code between C and C++. Consider: char *s = NULL; where NULL is
10462 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10463 // C++, which is valid in C++. Ignore parentheses around the macro when
10464 // checking where the expression originates.
10465 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10466 !RHS.get()->IgnoreParens()->getBeginLoc().isMacroID()) {
10467 QualType CanRHS =
10468 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10469 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10470 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10471 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10472 Loc: RHS.get()->getExprLoc());
10473 // Anything that's not considered perfectly compatible would be
10474 // incompatible in C++.
10475 if (Ret != AssignConvertType::Compatible)
10476 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10477 }
10478 }
10479
10480 if (ConvertRHS)
10481 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10482 }
10483 return Ret;
10484 }
10485 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10486 // unqualified bool, and the right operand is a pointer or its type is
10487 // nullptr_t.
10488 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10489 RHS.get()->getType()->isNullPtrType()) {
10490 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10491 // only handles nullptr -> _Bool due to needing an extra conversion
10492 // step.
10493 // We model this by converting from nullptr -> void * and then let the
10494 // conversion from void * -> _Bool happen naturally.
10495 if (Diagnose || ConvertRHS) {
10496 CastKind Kind;
10497 CXXCastPath Path;
10498 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10499 /*IgnoreBaseAccess=*/false, Diagnose);
10500 if (ConvertRHS)
10501 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10502 BasePath: &Path);
10503 }
10504 }
10505
10506 // OpenCL queue_t type assignment.
10507 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10508 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10509 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10510 return AssignConvertType::Compatible;
10511 }
10512
10513 CastKind Kind;
10514 AssignConvertType result =
10515 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10516
10517 // If assigning a void * created by an allocation function call to some other
10518 // type, check that the allocated size is sufficient for that type.
10519 if (result != AssignConvertType::Incompatible &&
10520 RHS.get()->getType()->isVoidPointerType())
10521 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10522
10523 // C99 6.5.16.1p2: The value of the right operand is converted to the
10524 // type of the assignment expression.
10525 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10526 // so that we can use references in built-in functions even in C.
10527 // The getNonReferenceType() call makes sure that the resulting expression
10528 // does not have reference type.
10529 if (result != AssignConvertType::Incompatible &&
10530 RHS.get()->getType() != LHSType) {
10531 QualType Ty = LHSType.getNonLValueExprType(Context);
10532 Expr *E = RHS.get();
10533
10534 // Check for various Objective-C errors. If we are not reporting
10535 // diagnostics and just checking for errors, e.g., during overload
10536 // resolution, return Incompatible to indicate the failure.
10537 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10538 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10539 CCK: CheckedConversionKind::Implicit, Diagnose,
10540 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10541 if (!Diagnose)
10542 return AssignConvertType::Incompatible;
10543 }
10544 if (getLangOpts().ObjC &&
10545 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10546 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10547 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10548 if (!Diagnose)
10549 return AssignConvertType::Incompatible;
10550 // Replace the expression with a corrected version and continue so we
10551 // can find further errors.
10552 RHS = E;
10553 return AssignConvertType::Compatible;
10554 }
10555
10556 if (ConvertRHS)
10557 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10558 }
10559
10560 return result;
10561}
10562
10563namespace {
10564/// The original operand to an operator, prior to the application of the usual
10565/// arithmetic conversions and converting the arguments of a builtin operator
10566/// candidate.
10567struct OriginalOperand {
10568 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10570 Op = MTE->getSubExpr();
10571 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10572 Op = BTE->getSubExpr();
10573 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10574 Orig = ICE->getSubExprAsWritten();
10575 Conversion = ICE->getConversionFunction();
10576 }
10577 }
10578
10579 QualType getType() const { return Orig->getType(); }
10580
10581 Expr *Orig;
10582 NamedDecl *Conversion;
10583};
10584}
10585
10586QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10587 ExprResult &RHS) {
10588 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10589
10590 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10591 << OrigLHS.getType() << OrigRHS.getType()
10592 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10593
10594 // If a user-defined conversion was applied to either of the operands prior
10595 // to applying the built-in operator rules, tell the user about it.
10596 if (OrigLHS.Conversion) {
10597 Diag(Loc: OrigLHS.Conversion->getLocation(),
10598 DiagID: diag::note_typecheck_invalid_operands_converted)
10599 << 0 << LHS.get()->getType();
10600 }
10601 if (OrigRHS.Conversion) {
10602 Diag(Loc: OrigRHS.Conversion->getLocation(),
10603 DiagID: diag::note_typecheck_invalid_operands_converted)
10604 << 1 << RHS.get()->getType();
10605 }
10606
10607 return QualType();
10608}
10609
10610QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10611 ExprResult &RHS) {
10612 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10613 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10614
10615 bool LHSNatVec = LHSType->isVectorType();
10616 bool RHSNatVec = RHSType->isVectorType();
10617
10618 if (!(LHSNatVec && RHSNatVec)) {
10619 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10620 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10621 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10622 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10623 << Vector->getSourceRange();
10624 return QualType();
10625 }
10626
10627 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10628 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10629 << RHS.get()->getSourceRange();
10630
10631 return QualType();
10632}
10633
10634/// Try to convert a value of non-vector type to a vector type by converting
10635/// the type to the element type of the vector and then performing a splat.
10636/// If the language is OpenCL, we only use conversions that promote scalar
10637/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10638/// for float->int.
10639///
10640/// OpenCL V2.0 6.2.6.p2:
10641/// An error shall occur if any scalar operand type has greater rank
10642/// than the type of the vector element.
10643///
10644/// \param scalar - if non-null, actually perform the conversions
10645/// \return true if the operation fails (but without diagnosing the failure)
10646static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10647 QualType scalarTy,
10648 QualType vectorEltTy,
10649 QualType vectorTy,
10650 unsigned &DiagID) {
10651 // The conversion to apply to the scalar before splatting it,
10652 // if necessary.
10653 CastKind scalarCast = CK_NoOp;
10654
10655 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10656 scalarCast = CK_IntegralToBoolean;
10657 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10658 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10659 (scalarTy->isIntegerType() &&
10660 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10661 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10662 return true;
10663 }
10664 if (!scalarTy->isIntegralType(Ctx: S.Context))
10665 return true;
10666 scalarCast = CK_IntegralCast;
10667 } else if (vectorEltTy->isRealFloatingType()) {
10668 if (scalarTy->isRealFloatingType()) {
10669 if (S.getLangOpts().OpenCL &&
10670 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10671 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10672 return true;
10673 }
10674 scalarCast = CK_FloatingCast;
10675 }
10676 else if (scalarTy->isIntegralType(Ctx: S.Context))
10677 scalarCast = CK_IntegralToFloating;
10678 else
10679 return true;
10680 } else {
10681 return true;
10682 }
10683
10684 // Adjust scalar if desired.
10685 if (scalar) {
10686 if (scalarCast != CK_NoOp)
10687 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10688 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10689 }
10690 return false;
10691}
10692
10693/// Convert vector E to a vector with the same number of elements but different
10694/// element type.
10695static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10696 const auto *VecTy = E->getType()->getAs<VectorType>();
10697 assert(VecTy && "Expression E must be a vector");
10698 QualType NewVecTy =
10699 VecTy->isExtVectorType()
10700 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10701 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10702 VecKind: VecTy->getVectorKind());
10703
10704 // Look through the implicit cast. Return the subexpression if its type is
10705 // NewVecTy.
10706 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10707 if (ICE->getSubExpr()->getType() == NewVecTy)
10708 return ICE->getSubExpr();
10709
10710 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10711 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10712}
10713
10714/// Test if a (constant) integer Int can be casted to another integer type
10715/// IntTy without losing precision.
10716static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10717 QualType OtherIntTy) {
10718 Expr *E = Int->get();
10719 if (E->containsErrors() || E->isInstantiationDependent())
10720 return false;
10721
10722 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10723
10724 // Reject cases where the value of the Int is unknown as that would
10725 // possibly cause truncation, but accept cases where the scalar can be
10726 // demoted without loss of precision.
10727 Expr::EvalResult EVResult;
10728 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10729 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10730 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10731 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10732
10733 if (CstInt) {
10734 // If the scalar is constant and is of a higher order and has more active
10735 // bits that the vector element type, reject it.
10736 llvm::APSInt Result = EVResult.Val.getInt();
10737 unsigned NumBits = IntSigned
10738 ? (Result.isNegative() ? Result.getSignificantBits()
10739 : Result.getActiveBits())
10740 : Result.getActiveBits();
10741 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10742 return true;
10743
10744 // If the signedness of the scalar type and the vector element type
10745 // differs and the number of bits is greater than that of the vector
10746 // element reject it.
10747 return (IntSigned != OtherIntSigned &&
10748 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10749 }
10750
10751 // Reject cases where the value of the scalar is not constant and it's
10752 // order is greater than that of the vector element type.
10753 return (Order < 0);
10754}
10755
10756/// Test if a (constant) integer Int can be casted to floating point type
10757/// FloatTy without losing precision.
10758static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10759 QualType FloatTy) {
10760 if (Int->get()->containsErrors())
10761 return false;
10762
10763 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10764
10765 // Determine if the integer constant can be expressed as a floating point
10766 // number of the appropriate type.
10767 Expr::EvalResult EVResult;
10768 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10769
10770 uint64_t Bits = 0;
10771 if (CstInt) {
10772 // Reject constants that would be truncated if they were converted to
10773 // the floating point type. Test by simple to/from conversion.
10774 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10775 // could be avoided if there was a convertFromAPInt method
10776 // which could signal back if implicit truncation occurred.
10777 llvm::APSInt Result = EVResult.Val.getInt();
10778 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10779 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10780 RM: llvm::APFloat::rmTowardZero);
10781 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10782 !IntTy->hasSignedIntegerRepresentation());
10783 bool Ignored = false;
10784 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10785 IsExact: &Ignored);
10786 if (Result != ConvertBack)
10787 return true;
10788 } else {
10789 // Reject types that cannot be fully encoded into the mantissa of
10790 // the float.
10791 Bits = S.Context.getTypeSize(T: IntTy);
10792 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10793 S.Context.getFloatTypeSemantics(T: FloatTy));
10794 if (Bits > FloatPrec)
10795 return true;
10796 }
10797
10798 return false;
10799}
10800
10801/// Attempt to convert and splat Scalar into a vector whose types matches
10802/// Vector following GCC conversion rules. The rule is that implicit
10803/// conversion can occur when Scalar can be casted to match Vector's element
10804/// type without causing truncation of Scalar.
10805static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10806 ExprResult *Vector) {
10807 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10808 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10809 QualType VectorEltTy;
10810
10811 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10812 assert(!isa<ExtVectorType>(VT) &&
10813 "ExtVectorTypes should not be handled here!");
10814 VectorEltTy = VT->getElementType();
10815 } else if (VectorTy->isSveVLSBuiltinType()) {
10816 VectorEltTy =
10817 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10818 } else {
10819 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10820 }
10821
10822 // Reject cases where the vector element type or the scalar element type are
10823 // not integral or floating point types.
10824 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10825 return true;
10826
10827 // The conversion to apply to the scalar before splatting it,
10828 // if necessary.
10829 CastKind ScalarCast = CK_NoOp;
10830
10831 // Accept cases where the vector elements are integers and the scalar is
10832 // an integer.
10833 // FIXME: Notionally if the scalar was a floating point value with a precise
10834 // integral representation, we could cast it to an appropriate integer
10835 // type and then perform the rest of the checks here. GCC will perform
10836 // this conversion in some cases as determined by the input language.
10837 // We should accept it on a language independent basis.
10838 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10839 ScalarTy->isIntegralType(Ctx: S.Context) &&
10840 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10841
10842 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10843 return true;
10844
10845 ScalarCast = CK_IntegralCast;
10846 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10847 ScalarTy->isRealFloatingType()) {
10848 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10849 ScalarCast = CK_FloatingToIntegral;
10850 else
10851 return true;
10852 } else if (VectorEltTy->isRealFloatingType()) {
10853 if (ScalarTy->isRealFloatingType()) {
10854
10855 // Reject cases where the scalar type is not a constant and has a higher
10856 // Order than the vector element type.
10857 llvm::APFloat Result(0.0);
10858
10859 // Determine whether this is a constant scalar. In the event that the
10860 // value is dependent (and thus cannot be evaluated by the constant
10861 // evaluator), skip the evaluation. This will then diagnose once the
10862 // expression is instantiated.
10863 bool CstScalar = Scalar->get()->isValueDependent() ||
10864 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10865 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10866 if (!CstScalar && Order < 0)
10867 return true;
10868
10869 // If the scalar cannot be safely casted to the vector element type,
10870 // reject it.
10871 if (CstScalar) {
10872 bool Truncated = false;
10873 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10874 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10875 if (Truncated)
10876 return true;
10877 }
10878
10879 ScalarCast = CK_FloatingCast;
10880 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10881 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10882 return true;
10883
10884 ScalarCast = CK_IntegralToFloating;
10885 } else
10886 return true;
10887 } else if (ScalarTy->isEnumeralType())
10888 return true;
10889
10890 // Adjust scalar if desired.
10891 if (ScalarCast != CK_NoOp)
10892 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10893 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10894 return false;
10895}
10896
10897QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10898 SourceLocation Loc, bool IsCompAssign,
10899 bool AllowBothBool,
10900 bool AllowBoolConversions,
10901 bool AllowBoolOperation) {
10902 if (!IsCompAssign) {
10903 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10904 if (LHS.isInvalid())
10905 return QualType();
10906 }
10907 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10908 if (RHS.isInvalid())
10909 return QualType();
10910
10911 // For conversion purposes, we ignore any qualifiers.
10912 // For example, "const float" and "float" are equivalent.
10913 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10914 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10915
10916 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10917 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10918 assert(LHSVecType || RHSVecType);
10919
10920 if (getLangOpts().HLSL)
10921 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10922 IsCompAssign);
10923
10924 // Any operation with MFloat8 type is only possible with C intrinsics
10925 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10926 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10927 return InvalidOperands(Loc, LHS, RHS);
10928
10929 // AltiVec-style "vector bool op vector bool" combinations are allowed
10930 // for some operators but not others.
10931 if (!AllowBothBool && LHSVecType &&
10932 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10933 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10934 return InvalidOperands(Loc, LHS, RHS);
10935
10936 // This operation may not be performed on boolean vectors.
10937 if (!AllowBoolOperation &&
10938 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10939 return InvalidOperands(Loc, LHS, RHS);
10940
10941 // If the vector types are identical, return.
10942 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10943 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10944
10945 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10946 if (LHSVecType && RHSVecType &&
10947 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10948 if (isa<ExtVectorType>(Val: LHSVecType)) {
10949 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10950 return LHSType;
10951 }
10952
10953 if (!IsCompAssign)
10954 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10955 return RHSType;
10956 }
10957
10958 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10959 // can be mixed, with the result being the non-bool type. The non-bool
10960 // operand must have integer element type.
10961 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10962 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10963 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10964 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10965 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10966 LHSVecType->getElementType()->isIntegerType() &&
10967 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10968 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10969 return LHSType;
10970 }
10971 if (!IsCompAssign &&
10972 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10973 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10974 RHSVecType->getElementType()->isIntegerType()) {
10975 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10976 return RHSType;
10977 }
10978 }
10979
10980 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10981 // invalid since the ambiguity can affect the ABI.
10982 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10983 unsigned &SVEorRVV) {
10984 const VectorType *VecType = SecondType->getAs<VectorType>();
10985 SVEorRVV = 0;
10986 if (FirstType->isSizelessBuiltinType() && VecType) {
10987 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10988 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10989 return true;
10990 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10991 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10992 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10993 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10994 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10995 SVEorRVV = 1;
10996 return true;
10997 }
10998 }
10999
11000 return false;
11001 };
11002
11003 unsigned SVEorRVV;
11004 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11005 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11006 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
11007 << SVEorRVV << LHSType << RHSType;
11008 return QualType();
11009 }
11010
11011 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11012 // invalid since the ambiguity can affect the ABI.
11013 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11014 unsigned &SVEorRVV) {
11015 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11016 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11017
11018 SVEorRVV = 0;
11019 if (FirstVecType && SecondVecType) {
11020 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11021 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11022 SecondVecType->getVectorKind() ==
11023 VectorKind::SveFixedLengthPredicate)
11024 return true;
11025 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
11026 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
11027 SecondVecType->getVectorKind() ==
11028 VectorKind::RVVFixedLengthMask_1 ||
11029 SecondVecType->getVectorKind() ==
11030 VectorKind::RVVFixedLengthMask_2 ||
11031 SecondVecType->getVectorKind() ==
11032 VectorKind::RVVFixedLengthMask_4) {
11033 SVEorRVV = 1;
11034 return true;
11035 }
11036 }
11037 return false;
11038 }
11039
11040 if (SecondVecType &&
11041 SecondVecType->getVectorKind() == VectorKind::Generic) {
11042 if (FirstType->isSVESizelessBuiltinType())
11043 return true;
11044 if (FirstType->isRVVSizelessBuiltinType()) {
11045 SVEorRVV = 1;
11046 return true;
11047 }
11048 }
11049
11050 return false;
11051 };
11052
11053 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11054 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11055 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
11056 << SVEorRVV << LHSType << RHSType;
11057 return QualType();
11058 }
11059
11060 // If there's a vector type and a scalar, try to convert the scalar to
11061 // the vector element type and splat.
11062 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11063 if (!RHSVecType) {
11064 if (isa<ExtVectorType>(Val: LHSVecType)) {
11065 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
11066 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
11067 DiagID))
11068 return LHSType;
11069 } else {
11070 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11071 return LHSType;
11072 }
11073 }
11074 if (!LHSVecType) {
11075 if (isa<ExtVectorType>(Val: RHSVecType)) {
11076 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
11077 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
11078 vectorTy: RHSType, DiagID))
11079 return RHSType;
11080 } else {
11081 if (LHS.get()->isLValue() ||
11082 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11083 return RHSType;
11084 }
11085 }
11086
11087 // FIXME: The code below also handles conversion between vectors and
11088 // non-scalars, we should break this down into fine grained specific checks
11089 // and emit proper diagnostics.
11090 QualType VecType = LHSVecType ? LHSType : RHSType;
11091 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11092 QualType OtherType = LHSVecType ? RHSType : LHSType;
11093 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11094 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
11095 if (Context.getTargetInfo().getTriple().isPPC() &&
11096 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
11097 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
11098 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11099 // If we're allowing lax vector conversions, only the total (data) size
11100 // needs to be the same. For non compound assignment, if one of the types is
11101 // scalar, the result is always the vector type.
11102 if (!IsCompAssign) {
11103 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
11104 return VecType;
11105 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11106 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11107 // type. Note that this is already done by non-compound assignments in
11108 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11109 // <1 x T> -> T. The result is also a vector type.
11110 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11111 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11112 ExprResult *RHSExpr = &RHS;
11113 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
11114 return VecType;
11115 }
11116 }
11117
11118 // Okay, the expression is invalid.
11119
11120 // If there's a non-vector, non-real operand, diagnose that.
11121 if ((!RHSVecType && !RHSType->isRealType()) ||
11122 (!LHSVecType && !LHSType->isRealType())) {
11123 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11124 << LHSType << RHSType
11125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11126 return QualType();
11127 }
11128
11129 // OpenCL V1.1 6.2.6.p1:
11130 // If the operands are of more than one vector type, then an error shall
11131 // occur. Implicit conversions between vector types are not permitted, per
11132 // section 6.2.1.
11133 if (getLangOpts().OpenCL &&
11134 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
11135 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
11136 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
11137 << RHSType;
11138 return QualType();
11139 }
11140
11141
11142 // If there is a vector type that is not a ExtVector and a scalar, we reach
11143 // this point if scalar could not be converted to the vector's element type
11144 // without truncation.
11145 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11146 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11147 QualType Scalar = LHSVecType ? RHSType : LHSType;
11148 QualType Vector = LHSVecType ? LHSType : RHSType;
11149 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11150 Diag(Loc,
11151 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11152 << ScalarOrVector << Scalar << Vector;
11153
11154 return QualType();
11155 }
11156
11157 // Otherwise, use the generic diagnostic.
11158 Diag(Loc, DiagID)
11159 << LHSType << RHSType
11160 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11161 return QualType();
11162}
11163
11164QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11165 SourceLocation Loc,
11166 bool IsCompAssign,
11167 ArithConvKind OperationKind) {
11168 if (!IsCompAssign) {
11169 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11170 if (LHS.isInvalid())
11171 return QualType();
11172 }
11173 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11174 if (RHS.isInvalid())
11175 return QualType();
11176
11177 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11178 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11179
11180 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11181 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11182
11183 unsigned DiagID = diag::err_typecheck_invalid_operands;
11184 if ((OperationKind == ArithConvKind::Arithmetic) &&
11185 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11186 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11187 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11188 << RHS.get()->getSourceRange();
11189 return QualType();
11190 }
11191
11192 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11193 return LHSType;
11194
11195 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11196 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11197 return LHSType;
11198 }
11199 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11200 if (LHS.get()->isLValue() ||
11201 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11202 return RHSType;
11203 }
11204
11205 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11206 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11207 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11208 << LHSType << RHSType << LHS.get()->getSourceRange()
11209 << RHS.get()->getSourceRange();
11210 return QualType();
11211 }
11212
11213 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11214 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11215 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11216 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11217 << LHSType << RHSType << LHS.get()->getSourceRange()
11218 << RHS.get()->getSourceRange();
11219 return QualType();
11220 }
11221
11222 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11223 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11224 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11225 bool ScalarOrVector =
11226 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11227
11228 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11229 << ScalarOrVector << Scalar << Vector;
11230
11231 return QualType();
11232 }
11233
11234 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11235 << RHS.get()->getSourceRange();
11236 return QualType();
11237}
11238
11239// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11240// expression. These are mainly cases where the null pointer is used as an
11241// integer instead of a pointer.
11242static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11243 SourceLocation Loc, bool IsCompare) {
11244 // The canonical way to check for a GNU null is with isNullPointerConstant,
11245 // but we use a bit of a hack here for speed; this is a relatively
11246 // hot path, and isNullPointerConstant is slow.
11247 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11248 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11249
11250 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11251
11252 // Avoid analyzing cases where the result will either be invalid (and
11253 // diagnosed as such) or entirely valid and not something to warn about.
11254 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11255 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11256 return;
11257
11258 // Comparison operations would not make sense with a null pointer no matter
11259 // what the other expression is.
11260 if (!IsCompare) {
11261 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11262 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11263 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11264 return;
11265 }
11266
11267 // The rest of the operations only make sense with a null pointer
11268 // if the other expression is a pointer.
11269 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11270 NonNullType->canDecayToPointerType())
11271 return;
11272
11273 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11274 << LHSNull /* LHS is NULL */ << NonNullType
11275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11276}
11277
11278static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11279 SourceLocation OpLoc) {
11280 // If the divisor is real, then this is real/real or complex/real division.
11281 // Either way there can be no precision loss.
11282 auto *CT = DivisorTy->getAs<ComplexType>();
11283 if (!CT)
11284 return;
11285
11286 QualType ElementType = CT->getElementType().getCanonicalType();
11287 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11288 LangOptions::ComplexRangeKind::CX_Promoted;
11289 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11290 return;
11291
11292 ASTContext &Ctx = S.getASTContext();
11293 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11294 const llvm::fltSemantics &ElementTypeSemantics =
11295 Ctx.getFloatTypeSemantics(T: ElementType);
11296 const llvm::fltSemantics &HigherElementTypeSemantics =
11297 Ctx.getFloatTypeSemantics(T: HigherElementType);
11298
11299 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11300 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11301 (HigherElementType == Ctx.LongDoubleTy &&
11302 !Ctx.getTargetInfo().hasLongDoubleType())) {
11303 // Retain the location of the first use of higher precision type.
11304 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11305 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11306 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11307 if (Type == HigherElementType) {
11308 Num++;
11309 return;
11310 }
11311 }
11312 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11313 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11314 }
11315}
11316
11317static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11318 SourceLocation Loc) {
11319 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11320 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11321 if (!LUE || !RUE)
11322 return;
11323 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11324 RUE->getKind() != UETT_SizeOf)
11325 return;
11326
11327 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11328 QualType LHSTy = LHSArg->getType();
11329 QualType RHSTy;
11330
11331 if (RUE->isArgumentType())
11332 RHSTy = RUE->getArgumentType().getNonReferenceType();
11333 else
11334 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11335
11336 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11337 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11338 return;
11339
11340 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11341 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11342 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11343 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11344 << LHSArgDecl;
11345 }
11346 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11347 QualType ArrayElemTy = ArrayTy->getElementType();
11348 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11349 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11350 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11351 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11352 return;
11353 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11354 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11355 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11356 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11357 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11358 << LHSArgDecl;
11359 }
11360
11361 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11362 }
11363}
11364
11365static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11366 ExprResult &RHS,
11367 SourceLocation Loc, bool IsDiv) {
11368 // Check for division/remainder by zero.
11369 Expr::EvalResult RHSValue;
11370 if (!RHS.get()->isValueDependent() &&
11371 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11372 RHSValue.Val.getInt() == 0)
11373 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11374 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11375 << IsDiv << RHS.get()->getSourceRange());
11376}
11377
11378static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11379 const ExprResult &LHS, const ExprResult &RHS,
11380 BinaryOperatorKind Opc) {
11381 if (!LHS.isUsable() || !RHS.isUsable())
11382 return;
11383 const Expr *LHSExpr = LHS.get();
11384 const Expr *RHSExpr = RHS.get();
11385 const QualType LHSType = LHSExpr->getType();
11386 const QualType RHSType = RHSExpr->getType();
11387 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11388 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11389 if (!LHSIsScoped && !RHSIsScoped)
11390 return;
11391 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11392 return;
11393 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11394 return;
11395 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11396 return;
11397 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11398 SourceLocation BeginLoc = expr->getBeginLoc();
11399 QualType IntType = type->castAs<EnumType>()
11400 ->getDecl()
11401 ->getDefinitionOrSelf()
11402 ->getIntegerType();
11403 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11404 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11405 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11406 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11407 };
11408 if (LHSIsScoped) {
11409 DiagnosticHelper(LHSExpr, LHSType);
11410 }
11411 if (RHSIsScoped) {
11412 DiagnosticHelper(RHSExpr, RHSType);
11413 }
11414}
11415
11416QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11417 SourceLocation Loc,
11418 BinaryOperatorKind Opc) {
11419 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11420 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11421
11422 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11423
11424 QualType LHSTy = LHS.get()->getType();
11425 QualType RHSTy = RHS.get()->getType();
11426 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11427 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11428 /*AllowBothBool*/ getLangOpts().AltiVec,
11429 /*AllowBoolConversions*/ false,
11430 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11431 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11432 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11433 OperationKind: ArithConvKind::Arithmetic);
11434 if (!IsDiv &&
11435 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11436 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11437 // For division, only matrix-by-scalar is supported. Other combinations with
11438 // matrix types are invalid.
11439 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11440 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11441
11442 QualType compType = UsualArithmeticConversions(
11443 LHS, RHS, Loc,
11444 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11445 if (LHS.isInvalid() || RHS.isInvalid())
11446 return QualType();
11447
11448 if (compType.isNull() || !compType->isArithmeticType()) {
11449 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11450 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11451 return ResultTy;
11452 }
11453 if (IsDiv) {
11454 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11455 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11456 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11457 }
11458 return compType;
11459}
11460
11461QualType Sema::CheckRemainderOperands(
11462 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11463 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11464
11465 // Note: This check is here to simplify the double exclusions of
11466 // scalar and vector HLSL checks. No getLangOpts().HLSL
11467 // is needed since all languages exlcude doubles.
11468 if (LHS.get()->getType()->isDoubleType() ||
11469 RHS.get()->getType()->isDoubleType() ||
11470 (LHS.get()->getType()->isVectorType() && LHS.get()
11471 ->getType()
11472 ->getAs<VectorType>()
11473 ->getElementType()
11474 ->isDoubleType()) ||
11475 (RHS.get()->getType()->isVectorType() && RHS.get()
11476 ->getType()
11477 ->getAs<VectorType>()
11478 ->getElementType()
11479 ->isDoubleType()))
11480 return InvalidOperands(Loc, LHS, RHS);
11481
11482 if (LHS.get()->getType()->isVectorType() ||
11483 RHS.get()->getType()->isVectorType()) {
11484 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11485 RHS.get()->getType()->hasIntegerRepresentation()) ||
11486 (getLangOpts().HLSL &&
11487 (LHS.get()->getType()->hasFloatingRepresentation() ||
11488 RHS.get()->getType()->hasFloatingRepresentation())))
11489 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11490 /*AllowBothBool*/ getLangOpts().AltiVec,
11491 /*AllowBoolConversions*/ false,
11492 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11493 return InvalidOperands(Loc, LHS, RHS);
11494 }
11495
11496 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11497 RHS.get()->getType()->isSveVLSBuiltinType()) {
11498 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11499 RHS.get()->getType()->hasIntegerRepresentation())
11500 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11501 OperationKind: ArithConvKind::Arithmetic);
11502
11503 return InvalidOperands(Loc, LHS, RHS);
11504 }
11505
11506 QualType compType = UsualArithmeticConversions(
11507 LHS, RHS, Loc,
11508 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11509 if (LHS.isInvalid() || RHS.isInvalid())
11510 return QualType();
11511
11512 if (compType.isNull() ||
11513 (!compType->isIntegerType() &&
11514 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11515 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11516 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11517 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11518 return ResultTy;
11519 }
11520 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11521 return compType;
11522}
11523
11524/// Diagnose invalid arithmetic on two void pointers.
11525static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11526 Expr *LHSExpr, Expr *RHSExpr) {
11527 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11528 ? diag::err_typecheck_pointer_arith_void_type
11529 : diag::ext_gnu_void_ptr)
11530 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11531 << RHSExpr->getSourceRange();
11532}
11533
11534/// Diagnose invalid arithmetic on a void pointer.
11535static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11536 Expr *Pointer) {
11537 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11538 ? diag::err_typecheck_pointer_arith_void_type
11539 : diag::ext_gnu_void_ptr)
11540 << 0 /* one pointer */ << Pointer->getSourceRange();
11541}
11542
11543/// Diagnose invalid arithmetic on a null pointer.
11544///
11545/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11546/// idiom, which we recognize as a GNU extension.
11547///
11548static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11549 Expr *Pointer, bool IsGNUIdiom) {
11550 if (IsGNUIdiom)
11551 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11552 << Pointer->getSourceRange();
11553 else
11554 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11555 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11556}
11557
11558/// Diagnose invalid subraction on a null pointer.
11559///
11560static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11561 Expr *Pointer, bool BothNull) {
11562 // Null - null is valid in C++ [expr.add]p7
11563 if (BothNull && S.getLangOpts().CPlusPlus)
11564 return;
11565
11566 // Is this s a macro from a system header?
11567 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11568 return;
11569
11570 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11571 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11572 << S.getLangOpts().CPlusPlus
11573 << Pointer->getSourceRange());
11574}
11575
11576/// Diagnose invalid arithmetic on two function pointers.
11577static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11578 Expr *LHS, Expr *RHS) {
11579 assert(LHS->getType()->isAnyPointerType());
11580 assert(RHS->getType()->isAnyPointerType());
11581 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11582 ? diag::err_typecheck_pointer_arith_function_type
11583 : diag::ext_gnu_ptr_func_arith)
11584 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11585 // We only show the second type if it differs from the first.
11586 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11587 T2: RHS->getType())
11588 << RHS->getType()->getPointeeType()
11589 << LHS->getSourceRange() << RHS->getSourceRange();
11590}
11591
11592/// Diagnose invalid arithmetic on a function pointer.
11593static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11594 Expr *Pointer) {
11595 assert(Pointer->getType()->isAnyPointerType());
11596 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11597 ? diag::err_typecheck_pointer_arith_function_type
11598 : diag::ext_gnu_ptr_func_arith)
11599 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11600 << 0 /* one pointer, so only one type */
11601 << Pointer->getSourceRange();
11602}
11603
11604/// Emit error if Operand is incomplete pointer type
11605///
11606/// \returns True if pointer has incomplete type
11607static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11608 Expr *Operand) {
11609 QualType ResType = Operand->getType();
11610 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11611 ResType = ResAtomicType->getValueType();
11612
11613 assert(ResType->isAnyPointerType());
11614 QualType PointeeTy = ResType->getPointeeType();
11615 return S.RequireCompleteSizedType(
11616 Loc, T: PointeeTy,
11617 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11618 Args: Operand->getSourceRange());
11619}
11620
11621/// Check the validity of an arithmetic pointer operand.
11622///
11623/// If the operand has pointer type, this code will check for pointer types
11624/// which are invalid in arithmetic operations. These will be diagnosed
11625/// appropriately, including whether or not the use is supported as an
11626/// extension.
11627///
11628/// \returns True when the operand is valid to use (even if as an extension).
11629static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11630 Expr *Operand) {
11631 QualType ResType = Operand->getType();
11632 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11633 ResType = ResAtomicType->getValueType();
11634
11635 if (!ResType->isAnyPointerType()) return true;
11636
11637 QualType PointeeTy = ResType->getPointeeType();
11638 if (PointeeTy->isVoidType()) {
11639 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11640 return !S.getLangOpts().CPlusPlus;
11641 }
11642 if (PointeeTy->isFunctionType()) {
11643 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11644 return !S.getLangOpts().CPlusPlus;
11645 }
11646
11647 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11648
11649 return true;
11650}
11651
11652/// Check the validity of a binary arithmetic operation w.r.t. pointer
11653/// operands.
11654///
11655/// This routine will diagnose any invalid arithmetic on pointer operands much
11656/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11657/// for emitting a single diagnostic even for operations where both LHS and RHS
11658/// are (potentially problematic) pointers.
11659///
11660/// \returns True when the operand is valid to use (even if as an extension).
11661static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11662 Expr *LHSExpr, Expr *RHSExpr) {
11663 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11664 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11665 if (!isLHSPointer && !isRHSPointer) return true;
11666
11667 QualType LHSPointeeTy, RHSPointeeTy;
11668 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11669 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11670
11671 // if both are pointers check if operation is valid wrt address spaces
11672 if (isLHSPointer && isRHSPointer) {
11673 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11674 Ctx: S.getASTContext())) {
11675 S.Diag(Loc,
11676 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11677 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11678 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11679 return false;
11680 }
11681 }
11682
11683 // Check for arithmetic on pointers to incomplete types.
11684 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11685 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11686 if (isLHSVoidPtr || isRHSVoidPtr) {
11687 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11688 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11689 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11690
11691 return !S.getLangOpts().CPlusPlus;
11692 }
11693
11694 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11695 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11696 if (isLHSFuncPtr || isRHSFuncPtr) {
11697 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11698 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11699 Pointer: RHSExpr);
11700 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11701
11702 return !S.getLangOpts().CPlusPlus;
11703 }
11704
11705 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11706 return false;
11707 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11708 return false;
11709
11710 return true;
11711}
11712
11713/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11714/// literal.
11715static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11716 Expr *LHSExpr, Expr *RHSExpr) {
11717 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11718 Expr* IndexExpr = RHSExpr;
11719 if (!StrExpr) {
11720 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11721 IndexExpr = LHSExpr;
11722 }
11723
11724 bool IsStringPlusInt = StrExpr &&
11725 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11726 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11727 return;
11728
11729 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11730 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11731 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11732
11733 // Only print a fixit for "str" + int, not for int + "str".
11734 if (IndexExpr == RHSExpr) {
11735 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11736 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11737 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11738 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11739 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11740 } else
11741 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11742}
11743
11744/// Emit a warning when adding a char literal to a string.
11745static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11746 Expr *LHSExpr, Expr *RHSExpr) {
11747 const Expr *StringRefExpr = LHSExpr;
11748 const CharacterLiteral *CharExpr =
11749 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11750
11751 if (!CharExpr) {
11752 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11753 StringRefExpr = RHSExpr;
11754 }
11755
11756 if (!CharExpr || !StringRefExpr)
11757 return;
11758
11759 const QualType StringType = StringRefExpr->getType();
11760
11761 // Return if not a PointerType.
11762 if (!StringType->isAnyPointerType())
11763 return;
11764
11765 // Return if not a CharacterType.
11766 if (!StringType->getPointeeType()->isAnyCharacterType())
11767 return;
11768
11769 ASTContext &Ctx = Self.getASTContext();
11770 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11771
11772 const QualType CharType = CharExpr->getType();
11773 if (!CharType->isAnyCharacterType() &&
11774 CharType->isIntegerType() &&
11775 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11776 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11777 << DiagRange << Ctx.CharTy;
11778 } else {
11779 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11780 << DiagRange << CharExpr->getType();
11781 }
11782
11783 // Only print a fixit for str + char, not for char + str.
11784 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11785 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11786 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11787 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11788 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11789 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11790 } else {
11791 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11792 }
11793}
11794
11795/// Emit error when two pointers are incompatible.
11796static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11797 Expr *LHSExpr, Expr *RHSExpr) {
11798 assert(LHSExpr->getType()->isAnyPointerType());
11799 assert(RHSExpr->getType()->isAnyPointerType());
11800 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11801 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11802 << RHSExpr->getSourceRange();
11803}
11804
11805// C99 6.5.6
11806QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11807 SourceLocation Loc, BinaryOperatorKind Opc,
11808 QualType* CompLHSTy) {
11809 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11810
11811 if (LHS.get()->getType()->isVectorType() ||
11812 RHS.get()->getType()->isVectorType()) {
11813 QualType compType =
11814 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11815 /*AllowBothBool*/ getLangOpts().AltiVec,
11816 /*AllowBoolConversions*/ getLangOpts().ZVector,
11817 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11818 if (CompLHSTy) *CompLHSTy = compType;
11819 return compType;
11820 }
11821
11822 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11823 RHS.get()->getType()->isSveVLSBuiltinType()) {
11824 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11825 OperationKind: ArithConvKind::Arithmetic);
11826 if (CompLHSTy)
11827 *CompLHSTy = compType;
11828 return compType;
11829 }
11830
11831 if (LHS.get()->getType()->isConstantMatrixType() ||
11832 RHS.get()->getType()->isConstantMatrixType()) {
11833 QualType compType =
11834 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11835 if (CompLHSTy)
11836 *CompLHSTy = compType;
11837 return compType;
11838 }
11839
11840 QualType compType = UsualArithmeticConversions(
11841 LHS, RHS, Loc,
11842 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11843 if (LHS.isInvalid() || RHS.isInvalid())
11844 return QualType();
11845
11846 // Diagnose "string literal" '+' int and string '+' "char literal".
11847 if (Opc == BO_Add) {
11848 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11849 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11850 }
11851
11852 // handle the common case first (both operands are arithmetic).
11853 if (!compType.isNull() && compType->isArithmeticType()) {
11854 if (CompLHSTy) *CompLHSTy = compType;
11855 return compType;
11856 }
11857
11858 // Type-checking. Ultimately the pointer's going to be in PExp;
11859 // note that we bias towards the LHS being the pointer.
11860 Expr *PExp = LHS.get(), *IExp = RHS.get();
11861
11862 bool isObjCPointer;
11863 if (PExp->getType()->isPointerType()) {
11864 isObjCPointer = false;
11865 } else if (PExp->getType()->isObjCObjectPointerType()) {
11866 isObjCPointer = true;
11867 } else {
11868 std::swap(a&: PExp, b&: IExp);
11869 if (PExp->getType()->isPointerType()) {
11870 isObjCPointer = false;
11871 } else if (PExp->getType()->isObjCObjectPointerType()) {
11872 isObjCPointer = true;
11873 } else {
11874 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11875 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11876 return ResultTy;
11877 }
11878 }
11879 assert(PExp->getType()->isAnyPointerType());
11880
11881 if (!IExp->getType()->isIntegerType())
11882 return InvalidOperands(Loc, LHS, RHS);
11883
11884 // Adding to a null pointer results in undefined behavior.
11885 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11886 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11887 // In C++ adding zero to a null pointer is defined.
11888 Expr::EvalResult KnownVal;
11889 if (!getLangOpts().CPlusPlus ||
11890 (!IExp->isValueDependent() &&
11891 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11892 KnownVal.Val.getInt() != 0))) {
11893 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11894 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11895 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11896 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11897 }
11898 }
11899
11900 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11901 return QualType();
11902
11903 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11904 return QualType();
11905
11906 // Arithmetic on label addresses is normally allowed, except when we add
11907 // a ptrauth signature to the addresses.
11908 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11909 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11910 << /*addition*/ 1;
11911 return QualType();
11912 }
11913
11914 // Check array bounds for pointer arithemtic
11915 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11916
11917 if (CompLHSTy) {
11918 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11919 if (LHSTy.isNull()) {
11920 LHSTy = LHS.get()->getType();
11921 if (Context.isPromotableIntegerType(T: LHSTy))
11922 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11923 }
11924 *CompLHSTy = LHSTy;
11925 }
11926
11927 return PExp->getType();
11928}
11929
11930/// Determine whether the size of \p T is provably zero: some array dimension
11931/// is provably zero or the base element type has zero size. A variable
11932/// dimension that does not fold to an integer constant is assumed nonzero.
11933static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T) {
11934 while (const ArrayType *AT = Ctx.getAsArrayType(T)) {
11935 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
11936 if (CAT->isZeroSize())
11937 return true;
11938 } else if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
11939 if (const Expr *Bound = VAT->getSizeExpr())
11940 if (std::optional<llvm::APSInt> Size =
11941 Bound->getIntegerConstantExpr(Ctx))
11942 if (*Size == 0)
11943 return true;
11944 }
11945 T = AT->getElementType();
11946 }
11947 return !T->isIncompleteType() && Ctx.getTypeSizeInChars(T).isZero();
11948}
11949
11950// C99 6.5.6
11951QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11952 SourceLocation Loc,
11953 BinaryOperatorKind Opc,
11954 QualType *CompLHSTy) {
11955 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11956
11957 if (LHS.get()->getType()->isVectorType() ||
11958 RHS.get()->getType()->isVectorType()) {
11959 QualType compType =
11960 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11961 /*AllowBothBool*/ getLangOpts().AltiVec,
11962 /*AllowBoolConversions*/ getLangOpts().ZVector,
11963 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11964 if (CompLHSTy) *CompLHSTy = compType;
11965 return compType;
11966 }
11967
11968 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11969 RHS.get()->getType()->isSveVLSBuiltinType()) {
11970 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11971 OperationKind: ArithConvKind::Arithmetic);
11972 if (CompLHSTy)
11973 *CompLHSTy = compType;
11974 return compType;
11975 }
11976
11977 if (LHS.get()->getType()->isConstantMatrixType() ||
11978 RHS.get()->getType()->isConstantMatrixType()) {
11979 QualType compType =
11980 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11981 if (CompLHSTy)
11982 *CompLHSTy = compType;
11983 return compType;
11984 }
11985
11986 QualType compType = UsualArithmeticConversions(
11987 LHS, RHS, Loc,
11988 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11989 if (LHS.isInvalid() || RHS.isInvalid())
11990 return QualType();
11991
11992 // Enforce type constraints: C99 6.5.6p3.
11993
11994 // Handle the common case first (both operands are arithmetic).
11995 if (!compType.isNull() && compType->isArithmeticType()) {
11996 if (CompLHSTy) *CompLHSTy = compType;
11997 return compType;
11998 }
11999
12000 // Either ptr - int or ptr - ptr.
12001 if (LHS.get()->getType()->isAnyPointerType()) {
12002 QualType lpointee = LHS.get()->getType()->getPointeeType();
12003
12004 // Diagnose bad cases where we step over interface counts.
12005 if (LHS.get()->getType()->isObjCObjectPointerType() &&
12006 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
12007 return QualType();
12008
12009 // Arithmetic on label addresses is normally allowed, except when we add
12010 // a ptrauth signature to the addresses.
12011 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
12012 getLangOpts().PointerAuthIndirectGotos) {
12013 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
12014 << /*subtraction*/ 0;
12015 return QualType();
12016 }
12017
12018 // The result type of a pointer-int computation is the pointer type.
12019 if (RHS.get()->getType()->isIntegerType()) {
12020 // Subtracting from a null pointer should produce a warning.
12021 // The last argument to the diagnose call says this doesn't match the
12022 // GNU int-to-pointer idiom.
12023 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
12024 NPC: Expr::NPC_ValueDependentIsNotNull)) {
12025 // In C++ adding zero to a null pointer is defined.
12026 Expr::EvalResult KnownVal;
12027 if (!getLangOpts().CPlusPlus ||
12028 (!RHS.get()->isValueDependent() &&
12029 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
12030 KnownVal.Val.getInt() != 0))) {
12031 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
12032 }
12033 }
12034
12035 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
12036 return QualType();
12037
12038 // Check array bounds for pointer arithemtic
12039 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
12040 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12041
12042 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12043 return LHS.get()->getType();
12044 }
12045
12046 // Handle pointer-pointer subtractions.
12047 if (const PointerType *RHSPTy
12048 = RHS.get()->getType()->getAs<PointerType>()) {
12049 QualType rpointee = RHSPTy->getPointeeType();
12050
12051 if (getLangOpts().CPlusPlus) {
12052 // Pointee types must be the same: C++ [expr.add]
12053 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
12054 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12055 }
12056 } else {
12057 // Pointee types must be compatible C99 6.5.6p3
12058 if (!Context.typesAreCompatible(
12059 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
12060 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
12061 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12062 return QualType();
12063 }
12064 }
12065
12066 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
12067 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
12068 return QualType();
12069
12070 // For pointer subtraction, if the address spaces differ but overlap,
12071 // convert both pointers to the composite (superset) address space.
12072 // This is needed because address spaces may use different
12073 // representations, such as a private offset vs a flat address.
12074 LangAS LAddrSpace = lpointee.getAddressSpace();
12075 LangAS RAddrSpace = rpointee.getAddressSpace();
12076 if (LAddrSpace != RAddrSpace) {
12077 Qualifiers LQual = lpointee.getQualifiers();
12078 Qualifiers RQual = rpointee.getQualifiers();
12079 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(other: RQual, Ctx: Context)
12080 ? LAddrSpace
12081 : RAddrSpace;
12082
12083 if (LAddrSpace != ResultAddrSpace) {
12084 QualType NewPteTy = Context.getAddrSpaceQualType(
12085 T: lpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12086 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12087 LHS =
12088 ImpCastExprToType(E: LHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12089 }
12090 if (RAddrSpace != ResultAddrSpace) {
12091 QualType NewPteTy = Context.getAddrSpaceQualType(
12092 T: rpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12093 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12094 RHS =
12095 ImpCastExprToType(E: RHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12096 }
12097 }
12098
12099 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12100 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12101 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12102 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12103
12104 // Subtracting nullptr or from nullptr is suspect
12105 if (LHSIsNullPtr)
12106 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
12107 if (RHSIsNullPtr)
12108 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
12109
12110 // The pointee type may have zero size. As an extension, a structure or
12111 // union may have zero size or an array may have zero length. In this
12112 // case subtraction does not make sense. For a variably modified type,
12113 // warn only when the size is provably zero.
12114 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12115 isProvablyZeroSize(Ctx: Context, T: rpointee))
12116 Diag(Loc, DiagID: diag::warn_sub_ptr_zero_size_types)
12117 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12118 << RHS.get()->getSourceRange();
12119
12120 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12121 return Context.getPointerDiffType();
12122 }
12123 }
12124
12125 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12126 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12127 return ResultTy;
12128}
12129
12130static bool isScopedEnumerationType(QualType T) {
12131 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12132 return ET->getDecl()->isScoped();
12133 return false;
12134}
12135
12136static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12137 SourceLocation Loc, BinaryOperatorKind Opc,
12138 QualType LHSType) {
12139 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12140 // so skip remaining warnings as we don't want to modify values within Sema.
12141 if (S.getLangOpts().OpenCL)
12142 return;
12143
12144 if (Opc == BO_Shr &&
12145 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
12146 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
12147
12148 // Check right/shifter operand
12149 Expr::EvalResult RHSResult;
12150 if (RHS.get()->isValueDependent() ||
12151 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
12152 return;
12153 llvm::APSInt Right = RHSResult.Val.getInt();
12154
12155 if (Right.isNegative()) {
12156 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12157 PD: S.PDiag(DiagID: diag::warn_shift_negative)
12158 << RHS.get()->getSourceRange());
12159 return;
12160 }
12161
12162 QualType LHSExprType = LHS.get()->getType();
12163 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
12164 if (LHSExprType->isBitIntType())
12165 LeftSize = S.Context.getIntWidth(T: LHSExprType);
12166 else if (LHSExprType->isFixedPointType()) {
12167 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
12168 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12169 }
12170 if (Right.uge(RHS: LeftSize)) {
12171 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12172 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
12173 << RHS.get()->getSourceRange());
12174 return;
12175 }
12176
12177 // FIXME: We probably need to handle fixed point types specially here.
12178 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12179 return;
12180
12181 // When left shifting an ICE which is signed, we can check for overflow which
12182 // according to C++ standards prior to C++2a has undefined behavior
12183 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12184 // more than the maximum value representable in the result type, so never
12185 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12186 // expression is still probably a bug.)
12187 Expr::EvalResult LHSResult;
12188 if (LHS.get()->isValueDependent() ||
12189 LHSType->hasUnsignedIntegerRepresentation() ||
12190 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12191 return;
12192 llvm::APSInt Left = LHSResult.Val.getInt();
12193
12194 // Don't warn if signed overflow is defined, then all the rest of the
12195 // diagnostics will not be triggered because the behavior is defined.
12196 // Also don't warn in C++20 mode (and newer), as signed left shifts
12197 // always wrap and never overflow.
12198 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12199 return;
12200
12201 // If LHS does not have a non-negative value then, the
12202 // behavior is undefined before C++2a. Warn about it.
12203 if (Left.isNegative()) {
12204 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
12205 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
12206 << LHS.get()->getSourceRange());
12207 return;
12208 }
12209
12210 llvm::APInt ResultBits =
12211 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12212 if (ResultBits.ule(RHS: LeftSize))
12213 return;
12214 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12215 Result = Result.shl(ShiftAmt: Right);
12216
12217 // Print the bit representation of the signed integer as an unsigned
12218 // hexadecimal number.
12219 SmallString<40> HexResult;
12220 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12221
12222 // If we are only missing a sign bit, this is less likely to result in actual
12223 // bugs -- if the result is cast back to an unsigned type, it will have the
12224 // expected value. Thus we place this behind a different warning that can be
12225 // turned off separately if needed.
12226 if (ResultBits - 1 == LeftSize) {
12227 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12228 << HexResult << LHSType
12229 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12230 return;
12231 }
12232
12233 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12234 << HexResult.str() << Result.getSignificantBits() << LHSType
12235 << Left.getBitWidth() << LHS.get()->getSourceRange()
12236 << RHS.get()->getSourceRange();
12237}
12238
12239/// Return the resulting type when a vector is shifted
12240/// by a scalar or vector shift amount.
12241static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12242 SourceLocation Loc, bool IsCompAssign) {
12243 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12244 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12245 !LHS.get()->getType()->isVectorType()) {
12246 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12247 << RHS.get()->getType() << LHS.get()->getType()
12248 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12249 return QualType();
12250 }
12251
12252 if (!IsCompAssign) {
12253 LHS = S.UsualUnaryConversions(E: LHS.get());
12254 if (LHS.isInvalid()) return QualType();
12255 }
12256
12257 RHS = S.UsualUnaryConversions(E: RHS.get());
12258 if (RHS.isInvalid()) return QualType();
12259
12260 QualType LHSType = LHS.get()->getType();
12261 // Note that LHS might be a scalar because the routine calls not only in
12262 // OpenCL case.
12263 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12264 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12265
12266 // Note that RHS might not be a vector.
12267 QualType RHSType = RHS.get()->getType();
12268 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12269 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12270
12271 // Do not allow shifts for boolean vectors.
12272 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12273 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12274 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12275 << LHS.get()->getType() << RHS.get()->getType()
12276 << LHS.get()->getSourceRange();
12277 return QualType();
12278 }
12279
12280 // The operands need to be integers.
12281 if (!LHSEleType->isIntegerType()) {
12282 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12283 << LHS.get()->getType() << LHS.get()->getSourceRange();
12284 return QualType();
12285 }
12286
12287 if (!RHSEleType->isIntegerType()) {
12288 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12289 << RHS.get()->getType() << RHS.get()->getSourceRange();
12290 return QualType();
12291 }
12292
12293 if (!LHSVecTy) {
12294 assert(RHSVecTy);
12295 if (IsCompAssign)
12296 return RHSType;
12297 if (LHSEleType != RHSEleType) {
12298 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12299 LHSEleType = RHSEleType;
12300 }
12301 QualType VecTy =
12302 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12303 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12304 LHSType = VecTy;
12305 } else if (RHSVecTy) {
12306 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12307 // are applied component-wise. So if RHS is a vector, then ensure
12308 // that the number of elements is the same as LHS...
12309 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12310 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12311 << LHS.get()->getType() << RHS.get()->getType()
12312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12313 return QualType();
12314 }
12315 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12316 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12317 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12318 if (LHSBT != RHSBT &&
12319 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12320 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12321 << LHS.get()->getType() << RHS.get()->getType()
12322 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12323 }
12324 }
12325 } else {
12326 // ...else expand RHS to match the number of elements in LHS.
12327 QualType VecTy =
12328 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12329 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12330 }
12331
12332 return LHSType;
12333}
12334
12335static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12336 ExprResult &RHS, SourceLocation Loc,
12337 bool IsCompAssign) {
12338 if (!IsCompAssign) {
12339 LHS = S.UsualUnaryConversions(E: LHS.get());
12340 if (LHS.isInvalid())
12341 return QualType();
12342 }
12343
12344 RHS = S.UsualUnaryConversions(E: RHS.get());
12345 if (RHS.isInvalid())
12346 return QualType();
12347
12348 QualType LHSType = LHS.get()->getType();
12349 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12350 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12351 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12352 : LHSType;
12353
12354 // Note that RHS might not be a vector
12355 QualType RHSType = RHS.get()->getType();
12356 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12357 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12358 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12359 : RHSType;
12360
12361 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12362 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12363 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12364 << LHSType << RHSType << LHS.get()->getSourceRange();
12365 return QualType();
12366 }
12367
12368 if (!LHSEleType->isIntegerType()) {
12369 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12370 << LHS.get()->getType() << LHS.get()->getSourceRange();
12371 return QualType();
12372 }
12373
12374 if (!RHSEleType->isIntegerType()) {
12375 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12376 << RHS.get()->getType() << RHS.get()->getSourceRange();
12377 return QualType();
12378 }
12379
12380 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12381 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12382 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12383 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12384 << LHSType << RHSType << LHS.get()->getSourceRange()
12385 << RHS.get()->getSourceRange();
12386 return QualType();
12387 }
12388
12389 if (!LHSType->isSveVLSBuiltinType()) {
12390 assert(RHSType->isSveVLSBuiltinType());
12391 if (IsCompAssign)
12392 return RHSType;
12393 if (LHSEleType != RHSEleType) {
12394 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12395 LHSEleType = RHSEleType;
12396 }
12397 const llvm::ElementCount VecSize =
12398 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12399 QualType VecTy =
12400 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12401 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12402 LHSType = VecTy;
12403 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12404 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12405 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12406 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12407 << LHSType << RHSType << LHS.get()->getSourceRange()
12408 << RHS.get()->getSourceRange();
12409 return QualType();
12410 }
12411 } else {
12412 const llvm::ElementCount VecSize =
12413 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12414 if (LHSEleType != RHSEleType) {
12415 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12416 RHSEleType = LHSEleType;
12417 }
12418 QualType VecTy =
12419 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12420 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12421 }
12422
12423 return LHSType;
12424}
12425
12426// C99 6.5.7
12427QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12428 SourceLocation Loc, BinaryOperatorKind Opc,
12429 bool IsCompAssign) {
12430 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12431
12432 // Vector shifts promote their scalar inputs to vector type.
12433 if (LHS.get()->getType()->isVectorType() ||
12434 RHS.get()->getType()->isVectorType()) {
12435 if (LangOpts.ZVector) {
12436 // The shift operators for the z vector extensions work basically
12437 // like general shifts, except that neither the LHS nor the RHS is
12438 // allowed to be a "vector bool".
12439 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12440 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12441 return InvalidOperands(Loc, LHS, RHS);
12442 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12443 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12444 return InvalidOperands(Loc, LHS, RHS);
12445 }
12446 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12447 }
12448
12449 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12450 RHS.get()->getType()->isSveVLSBuiltinType())
12451 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12452
12453 // Shifts don't perform usual arithmetic conversions, they just do integer
12454 // promotions on each operand. C99 6.5.7p3
12455
12456 // For the LHS, do usual unary conversions, but then reset them away
12457 // if this is a compound assignment.
12458 ExprResult OldLHS = LHS;
12459 LHS = UsualUnaryConversions(E: LHS.get());
12460 if (LHS.isInvalid())
12461 return QualType();
12462 QualType LHSType = LHS.get()->getType();
12463 if (IsCompAssign) LHS = OldLHS;
12464
12465 // The RHS is simpler.
12466 RHS = UsualUnaryConversions(E: RHS.get());
12467 if (RHS.isInvalid())
12468 return QualType();
12469 QualType RHSType = RHS.get()->getType();
12470
12471 // C99 6.5.7p2: Each of the operands shall have integer type.
12472 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12473 if ((!LHSType->isFixedPointOrIntegerType() &&
12474 !LHSType->hasIntegerRepresentation()) ||
12475 !RHSType->hasIntegerRepresentation()) {
12476 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12477 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12478 return ResultTy;
12479 }
12480
12481 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12482
12483 // "The type of the result is that of the promoted left operand."
12484 return LHSType;
12485}
12486
12487/// Diagnose bad pointer comparisons.
12488static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12489 ExprResult &LHS, ExprResult &RHS,
12490 bool IsError) {
12491 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12492 : diag::ext_typecheck_comparison_of_distinct_pointers)
12493 << LHS.get()->getType() << RHS.get()->getType()
12494 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12495}
12496
12497/// Returns false if the pointers are converted to a composite type,
12498/// true otherwise.
12499static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12500 ExprResult &LHS, ExprResult &RHS) {
12501 // C++ [expr.rel]p2:
12502 // [...] Pointer conversions (4.10) and qualification
12503 // conversions (4.4) are performed on pointer operands (or on
12504 // a pointer operand and a null pointer constant) to bring
12505 // them to their composite pointer type. [...]
12506 //
12507 // C++ [expr.eq]p1 uses the same notion for (in)equality
12508 // comparisons of pointers.
12509
12510 QualType LHSType = LHS.get()->getType();
12511 QualType RHSType = RHS.get()->getType();
12512 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12513 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12514
12515 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12516 if (T.isNull()) {
12517 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12518 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12519 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12520 else
12521 S.InvalidOperands(Loc, LHS, RHS);
12522 return true;
12523 }
12524
12525 return false;
12526}
12527
12528static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12529 ExprResult &LHS,
12530 ExprResult &RHS,
12531 bool IsError) {
12532 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12533 : diag::ext_typecheck_comparison_of_fptr_to_void)
12534 << LHS.get()->getType() << RHS.get()->getType()
12535 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12536}
12537
12538static bool isObjCObjectLiteral(ExprResult &E) {
12539 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12540 case Stmt::ObjCArrayLiteralClass:
12541 case Stmt::ObjCDictionaryLiteralClass:
12542 case Stmt::ObjCStringLiteralClass:
12543 case Stmt::ObjCBoxedExprClass:
12544 return true;
12545 default:
12546 // Note that ObjCBoolLiteral is NOT an object literal!
12547 return false;
12548 }
12549}
12550
12551static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12552 const ObjCObjectPointerType *Type =
12553 LHS->getType()->getAs<ObjCObjectPointerType>();
12554
12555 // If this is not actually an Objective-C object, bail out.
12556 if (!Type)
12557 return false;
12558
12559 // Get the LHS object's interface type.
12560 QualType InterfaceType = Type->getPointeeType();
12561
12562 // If the RHS isn't an Objective-C object, bail out.
12563 if (!RHS->getType()->isObjCObjectPointerType())
12564 return false;
12565
12566 // Try to find the -isEqual: method.
12567 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12568 ObjCMethodDecl *Method =
12569 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12570 /*IsInstance=*/true);
12571 if (!Method) {
12572 if (Type->isObjCIdType()) {
12573 // For 'id', just check the global pool.
12574 Method =
12575 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12576 /*receiverId=*/receiverIdOrClass: true);
12577 } else {
12578 // Check protocols.
12579 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12580 /*IsInstance=*/true);
12581 }
12582 }
12583
12584 if (!Method)
12585 return false;
12586
12587 QualType T = Method->parameters()[0]->getType();
12588 if (!T->isObjCObjectPointerType())
12589 return false;
12590
12591 QualType R = Method->getReturnType();
12592 if (!R->isScalarType())
12593 return false;
12594
12595 return true;
12596}
12597
12598static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12599 ExprResult &LHS, ExprResult &RHS,
12600 BinaryOperator::Opcode Opc){
12601 Expr *Literal;
12602 Expr *Other;
12603 if (isObjCObjectLiteral(E&: LHS)) {
12604 Literal = LHS.get();
12605 Other = RHS.get();
12606 } else {
12607 Literal = RHS.get();
12608 Other = LHS.get();
12609 }
12610
12611 // Don't warn on comparisons against nil.
12612 Other = Other->IgnoreParenCasts();
12613 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12614 NPC: Expr::NPC_ValueDependentIsNotNull))
12615 return;
12616
12617 // This should be kept in sync with warn_objc_literal_comparison.
12618 // LK_String should always be after the other literals, since it has its own
12619 // warning flag.
12620 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12621 assert(LiteralKind != SemaObjC::LK_Block);
12622 if (LiteralKind == SemaObjC::LK_None) {
12623 llvm_unreachable("Unknown Objective-C object literal kind");
12624 }
12625
12626 if (LiteralKind == SemaObjC::LK_String)
12627 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12628 << Literal->getSourceRange();
12629 else
12630 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12631 << LiteralKind << Literal->getSourceRange();
12632
12633 if (BinaryOperator::isEqualityOp(Opc) &&
12634 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12635 SourceLocation Start = LHS.get()->getBeginLoc();
12636 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12637 CharSourceRange OpRange =
12638 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12639
12640 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12641 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12642 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12643 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12644 }
12645}
12646
12647/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12648static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12649 ExprResult &RHS, SourceLocation Loc,
12650 BinaryOperatorKind Opc) {
12651 // Check that left hand side is !something.
12652 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12653 if (!UO || UO->getOpcode() != UO_LNot) return;
12654
12655 // Only check if the right hand side is non-bool arithmetic type.
12656 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12657
12658 // Make sure that the something in !something is not bool.
12659 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12660 if (SubExpr->isKnownToHaveBooleanValue()) return;
12661
12662 // Emit warning.
12663 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12664 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12665 << Loc << IsBitwiseOp;
12666
12667 // First note suggest !(x < y)
12668 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12669 SourceLocation FirstClose = RHS.get()->getEndLoc();
12670 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12671 if (FirstClose.isInvalid())
12672 FirstOpen = SourceLocation();
12673 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12674 << IsBitwiseOp
12675 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12676 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12677
12678 // Second note suggests (!x) < y
12679 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12680 SourceLocation SecondClose = LHS.get()->getEndLoc();
12681 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12682 if (SecondClose.isInvalid())
12683 SecondOpen = SourceLocation();
12684 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12685 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12686 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12687}
12688
12689// Returns true if E refers to a non-weak array.
12690static bool checkForArray(const Expr *E) {
12691 const ValueDecl *D = nullptr;
12692 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12693 D = DR->getDecl();
12694 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12695 if (Mem->isImplicitAccess())
12696 D = Mem->getMemberDecl();
12697 }
12698 if (!D)
12699 return false;
12700 return D->getType()->isArrayType() && !D->isWeak();
12701}
12702
12703/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12704/// pointer and size is an unsigned integer. Return whether the result is
12705/// always true/false.
12706static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12707 const Expr *RHS,
12708 BinaryOperatorKind Opc) {
12709 if (!LHS->getType()->isPointerType() ||
12710 S.getLangOpts().PointerOverflowDefined)
12711 return std::nullopt;
12712
12713 // Canonicalize to >= or < predicate.
12714 switch (Opc) {
12715 case BO_GE:
12716 case BO_LT:
12717 break;
12718 case BO_GT:
12719 std::swap(a&: LHS, b&: RHS);
12720 Opc = BO_LT;
12721 break;
12722 case BO_LE:
12723 std::swap(a&: LHS, b&: RHS);
12724 Opc = BO_GE;
12725 break;
12726 default:
12727 return std::nullopt;
12728 }
12729
12730 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12731 if (!BO || BO->getOpcode() != BO_Add)
12732 return std::nullopt;
12733
12734 Expr *Other;
12735 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12736 Other = BO->getRHS();
12737 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12738 Other = BO->getLHS();
12739 else
12740 return std::nullopt;
12741
12742 if (!Other->getType()->isUnsignedIntegerType())
12743 return std::nullopt;
12744
12745 return Opc == BO_GE;
12746}
12747
12748/// Diagnose some forms of syntactically-obvious tautological comparison.
12749static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12750 Expr *LHS, Expr *RHS,
12751 BinaryOperatorKind Opc) {
12752 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12753 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12754
12755 QualType LHSType = LHS->getType();
12756 QualType RHSType = RHS->getType();
12757 if (LHSType->hasFloatingRepresentation() ||
12758 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12759 S.inTemplateInstantiation())
12760 return;
12761
12762 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12763 // Tautological diagnostics.
12764 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12765 return;
12766
12767 // Comparisons between two array types are ill-formed for operator<=>, so
12768 // we shouldn't emit any additional warnings about it.
12769 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12770 return;
12771
12772 // For non-floating point types, check for self-comparisons of the form
12773 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12774 // often indicate logic errors in the program.
12775 //
12776 // NOTE: Don't warn about comparison expressions resulting from macro
12777 // expansion. Also don't warn about comparisons which are only self
12778 // comparisons within a template instantiation. The warnings should catch
12779 // obvious cases in the definition of the template anyways. The idea is to
12780 // warn when the typed comparison operator will always evaluate to the same
12781 // result.
12782
12783 // Used for indexing into %select in warn_comparison_always
12784 enum {
12785 AlwaysConstant,
12786 AlwaysTrue,
12787 AlwaysFalse,
12788 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12789 };
12790
12791 // C++1a [array.comp]:
12792 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12793 // operands of array type.
12794 // C++2a [depr.array.comp]:
12795 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12796 // operands of array type are deprecated.
12797 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12798 RHSStripped->getType()->isArrayType()) {
12799 auto IsDeprArrayComparionIgnored =
12800 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12801 auto DiagID = S.getLangOpts().CPlusPlus26
12802 ? diag::warn_array_comparison_cxx26
12803 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12804 ? diag::warn_array_comparison
12805 : diag::warn_depr_array_comparison;
12806 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12807 << LHSStripped->getType() << RHSStripped->getType();
12808 // Carry on to produce the tautological comparison warning, if this
12809 // expression is potentially-evaluated, we can resolve the array to a
12810 // non-weak declaration, and so on.
12811 }
12812
12813 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12814 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12815 unsigned Result;
12816 switch (Opc) {
12817 case BO_EQ:
12818 case BO_LE:
12819 case BO_GE:
12820 Result = AlwaysTrue;
12821 break;
12822 case BO_NE:
12823 case BO_LT:
12824 case BO_GT:
12825 Result = AlwaysFalse;
12826 break;
12827 case BO_Cmp:
12828 Result = AlwaysEqual;
12829 break;
12830 default:
12831 Result = AlwaysConstant;
12832 break;
12833 }
12834 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12835 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12836 << 0 /*self-comparison*/
12837 << Result);
12838 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12839 // What is it always going to evaluate to?
12840 unsigned Result;
12841 switch (Opc) {
12842 case BO_EQ: // e.g. array1 == array2
12843 Result = AlwaysFalse;
12844 break;
12845 case BO_NE: // e.g. array1 != array2
12846 Result = AlwaysTrue;
12847 break;
12848 default: // e.g. array1 <= array2
12849 // The best we can say is 'a constant'
12850 Result = AlwaysConstant;
12851 break;
12852 }
12853 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12854 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12855 << 1 /*array comparison*/
12856 << Result);
12857 } else if (std::optional<bool> Res =
12858 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12859 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12860 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12861 << 2 /*pointer comparison*/
12862 << (*Res ? AlwaysTrue : AlwaysFalse));
12863 }
12864 }
12865
12866 if (isa<CastExpr>(Val: LHSStripped))
12867 LHSStripped = LHSStripped->IgnoreParenCasts();
12868 if (isa<CastExpr>(Val: RHSStripped))
12869 RHSStripped = RHSStripped->IgnoreParenCasts();
12870
12871 // Warn about comparisons against a string constant (unless the other
12872 // operand is null); the user probably wants string comparison function.
12873 Expr *LiteralString = nullptr;
12874 Expr *LiteralStringStripped = nullptr;
12875 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12876 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12877 NPC: Expr::NPC_ValueDependentIsNull)) {
12878 LiteralString = LHS;
12879 LiteralStringStripped = LHSStripped;
12880 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12881 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12882 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12883 NPC: Expr::NPC_ValueDependentIsNull)) {
12884 LiteralString = RHS;
12885 LiteralStringStripped = RHSStripped;
12886 }
12887
12888 if (LiteralString) {
12889 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12890 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12891 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12892 << LiteralString->getSourceRange());
12893 }
12894}
12895
12896static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12897 switch (CK) {
12898 default: {
12899#ifndef NDEBUG
12900 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12901 << "\n";
12902#endif
12903 llvm_unreachable("unhandled cast kind");
12904 }
12905 case CK_UserDefinedConversion:
12906 return ICK_Identity;
12907 case CK_LValueToRValue:
12908 return ICK_Lvalue_To_Rvalue;
12909 case CK_ArrayToPointerDecay:
12910 return ICK_Array_To_Pointer;
12911 case CK_FunctionToPointerDecay:
12912 return ICK_Function_To_Pointer;
12913 case CK_IntegralCast:
12914 return ICK_Integral_Conversion;
12915 case CK_FloatingCast:
12916 return ICK_Floating_Conversion;
12917 case CK_IntegralToFloating:
12918 case CK_FloatingToIntegral:
12919 return ICK_Floating_Integral;
12920 case CK_IntegralComplexCast:
12921 case CK_FloatingComplexCast:
12922 case CK_FloatingComplexToIntegralComplex:
12923 case CK_IntegralComplexToFloatingComplex:
12924 return ICK_Complex_Conversion;
12925 case CK_FloatingComplexToReal:
12926 case CK_FloatingRealToComplex:
12927 case CK_IntegralComplexToReal:
12928 case CK_IntegralRealToComplex:
12929 return ICK_Complex_Real;
12930 case CK_HLSLArrayRValue:
12931 return ICK_HLSL_Array_RValue;
12932 }
12933}
12934
12935static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12936 QualType FromType,
12937 SourceLocation Loc) {
12938 // Check for a narrowing implicit conversion.
12939 StandardConversionSequence SCS;
12940 SCS.setAsIdentityConversion();
12941 SCS.setToType(Idx: 0, T: FromType);
12942 SCS.setToType(Idx: 1, T: ToType);
12943 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12944 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12945
12946 APValue PreNarrowingValue;
12947 QualType PreNarrowingType;
12948 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12949 ConstantType&: PreNarrowingType,
12950 /*IgnoreFloatToIntegralConversion*/ true)) {
12951 case NK_Dependent_Narrowing:
12952 // Implicit conversion to a narrower type, but the expression is
12953 // value-dependent so we can't tell whether it's actually narrowing.
12954 case NK_Not_Narrowing:
12955 return false;
12956
12957 case NK_Constant_Narrowing:
12958 // Implicit conversion to a narrower type, and the value is not a constant
12959 // expression.
12960 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12961 << /*Constant*/ 1
12962 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12963 return true;
12964
12965 case NK_Variable_Narrowing:
12966 // Implicit conversion to a narrower type, and the value is not a constant
12967 // expression.
12968 case NK_Type_Narrowing:
12969 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12970 << /*Constant*/ 0 << FromType << ToType;
12971 // TODO: It's not a constant expression, but what if the user intended it
12972 // to be? Can we produce notes to help them figure out why it isn't?
12973 return true;
12974 }
12975 llvm_unreachable("unhandled case in switch");
12976}
12977
12978static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12979 ExprResult &LHS,
12980 ExprResult &RHS,
12981 SourceLocation Loc) {
12982 QualType LHSType = LHS.get()->getType();
12983 QualType RHSType = RHS.get()->getType();
12984 // Dig out the original argument type and expression before implicit casts
12985 // were applied. These are the types/expressions we need to check the
12986 // [expr.spaceship] requirements against.
12987 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12988 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12989 QualType LHSStrippedType = LHSStripped.get()->getType();
12990 QualType RHSStrippedType = RHSStripped.get()->getType();
12991
12992 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12993 // other is not, the program is ill-formed.
12994 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12995 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12996 return QualType();
12997 }
12998
12999 // FIXME: Consider combining this with checkEnumArithmeticConversions.
13000 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
13001 RHSStrippedType->isEnumeralType();
13002 if (NumEnumArgs == 1) {
13003 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
13004 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
13005 if (OtherTy->hasFloatingRepresentation()) {
13006 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
13007 return QualType();
13008 }
13009 }
13010 if (NumEnumArgs == 2) {
13011 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
13012 // type E, the operator yields the result of converting the operands
13013 // to the underlying type of E and applying <=> to the converted operands.
13014 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
13015 S.InvalidOperands(Loc, LHS, RHS);
13016 return QualType();
13017 }
13018 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
13019 assert(IntType->isArithmeticType());
13020
13021 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
13022 // promote the boolean type, and all other promotable integer types, to
13023 // avoid this.
13024 if (S.Context.isPromotableIntegerType(T: IntType))
13025 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
13026
13027 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
13028 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
13029 LHSType = RHSType = IntType;
13030 }
13031
13032 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13033 // usual arithmetic conversions are applied to the operands.
13034 QualType Type =
13035 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13036 if (LHS.isInvalid() || RHS.isInvalid())
13037 return QualType();
13038 if (Type.isNull()) {
13039 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13040 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
13041 return ResultTy;
13042 }
13043
13044 std::optional<ComparisonCategoryType> CCT =
13045 getComparisonCategoryForBuiltinCmp(T: Type);
13046 if (!CCT)
13047 return S.InvalidOperands(Loc, LHS, RHS);
13048
13049 bool HasNarrowing = checkThreeWayNarrowingConversion(
13050 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
13051 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
13052 Loc: RHS.get()->getBeginLoc());
13053 if (HasNarrowing)
13054 return QualType();
13055
13056 assert(!Type.isNull() && "composite type for <=> has not been set");
13057
13058 return S.CheckComparisonCategoryType(
13059 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
13060}
13061
13062static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13063 ExprResult &RHS,
13064 SourceLocation Loc,
13065 BinaryOperatorKind Opc) {
13066 if (Opc == BO_Cmp)
13067 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13068
13069 // C99 6.5.8p3 / C99 6.5.9p4
13070 QualType Type =
13071 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13072 if (LHS.isInvalid() || RHS.isInvalid())
13073 return QualType();
13074 if (Type.isNull()) {
13075 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13076 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13077 return ResultTy;
13078 }
13079 assert(Type->isArithmeticType() || Type->isEnumeralType());
13080
13081 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13082 return S.InvalidOperands(Loc, LHS, RHS);
13083
13084 // Check for comparisons of floating point operands using != and ==.
13085 if (Type->hasFloatingRepresentation())
13086 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13087
13088 // The result of comparisons is 'bool' in C++, 'int' in C.
13089 return S.Context.getLogicalOperationType();
13090}
13091
13092void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13093 if (!NullE.get()->getType()->isAnyPointerType())
13094 return;
13095 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
13096 if (!E.get()->getType()->isAnyPointerType() &&
13097 E.get()->isNullPointerConstant(Ctx&: Context,
13098 NPC: Expr::NPC_ValueDependentIsNotNull) ==
13099 Expr::NPCK_ZeroExpression) {
13100 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
13101 if (CL->getValue() == 0)
13102 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13103 << NullValue
13104 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13105 Code: NullValue ? "NULL" : "(void *)0");
13106 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
13107 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13108 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
13109 if (T == Context.CharTy)
13110 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13111 << NullValue
13112 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13113 Code: NullValue ? "NULL" : "(void *)0");
13114 }
13115 }
13116}
13117
13118// C99 6.5.8, C++ [expr.rel]
13119QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13120 SourceLocation Loc,
13121 BinaryOperatorKind Opc) {
13122 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13123 bool IsThreeWay = Opc == BO_Cmp;
13124 bool IsOrdered = IsRelational || IsThreeWay;
13125 auto IsAnyPointerType = [](ExprResult E) {
13126 QualType Ty = E.get()->getType();
13127 return Ty->isPointerType() || Ty->isMemberPointerType();
13128 };
13129
13130 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13131 // type, array-to-pointer, ..., conversions are performed on both operands to
13132 // bring them to their composite type.
13133 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13134 // any type-related checks.
13135 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13136 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13137 if (LHS.isInvalid())
13138 return QualType();
13139 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13140 if (RHS.isInvalid())
13141 return QualType();
13142 } else {
13143 LHS = DefaultLvalueConversion(E: LHS.get());
13144 if (LHS.isInvalid())
13145 return QualType();
13146 RHS = DefaultLvalueConversion(E: RHS.get());
13147 if (RHS.isInvalid())
13148 return QualType();
13149 }
13150
13151 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
13152 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13153 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
13154 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
13155 }
13156
13157 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13158 RHS.get()->getType()->isConstantMatrixType()))
13159 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13160
13161 // Handle vector comparisons separately.
13162 if (LHS.get()->getType()->isVectorType() ||
13163 RHS.get()->getType()->isVectorType())
13164 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13165
13166 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13167 RHS.get()->getType()->isSveVLSBuiltinType())
13168 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13169
13170 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13171 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13172
13173 QualType LHSType = LHS.get()->getType();
13174 QualType RHSType = RHS.get()->getType();
13175 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13176 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13177 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
13178
13179 if ((LHSType->isPointerType() &&
13180 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13181 (RHSType->isPointerType() &&
13182 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13183 return InvalidOperands(Loc, LHS, RHS);
13184
13185 const Expr::NullPointerConstantKind LHSNullKind =
13186 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13187 const Expr::NullPointerConstantKind RHSNullKind =
13188 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13189 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13190 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13191
13192 auto computeResultTy = [&]() {
13193 if (Opc != BO_Cmp)
13194 return QualType(Context.getLogicalOperationType());
13195 assert(getLangOpts().CPlusPlus);
13196 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13197
13198 QualType CompositeTy = LHS.get()->getType();
13199 assert(!CompositeTy->isReferenceType());
13200
13201 std::optional<ComparisonCategoryType> CCT =
13202 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13203 if (!CCT)
13204 return InvalidOperands(Loc, LHS, RHS);
13205
13206 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13207 // P0946R0: Comparisons between a null pointer constant and an object
13208 // pointer result in std::strong_equality, which is ill-formed under
13209 // P1959R0.
13210 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13211 << (LHSIsNull ? LHS.get()->getSourceRange()
13212 : RHS.get()->getSourceRange());
13213 return QualType();
13214 }
13215
13216 return CheckComparisonCategoryType(
13217 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13218 };
13219
13220 if (LHSType->isMetaInfoType() && RHSType->isMetaInfoType()) {
13221 if (!BinaryOperator::isEqualityOp(Opc)) {
13222 return InvalidOperands(Loc, LHS, RHS);
13223 }
13224 return computeResultTy();
13225 }
13226
13227 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13228 bool IsEquality = Opc == BO_EQ;
13229 if (RHSIsNull)
13230 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13231 Range: RHS.get()->getSourceRange());
13232 else
13233 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13234 Range: LHS.get()->getSourceRange());
13235 }
13236
13237 if (IsOrdered && LHSType->isFunctionPointerType() &&
13238 RHSType->isFunctionPointerType()) {
13239 // Valid unless a relational comparison of function pointers
13240 bool IsError = Opc == BO_Cmp;
13241 auto DiagID =
13242 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13243 : getLangOpts().CPlusPlus
13244 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13245 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13246 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13247 << RHS.get()->getSourceRange();
13248 if (IsError)
13249 return QualType();
13250 }
13251
13252 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13253 (RHSType->isIntegerType() && !RHSIsNull)) {
13254 // Skip normal pointer conversion checks in this case; we have better
13255 // diagnostics for this below.
13256 } else if (getLangOpts().CPlusPlus) {
13257 // Equality comparison of a function pointer to a void pointer is invalid,
13258 // but we allow it as an extension.
13259 // FIXME: If we really want to allow this, should it be part of composite
13260 // pointer type computation so it works in conditionals too?
13261 if (!IsOrdered &&
13262 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13263 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13264 // This is a gcc extension compatibility comparison.
13265 // In a SFINAE context, we treat this as a hard error to maintain
13266 // conformance with the C++ standard.
13267 bool IsError = isSFINAEContext();
13268 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13269
13270 if (IsError)
13271 return QualType();
13272
13273 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13274 return computeResultTy();
13275 }
13276
13277 // C++ [expr.eq]p2:
13278 // If at least one operand is a pointer [...] bring them to their
13279 // composite pointer type.
13280 // C++ [expr.spaceship]p6
13281 // If at least one of the operands is of pointer type, [...] bring them
13282 // to their composite pointer type.
13283 // C++ [expr.rel]p2:
13284 // If both operands are pointers, [...] bring them to their composite
13285 // pointer type.
13286 // For <=>, the only valid non-pointer types are arrays and functions, and
13287 // we already decayed those, so this is really the same as the relational
13288 // comparison rule.
13289 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13290 (IsOrdered ? 2 : 1) &&
13291 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13292 RHSType->isObjCObjectPointerType()))) {
13293 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13294 return QualType();
13295 return computeResultTy();
13296 }
13297 } else if (LHSType->isPointerType() &&
13298 RHSType->isPointerType()) { // C99 6.5.8p2
13299 // All of the following pointer-related warnings are GCC extensions, except
13300 // when handling null pointer constants.
13301 QualType LCanPointeeTy =
13302 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13303 QualType RCanPointeeTy =
13304 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13305
13306 // C99 6.5.9p2 and C99 6.5.8p2
13307 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13308 T2: RCanPointeeTy.getUnqualifiedType())) {
13309 if (IsRelational) {
13310 // Pointers both need to point to complete or incomplete types
13311 if ((LCanPointeeTy->isIncompleteType() !=
13312 RCanPointeeTy->isIncompleteType()) &&
13313 !getLangOpts().C11) {
13314 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13315 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13316 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13317 << RCanPointeeTy->isIncompleteType();
13318 }
13319 }
13320 } else if (!IsRelational &&
13321 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13322 // Valid unless comparison between non-null pointer and function pointer
13323 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13324 && !LHSIsNull && !RHSIsNull)
13325 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13326 /*isError*/IsError: false);
13327 } else {
13328 // Invalid
13329 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13330 }
13331 if (LCanPointeeTy != RCanPointeeTy) {
13332 // Treat NULL constant as a special case in OpenCL.
13333 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13334 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13335 Ctx: getASTContext())) {
13336 Diag(Loc,
13337 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13338 << LHSType << RHSType << 0 /* comparison */
13339 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13340 }
13341 }
13342 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13343 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13344 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13345 : CK_BitCast;
13346
13347 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13348 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13349 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13350 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13351 bool ChangingCFIUncheckedCallee =
13352 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13353
13354 if (LHSIsNull && !RHSIsNull)
13355 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13356 else if (!ChangingCFIUncheckedCallee)
13357 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13358 }
13359 return computeResultTy();
13360 }
13361
13362
13363 // C++ [expr.eq]p4:
13364 // Two operands of type std::nullptr_t or one operand of type
13365 // std::nullptr_t and the other a null pointer constant compare
13366 // equal.
13367 // C23 6.5.9p5:
13368 // If both operands have type nullptr_t or one operand has type nullptr_t
13369 // and the other is a null pointer constant, they compare equal if the
13370 // former is a null pointer.
13371 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13372 if (LHSType->isNullPtrType()) {
13373 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13374 return computeResultTy();
13375 }
13376 if (RHSType->isNullPtrType()) {
13377 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13378 return computeResultTy();
13379 }
13380 }
13381
13382 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13383 // C23 6.5.9p6:
13384 // Otherwise, at least one operand is a pointer. If one is a pointer and
13385 // the other is a null pointer constant or has type nullptr_t, they
13386 // compare equal
13387 if (LHSIsNull && RHSType->isPointerType()) {
13388 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13389 return computeResultTy();
13390 }
13391 if (RHSIsNull && LHSType->isPointerType()) {
13392 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13393 return computeResultTy();
13394 }
13395 }
13396
13397 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13398 // These aren't covered by the composite pointer type rules.
13399 if (!IsOrdered && RHSType->isNullPtrType() &&
13400 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13401 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13402 return computeResultTy();
13403 }
13404 if (!IsOrdered && LHSType->isNullPtrType() &&
13405 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13406 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13407 return computeResultTy();
13408 }
13409
13410 if (getLangOpts().CPlusPlus) {
13411 if (IsRelational &&
13412 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13413 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13414 // HACK: Relational comparison of nullptr_t against a pointer type is
13415 // invalid per DR583, but we allow it within std::less<> and friends,
13416 // since otherwise common uses of it break.
13417 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13418 // friends to have std::nullptr_t overload candidates.
13419 DeclContext *DC = CurContext;
13420 if (isa<FunctionDecl>(Val: DC))
13421 DC = DC->getParent();
13422 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13423 if (CTSD->isInStdNamespace() &&
13424 llvm::StringSwitch<bool>(CTSD->getName())
13425 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13426 .Default(Value: false)) {
13427 if (RHSType->isNullPtrType())
13428 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13429 else
13430 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13431 return computeResultTy();
13432 }
13433 }
13434 }
13435
13436 // C++ [expr.eq]p2:
13437 // If at least one operand is a pointer to member, [...] bring them to
13438 // their composite pointer type.
13439 if (!IsOrdered &&
13440 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13441 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13442 return QualType();
13443 else
13444 return computeResultTy();
13445 }
13446 }
13447
13448 // Handle block pointer types.
13449 if (!IsOrdered && LHSType->isBlockPointerType() &&
13450 RHSType->isBlockPointerType()) {
13451 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13452 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13453
13454 if (!LHSIsNull && !RHSIsNull &&
13455 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13456 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13457 << LHSType << RHSType << LHS.get()->getSourceRange()
13458 << RHS.get()->getSourceRange();
13459 }
13460 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13461 return computeResultTy();
13462 }
13463
13464 // Allow block pointers to be compared with null pointer constants.
13465 if (!IsOrdered
13466 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13467 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13468 if (!LHSIsNull && !RHSIsNull) {
13469 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13470 ->getPointeeType()->isVoidType())
13471 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13472 ->getPointeeType()->isVoidType())))
13473 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13474 << LHSType << RHSType << LHS.get()->getSourceRange()
13475 << RHS.get()->getSourceRange();
13476 }
13477 if (LHSIsNull && !RHSIsNull)
13478 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13479 CK: RHSType->isPointerType() ? CK_BitCast
13480 : CK_AnyPointerToBlockPointerCast);
13481 else
13482 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13483 CK: LHSType->isPointerType() ? CK_BitCast
13484 : CK_AnyPointerToBlockPointerCast);
13485 return computeResultTy();
13486 }
13487
13488 if (LHSType->isObjCObjectPointerType() ||
13489 RHSType->isObjCObjectPointerType()) {
13490 const PointerType *LPT = LHSType->getAs<PointerType>();
13491 const PointerType *RPT = RHSType->getAs<PointerType>();
13492 if (LPT || RPT) {
13493 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13494 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13495
13496 if (!LPtrToVoid && !RPtrToVoid &&
13497 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13498 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13499 /*isError*/IsError: false);
13500 }
13501 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13502 // the RHS, but we have test coverage for this behavior.
13503 // FIXME: Consider using convertPointersToCompositeType in C++.
13504 if (LHSIsNull && !RHSIsNull) {
13505 Expr *E = LHS.get();
13506 if (getLangOpts().ObjCAutoRefCount)
13507 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13508 CCK: CheckedConversionKind::Implicit);
13509 LHS = ImpCastExprToType(E, Type: RHSType,
13510 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13511 }
13512 else {
13513 Expr *E = RHS.get();
13514 if (getLangOpts().ObjCAutoRefCount)
13515 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13516 CCK: CheckedConversionKind::Implicit,
13517 /*Diagnose=*/true,
13518 /*DiagnoseCFAudited=*/false, Opc);
13519 RHS = ImpCastExprToType(E, Type: LHSType,
13520 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13521 }
13522 return computeResultTy();
13523 }
13524 if (LHSType->isObjCObjectPointerType() &&
13525 RHSType->isObjCObjectPointerType()) {
13526 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13527 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13528 /*isError*/IsError: false);
13529 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13530 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13531
13532 if (LHSIsNull && !RHSIsNull)
13533 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13534 else
13535 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13536 return computeResultTy();
13537 }
13538
13539 if (!IsOrdered && LHSType->isBlockPointerType() &&
13540 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13541 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13542 CK: CK_BlockPointerToObjCPointerCast);
13543 return computeResultTy();
13544 } else if (!IsOrdered &&
13545 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13546 RHSType->isBlockPointerType()) {
13547 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13548 CK: CK_BlockPointerToObjCPointerCast);
13549 return computeResultTy();
13550 }
13551 }
13552 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13553 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13554 unsigned DiagID = 0;
13555 bool isError = false;
13556 if (LangOpts.DebuggerSupport) {
13557 // Under a debugger, allow the comparison of pointers to integers,
13558 // since users tend to want to compare addresses.
13559 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13560 (RHSIsNull && RHSType->isIntegerType())) {
13561 if (IsOrdered) {
13562 isError = getLangOpts().CPlusPlus;
13563 DiagID =
13564 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13565 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13566 }
13567 } else if (getLangOpts().CPlusPlus) {
13568 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13569 isError = true;
13570 } else if (IsOrdered)
13571 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13572 else
13573 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13574
13575 if (DiagID) {
13576 Diag(Loc, DiagID)
13577 << LHSType << RHSType << LHS.get()->getSourceRange()
13578 << RHS.get()->getSourceRange();
13579 if (isError)
13580 return QualType();
13581 }
13582
13583 if (LHSType->isIntegerType())
13584 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13585 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13586 else
13587 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13588 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13589 return computeResultTy();
13590 }
13591
13592 // Handle block pointers.
13593 if (!IsOrdered && RHSIsNull
13594 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13595 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13596 return computeResultTy();
13597 }
13598 if (!IsOrdered && LHSIsNull
13599 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13600 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13601 return computeResultTy();
13602 }
13603
13604 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13605 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13606 return computeResultTy();
13607 }
13608
13609 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13610 return computeResultTy();
13611 }
13612
13613 if (LHSIsNull && RHSType->isQueueT()) {
13614 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13615 return computeResultTy();
13616 }
13617
13618 if (LHSType->isQueueT() && RHSIsNull) {
13619 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13620 return computeResultTy();
13621 }
13622 }
13623
13624 return InvalidOperands(Loc, LHS, RHS);
13625}
13626
13627QualType Sema::GetSignedVectorType(QualType V) {
13628 const VectorType *VTy = V->castAs<VectorType>();
13629 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13630
13631 if (isa<ExtVectorType>(Val: VTy)) {
13632 if (VTy->isExtVectorBoolType())
13633 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13634 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13635 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13636 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13637 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13638 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13639 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13640 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13641 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13642 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13643 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13644 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13645 "Unhandled vector element size in vector compare");
13646 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13647 }
13648
13649 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13650 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13651 VecKind: VectorKind::Generic);
13652 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13653 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13654 VecKind: VectorKind::Generic);
13655 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13656 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13657 VecKind: VectorKind::Generic);
13658 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13659 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13660 VecKind: VectorKind::Generic);
13661 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13662 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13663 VecKind: VectorKind::Generic);
13664 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13665 "Unhandled vector element size in vector compare");
13666 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13667 VecKind: VectorKind::Generic);
13668}
13669
13670QualType Sema::GetSignedSizelessVectorType(QualType V) {
13671 const BuiltinType *VTy = V->castAs<BuiltinType>();
13672 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13673
13674 const QualType ETy = V->getSveEltType(Ctx: Context);
13675 const auto TypeSize = Context.getTypeSize(T: ETy);
13676
13677 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13678 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13679 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13680}
13681
13682QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13683 SourceLocation Loc,
13684 BinaryOperatorKind Opc) {
13685 if (Opc == BO_Cmp) {
13686 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13687 return QualType();
13688 }
13689
13690 // Check to make sure we're operating on vectors of the same type and width,
13691 // Allowing one side to be a scalar of element type.
13692 QualType vType =
13693 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13694 /*AllowBothBool*/ true,
13695 /*AllowBoolConversions*/ getLangOpts().ZVector,
13696 /*AllowBooleanOperation*/ AllowBoolOperation: true);
13697 if (vType.isNull())
13698 return vType;
13699
13700 QualType LHSType = LHS.get()->getType();
13701
13702 // Determine the return type of a vector compare. By default clang will return
13703 // a scalar for all vector compares except vector bool and vector pixel.
13704 // With the gcc compiler we will always return a vector type and with the xl
13705 // compiler we will always return a scalar type. This switch allows choosing
13706 // which behavior is prefered.
13707 if (getLangOpts().AltiVec) {
13708 switch (getLangOpts().getAltivecSrcCompat()) {
13709 case LangOptions::AltivecSrcCompatKind::Mixed:
13710 // If AltiVec, the comparison results in a numeric type, i.e.
13711 // bool for C++, int for C
13712 if (vType->castAs<VectorType>()->getVectorKind() ==
13713 VectorKind::AltiVecVector)
13714 return Context.getLogicalOperationType();
13715 else
13716 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13717 break;
13718 case LangOptions::AltivecSrcCompatKind::GCC:
13719 // For GCC we always return the vector type.
13720 break;
13721 case LangOptions::AltivecSrcCompatKind::XL:
13722 return Context.getLogicalOperationType();
13723 break;
13724 }
13725 }
13726
13727 // For non-floating point types, check for self-comparisons of the form
13728 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13729 // often indicate logic errors in the program.
13730 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13731
13732 // Check for comparisons of floating point operands using != and ==.
13733 if (LHSType->hasFloatingRepresentation()) {
13734 assert(RHS.get()->getType()->hasFloatingRepresentation());
13735 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13736 }
13737
13738 // Return a signed type for the vector.
13739 return GetSignedVectorType(V: vType);
13740}
13741
13742QualType Sema::CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
13743 SourceLocation Loc,
13744 BinaryOperatorKind Opc) {
13745 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13746 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13747
13748 QualType MatrixTy =
13749 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13750 if (MatrixTy.isNull())
13751 return QualType();
13752
13753 if (!LHS.get()->getType()->isMatrixType()) {
13754 LHS = prepareMatrixSplat(MatrixTy, SplattedExpr: LHS.get());
13755 if (LHS.isInvalid())
13756 return QualType();
13757 LHS = ImpCastExprToType(E: LHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13758 }
13759 if (!RHS.get()->getType()->isMatrixType()) {
13760 RHS = prepareMatrixSplat(MatrixTy, SplattedExpr: RHS.get());
13761 if (RHS.isInvalid())
13762 return QualType();
13763 RHS = ImpCastExprToType(E: RHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13764 }
13765
13766 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13767 return Context.getConstantMatrixType(ElementType: Context.BoolTy, NumRows: MT->getNumRows(),
13768 NumColumns: MT->getNumColumns());
13769}
13770
13771QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13772 ExprResult &RHS,
13773 SourceLocation Loc,
13774 BinaryOperatorKind Opc) {
13775 if (Opc == BO_Cmp) {
13776 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13777 return QualType();
13778 }
13779
13780 // Check to make sure we're operating on vectors of the same type and width,
13781 // Allowing one side to be a scalar of element type.
13782 QualType vType = CheckSizelessVectorOperands(
13783 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13784
13785 if (vType.isNull())
13786 return vType;
13787
13788 QualType LHSType = LHS.get()->getType();
13789
13790 // For non-floating point types, check for self-comparisons of the form
13791 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13792 // often indicate logic errors in the program.
13793 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13794
13795 // Check for comparisons of floating point operands using != and ==.
13796 if (LHSType->hasFloatingRepresentation()) {
13797 assert(RHS.get()->getType()->hasFloatingRepresentation());
13798 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13799 }
13800
13801 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13802 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13803
13804 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13805 RHSBuiltinTy->isSVEBool())
13806 return LHSType;
13807
13808 // Return a signed type for the vector.
13809 return GetSignedSizelessVectorType(V: vType);
13810}
13811
13812static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13813 const ExprResult &XorRHS,
13814 const SourceLocation Loc) {
13815 // Do not diagnose macros.
13816 if (Loc.isMacroID())
13817 return;
13818
13819 // Do not diagnose if both LHS and RHS are macros.
13820 if (XorLHS.get()->getExprLoc().isMacroID() &&
13821 XorRHS.get()->getExprLoc().isMacroID())
13822 return;
13823
13824 bool Negative = false;
13825 bool ExplicitPlus = false;
13826 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13827 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13828
13829 if (!LHSInt)
13830 return;
13831 if (!RHSInt) {
13832 // Check negative literals.
13833 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13834 UnaryOperatorKind Opc = UO->getOpcode();
13835 if (Opc != UO_Minus && Opc != UO_Plus)
13836 return;
13837 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13838 if (!RHSInt)
13839 return;
13840 Negative = (Opc == UO_Minus);
13841 ExplicitPlus = !Negative;
13842 } else {
13843 return;
13844 }
13845 }
13846
13847 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13848 llvm::APInt RightSideValue = RHSInt->getValue();
13849 if (LeftSideValue != 2 && LeftSideValue != 10)
13850 return;
13851
13852 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13853 return;
13854
13855 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13856 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13857 llvm::StringRef ExprStr =
13858 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13859
13860 CharSourceRange XorRange =
13861 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13862 llvm::StringRef XorStr =
13863 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13864 // Do not diagnose if xor keyword/macro is used.
13865 if (XorStr == "xor")
13866 return;
13867
13868 std::string LHSStr = std::string(Lexer::getSourceText(
13869 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13870 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13871 std::string RHSStr = std::string(Lexer::getSourceText(
13872 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13873 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13874
13875 if (Negative) {
13876 RightSideValue = -RightSideValue;
13877 RHSStr = "-" + RHSStr;
13878 } else if (ExplicitPlus) {
13879 RHSStr = "+" + RHSStr;
13880 }
13881
13882 StringRef LHSStrRef = LHSStr;
13883 StringRef RHSStrRef = RHSStr;
13884 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13885 // literals.
13886 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13887 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13888 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13889 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13890 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13891 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13892 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13893 return;
13894
13895 bool SuggestXor =
13896 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13897 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13898 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13899 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13900 std::string SuggestedExpr = "1 << " + RHSStr;
13901 bool Overflow = false;
13902 llvm::APInt One = (LeftSideValue - 1);
13903 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13904 if (Overflow) {
13905 if (RightSideIntValue < 64)
13906 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13907 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13908 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13909 else if (RightSideIntValue == 64)
13910 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13911 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13912 else
13913 return;
13914 } else {
13915 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13916 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13917 << toString(I: PowValue, Radix: 10, Signed: true)
13918 << FixItHint::CreateReplacement(
13919 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13920 }
13921
13922 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13923 << ("0x2 ^ " + RHSStr) << SuggestXor;
13924 } else if (LeftSideValue == 10) {
13925 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13926 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13927 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13928 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13929 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13930 << ("0xA ^ " + RHSStr) << SuggestXor;
13931 }
13932}
13933
13934QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13935 SourceLocation Loc,
13936 BinaryOperatorKind Opc) {
13937 // Ensure that either both operands are of the same vector type, or
13938 // one operand is of a vector type and the other is of its element type.
13939 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13940 /*AllowBothBool*/ true,
13941 /*AllowBoolConversions*/ false,
13942 /*AllowBooleanOperation*/ AllowBoolOperation: false);
13943 if (vType.isNull())
13944 return QualType();
13945 if (getLangOpts().OpenCL &&
13946 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13947 vType->hasFloatingRepresentation())
13948 return InvalidOperands(Loc, LHS, RHS);
13949 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13950 // usage of the logical operators && and || with vectors in C. This
13951 // check could be notionally dropped.
13952 if (!getLangOpts().CPlusPlus &&
13953 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13954 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13955 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13956 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13957 // `select` functions.
13958 if (getLangOpts().HLSL &&
13959 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13960 (void)InvalidOperands(Loc, LHS, RHS);
13961 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13962 return QualType();
13963 }
13964
13965 return GetSignedVectorType(V: LHS.get()->getType());
13966}
13967
13968QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13969 SourceLocation Loc,
13970 BinaryOperatorKind Opc) {
13971
13972 if (!getLangOpts().HLSL) {
13973 SemaRef.Diag(Loc, DiagID: diag::err_matrix_logical_operations_supported_for_hlsl);
13974 return QualType();
13975 }
13976
13977 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13978 (void)InvalidOperands(Loc, LHS, RHS);
13979 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13980 return QualType();
13981 }
13982 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13983 << getLangOpts().getHLSLVersion();
13984 return QualType();
13985}
13986
13987QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13988 SourceLocation Loc,
13989 bool IsCompAssign) {
13990 if (!IsCompAssign) {
13991 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13992 if (LHS.isInvalid())
13993 return QualType();
13994 }
13995 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13996 if (RHS.isInvalid())
13997 return QualType();
13998
13999 // For conversion purposes, we ignore any qualifiers.
14000 // For example, "const float" and "float" are equivalent.
14001 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
14002 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
14003
14004 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
14005 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
14006 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14007
14008 if (Context.hasSameType(T1: LHSType, T2: RHSType))
14009 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
14010
14011 // Type conversion may change LHS/RHS. Keep copies to the original results, in
14012 // case we have to return InvalidOperands.
14013 ExprResult OriginalLHS = LHS;
14014 ExprResult OriginalRHS = RHS;
14015 if (LHSMatType && !RHSMatType) {
14016 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
14017 if (!RHS.isInvalid())
14018 return LHSType;
14019
14020 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
14021 }
14022
14023 if (!LHSMatType && RHSMatType) {
14024 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
14025 if (!LHS.isInvalid())
14026 return RHSType;
14027 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
14028 }
14029
14030 return InvalidOperands(Loc, LHS, RHS);
14031}
14032
14033QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
14034 SourceLocation Loc,
14035 bool IsCompAssign) {
14036 if (!IsCompAssign) {
14037 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
14038 if (LHS.isInvalid())
14039 return QualType();
14040 }
14041 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
14042 if (RHS.isInvalid())
14043 return QualType();
14044
14045 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14046 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14047 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14048
14049 if (LHSMatType && RHSMatType) {
14050 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14051 return InvalidOperands(Loc, LHS, RHS);
14052
14053 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
14054 return Context.getCommonSugaredType(
14055 X: LHS.get()->getType().getUnqualifiedType(),
14056 Y: RHS.get()->getType().getUnqualifiedType());
14057
14058 QualType LHSELTy = LHSMatType->getElementType(),
14059 RHSELTy = RHSMatType->getElementType();
14060 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
14061 return InvalidOperands(Loc, LHS, RHS);
14062
14063 return Context.getConstantMatrixType(
14064 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
14065 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
14066 }
14067 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14068}
14069
14070static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
14071 switch (Opc) {
14072 default:
14073 return false;
14074 case BO_And:
14075 case BO_AndAssign:
14076 case BO_Or:
14077 case BO_OrAssign:
14078 case BO_Xor:
14079 case BO_XorAssign:
14080 return true;
14081 }
14082}
14083
14084inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
14085 SourceLocation Loc,
14086 BinaryOperatorKind Opc) {
14087 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
14088
14089 bool IsCompAssign =
14090 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14091
14092 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14093
14094 if (LHS.get()->getType()->isVectorType() ||
14095 RHS.get()->getType()->isVectorType()) {
14096 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14097 RHS.get()->getType()->hasIntegerRepresentation())
14098 return CheckVectorOperands(
14099 LHS, RHS, Loc, IsCompAssign,
14100 /*AllowBothBool*/ true,
14101 /*AllowBoolConversions*/ getLangOpts().ZVector,
14102 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator);
14103 return InvalidOperands(Loc, LHS, RHS);
14104 }
14105
14106 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14107 RHS.get()->getType()->isSveVLSBuiltinType()) {
14108 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14109 RHS.get()->getType()->hasIntegerRepresentation())
14110 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14111 OperationKind: ArithConvKind::BitwiseOp);
14112 return InvalidOperands(Loc, LHS, RHS);
14113 }
14114
14115 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14116 RHS.get()->getType()->isSveVLSBuiltinType()) {
14117 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14118 RHS.get()->getType()->hasIntegerRepresentation())
14119 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14120 OperationKind: ArithConvKind::BitwiseOp);
14121 return InvalidOperands(Loc, LHS, RHS);
14122 }
14123
14124 if (Opc == BO_And)
14125 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
14126
14127 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14128 RHS.get()->getType()->hasFloatingRepresentation())
14129 return InvalidOperands(Loc, LHS, RHS);
14130
14131 ExprResult LHSResult = LHS, RHSResult = RHS;
14132 QualType compType = UsualArithmeticConversions(
14133 LHS&: LHSResult, RHS&: RHSResult, Loc,
14134 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
14135 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14136 return QualType();
14137 LHS = LHSResult.get();
14138 RHS = RHSResult.get();
14139
14140 if (Opc == BO_Xor)
14141 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
14142
14143 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14144 return compType;
14145 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14146 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14147 return ResultTy;
14148}
14149
14150// C99 6.5.[13,14]
14151inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14152 SourceLocation Loc,
14153 BinaryOperatorKind Opc) {
14154 // Check vector operands differently.
14155 if (LHS.get()->getType()->isVectorType() ||
14156 RHS.get()->getType()->isVectorType())
14157 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14158
14159 if (LHS.get()->getType()->isConstantMatrixType() ||
14160 RHS.get()->getType()->isConstantMatrixType())
14161 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14162
14163 bool EnumConstantInBoolContext = false;
14164 for (const ExprResult &HS : {LHS, RHS}) {
14165 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
14166 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
14167 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14168 EnumConstantInBoolContext = true;
14169 }
14170 }
14171
14172 if (EnumConstantInBoolContext)
14173 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
14174
14175 // WebAssembly tables can't be used with logical operators.
14176 QualType LHSTy = LHS.get()->getType();
14177 QualType RHSTy = RHS.get()->getType();
14178 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
14179 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
14180 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14181 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14182 return InvalidOperands(Loc, LHS, RHS);
14183 }
14184
14185 // Diagnose cases where the user write a logical and/or but probably meant a
14186 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14187 // is a constant.
14188 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14189 !LHS.get()->getType()->isBooleanType() &&
14190 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14191 // Don't warn in macros or template instantiations.
14192 !Loc.isMacroID() && !inTemplateInstantiation()) {
14193 // If the RHS can be constant folded, and if it constant folds to something
14194 // that isn't 0 or 1 (which indicate a potential logical operation that
14195 // happened to fold to true/false) then warn.
14196 // Parens on the RHS are ignored.
14197 Expr::EvalResult EVResult;
14198 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
14199 llvm::APSInt Result = EVResult.Val.getInt();
14200 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14201 !RHS.get()->getExprLoc().isMacroID()) ||
14202 (Result != 0 && Result != 1)) {
14203 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
14204 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14205 // Suggest replacing the logical operator with the bitwise version
14206 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
14207 << (Opc == BO_LAnd ? "&" : "|")
14208 << FixItHint::CreateReplacement(
14209 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
14210 Code: Opc == BO_LAnd ? "&" : "|");
14211 if (Opc == BO_LAnd)
14212 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14213 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
14214 << FixItHint::CreateRemoval(
14215 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
14216 RHS.get()->getEndLoc()));
14217 }
14218 }
14219 }
14220
14221 if (!Context.getLangOpts().CPlusPlus) {
14222 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14223 // not operate on the built-in scalar and vector float types.
14224 if (Context.getLangOpts().OpenCL &&
14225 Context.getLangOpts().OpenCLVersion < 120) {
14226 if (LHS.get()->getType()->isFloatingType() ||
14227 RHS.get()->getType()->isFloatingType())
14228 return InvalidOperands(Loc, LHS, RHS);
14229 }
14230
14231 LHS = UsualUnaryConversions(E: LHS.get());
14232 if (LHS.isInvalid())
14233 return QualType();
14234
14235 RHS = UsualUnaryConversions(E: RHS.get());
14236 if (RHS.isInvalid())
14237 return QualType();
14238
14239 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14240 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
14241 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14242 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
14243
14244 if (!LHS.get()->getType()->isScalarType() ||
14245 !RHS.get()->getType()->isScalarType())
14246 return InvalidOperands(Loc, LHS, RHS);
14247
14248 return Context.IntTy;
14249 }
14250
14251 // The following is safe because we only use this method for
14252 // non-overloadable operands.
14253
14254 // C++ [expr.log.and]p1
14255 // C++ [expr.log.or]p1
14256 // The operands are both contextually converted to type bool.
14257 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14258 if (LHSRes.isInvalid()) {
14259 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14260 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14261 return ResultTy;
14262 }
14263 LHS = LHSRes;
14264
14265 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14266 if (RHSRes.isInvalid()) {
14267 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14268 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14269 return ResultTy;
14270 }
14271 RHS = RHSRes;
14272
14273 // C++ [expr.log.and]p2
14274 // C++ [expr.log.or]p2
14275 // The result is a bool.
14276 return Context.BoolTy;
14277}
14278
14279static bool IsReadonlyMessage(Expr *E, Sema &S) {
14280 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14281 if (!ME) return false;
14282 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14283 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14284 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14285 if (!Base) return false;
14286 return Base->getMethodDecl() != nullptr;
14287}
14288
14289/// Is the given expression (which must be 'const') a reference to a
14290/// variable which was originally non-const, but which has become
14291/// 'const' due to being captured within a block?
14292enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14293static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14294 assert(E->isLValue() && E->getType().isConstQualified());
14295 E = E->IgnoreParens();
14296
14297 // Must be a reference to a declaration from an enclosing scope.
14298 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14299 if (!DRE) return NCCK_None;
14300 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14301
14302 ValueDecl *Value = DRE->getDecl();
14303
14304 // The declaration must be a value which is not declared 'const'.
14305 if (Value->getType().isConstQualified())
14306 return NCCK_None;
14307
14308 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14309 if (Binding) {
14310 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14311 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14312 return NCCK_Lambda;
14313 }
14314
14315 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14316 if (!Var)
14317 return NCCK_None;
14318 if (Var->getType()->isReferenceType())
14319 return NCCK_None;
14320
14321 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14322
14323 // Decide whether the first capture was for a block or a lambda.
14324 DeclContext *DC = S.CurContext, *Prev = nullptr;
14325 // Decide whether the first capture was for a block or a lambda.
14326 while (DC) {
14327 // For init-capture, it is possible that the variable belongs to the
14328 // template pattern of the current context.
14329 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14330 if (Var->isInitCapture() &&
14331 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14332 break;
14333 if (DC == Var->getDeclContext())
14334 break;
14335 Prev = DC;
14336 DC = DC->getParent();
14337 }
14338 // Unless we have an init-capture, we've gone one step too far.
14339 if (!Var->isInitCapture())
14340 DC = Prev;
14341 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14342}
14343
14344static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14345 Ty = Ty.getNonReferenceType();
14346 if (IsDereference && Ty->isPointerType())
14347 Ty = Ty->getPointeeType();
14348 return !Ty.isConstQualified();
14349}
14350
14351// Update err_typecheck_assign_const and note_typecheck_assign_const
14352// when this enum is changed.
14353enum {
14354 ConstFunction,
14355 ConstVariable,
14356 ConstMember,
14357 NestedConstMember,
14358 ConstUnknown, // Keep as last element
14359};
14360
14361/// Emit the "read-only variable not assignable" error and print notes to give
14362/// more information about why the variable is not assignable, such as pointing
14363/// to the declaration of a const variable, showing that a method is const, or
14364/// that the function is returning a const reference.
14365static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14366 SourceLocation Loc) {
14367 SourceRange ExprRange = E->getSourceRange();
14368
14369 // Only emit one error on the first const found. All other consts will emit
14370 // a note to the error.
14371 bool DiagnosticEmitted = false;
14372
14373 // Track if the current expression is the result of a dereference, and if the
14374 // next checked expression is the result of a dereference.
14375 bool IsDereference = false;
14376 bool NextIsDereference = false;
14377
14378 // Loop to process MemberExpr chains.
14379 while (true) {
14380 IsDereference = NextIsDereference;
14381
14382 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14383 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14384 NextIsDereference = ME->isArrow();
14385 const ValueDecl *VD = ME->getMemberDecl();
14386 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14387 // Mutable fields can be modified even if the class is const.
14388 if (Field->isMutable()) {
14389 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14390 break;
14391 }
14392
14393 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14394 if (!DiagnosticEmitted) {
14395 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14396 << ExprRange << ConstMember << false /*static*/ << Field
14397 << Field->getType();
14398 DiagnosticEmitted = true;
14399 }
14400 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14401 << ConstMember << false /*static*/ << Field << Field->getType()
14402 << Field->getSourceRange();
14403 }
14404 E = ME->getBase();
14405 continue;
14406 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14407 if (VDecl->getType().isConstQualified()) {
14408 if (!DiagnosticEmitted) {
14409 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14410 << ExprRange << ConstMember << true /*static*/ << VDecl
14411 << VDecl->getType();
14412 DiagnosticEmitted = true;
14413 }
14414 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14415 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14416 << VDecl->getSourceRange();
14417 }
14418 // Static fields do not inherit constness from parents.
14419 break;
14420 }
14421 break; // End MemberExpr
14422 } else if (const ArraySubscriptExpr *ASE =
14423 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14424 E = ASE->getBase()->IgnoreParenImpCasts();
14425 continue;
14426 } else if (const ExtVectorElementExpr *EVE =
14427 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14428 E = EVE->getBase()->IgnoreParenImpCasts();
14429 continue;
14430 }
14431 break;
14432 }
14433
14434 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14435 // Function calls
14436 const FunctionDecl *FD = CE->getDirectCallee();
14437 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14438 if (!DiagnosticEmitted) {
14439 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14440 << ConstFunction << FD;
14441 DiagnosticEmitted = true;
14442 }
14443 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14444 DiagID: diag::note_typecheck_assign_const)
14445 << ConstFunction << FD << FD->getReturnType()
14446 << FD->getReturnTypeSourceRange();
14447 }
14448 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14449 // Point to variable declaration.
14450 if (const ValueDecl *VD = DRE->getDecl()) {
14451 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14452 if (!DiagnosticEmitted) {
14453 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14454 << ExprRange << ConstVariable << VD << VD->getType();
14455 DiagnosticEmitted = true;
14456 }
14457 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14458 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14459 }
14460 }
14461 } else if (isa<CXXThisExpr>(Val: E)) {
14462 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14463 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14464 if (MD->isConst()) {
14465 if (!DiagnosticEmitted) {
14466 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14467 << ExprRange << MD;
14468 DiagnosticEmitted = true;
14469 }
14470 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14471 << MD << MD->getSourceRange();
14472 }
14473 }
14474 }
14475 }
14476
14477 if (DiagnosticEmitted)
14478 return;
14479
14480 // Can't determine a more specific message, so display the generic error.
14481 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14482}
14483
14484enum OriginalExprKind {
14485 OEK_Variable,
14486 OEK_Member,
14487 OEK_LValue
14488};
14489
14490static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14491 const RecordType *Ty,
14492 SourceLocation Loc, SourceRange Range,
14493 OriginalExprKind OEK,
14494 bool &DiagnosticEmitted) {
14495 std::vector<const RecordType *> RecordTypeList;
14496 RecordTypeList.push_back(x: Ty);
14497 unsigned NextToCheckIndex = 0;
14498 // We walk the record hierarchy breadth-first to ensure that we print
14499 // diagnostics in field nesting order.
14500 while (RecordTypeList.size() > NextToCheckIndex) {
14501 bool IsNested = NextToCheckIndex > 0;
14502 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14503 ->getDecl()
14504 ->getDefinitionOrSelf()
14505 ->fields()) {
14506 // First, check every field for constness.
14507 QualType FieldTy = Field->getType();
14508 if (FieldTy.isConstQualified()) {
14509 if (!DiagnosticEmitted) {
14510 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14511 << Range << NestedConstMember << OEK << VD
14512 << IsNested << Field;
14513 DiagnosticEmitted = true;
14514 }
14515 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14516 << NestedConstMember << IsNested << Field
14517 << FieldTy << Field->getSourceRange();
14518 }
14519
14520 // Then we append it to the list to check next in order.
14521 FieldTy = FieldTy.getCanonicalType();
14522 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14523 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14524 RecordTypeList.push_back(x: FieldRecTy);
14525 }
14526 }
14527 ++NextToCheckIndex;
14528 }
14529}
14530
14531/// Emit an error for the case where a record we are trying to assign to has a
14532/// const-qualified field somewhere in its hierarchy.
14533static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14534 SourceLocation Loc) {
14535 QualType Ty = E->getType();
14536 assert(Ty->isRecordType() && "lvalue was not record?");
14537 SourceRange Range = E->getSourceRange();
14538 const auto *RTy = Ty->getAsCanonical<RecordType>();
14539 bool DiagEmitted = false;
14540
14541 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14542 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14543 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14544 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14545 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14546 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14547 else
14548 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14549 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14550 if (!DiagEmitted)
14551 DiagnoseConstAssignment(S, E, Loc);
14552}
14553
14554/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14555/// emit an error and return true. If so, return false.
14556static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14557 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14558
14559 S.CheckShadowingDeclModification(E, Loc);
14560
14561 SourceLocation OrigLoc = Loc;
14562 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14563 Loc: &Loc);
14564 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14565 IsLV = Expr::MLV_InvalidMessageExpression;
14566 if (IsLV == Expr::MLV_Valid)
14567 return false;
14568
14569 unsigned DiagID = 0;
14570 bool NeedType = false;
14571 switch (IsLV) { // C99 6.5.16p2
14572 case Expr::MLV_ConstQualified:
14573 // Use a specialized diagnostic when we're assigning to an object
14574 // from an enclosing function or block.
14575 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14576 if (NCCK == NCCK_Block)
14577 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14578 else
14579 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14580 break;
14581 }
14582
14583 // In ARC, use some specialized diagnostics for occasions where we
14584 // infer 'const'. These are always pseudo-strong variables.
14585 if (S.getLangOpts().ObjCAutoRefCount) {
14586 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14587 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14588 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14589
14590 // Use the normal diagnostic if it's pseudo-__strong but the
14591 // user actually wrote 'const'.
14592 if (var->isARCPseudoStrong() &&
14593 (!var->getTypeSourceInfo() ||
14594 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14595 // There are three pseudo-strong cases:
14596 // - self
14597 ObjCMethodDecl *method = S.getCurMethodDecl();
14598 if (method && var == method->getSelfDecl()) {
14599 DiagID = method->isClassMethod()
14600 ? diag::err_typecheck_arc_assign_self_class_method
14601 : diag::err_typecheck_arc_assign_self;
14602
14603 // - Objective-C externally_retained attribute.
14604 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14605 isa<ParmVarDecl>(Val: var)) {
14606 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14607
14608 // - fast enumeration variables
14609 } else {
14610 DiagID = diag::err_typecheck_arr_assign_enumeration;
14611 }
14612
14613 SourceRange Assign;
14614 if (Loc != OrigLoc)
14615 Assign = SourceRange(OrigLoc, OrigLoc);
14616 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14617 // We need to preserve the AST regardless, so migration tool
14618 // can do its job.
14619 return false;
14620 }
14621 }
14622 }
14623
14624 // If none of the special cases above are triggered, then this is a
14625 // simple const assignment.
14626 if (DiagID == 0) {
14627 DiagnoseConstAssignment(S, E, Loc);
14628 return true;
14629 }
14630
14631 break;
14632 case Expr::MLV_ConstAddrSpace:
14633 DiagnoseConstAssignment(S, E, Loc);
14634 return true;
14635 case Expr::MLV_ConstQualifiedField:
14636 DiagnoseRecursiveConstFields(S, E, Loc);
14637 return true;
14638 case Expr::MLV_ArrayType:
14639 case Expr::MLV_ArrayTemporary:
14640 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14641 NeedType = true;
14642 break;
14643 case Expr::MLV_NotObjectType:
14644 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14645 NeedType = true;
14646 break;
14647 case Expr::MLV_LValueCast:
14648 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14649 break;
14650 case Expr::MLV_Valid:
14651 llvm_unreachable("did not take early return for MLV_Valid");
14652 case Expr::MLV_InvalidExpression:
14653 case Expr::MLV_MemberFunction:
14654 case Expr::MLV_ClassTemporary: {
14655 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E)) {
14656 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14657 if (UnaryOp->getOpcode() == UO_Imag &&
14658 !Op->getType()->isAnyComplexType()) {
14659 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14660 NeedType = true;
14661 break;
14662 }
14663 }
14664
14665 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14666 break;
14667 }
14668 case Expr::MLV_IncompleteType:
14669 case Expr::MLV_IncompleteVoidType:
14670 return S.RequireCompleteType(Loc, T: E->getType(),
14671 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14672 case Expr::MLV_DuplicateVectorComponents:
14673 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14674 break;
14675 case Expr::MLV_DuplicateMatrixComponents:
14676 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14677 break;
14678 case Expr::MLV_NoSetterProperty:
14679 llvm_unreachable("readonly properties should be processed differently");
14680 case Expr::MLV_InvalidMessageExpression:
14681 DiagID = diag::err_readonly_message_assignment;
14682 break;
14683 case Expr::MLV_SubObjCPropertySetting:
14684 DiagID = diag::err_no_subobject_property_setting;
14685 break;
14686 }
14687
14688 SourceRange Assign;
14689 if (Loc != OrigLoc)
14690 Assign = SourceRange(OrigLoc, OrigLoc);
14691 if (NeedType)
14692 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14693 else
14694 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14695 return true;
14696}
14697
14698static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14699 SourceLocation Loc,
14700 Sema &Sema) {
14701 if (Sema.inTemplateInstantiation())
14702 return;
14703 if (Sema.isUnevaluatedContext())
14704 return;
14705 if (Loc.isInvalid() || Loc.isMacroID())
14706 return;
14707 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14708 return;
14709
14710 // C / C++ fields
14711 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14712 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14713 if (ML && MR) {
14714 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14715 return;
14716 const ValueDecl *LHSDecl =
14717 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14718 const ValueDecl *RHSDecl =
14719 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14720 if (LHSDecl != RHSDecl)
14721 return;
14722 if (LHSDecl->getType().isVolatileQualified())
14723 return;
14724 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14725 if (RefTy->getPointeeType().isVolatileQualified())
14726 return;
14727
14728 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14729 }
14730
14731 // Objective-C instance variables
14732 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14733 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14734 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14735 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14736 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14737 if (RL && RR && RL->getDecl() == RR->getDecl())
14738 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14739 }
14740}
14741
14742// C99 6.5.16.1
14743QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14744 SourceLocation Loc,
14745 QualType CompoundType,
14746 BinaryOperatorKind Opc) {
14747 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14748
14749 // Verify that LHS is a modifiable lvalue, and emit error if not.
14750 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14751 return QualType();
14752
14753 QualType LHSType = LHSExpr->getType();
14754 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14755 CompoundType;
14756
14757 if (RHS.isUsable()) {
14758 // Even if this check fails don't return early to allow the best
14759 // possible error recovery and to allow any subsequent diagnostics to
14760 // work.
14761 const ValueDecl *Assignee = nullptr;
14762 bool ShowFullyQualifiedAssigneeName = false;
14763 // In simple cases describe what is being assigned to
14764 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14765 Assignee = DR->getDecl();
14766 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14767 Assignee = ME->getMemberDecl();
14768 ShowFullyQualifiedAssigneeName = true;
14769 }
14770
14771 BoundsSafetyCheckAssignmentToCountAttrPtr(
14772 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14773 ShowFullyQualifiedAssigneeName);
14774 }
14775
14776 // OpenCL v1.2 s6.1.1.1 p2:
14777 // The half data type can only be used to declare a pointer to a buffer that
14778 // contains half values
14779 if (getLangOpts().OpenCL &&
14780 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14781 LHSType->isHalfType()) {
14782 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14783 << LHSType.getUnqualifiedType();
14784 return QualType();
14785 }
14786
14787 // WebAssembly tables can't be used on RHS of an assignment expression.
14788 if (RHSType->isWebAssemblyTableType()) {
14789 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14790 return QualType();
14791 }
14792
14793 AssignConvertType ConvTy;
14794 if (CompoundType.isNull()) {
14795 Expr *RHSCheck = RHS.get();
14796
14797 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14798
14799 QualType LHSTy(LHSType);
14800 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14801 if (RHS.isInvalid())
14802 return QualType();
14803 // Special case of NSObject attributes on c-style pointer types.
14804 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14805 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14806 RHSType->isObjCObjectPointerType()) ||
14807 (Context.isObjCNSObjectType(Ty: RHSType) &&
14808 LHSType->isObjCObjectPointerType())))
14809 ConvTy = AssignConvertType::Compatible;
14810
14811 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14812 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14813
14814 // If the RHS is a unary plus or minus, check to see if they = and + are
14815 // right next to each other. If so, the user may have typo'd "x =+ 4"
14816 // instead of "x += 4".
14817 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14818 RHSCheck = ICE->getSubExpr();
14819 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14820 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14821 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14822 // Only if the two operators are exactly adjacent.
14823 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14824 // And there is a space or other character before the subexpr of the
14825 // unary +/-. We don't want to warn on "x=-1".
14826 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14827 UO->getSubExpr()->getBeginLoc().isFileID()) {
14828 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14829 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14830 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14831 }
14832 }
14833
14834 if (IsAssignConvertCompatible(ConvTy)) {
14835 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14836 // Warn about retain cycles where a block captures the LHS, but
14837 // not if the LHS is a simple variable into which the block is
14838 // being stored...unless that variable can be captured by reference!
14839 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14840 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14841 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14842 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14843 }
14844
14845 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14846 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14847 // It is safe to assign a weak reference into a strong variable.
14848 // Although this code can still have problems:
14849 // id x = self.weakProp;
14850 // id y = self.weakProp;
14851 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14852 // paths through the function. This should be revisited if
14853 // -Wrepeated-use-of-weak is made flow-sensitive.
14854 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14855 // variable, which will be valid for the current autorelease scope.
14856 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14857 Loc: RHS.get()->getBeginLoc()))
14858 getCurFunction()->markSafeWeakUse(E: RHS.get());
14859
14860 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14861 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14862 }
14863 }
14864 } else {
14865 // Compound assignment "x += y"
14866 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14867 }
14868
14869 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14870 Action: AssignmentAction::Assigning))
14871 return QualType();
14872
14873 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14874
14875 AssignedEntity AE{.LHS: LHSExpr};
14876 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14877
14878 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14879 if (CompoundType.isNull()) {
14880 // C++2a [expr.ass]p5:
14881 // A simple-assignment whose left operand is of a volatile-qualified
14882 // type is deprecated unless the assignment is either a discarded-value
14883 // expression or an unevaluated operand
14884 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14885 }
14886 }
14887
14888 // C11 6.5.16p3: The type of an assignment expression is the type of the
14889 // left operand would have after lvalue conversion.
14890 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14891 // qualified type, the value has the unqualified version of the type of the
14892 // lvalue; additionally, if the lvalue has atomic type, the value has the
14893 // non-atomic version of the type of the lvalue.
14894 // C++ 5.17p1: the type of the assignment expression is that of its left
14895 // operand.
14896 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14897}
14898
14899// Scenarios to ignore if expression E is:
14900// 1. an explicit cast expression into void
14901// 2. a function call expression that returns void
14902static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14903 E = E->IgnoreParens();
14904
14905 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14906 if (CE->getCastKind() == CK_ToVoid) {
14907 return true;
14908 }
14909
14910 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14911 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14912 CE->getSubExpr()->getType()->isDependentType()) {
14913 return true;
14914 }
14915 }
14916
14917 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14918 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14919 return false;
14920}
14921
14922void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14923 // No warnings in macros
14924 if (Loc.isMacroID())
14925 return;
14926
14927 // Don't warn in template instantiations.
14928 if (inTemplateInstantiation())
14929 return;
14930
14931 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14932 // instead, skip more than needed, then call back into here with the
14933 // CommaVisitor in SemaStmt.cpp.
14934 // The listed locations are the initialization and increment portions
14935 // of a for loop. The additional checks are on the condition of
14936 // if statements, do/while loops, and for loops.
14937 if (getCurScope()->isControlScope())
14938 return;
14939
14940 // If there are multiple comma operators used together, get the RHS of the
14941 // of the comma operator as the LHS.
14942 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14943 if (BO->getOpcode() != BO_Comma)
14944 break;
14945 LHS = BO->getRHS();
14946 }
14947
14948 // Only allow some expressions on LHS to not warn.
14949 if (IgnoreCommaOperand(E: LHS, Context))
14950 return;
14951
14952 Diag(Loc, DiagID: diag::warn_comma_operator);
14953 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14954 << LHS->getSourceRange()
14955 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14956 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14957 : "(void)(")
14958 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14959 Code: ")");
14960}
14961
14962// C99 6.5.17
14963static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14964 SourceLocation Loc) {
14965 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14966 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14967 if (LHS.isInvalid() || RHS.isInvalid())
14968 return QualType();
14969
14970 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14971 // operands, but not unary promotions.
14972 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14973
14974 // So we treat the LHS as a ignored value, and in C++ we allow the
14975 // containing site to determine what should be done with the RHS.
14976 LHS = S.IgnoredValueConversions(E: LHS.get());
14977 if (LHS.isInvalid())
14978 return QualType();
14979
14980 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14981
14982 if (!S.getLangOpts().CPlusPlus) {
14983 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14984 if (RHS.isInvalid())
14985 return QualType();
14986 if (!RHS.get()->getType()->isVoidType())
14987 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14988 DiagID: diag::err_incomplete_type);
14989 }
14990
14991 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14992 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14993
14994 return RHS.get()->getType();
14995}
14996
14997/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14998/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14999static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
15000 ExprValueKind &VK,
15001 ExprObjectKind &OK,
15002 SourceLocation OpLoc, bool IsInc,
15003 bool IsPrefix) {
15004 QualType ResType = Op->getType();
15005 // Atomic types can be used for increment / decrement where the non-atomic
15006 // versions can, so ignore the _Atomic() specifier for the purpose of
15007 // checking.
15008 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
15009 ResType = ResAtomicType->getValueType();
15010
15011 assert(!ResType.isNull() && "no type for increment/decrement expression");
15012
15013 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
15014 // Decrement of bool is not allowed.
15015 if (!IsInc) {
15016 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
15017 return QualType();
15018 }
15019 // Increment of bool sets it to true, but is deprecated.
15020 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
15021 : diag::warn_increment_bool)
15022 << Op->getSourceRange();
15023 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
15024 // Error on enum increments and decrements in C++ mode
15025 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
15026 return QualType();
15027 } else if (ResType->isRealType()) {
15028 // OK!
15029 } else if (ResType->isPointerType()) {
15030 // C99 6.5.2.4p2, 6.5.6p2
15031 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
15032 return QualType();
15033 } else if (ResType->isOverflowBehaviorType()) {
15034 // OK!
15035 } else if (ResType->isObjCObjectPointerType()) {
15036 // On modern runtimes, ObjC pointer arithmetic is forbidden.
15037 // Otherwise, we just need a complete type.
15038 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
15039 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
15040 return QualType();
15041 } else if (ResType->isAnyComplexType()) {
15042 // C99 does not support ++/-- on complex types, we allow as an extension.
15043 S.DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::increment_complex)
15044 << IsInc << Op->getSourceRange();
15045 } else if (ResType->isPlaceholderType()) {
15046 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15047 if (PR.isInvalid()) return QualType();
15048 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
15049 IsInc, IsPrefix);
15050 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15051 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15052 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15053 (ResType->castAs<VectorType>()->getVectorKind() !=
15054 VectorKind::AltiVecBool)) {
15055 // The z vector extensions allow ++ and -- for non-bool vectors.
15056 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15057 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15058 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15059 } else {
15060 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
15061 << ResType << int(IsInc) << Op->getSourceRange();
15062 return QualType();
15063 }
15064 // At this point, we know we have a real, complex or pointer type.
15065 // Now make sure the operand is a modifiable lvalue.
15066 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
15067 return QualType();
15068 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15069 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15070 // An operand with volatile-qualified type is deprecated
15071 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
15072 << IsInc << ResType;
15073 }
15074 // In C++, a prefix increment is the same type as the operand. Otherwise
15075 // (in C or with postfix), the increment is the unqualified type of the
15076 // operand.
15077 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15078 VK = VK_LValue;
15079 OK = Op->getObjectKind();
15080 return ResType;
15081 } else {
15082 VK = VK_PRValue;
15083 return ResType.getUnqualifiedType();
15084 }
15085}
15086
15087/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15088/// This routine allows us to typecheck complex/recursive expressions
15089/// where the declaration is needed for type checking. We only need to
15090/// handle cases when the expression references a function designator
15091/// or is an lvalue. Here are some examples:
15092/// - &(x) => x
15093/// - &*****f => f for f a function designator.
15094/// - &s.xx => s
15095/// - &s.zz[1].yy -> s, if zz is an array
15096/// - *(x + 1) -> x, if x is an array
15097/// - &"123"[2] -> 0
15098/// - & __real__ x -> x
15099///
15100/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15101/// members.
15102static ValueDecl *getPrimaryDecl(Expr *E) {
15103 switch (E->getStmtClass()) {
15104 case Stmt::DeclRefExprClass:
15105 return cast<DeclRefExpr>(Val: E)->getDecl();
15106 case Stmt::MemberExprClass:
15107 // If this is an arrow operator, the address is an offset from
15108 // the base's value, so the object the base refers to is
15109 // irrelevant.
15110 if (cast<MemberExpr>(Val: E)->isArrow())
15111 return nullptr;
15112 // Otherwise, the expression refers to a part of the base
15113 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
15114 case Stmt::ArraySubscriptExprClass: {
15115 // FIXME: This code shouldn't be necessary! We should catch the implicit
15116 // promotion of register arrays earlier.
15117 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
15118 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
15119 if (ICE->getSubExpr()->getType()->isArrayType())
15120 return getPrimaryDecl(E: ICE->getSubExpr());
15121 }
15122 return nullptr;
15123 }
15124 case Stmt::UnaryOperatorClass: {
15125 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
15126
15127 switch(UO->getOpcode()) {
15128 case UO_Real:
15129 case UO_Imag:
15130 case UO_Extension:
15131 return getPrimaryDecl(E: UO->getSubExpr());
15132 default:
15133 return nullptr;
15134 }
15135 }
15136 case Stmt::ParenExprClass:
15137 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
15138 case Stmt::ImplicitCastExprClass:
15139 // If the result of an implicit cast is an l-value, we care about
15140 // the sub-expression; otherwise, the result here doesn't matter.
15141 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
15142 case Stmt::CXXUuidofExprClass:
15143 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
15144 default:
15145 return nullptr;
15146 }
15147}
15148
15149namespace {
15150enum {
15151 AO_Bit_Field = 0,
15152 AO_Vector_Element = 1,
15153 AO_Property_Expansion = 2,
15154 AO_Register_Variable = 3,
15155 AO_Matrix_Element = 4,
15156 AO_No_Error = 5
15157};
15158}
15159/// Diagnose invalid operand for address of operations.
15160///
15161/// \param Type The type of operand which cannot have its address taken.
15162static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
15163 Expr *E, unsigned Type) {
15164 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
15165}
15166
15167bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
15168 const Expr *Op,
15169 const CXXMethodDecl *MD) {
15170 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
15171
15172 if (Op != DRE)
15173 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
15174 << Op->getSourceRange();
15175
15176 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15177 if (isa<CXXDestructorDecl>(Val: MD))
15178 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
15179 << DRE->getSourceRange();
15180
15181 if (DRE->getQualifier())
15182 return false;
15183
15184 if (MD->getParent()->getName().empty())
15185 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15186 << DRE->getSourceRange();
15187
15188 SmallString<32> Str;
15189 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
15190 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15191 << DRE->getSourceRange()
15192 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
15193}
15194
15195QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15196 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15197 if (PTy->getKind() == BuiltinType::Overload) {
15198 Expr *E = OrigOp.get()->IgnoreParens();
15199 if (!isa<OverloadExpr>(Val: E)) {
15200 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15201 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15202 << OrigOp.get()->getSourceRange();
15203 return QualType();
15204 }
15205
15206 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
15207 if (isa<UnresolvedMemberExpr>(Val: Ovl))
15208 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
15209 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15210 << OrigOp.get()->getSourceRange();
15211 return QualType();
15212 }
15213
15214 return Context.OverloadTy;
15215 }
15216
15217 if (PTy->getKind() == BuiltinType::UnknownAny)
15218 return Context.UnknownAnyTy;
15219
15220 if (PTy->getKind() == BuiltinType::BoundMember) {
15221 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15222 << OrigOp.get()->getSourceRange();
15223 return QualType();
15224 }
15225
15226 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15227 if (OrigOp.isInvalid()) return QualType();
15228 }
15229
15230 if (OrigOp.get()->isTypeDependent())
15231 return Context.DependentTy;
15232
15233 assert(!OrigOp.get()->hasPlaceholderType());
15234
15235 // Make sure to ignore parentheses in subsequent checks
15236 Expr *op = OrigOp.get()->IgnoreParens();
15237
15238 // In OpenCL captures for blocks called as lambda functions
15239 // are located in the private address space. Blocks used in
15240 // enqueue_kernel can be located in a different address space
15241 // depending on a vendor implementation. Thus preventing
15242 // taking an address of the capture to avoid invalid AS casts.
15243 if (LangOpts.OpenCL) {
15244 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15245 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15246 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
15247 return QualType();
15248 }
15249 }
15250
15251 if (getLangOpts().C99) {
15252 // Implement C99-only parts of addressof rules.
15253 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15254 if (uOp->getOpcode() == UO_Deref)
15255 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15256 // (assuming the deref expression is valid).
15257 return uOp->getSubExpr()->getType();
15258 }
15259 // Technically, there should be a check for array subscript
15260 // expressions here, but the result of one is always an lvalue anyway.
15261 }
15262 ValueDecl *dcl = getPrimaryDecl(E: op);
15263
15264 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15265 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15266 Loc: op->getBeginLoc()))
15267 return QualType();
15268
15269 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15270 unsigned AddressOfError = AO_No_Error;
15271
15272 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15273 bool IsError = isSFINAEContext();
15274 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15275 : diag::ext_typecheck_addrof_temporary)
15276 << op->getType() << op->getSourceRange();
15277 if (IsError)
15278 return QualType();
15279 // Materialize the temporary as an lvalue so that we can take its address.
15280 OrigOp = op =
15281 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15282 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15283 return Context.getPointerType(T: op->getType());
15284 } else if (lval == Expr::LV_MemberFunction) {
15285 // If it's an instance method, make a member pointer.
15286 // The expression must have exactly the form &A::foo.
15287
15288 // If the underlying expression isn't a decl ref, give up.
15289 if (!isa<DeclRefExpr>(Val: op)) {
15290 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15291 << OrigOp.get()->getSourceRange();
15292 return QualType();
15293 }
15294 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15295 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15296
15297 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15298 QualType MPTy = Context.getMemberPointerType(
15299 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15300
15301 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15302 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15303 // When pointer authentication is enabled, argument and return types of
15304 // vitual member functions must be complete. This is because vitrual
15305 // member function pointers are implemented using virtual dispatch
15306 // thunks and the thunks cannot be emitted if the argument or return
15307 // types are incomplete.
15308 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15309 SourceLocation DeclRefLoc,
15310 SourceLocation RetArgTypeLoc) {
15311 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15312 Diag(Loc: DeclRefLoc,
15313 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15314 Diag(Loc: RetArgTypeLoc,
15315 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15316 << T;
15317 return true;
15318 }
15319 return false;
15320 };
15321 QualType RetTy = MD->getReturnType();
15322 bool IsIncomplete =
15323 !RetTy->isVoidType() &&
15324 ReturnOrParamTypeIsIncomplete(
15325 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15326 for (auto *PVD : MD->parameters())
15327 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15328 PVD->getBeginLoc());
15329 if (IsIncomplete)
15330 return QualType();
15331 }
15332
15333 // Under the MS ABI, lock down the inheritance model now.
15334 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15335 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15336 return MPTy;
15337 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15338 // C99 6.5.3.2p1
15339 // The operand must be either an l-value or a function designator
15340 if (!op->getType()->isFunctionType()) {
15341 // Use a special diagnostic for loads from property references.
15342 if (isa<PseudoObjectExpr>(Val: op)) {
15343 AddressOfError = AO_Property_Expansion;
15344 } else {
15345 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15346 << op->getType() << op->getSourceRange();
15347 return QualType();
15348 }
15349 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15350 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15351 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15352 }
15353
15354 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15355 // The operand cannot be a bit-field
15356 AddressOfError = AO_Bit_Field;
15357 } else if (op->getObjectKind() == OK_VectorComponent) {
15358 // The operand cannot be an element of a vector
15359 AddressOfError = AO_Vector_Element;
15360 } else if (op->getObjectKind() == OK_MatrixComponent) {
15361 // The operand cannot be an element of a matrix.
15362 AddressOfError = AO_Matrix_Element;
15363 } else if (dcl) { // C99 6.5.3.2p1
15364 // We have an lvalue with a decl. Make sure the decl is not declared
15365 // with the register storage-class specifier.
15366 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15367 // in C++ it is not error to take address of a register
15368 // variable (c++03 7.1.1P3)
15369 if (vd->getStorageClass() == SC_Register &&
15370 !getLangOpts().CPlusPlus) {
15371 AddressOfError = AO_Register_Variable;
15372 }
15373 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15374 AddressOfError = AO_Property_Expansion;
15375 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15376 return Context.OverloadTy;
15377 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15378 // Okay: we can take the address of a field.
15379 // Could be a pointer to member, though, if there is an explicit
15380 // scope qualifier for the class.
15381
15382 // [C++26] [expr.prim.id.general]
15383 // If an id-expression E denotes a non-static non-type member
15384 // of some class C [...] and if E is a qualified-id, E is
15385 // not the un-parenthesized operand of the unary & operator [...]
15386 // the id-expression is transformed into a class member access expression.
15387 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15388 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15389 DeclContext *Ctx = dcl->getDeclContext();
15390 if (Ctx && Ctx->isRecord()) {
15391 if (dcl->getType()->isReferenceType()) {
15392 Diag(Loc: OpLoc,
15393 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15394 << dcl->getDeclName() << dcl->getType();
15395 return QualType();
15396 }
15397
15398 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15399 Ctx = Ctx->getParent();
15400
15401 QualType MPTy = Context.getMemberPointerType(
15402 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15403 // Under the MS ABI, lock down the inheritance model now.
15404 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15405 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15406 return MPTy;
15407 }
15408 }
15409 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15410 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15411 UnnamedGlobalConstantDecl>(Val: dcl))
15412 llvm_unreachable("Unknown/unexpected decl type");
15413 }
15414
15415 if (AddressOfError != AO_No_Error) {
15416 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15417 return QualType();
15418 }
15419
15420 if (lval == Expr::LV_IncompleteVoidType) {
15421 // Taking the address of a void variable is technically illegal, but we
15422 // allow it in cases which are otherwise valid.
15423 // Example: "extern void x; void* y = &x;".
15424 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15425 }
15426
15427 // If the operand has type "type", the result has type "pointer to type".
15428 if (op->getType()->isObjCObjectType())
15429 return Context.getObjCObjectPointerType(OIT: op->getType());
15430
15431 // Cannot take the address of WebAssembly references or tables.
15432 if (Context.getTargetInfo().getTriple().isWasm()) {
15433 QualType OpTy = op->getType();
15434 if (OpTy.isWebAssemblyReferenceType()) {
15435 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15436 << 1 << OrigOp.get()->getSourceRange();
15437 return QualType();
15438 }
15439 if (OpTy->isWebAssemblyTableType()) {
15440 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15441 << 1 << OrigOp.get()->getSourceRange();
15442 return QualType();
15443 }
15444 }
15445
15446 CheckAddressOfPackedMember(rhs: op);
15447
15448 return Context.getPointerType(T: op->getType());
15449}
15450
15451static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15452 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15453 if (!DRE)
15454 return;
15455 const Decl *D = DRE->getDecl();
15456 if (!D)
15457 return;
15458 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15459 if (!Param)
15460 return;
15461 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15462 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15463 return;
15464 if (FunctionScopeInfo *FD = S.getCurFunction())
15465 FD->ModifiedNonNullParams.insert(Ptr: Param);
15466}
15467
15468/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15469static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15470 SourceLocation OpLoc,
15471 bool IsAfterAmp = false) {
15472 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15473 if (ConvResult.isInvalid())
15474 return QualType();
15475 Op = ConvResult.get();
15476 QualType OpTy = Op->getType();
15477 QualType Result;
15478
15479 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15480 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15481 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15482 Range: Op->getSourceRange());
15483 }
15484
15485 if (const PointerType *PT = OpTy->getAs<PointerType>())
15486 {
15487 Result = PT->getPointeeType();
15488 }
15489 else if (const ObjCObjectPointerType *OPT =
15490 OpTy->getAs<ObjCObjectPointerType>())
15491 Result = OPT->getPointeeType();
15492 else {
15493 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15494 if (PR.isInvalid()) return QualType();
15495 if (PR.get() != Op)
15496 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15497 }
15498
15499 if (Result.isNull()) {
15500 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15501 << OpTy << Op->getSourceRange();
15502 return QualType();
15503 }
15504
15505 if (Result->isVoidType()) {
15506 // C++ [expr.unary.op]p1:
15507 // [...] the expression to which [the unary * operator] is applied shall
15508 // be a pointer to an object type, or a pointer to a function type
15509 LangOptions LO = S.getLangOpts();
15510 if (LO.CPlusPlus)
15511 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15512 << OpTy << Op->getSourceRange();
15513 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15514 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15515 << OpTy << Op->getSourceRange();
15516 }
15517
15518 // Dereferences are usually l-values...
15519 VK = VK_LValue;
15520
15521 // ...except that certain expressions are never l-values in C.
15522 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15523 VK = VK_PRValue;
15524
15525 return Result;
15526}
15527
15528BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15529 BinaryOperatorKind Opc;
15530 switch (Kind) {
15531 default: llvm_unreachable("Unknown binop!");
15532 case tok::periodstar: Opc = BO_PtrMemD; break;
15533 case tok::arrowstar: Opc = BO_PtrMemI; break;
15534 case tok::star: Opc = BO_Mul; break;
15535 case tok::slash: Opc = BO_Div; break;
15536 case tok::percent: Opc = BO_Rem; break;
15537 case tok::plus: Opc = BO_Add; break;
15538 case tok::minus: Opc = BO_Sub; break;
15539 case tok::lessless: Opc = BO_Shl; break;
15540 case tok::greatergreater: Opc = BO_Shr; break;
15541 case tok::lessequal: Opc = BO_LE; break;
15542 case tok::less: Opc = BO_LT; break;
15543 case tok::greaterequal: Opc = BO_GE; break;
15544 case tok::greater: Opc = BO_GT; break;
15545 case tok::exclaimequal: Opc = BO_NE; break;
15546 case tok::equalequal: Opc = BO_EQ; break;
15547 case tok::spaceship: Opc = BO_Cmp; break;
15548 case tok::amp: Opc = BO_And; break;
15549 case tok::caret: Opc = BO_Xor; break;
15550 case tok::pipe: Opc = BO_Or; break;
15551 case tok::ampamp: Opc = BO_LAnd; break;
15552 case tok::pipepipe: Opc = BO_LOr; break;
15553 case tok::equal: Opc = BO_Assign; break;
15554 case tok::starequal: Opc = BO_MulAssign; break;
15555 case tok::slashequal: Opc = BO_DivAssign; break;
15556 case tok::percentequal: Opc = BO_RemAssign; break;
15557 case tok::plusequal: Opc = BO_AddAssign; break;
15558 case tok::minusequal: Opc = BO_SubAssign; break;
15559 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15560 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15561 case tok::ampequal: Opc = BO_AndAssign; break;
15562 case tok::caretequal: Opc = BO_XorAssign; break;
15563 case tok::pipeequal: Opc = BO_OrAssign; break;
15564 case tok::comma: Opc = BO_Comma; break;
15565 }
15566 return Opc;
15567}
15568
15569static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15570 tok::TokenKind Kind) {
15571 UnaryOperatorKind Opc;
15572 switch (Kind) {
15573 default: llvm_unreachable("Unknown unary op!");
15574 case tok::plusplus: Opc = UO_PreInc; break;
15575 case tok::minusminus: Opc = UO_PreDec; break;
15576 case tok::amp: Opc = UO_AddrOf; break;
15577 case tok::star: Opc = UO_Deref; break;
15578 case tok::plus: Opc = UO_Plus; break;
15579 case tok::minus: Opc = UO_Minus; break;
15580 case tok::tilde: Opc = UO_Not; break;
15581 case tok::exclaim: Opc = UO_LNot; break;
15582 case tok::kw___real: Opc = UO_Real; break;
15583 case tok::kw___imag: Opc = UO_Imag; break;
15584 case tok::kw___extension__: Opc = UO_Extension; break;
15585 }
15586 return Opc;
15587}
15588
15589const FieldDecl *
15590Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15591 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15592 // common for setters.
15593 // struct A {
15594 // int X;
15595 // -void setX(int X) { X = X; }
15596 // +void setX(int X) { this->X = X; }
15597 // };
15598
15599 // Only consider parameters for self assignment fixes.
15600 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15601 return nullptr;
15602 const auto *Method =
15603 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15604 if (!Method)
15605 return nullptr;
15606
15607 const CXXRecordDecl *Parent = Method->getParent();
15608 // In theory this is fixable if the lambda explicitly captures this, but
15609 // that's added complexity that's rarely going to be used.
15610 if (Parent->isLambda())
15611 return nullptr;
15612
15613 // FIXME: Use an actual Lookup operation instead of just traversing fields
15614 // in order to get base class fields.
15615 auto Field =
15616 llvm::find_if(Range: Parent->fields(),
15617 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15618 return F->getDeclName() == Name;
15619 });
15620 return (Field != Parent->field_end()) ? *Field : nullptr;
15621}
15622
15623/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15624/// This warning suppressed in the event of macro expansions.
15625static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15626 SourceLocation OpLoc, bool IsBuiltin) {
15627 if (S.inTemplateInstantiation())
15628 return;
15629 if (S.isUnevaluatedContext())
15630 return;
15631 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15632 return;
15633 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15634 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15635 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15636 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15637 if (!LHSDeclRef || !RHSDeclRef ||
15638 LHSDeclRef->getLocation().isMacroID() ||
15639 RHSDeclRef->getLocation().isMacroID())
15640 return;
15641 const ValueDecl *LHSDecl =
15642 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15643 const ValueDecl *RHSDecl =
15644 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15645 if (LHSDecl != RHSDecl)
15646 return;
15647 if (LHSDecl->getType().isVolatileQualified())
15648 return;
15649 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15650 if (RefTy->getPointeeType().isVolatileQualified())
15651 return;
15652
15653 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15654 : diag::warn_self_assignment_overloaded)
15655 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15656 << RHSExpr->getSourceRange();
15657 if (const FieldDecl *SelfAssignField =
15658 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15659 Diag << 1 << SelfAssignField
15660 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15661 else
15662 Diag << 0;
15663}
15664
15665/// Check if a bitwise-& is performed on an Objective-C pointer. This
15666/// is usually indicative of introspection within the Objective-C pointer.
15667static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15668 SourceLocation OpLoc) {
15669 if (!S.getLangOpts().ObjC)
15670 return;
15671
15672 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15673 const Expr *LHS = L.get();
15674 const Expr *RHS = R.get();
15675
15676 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15677 ObjCPointerExpr = LHS;
15678 OtherExpr = RHS;
15679 }
15680 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15681 ObjCPointerExpr = RHS;
15682 OtherExpr = LHS;
15683 }
15684
15685 // This warning is deliberately made very specific to reduce false
15686 // positives with logic that uses '&' for hashing. This logic mainly
15687 // looks for code trying to introspect into tagged pointers, which
15688 // code should generally never do.
15689 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15690 unsigned Diag = diag::warn_objc_pointer_masking;
15691 // Determine if we are introspecting the result of performSelectorXXX.
15692 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15693 // Special case messages to -performSelector and friends, which
15694 // can return non-pointer values boxed in a pointer value.
15695 // Some clients may wish to silence warnings in this subcase.
15696 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15697 Selector S = ME->getSelector();
15698 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15699 if (SelArg0.starts_with(Prefix: "performSelector"))
15700 Diag = diag::warn_objc_pointer_masking_performSelector;
15701 }
15702
15703 S.Diag(Loc: OpLoc, DiagID: Diag)
15704 << ObjCPointerExpr->getSourceRange();
15705 }
15706}
15707
15708// This helper function promotes a binary operator's operands (which are of a
15709// half vector type) to a vector of floats and then truncates the result to
15710// a vector of either half or short.
15711static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15712 BinaryOperatorKind Opc, QualType ResultTy,
15713 ExprValueKind VK, ExprObjectKind OK,
15714 bool IsCompAssign, SourceLocation OpLoc,
15715 FPOptionsOverride FPFeatures) {
15716 auto &Context = S.getASTContext();
15717 assert((isVector(ResultTy, Context.HalfTy) ||
15718 isVector(ResultTy, Context.ShortTy)) &&
15719 "Result must be a vector of half or short");
15720 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15721 isVector(RHS.get()->getType(), Context.HalfTy) &&
15722 "both operands expected to be a half vector");
15723
15724 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15725 QualType BinOpResTy = RHS.get()->getType();
15726
15727 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15728 // change BinOpResTy to a vector of ints.
15729 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15730 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15731
15732 if (IsCompAssign)
15733 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15734 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15735 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15736
15737 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15738 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15739 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15740 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15741}
15742
15743/// Returns true if conversion between vectors of halfs and vectors of floats
15744/// is needed.
15745static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15746 QualType ResultTy, Expr *E0,
15747 Expr *E1 = nullptr) {
15748 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15749 return false;
15750
15751 // The conversion truncates the result to a half/short vector, so it shouldn't
15752 // apply when the result is not that type (e.g. HLSL comparisons).
15753 if (ResultTy->isVectorType() && !isVector(QT: ResultTy, ElementType: Ctx.HalfTy) &&
15754 !isVector(QT: ResultTy, ElementType: Ctx.ShortTy))
15755 return false;
15756
15757 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15758 QualType Ty = E->IgnoreImplicit()->getType();
15759
15760 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15761 // to vectors of floats. Although the element type of the vectors is __fp16,
15762 // the vectors shouldn't be treated as storage-only types. See the
15763 // discussion here: https://reviews.llvm.org/rG825235c140e7
15764 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15765 if (VT->getVectorKind() == VectorKind::Neon)
15766 return false;
15767 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15768 }
15769 return false;
15770 };
15771
15772 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15773}
15774
15775ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15776 BinaryOperatorKind Opc, Expr *LHSExpr,
15777 Expr *RHSExpr, bool ForFoldExpression) {
15778 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15779 // The syntax only allows initializer lists on the RHS of assignment,
15780 // so we don't need to worry about accepting invalid code for
15781 // non-assignment operators.
15782 // C++11 5.17p9:
15783 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15784 // of x = {} is x = T().
15785 InitializationKind Kind = InitializationKind::CreateDirectList(
15786 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15787 InitializedEntity Entity =
15788 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15789 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15790 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15791 if (Init.isInvalid())
15792 return Init;
15793 RHSExpr = Init.get();
15794 }
15795
15796 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15797 QualType ResultTy; // Result type of the binary operator.
15798 // The following two variables are used for compound assignment operators
15799 QualType CompLHSTy; // Type of LHS after promotions for computation
15800 QualType CompResultTy; // Type of computation result
15801 ExprValueKind VK = VK_PRValue;
15802 ExprObjectKind OK = OK_Ordinary;
15803 bool ConvertHalfVec = false;
15804
15805 if (!LHS.isUsable() || !RHS.isUsable())
15806 return ExprError();
15807
15808 if (getLangOpts().OpenCL) {
15809 QualType LHSTy = LHSExpr->getType();
15810 QualType RHSTy = RHSExpr->getType();
15811 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15812 // the ATOMIC_VAR_INIT macro.
15813 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15814 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15815 if (BO_Assign == Opc)
15816 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15817 else
15818 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15819 return ExprError();
15820 }
15821
15822 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15823 // only with a builtin functions and therefore should be disallowed here.
15824 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15825 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15826 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15827 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15828 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15829 return ExprError();
15830 }
15831 }
15832
15833 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15834 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15835
15836 switch (Opc) {
15837 case BO_Assign:
15838 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15839 if (getLangOpts().CPlusPlus &&
15840 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15841 VK = LHS.get()->getValueKind();
15842 OK = LHS.get()->getObjectKind();
15843 }
15844 if (!ResultTy.isNull()) {
15845 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15846 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15847
15848 // Avoid copying a block to the heap if the block is assigned to a local
15849 // auto variable that is declared in the same scope as the block. This
15850 // optimization is unsafe if the local variable is declared in an outer
15851 // scope. For example:
15852 //
15853 // BlockTy b;
15854 // {
15855 // b = ^{...};
15856 // }
15857 // // It is unsafe to invoke the block here if it wasn't copied to the
15858 // // heap.
15859 // b();
15860
15861 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15862 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15863 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15864 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15865 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15866
15867 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15868 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15869 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15870 }
15871 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15872 break;
15873 case BO_PtrMemD:
15874 case BO_PtrMemI:
15875 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15876 isIndirect: Opc == BO_PtrMemI);
15877 break;
15878 case BO_Mul:
15879 case BO_Div:
15880 ConvertHalfVec = true;
15881 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15882 break;
15883 case BO_Rem:
15884 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15885 break;
15886 case BO_Add:
15887 ConvertHalfVec = true;
15888 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15889 break;
15890 case BO_Sub:
15891 ConvertHalfVec = true;
15892 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15893 break;
15894 case BO_Shl:
15895 case BO_Shr:
15896 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15897 break;
15898 case BO_LE:
15899 case BO_LT:
15900 case BO_GE:
15901 case BO_GT:
15902 ConvertHalfVec = true;
15903 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15904
15905 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15906 !ForFoldExpression && BI && BI->isComparisonOp())
15907 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15908 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15909
15910 break;
15911 case BO_EQ:
15912 case BO_NE:
15913 ConvertHalfVec = true;
15914 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15915 break;
15916 case BO_Cmp:
15917 ConvertHalfVec = true;
15918 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15919 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15920 break;
15921 case BO_And:
15922 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15923 [[fallthrough]];
15924 case BO_Xor:
15925 case BO_Or:
15926 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15927 break;
15928 case BO_LAnd:
15929 case BO_LOr:
15930 ConvertHalfVec = true;
15931 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15932 break;
15933 case BO_MulAssign:
15934 case BO_DivAssign:
15935 ConvertHalfVec = true;
15936 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15937 CompLHSTy = CompResultTy;
15938 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15939 ResultTy =
15940 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15941 break;
15942 case BO_RemAssign:
15943 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15944 CompLHSTy = CompResultTy;
15945 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15946 ResultTy =
15947 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15948 break;
15949 case BO_AddAssign:
15950 ConvertHalfVec = true;
15951 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15952 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15953 ResultTy =
15954 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15955 break;
15956 case BO_SubAssign:
15957 ConvertHalfVec = true;
15958 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15959 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15960 ResultTy =
15961 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15962 break;
15963 case BO_ShlAssign:
15964 case BO_ShrAssign:
15965 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15966 CompLHSTy = CompResultTy;
15967 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15968 ResultTy =
15969 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15970 break;
15971 case BO_AndAssign:
15972 case BO_OrAssign: // fallthrough
15973 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15974 [[fallthrough]];
15975 case BO_XorAssign:
15976 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15977 CompLHSTy = CompResultTy;
15978 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15979 ResultTy =
15980 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15981 break;
15982 case BO_Comma:
15983 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15984 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15985 VK = RHS.get()->getValueKind();
15986 OK = RHS.get()->getObjectKind();
15987 }
15988 break;
15989 }
15990 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15991 return ExprError();
15992
15993 // Some of the binary operations require promoting operands of half vector to
15994 // float vectors and truncating the result back to half vector. For now, we do
15995 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15996 // arm64).
15997 assert(
15998 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15999 isVector(LHS.get()->getType(), Context.HalfTy)) &&
16000 "both sides are half vectors or neither sides are");
16001 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, ResultTy,
16002 E0: LHS.get(), E1: RHS.get());
16003
16004 // Check for array bounds violations for both sides of the BinaryOperator
16005 CheckArrayAccess(E: LHS.get());
16006 CheckArrayAccess(E: RHS.get());
16007
16008 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
16009 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
16010 Name: &Context.Idents.get(Name: "object_setClass"),
16011 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
16012 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
16013 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
16014 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
16015 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
16016 Code: "object_setClass(")
16017 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
16018 Code: ",")
16019 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
16020 }
16021 else
16022 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
16023 }
16024 else if (const ObjCIvarRefExpr *OIRE =
16025 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
16026 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
16027
16028 // Opc is not a compound assignment if CompResultTy is null.
16029 if (CompResultTy.isNull()) {
16030 if (ConvertHalfVec)
16031 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
16032 OpLoc, FPFeatures: CurFPFeatureOverrides());
16033 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
16034 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16035 }
16036
16037 // Handle compound assignments.
16038 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16039 OK_ObjCProperty) {
16040 VK = VK_LValue;
16041 OK = LHS.get()->getObjectKind();
16042 }
16043
16044 // The LHS is not converted to the result type for fixed-point compound
16045 // assignment as the common type is computed on demand. Reset the CompLHSTy
16046 // to the LHS type we would have gotten after unary conversions.
16047 if (CompResultTy->isFixedPointType())
16048 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
16049
16050 if (ConvertHalfVec)
16051 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
16052 OpLoc, FPFeatures: CurFPFeatureOverrides());
16053
16054 return CompoundAssignOperator::Create(
16055 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
16056 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
16057}
16058
16059/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16060/// operators are mixed in a way that suggests that the programmer forgot that
16061/// comparison operators have higher precedence. The most typical example of
16062/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16063static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
16064 SourceLocation OpLoc, Expr *LHSExpr,
16065 Expr *RHSExpr) {
16066 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
16067 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
16068
16069 // Check that one of the sides is a comparison operator and the other isn't.
16070 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16071 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16072 if (isLeftComp == isRightComp)
16073 return;
16074
16075 // Bitwise operations are sometimes used as eager logical ops.
16076 // Don't diagnose this.
16077 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16078 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16079 if (isLeftBitwise || isRightBitwise)
16080 return;
16081
16082 SourceRange DiagRange = isLeftComp
16083 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16084 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16085 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16086 SourceRange ParensRange =
16087 isLeftComp
16088 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16089 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16090
16091 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
16092 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
16093 SuggestParentheses(Self, Loc: OpLoc,
16094 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
16095 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16096 SuggestParentheses(Self, Loc: OpLoc,
16097 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
16098 << BinaryOperator::getOpcodeStr(Op: Opc),
16099 ParenRange: ParensRange);
16100}
16101
16102/// It accepts a '&&' expr that is inside a '||' one.
16103/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16104/// in parentheses.
16105static void
16106EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
16107 BinaryOperator *Bop) {
16108 assert(Bop->getOpcode() == BO_LAnd);
16109 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
16110 << Bop->getSourceRange() << OpLoc;
16111 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
16112 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
16113 << Bop->getOpcodeStr(),
16114 ParenRange: Bop->getSourceRange());
16115}
16116
16117/// Look for '&&' in the left hand of a '||' expr.
16118static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
16119 Expr *LHSExpr, Expr *RHSExpr) {
16120 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
16121 if (Bop->getOpcode() == BO_LAnd) {
16122 // If it's "string_literal && a || b" don't warn since the precedence
16123 // doesn't matter.
16124 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
16125 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16126 } else if (Bop->getOpcode() == BO_LOr) {
16127 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
16128 // If it's "a || b && string_literal || c" we didn't warn earlier for
16129 // "a || b && string_literal", but warn now.
16130 if (RBop->getOpcode() == BO_LAnd &&
16131 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
16132 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
16133 }
16134 }
16135 }
16136}
16137
16138/// Look for '&&' in the right hand of a '||' expr.
16139static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
16140 Expr *LHSExpr, Expr *RHSExpr) {
16141 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
16142 if (Bop->getOpcode() == BO_LAnd) {
16143 // If it's "a || b && string_literal" don't warn since the precedence
16144 // doesn't matter.
16145 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
16146 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16147 }
16148 }
16149}
16150
16151/// Look for bitwise op in the left or right hand of a bitwise op with
16152/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16153/// the '&' expression in parentheses.
16154static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
16155 SourceLocation OpLoc, Expr *SubExpr) {
16156 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16157 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16158 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
16159 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
16160 << Bop->getSourceRange() << OpLoc;
16161 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16162 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16163 << Bop->getOpcodeStr(),
16164 ParenRange: Bop->getSourceRange());
16165 }
16166 }
16167}
16168
16169static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
16170 Expr *SubExpr, StringRef Shift) {
16171 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16172 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16173 StringRef Op = Bop->getOpcodeStr();
16174 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
16175 << Bop->getSourceRange() << OpLoc << Shift << Op;
16176 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16177 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
16178 ParenRange: Bop->getSourceRange());
16179 }
16180 }
16181}
16182
16183static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16184 Expr *LHSExpr, Expr *RHSExpr) {
16185 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
16186 if (!OCE)
16187 return;
16188
16189 FunctionDecl *FD = OCE->getDirectCallee();
16190 if (!FD || !FD->isOverloadedOperator())
16191 return;
16192
16193 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16194 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16195 return;
16196
16197 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
16198 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16199 << (Kind == OO_LessLess);
16200 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
16201 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16202 << (Kind == OO_LessLess ? "<<" : ">>"),
16203 ParenRange: OCE->getSourceRange());
16204 SuggestParentheses(
16205 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
16206 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
16207}
16208
16209/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16210/// precedence.
16211static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16212 SourceLocation OpLoc, Expr *LHSExpr,
16213 Expr *RHSExpr){
16214 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16215 if (BinaryOperator::isBitwiseOp(Opc))
16216 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16217
16218 // Diagnose "arg1 & arg2 | arg3"
16219 if ((Opc == BO_Or || Opc == BO_Xor) &&
16220 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16221 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
16222 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
16223 }
16224
16225 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16226 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16227 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16228 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16229 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16230 }
16231
16232 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16233 || Opc == BO_Shr) {
16234 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16235 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16236 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16237 }
16238
16239 // Warn on overloaded shift operators and comparisons, such as:
16240 // cout << 5 == 4;
16241 if (BinaryOperator::isComparisonOp(Opc))
16242 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16243}
16244
16245ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16246 tok::TokenKind Kind,
16247 Expr *LHSExpr, Expr *RHSExpr) {
16248 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16249 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16250 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16251
16252 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16253 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16254
16255 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
16256 ? BuiltinCountedByRefKind::Assignment
16257 : BuiltinCountedByRefKind::BinaryExpr;
16258
16259 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
16260 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
16261
16262 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16263}
16264
16265void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16266 UnresolvedSetImpl &Functions) {
16267 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16268 if (OverOp != OO_None && OverOp != OO_Equal)
16269 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16270
16271 // In C++20 onwards, we may have a second operator to look up.
16272 if (getLangOpts().CPlusPlus20) {
16273 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16274 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16275 }
16276}
16277
16278/// Build an overloaded binary operator expression in the given scope.
16279static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16280 BinaryOperatorKind Opc,
16281 Expr *LHS, Expr *RHS) {
16282 switch (Opc) {
16283 case BO_Assign:
16284 // In the non-overloaded case, we warn about self-assignment (x = x) for
16285 // both simple assignment and certain compound assignments where algebra
16286 // tells us the operation yields a constant result. When the operator is
16287 // overloaded, we can't do the latter because we don't want to assume that
16288 // those algebraic identities still apply; for example, a path-building
16289 // library might use operator/= to append paths. But it's still reasonable
16290 // to assume that simple assignment is just moving/copying values around
16291 // and so self-assignment is likely a bug.
16292 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16293 [[fallthrough]];
16294 case BO_DivAssign:
16295 case BO_RemAssign:
16296 case BO_SubAssign:
16297 case BO_AndAssign:
16298 case BO_OrAssign:
16299 case BO_XorAssign:
16300 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16301 break;
16302 default:
16303 break;
16304 }
16305
16306 // Find all of the overloaded operators visible from this point.
16307 UnresolvedSet<16> Functions;
16308 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16309
16310 // Build the (potentially-overloaded, potentially-dependent)
16311 // binary operation.
16312 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16313}
16314
16315ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16316 BinaryOperatorKind Opc, Expr *LHSExpr,
16317 Expr *RHSExpr, bool ForFoldExpression) {
16318 if (!LHSExpr || !RHSExpr)
16319 return ExprError();
16320
16321 // We want to end up calling one of SemaPseudoObject::checkAssignment
16322 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16323 // both expressions are overloadable or either is type-dependent),
16324 // or CreateBuiltinBinOp (in any other case). We also want to get
16325 // any placeholder types out of the way.
16326
16327 // Handle pseudo-objects in the LHS.
16328 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16329 // Assignments with a pseudo-object l-value need special analysis.
16330 if (pty->getKind() == BuiltinType::PseudoObject &&
16331 BinaryOperator::isAssignmentOp(Opc))
16332 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16333
16334 // Don't resolve overloads if the other type is overloadable.
16335 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16336 // We can't actually test that if we still have a placeholder,
16337 // though. Fortunately, none of the exceptions we see in that
16338 // code below are valid when the LHS is an overload set. Note
16339 // that an overload set can be dependently-typed, but it never
16340 // instantiates to having an overloadable type.
16341 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16342 if (resolvedRHS.isInvalid()) return ExprError();
16343 RHSExpr = resolvedRHS.get();
16344
16345 if (RHSExpr->isTypeDependent() ||
16346 RHSExpr->getType()->isOverloadableType())
16347 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16348 }
16349
16350 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16351 // template, diagnose the missing 'template' keyword instead of diagnosing
16352 // an invalid use of a bound member function.
16353 //
16354 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16355 // to C++1z [over.over]/1.4, but we already checked for that case above.
16356 if (Opc == BO_LT && inTemplateInstantiation() &&
16357 (pty->getKind() == BuiltinType::BoundMember ||
16358 pty->getKind() == BuiltinType::Overload)) {
16359 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16360 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16361 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16362 return isa<FunctionTemplateDecl>(Val: ND);
16363 })) {
16364 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16365 : OE->getNameLoc(),
16366 DiagID: diag::err_template_kw_missing)
16367 << OE->getName().getAsIdentifierInfo();
16368 return ExprError();
16369 }
16370 }
16371
16372 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16373 if (LHS.isInvalid()) return ExprError();
16374 LHSExpr = LHS.get();
16375 }
16376
16377 // Handle pseudo-objects in the RHS.
16378 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16379 // An overload in the RHS can potentially be resolved by the type
16380 // being assigned to.
16381 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16382 if (getLangOpts().CPlusPlus &&
16383 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16384 LHSExpr->getType()->isOverloadableType()))
16385 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16386
16387 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16388 ForFoldExpression);
16389 }
16390
16391 // Don't resolve overloads if the other type is overloadable.
16392 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16393 LHSExpr->getType()->isOverloadableType())
16394 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16395
16396 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16397 if (!resolvedRHS.isUsable()) return ExprError();
16398 RHSExpr = resolvedRHS.get();
16399 }
16400
16401 if (getLangOpts().HLSL) {
16402 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16403 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16404 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16405 return ExprError();
16406 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16407 std::optional<ExprResult> ConvRHS =
16408 HLSL().tryPerformConstantBufferConversion(BaseExpr: RHSExpr);
16409 if (ConvRHS && Context.hasSameUnqualifiedType(
16410 T1: LHSExpr->getType(), T2: ConvRHS->get()->getType())) {
16411 assert(!ConvRHS->isInvalid());
16412 RHSExpr = ConvRHS->get();
16413 }
16414 }
16415 }
16416
16417 if (getLangOpts().CPlusPlus) {
16418 bool CanOverloadBinOp =
16419 !getLangOpts().HLSL ||
16420 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16421 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16422 bool TypeDependent =
16423 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16424 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16425 RHSExpr->getType()->isOverloadableType();
16426 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16427 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16428 }
16429
16430 if (getLangOpts().RecoveryAST &&
16431 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16432 assert(!getLangOpts().CPlusPlus);
16433 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16434 "Should only occur in error-recovery path.");
16435 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16436 // C [6.15.16] p3:
16437 // An assignment expression has the value of the left operand after the
16438 // assignment, but is not an lvalue.
16439 return CompoundAssignOperator::Create(
16440 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16441 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16442 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16443 QualType ResultType;
16444 switch (Opc) {
16445 case BO_Assign:
16446 ResultType = LHSExpr->getType().getUnqualifiedType();
16447 break;
16448 case BO_LT:
16449 case BO_GT:
16450 case BO_LE:
16451 case BO_GE:
16452 case BO_EQ:
16453 case BO_NE:
16454 case BO_LAnd:
16455 case BO_LOr:
16456 // These operators have a fixed result type regardless of operands.
16457 ResultType = Context.IntTy;
16458 break;
16459 case BO_Comma:
16460 ResultType = RHSExpr->getType();
16461 break;
16462 default:
16463 ResultType = Context.DependentTy;
16464 break;
16465 }
16466 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16467 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16468 FPFeatures: CurFPFeatureOverrides());
16469 }
16470
16471 // Build a built-in binary operation.
16472 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16473}
16474
16475static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16476 if (T.isNull() || T->isDependentType())
16477 return false;
16478
16479 if (!Ctx.isPromotableIntegerType(T))
16480 return true;
16481
16482 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16483}
16484
16485ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16486 UnaryOperatorKind Opc, Expr *InputExpr,
16487 bool IsAfterAmp) {
16488 ExprResult Input = InputExpr;
16489 ExprValueKind VK = VK_PRValue;
16490 ExprObjectKind OK = OK_Ordinary;
16491 QualType resultType;
16492 bool CanOverflow = false;
16493
16494 bool ConvertHalfVec = false;
16495 if (getLangOpts().OpenCL) {
16496 QualType Ty = InputExpr->getType();
16497 // The only legal unary operation for atomics is '&'.
16498 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16499 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16500 // only with a builtin functions and therefore should be disallowed here.
16501 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16502 || Ty->isBlockPointerType())) {
16503 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16504 << InputExpr->getType()
16505 << Input.get()->getSourceRange());
16506 }
16507 }
16508
16509 if (getLangOpts().HLSL && OpLoc.isValid()) {
16510 if (Opc == UO_AddrOf)
16511 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16512 if (Opc == UO_Deref)
16513 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16514 }
16515
16516 if (InputExpr->isTypeDependent() &&
16517 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16518 resultType = Context.DependentTy;
16519 } else {
16520 switch (Opc) {
16521 case UO_PreInc:
16522 case UO_PreDec:
16523 case UO_PostInc:
16524 case UO_PostDec:
16525 resultType =
16526 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16527 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16528 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16529 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16530 break;
16531 case UO_AddrOf:
16532 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16533 CheckAddressOfNoDeref(E: InputExpr);
16534 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16535 break;
16536 case UO_Deref: {
16537 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16538 if (Input.isInvalid())
16539 return ExprError();
16540 resultType =
16541 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16542 break;
16543 }
16544 case UO_Plus:
16545 case UO_Minus:
16546 CanOverflow = Opc == UO_Minus &&
16547 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16548 Input = UsualUnaryConversions(E: Input.get());
16549 if (Input.isInvalid())
16550 return ExprError();
16551 // Unary plus and minus require promoting an operand of half vector to a
16552 // float vector and truncating the result back to a half vector. For now,
16553 // we do this only when HalfArgsAndReturns is set (that is, when the
16554 // target is arm or arm64).
16555 ConvertHalfVec = needsConversionOfHalfVec(
16556 OpRequiresConversion: true, Ctx&: Context, ResultTy: Input.get()->getType(), E0: Input.get());
16557
16558 // If the operand is a half vector, promote it to a float vector.
16559 if (ConvertHalfVec)
16560 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16561 resultType = Input.get()->getType();
16562 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16563 break;
16564 else if (resultType->isVectorType() &&
16565 // The z vector extensions don't allow + or - with bool vectors.
16566 (!Context.getLangOpts().ZVector ||
16567 resultType->castAs<VectorType>()->getVectorKind() !=
16568 VectorKind::AltiVecBool))
16569 break;
16570 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16571 break;
16572 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16573 Opc == UO_Plus && resultType->isPointerType())
16574 break;
16575
16576 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16577 << resultType << Input.get()->getSourceRange());
16578
16579 case UO_Not: // bitwise complement
16580 Input = UsualUnaryConversions(E: Input.get());
16581 if (Input.isInvalid())
16582 return ExprError();
16583 resultType = Input.get()->getType();
16584 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16585 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16586 // C99 does not support '~' for complex conjugation.
16587 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16588 << resultType << Input.get()->getSourceRange();
16589 else if (resultType->hasIntegerRepresentation())
16590 break;
16591 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16592 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16593 // on vector float types.
16594 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16595 if (!T->isIntegerType())
16596 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16597 << resultType << Input.get()->getSourceRange());
16598 } else {
16599 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16600 << resultType << Input.get()->getSourceRange());
16601 }
16602 break;
16603
16604 case UO_LNot: // logical negation
16605 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16606 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16607 if (Input.isInvalid())
16608 return ExprError();
16609 resultType = Input.get()->getType();
16610
16611 // Though we still have to promote half FP to float...
16612 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16613 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16614 .get();
16615 resultType = Context.FloatTy;
16616 }
16617
16618 // WebAsembly tables can't be used in unary expressions.
16619 if (resultType->isPointerType() &&
16620 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16621 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16622 << resultType << Input.get()->getSourceRange());
16623 }
16624
16625 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType) &&
16626 !resultType->isMetaInfoType()) {
16627 // Before C++26, scalar types are contextually converted to bool,
16628 // std::meta::info is a scalar type but not an arithmetic type.
16629
16630 // C99 6.5.3.3p1: ok, fallthrough;
16631 if (Context.getLangOpts().CPlusPlus) {
16632 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16633 // operand contextually converted to bool.
16634 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16635 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16636 } else if (Context.getLangOpts().OpenCL &&
16637 Context.getLangOpts().OpenCLVersion < 120) {
16638 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16639 // operate on scalar float types.
16640 if (!resultType->isIntegerType() && !resultType->isPointerType())
16641 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16642 << resultType << Input.get()->getSourceRange());
16643 }
16644 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16645 !resultType->hasBooleanRepresentation()) {
16646 // HLSL unary logical 'not' behaves like C++, which states that the
16647 // operand is converted to bool and the result is bool, however HLSL
16648 // extends this property to vectors.
16649 const VectorType *VTy = resultType->castAs<VectorType>();
16650 resultType =
16651 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16652
16653 Input = ImpCastExprToType(
16654 E: Input.get(), Type: resultType,
16655 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16656 .get();
16657 break;
16658 } else if (resultType->isExtVectorType()) {
16659 if (Context.getLangOpts().OpenCL &&
16660 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16661 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16662 // operate on vector float types.
16663 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16664 if (!T->isIntegerType())
16665 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16666 << resultType << Input.get()->getSourceRange());
16667 }
16668 // Vector logical not returns the signed variant of the operand type.
16669 resultType = GetSignedVectorType(V: resultType);
16670 break;
16671 } else if (Context.getLangOpts().CPlusPlus &&
16672 resultType->isVectorType()) {
16673 const VectorType *VTy = resultType->castAs<VectorType>();
16674 if (VTy->getVectorKind() != VectorKind::Generic)
16675 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16676 << resultType << Input.get()->getSourceRange());
16677
16678 // Vector logical not returns the signed variant of the operand type.
16679 resultType = GetSignedVectorType(V: resultType);
16680 break;
16681 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16682 resultType = Context.getLogicalOperationType();
16683 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16684 break;
16685 } else {
16686 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16687 << resultType << Input.get()->getSourceRange());
16688 }
16689
16690 // LNot always has type int. C99 6.5.3.3p5.
16691 // In C++, it's bool. C++ 5.3.1p8
16692 resultType = Context.getLogicalOperationType();
16693 break;
16694 case UO_Real:
16695 case UO_Imag:
16696 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16697 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16698 // ordinary complex l-values to ordinary l-values and all other values to
16699 // r-values.
16700 if (Input.isInvalid())
16701 return ExprError();
16702 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16703 if (Input.get()->isGLValue() &&
16704 Input.get()->getObjectKind() == OK_Ordinary)
16705 VK = Input.get()->getValueKind();
16706 } else if (!getLangOpts().CPlusPlus) {
16707 // In C, a volatile scalar is read by __imag. In C++, it is not.
16708 Input = DefaultLvalueConversion(E: Input.get());
16709 }
16710 break;
16711 case UO_Extension:
16712 resultType = Input.get()->getType();
16713 VK = Input.get()->getValueKind();
16714 OK = Input.get()->getObjectKind();
16715 break;
16716 case UO_Coawait:
16717 // It's unnecessary to represent the pass-through operator co_await in the
16718 // AST; just return the input expression instead.
16719 assert(!Input.get()->getType()->isDependentType() &&
16720 "the co_await expression must be non-dependant before "
16721 "building operator co_await");
16722 return Input;
16723 }
16724 }
16725 if (resultType.isNull() || Input.isInvalid())
16726 return ExprError();
16727
16728 // Check for array bounds violations in the operand of the UnaryOperator,
16729 // except for the '*' and '&' operators that have to be handled specially
16730 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16731 // that are explicitly defined as valid by the standard).
16732 if (Opc != UO_AddrOf && Opc != UO_Deref)
16733 CheckArrayAccess(E: Input.get());
16734
16735 auto *UO =
16736 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16737 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16738
16739 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16740 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16741 !isUnevaluatedContext())
16742 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16743
16744 // Convert the result back to a half vector.
16745 if (ConvertHalfVec)
16746 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16747 return UO;
16748}
16749
16750bool Sema::isQualifiedMemberAccess(Expr *E) {
16751 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16752 if (!DRE->getQualifier())
16753 return false;
16754
16755 ValueDecl *VD = DRE->getDecl();
16756 if (!VD->isCXXClassMember())
16757 return false;
16758
16759 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16760 return true;
16761 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16762 return Method->isImplicitObjectMemberFunction();
16763
16764 return false;
16765 }
16766
16767 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16768 if (!ULE->getQualifier())
16769 return false;
16770
16771 for (NamedDecl *D : ULE->decls()) {
16772 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16773 if (Method->isImplicitObjectMemberFunction())
16774 return true;
16775 } else {
16776 // Overload set does not contain methods.
16777 break;
16778 }
16779 }
16780
16781 return false;
16782 }
16783
16784 return false;
16785}
16786
16787ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16788 UnaryOperatorKind Opc, Expr *Input,
16789 bool IsAfterAmp) {
16790 // First things first: handle placeholders so that the
16791 // overloaded-operator check considers the right type.
16792 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16793 // Increment and decrement of pseudo-object references.
16794 if (pty->getKind() == BuiltinType::PseudoObject &&
16795 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16796 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16797
16798 // extension is always a builtin operator.
16799 if (Opc == UO_Extension)
16800 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16801
16802 // & gets special logic for several kinds of placeholder.
16803 // The builtin code knows what to do.
16804 if (Opc == UO_AddrOf &&
16805 (pty->getKind() == BuiltinType::Overload ||
16806 pty->getKind() == BuiltinType::UnknownAny ||
16807 pty->getKind() == BuiltinType::BoundMember))
16808 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16809
16810 // Anything else needs to be handled now.
16811 ExprResult Result = CheckPlaceholderExpr(E: Input);
16812 if (Result.isInvalid()) return ExprError();
16813 Input = Result.get();
16814 }
16815
16816 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16817 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16818 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16819 // Find all of the overloaded operators visible from this point.
16820 UnresolvedSet<16> Functions;
16821 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16822 if (S && OverOp != OO_None)
16823 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16824
16825 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16826 }
16827
16828 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16829}
16830
16831ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16832 Expr *Input, bool IsAfterAmp) {
16833 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16834 IsAfterAmp);
16835}
16836
16837ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16838 LabelDecl *TheDecl) {
16839 TheDecl->markUsed(C&: Context);
16840 // Create the AST node. The address of a label always has type 'void*'.
16841 auto *Res = new (Context) AddrLabelExpr(
16842 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16843
16844 if (getCurFunction())
16845 getCurFunction()->AddrLabels.push_back(Elt: Res);
16846
16847 return Res;
16848}
16849
16850void Sema::ActOnStartStmtExpr() {
16851 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16852 // Make sure we diagnose jumping into a statement expression.
16853 setFunctionHasBranchProtectedScope();
16854}
16855
16856void Sema::ActOnStmtExprError() {
16857 // Note that function is also called by TreeTransform when leaving a
16858 // StmtExpr scope without rebuilding anything.
16859
16860 DiscardCleanupsInEvaluationContext();
16861 PopExpressionEvaluationContext();
16862}
16863
16864ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16865 SourceLocation RPLoc) {
16866 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16867}
16868
16869ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16870 SourceLocation RPLoc, unsigned TemplateDepth) {
16871 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16872 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16873
16874 if (hasAnyUnrecoverableErrorsInThisFunction())
16875 DiscardCleanupsInEvaluationContext();
16876 assert(!Cleanup.exprNeedsCleanups() &&
16877 "cleanups within StmtExpr not correctly bound!");
16878 PopExpressionEvaluationContext();
16879
16880 // FIXME: there are a variety of strange constraints to enforce here, for
16881 // example, it is not possible to goto into a stmt expression apparently.
16882 // More semantic analysis is needed.
16883
16884 // If there are sub-stmts in the compound stmt, take the type of the last one
16885 // as the type of the stmtexpr.
16886 QualType Ty = Context.VoidTy;
16887 bool StmtExprMayBindToTemp = false;
16888 if (!Compound->body_empty()) {
16889 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16890 if (const Expr *Value = LastStmt->getExprStmt()) {
16891 StmtExprMayBindToTemp = true;
16892 Ty = Value->getType();
16893 }
16894 }
16895 }
16896
16897 // FIXME: Check that expression type is complete/non-abstract; statement
16898 // expressions are not lvalues.
16899 Expr *ResStmtExpr =
16900 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16901 if (StmtExprMayBindToTemp)
16902 return MaybeBindToTemporary(E: ResStmtExpr);
16903 return ResStmtExpr;
16904}
16905
16906ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16907 if (ER.isInvalid())
16908 return ExprError();
16909
16910 // Do function/array conversion on the last expression, but not
16911 // lvalue-to-rvalue. However, initialize an unqualified type.
16912 ER = DefaultFunctionArrayConversion(E: ER.get());
16913 if (ER.isInvalid())
16914 return ExprError();
16915 Expr *E = ER.get();
16916
16917 if (E->isTypeDependent())
16918 return E;
16919
16920 // In ARC, if the final expression ends in a consume, splice
16921 // the consume out and bind it later. In the alternate case
16922 // (when dealing with a retainable type), the result
16923 // initialization will create a produce. In both cases the
16924 // result will be +1, and we'll need to balance that out with
16925 // a bind.
16926 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16927 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16928 return Cast->getSubExpr();
16929
16930 // FIXME: Provide a better location for the initialization.
16931 return PerformCopyInitialization(
16932 Entity: InitializedEntity::InitializeStmtExprResult(
16933 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16934 EqualLoc: SourceLocation(), Init: E);
16935}
16936
16937ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16938 TypeSourceInfo *TInfo,
16939 const Designation &Desig,
16940 SourceLocation RParenLoc) {
16941 QualType ArgTy = TInfo->getType();
16942 bool Dependent = ArgTy->isDependentType();
16943 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16944
16945 // We must have at least one component that refers to the type, and the first
16946 // one is known to be a field designator. Verify that the ArgTy represents
16947 // a struct/union/class.
16948 if (!Dependent && !ArgTy->isRecordType())
16949 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16950 << ArgTy << TypeRange);
16951
16952 // Type must be complete per C99 7.17p3 because a declaring a variable
16953 // with an incomplete type would be ill-formed.
16954 if (!Dependent
16955 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16956 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16957 return ExprError();
16958
16959 bool DidWarnAboutNonPOD = false;
16960 QualType CurrentType = ArgTy;
16961 SmallVector<OffsetOfNode, 4> Comps;
16962 SmallVector<Expr *, 4> Exprs;
16963 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16964 const Designator &D = Desig.getDesignator(Idx: I);
16965 assert(!D.isArrayRangeDesignator());
16966 if (D.isArrayDesignator()) {
16967 // Offset of an array sub-field. TODO: Should we allow vector elements?
16968 if (!CurrentType->isDependentType()) {
16969 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16970 if(!AT)
16971 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
16972 << CurrentType);
16973 CurrentType = AT->getElementType();
16974 } else
16975 CurrentType = Context.DependentTy;
16976
16977 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
16978 if (IdxRval.isInvalid())
16979 return ExprError();
16980 Expr *Idx = IdxRval.get();
16981
16982 // The expression must be an integral expression.
16983 // FIXME: An integral constant expression?
16984 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16985 !Idx->getType()->isIntegerType())
16986 return ExprError(
16987 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16988 << Idx->getSourceRange());
16989
16990 // Record this array index.
16991 Comps.push_back(
16992 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16993 Exprs.push_back(Elt: Idx);
16994 continue;
16995 }
16996
16997 assert(D.isFieldDesignator());
16998 const IdentifierInfo *Name = D.getFieldDecl();
16999
17000 // Offset of a field.
17001 if (CurrentType->isDependentType()) {
17002 // We have the offset of a field, but we can't look into the dependent
17003 // type. Just record the identifier of the field.
17004 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
17005 CurrentType = Context.DependentTy;
17006 continue;
17007 }
17008
17009 // We need to have a complete type to look into.
17010 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
17011 DiagID: diag::err_offsetof_incomplete_type))
17012 return ExprError();
17013
17014 // Look for the designated field.
17015 auto *RD = CurrentType->getAsRecordDecl();
17016 if (!RD)
17017 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
17018 << CurrentType);
17019
17020 // C++ [lib.support.types]p5:
17021 // The macro offsetof accepts a restricted set of type arguments in this
17022 // International Standard. type shall be a POD structure or a POD union
17023 // (clause 9).
17024 // C++11 [support.types]p4:
17025 // If type is not a standard-layout class (Clause 9), the results are
17026 // undefined.
17027 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
17028 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
17029 unsigned DiagID =
17030 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
17031 : diag::ext_offsetof_non_pod_type;
17032
17033 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
17034 Diag(Loc: BuiltinLoc, DiagID)
17035 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
17036 << CurrentType;
17037 DidWarnAboutNonPOD = true;
17038 }
17039 }
17040
17041 // Look for the field.
17042 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17043 LookupQualifiedName(R, LookupCtx: RD);
17044 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17045 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17046 if (!MemberDecl) {
17047 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17048 MemberDecl = IndirectMemberDecl->getAnonField();
17049 }
17050
17051 if (!MemberDecl) {
17052 // Lookup could be ambiguous when looking up a placeholder variable
17053 // __builtin_offsetof(S, _).
17054 // In that case we would already have emitted a diagnostic
17055 if (!R.isAmbiguous())
17056 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
17057 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17058 return ExprError();
17059 }
17060
17061 // C99 7.17p3:
17062 // (If the specified member is a bit-field, the behavior is undefined.)
17063 //
17064 // We diagnose this as an error.
17065 if (MemberDecl->isBitField()) {
17066 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
17067 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17068 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
17069 return ExprError();
17070 }
17071
17072 RecordDecl *Parent = MemberDecl->getParent();
17073 if (IndirectMemberDecl)
17074 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
17075
17076 // If the member was found in a base class, introduce OffsetOfNodes for
17077 // the base class indirections.
17078 CXXBasePaths Paths;
17079 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
17080 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
17081 if (Paths.getDetectedVirtual()) {
17082 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
17083 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17084 return ExprError();
17085 }
17086
17087 CXXBasePath &Path = Paths.front();
17088 for (const CXXBasePathElement &B : Path)
17089 Comps.push_back(Elt: OffsetOfNode(B.Base));
17090 }
17091
17092 if (IndirectMemberDecl) {
17093 for (auto *FI : IndirectMemberDecl->chain()) {
17094 assert(isa<FieldDecl>(FI));
17095 Comps.push_back(
17096 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
17097 }
17098 } else
17099 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17100
17101 CurrentType = MemberDecl->getType().getNonReferenceType();
17102 }
17103
17104 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
17105 comps: Comps, exprs: Exprs, RParenLoc);
17106}
17107
17108ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
17109 SourceLocation TypeLoc,
17110 ParsedType ParsedArgTy,
17111 const Designation &Desig,
17112 SourceLocation RParenLoc) {
17113
17114 TypeSourceInfo *ArgTInfo;
17115 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
17116 if (ArgTy.isNull())
17117 return ExprError();
17118
17119 if (!ArgTInfo)
17120 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
17121
17122 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
17123}
17124
17125ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
17126 Expr *CondExpr,
17127 Expr *LHSExpr, Expr *RHSExpr,
17128 SourceLocation RPLoc) {
17129 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17130
17131 ExprValueKind VK = VK_PRValue;
17132 ExprObjectKind OK = OK_Ordinary;
17133 QualType resType;
17134 bool CondIsTrue = false;
17135 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17136 resType = Context.DependentTy;
17137 } else {
17138 // The conditional expression is required to be a constant expression.
17139 llvm::APSInt condEval(32);
17140 ExprResult CondICE = VerifyIntegerConstantExpression(
17141 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
17142 if (CondICE.isInvalid())
17143 return ExprError();
17144 CondExpr = CondICE.get();
17145 CondIsTrue = condEval.getZExtValue();
17146
17147 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17148 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17149
17150 resType = ActiveExpr->getType();
17151 VK = ActiveExpr->getValueKind();
17152 OK = ActiveExpr->getObjectKind();
17153 }
17154
17155 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17156 resType, VK, OK, RPLoc, CondIsTrue);
17157}
17158
17159//===----------------------------------------------------------------------===//
17160// Clang Extensions.
17161//===----------------------------------------------------------------------===//
17162
17163void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17164 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
17165
17166 if (LangOpts.CPlusPlus) {
17167 MangleNumberingContext *MCtx;
17168 Decl *ManglingContextDecl;
17169 std::tie(args&: MCtx, args&: ManglingContextDecl) =
17170 getCurrentMangleNumberContext(DC: Block->getDeclContext());
17171 if (MCtx) {
17172 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
17173 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
17174 }
17175 }
17176
17177 PushBlockScope(BlockScope: CurScope, Block);
17178 CurContext->addDecl(D: Block);
17179 if (CurScope)
17180 PushDeclContext(S: CurScope, DC: Block);
17181 else
17182 CurContext = Block;
17183
17184 getCurBlock()->HasImplicitReturnType = true;
17185
17186 // Enter a new evaluation context to insulate the block from any
17187 // cleanups from the enclosing full-expression.
17188 PushExpressionEvaluationContext(
17189 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
17190}
17191
17192void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
17193 Scope *CurScope) {
17194 assert(ParamInfo.getIdentifier() == nullptr &&
17195 "block-id should have no identifier!");
17196 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17197 BlockScopeInfo *CurBlock = getCurBlock();
17198
17199 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
17200 QualType T = Sig->getType();
17201 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
17202
17203 // GetTypeForDeclarator always produces a function type for a block
17204 // literal signature. Furthermore, it is always a FunctionProtoType
17205 // unless the function was written with a typedef.
17206 assert(T->isFunctionType() &&
17207 "GetTypeForDeclarator made a non-function block signature");
17208
17209 // Look for an explicit signature in that function type.
17210 FunctionProtoTypeLoc ExplicitSignature;
17211
17212 if ((ExplicitSignature = Sig->getTypeLoc()
17213 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17214
17215 // Check whether that explicit signature was synthesized by
17216 // GetTypeForDeclarator. If so, don't save that as part of the
17217 // written signature.
17218 if (ExplicitSignature.getLocalRangeBegin() ==
17219 ExplicitSignature.getLocalRangeEnd()) {
17220 // This would be much cheaper if we stored TypeLocs instead of
17221 // TypeSourceInfos.
17222 TypeLoc Result = ExplicitSignature.getReturnLoc();
17223 unsigned Size = Result.getFullDataSize();
17224 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
17225 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
17226
17227 ExplicitSignature = FunctionProtoTypeLoc();
17228 }
17229 }
17230
17231 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17232 CurBlock->FunctionType = T;
17233
17234 const auto *Fn = T->castAs<FunctionType>();
17235 QualType RetTy = Fn->getReturnType();
17236 bool isVariadic =
17237 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17238
17239 CurBlock->TheDecl->setIsVariadic(isVariadic);
17240
17241 // Context.DependentTy is used as a placeholder for a missing block
17242 // return type. TODO: what should we do with declarators like:
17243 // ^ * { ... }
17244 // If the answer is "apply template argument deduction"....
17245 if (RetTy != Context.DependentTy) {
17246 CurBlock->ReturnType = RetTy;
17247 CurBlock->TheDecl->setBlockMissingReturnType(false);
17248 CurBlock->HasImplicitReturnType = false;
17249 }
17250
17251 // Push block parameters from the declarator if we had them.
17252 SmallVector<ParmVarDecl*, 8> Params;
17253 if (ExplicitSignature) {
17254 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17255 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
17256 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17257 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17258 // Diagnose this as an extension in C17 and earlier.
17259 if (!getLangOpts().C23)
17260 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
17261 }
17262 Params.push_back(Elt: Param);
17263 }
17264
17265 // Fake up parameter variables if we have a typedef, like
17266 // ^ fntype { ... }
17267 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17268 for (const auto &I : Fn->param_types()) {
17269 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17270 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
17271 Params.push_back(Elt: Param);
17272 }
17273 }
17274
17275 // Set the parameters on the block decl.
17276 if (!Params.empty()) {
17277 CurBlock->TheDecl->setParams(Params);
17278 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17279 /*CheckParameterNames=*/false);
17280 }
17281
17282 // Finally we can process decl attributes.
17283 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17284
17285 // Put the parameter variables in scope.
17286 for (auto *AI : CurBlock->TheDecl->parameters()) {
17287 AI->setOwningFunction(CurBlock->TheDecl);
17288
17289 // If this has an identifier, add it to the scope stack.
17290 if (AI->getIdentifier()) {
17291 CheckShadow(S: CurBlock->TheScope, D: AI);
17292
17293 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17294 }
17295
17296 if (AI->isInvalidDecl())
17297 CurBlock->TheDecl->setInvalidDecl();
17298 }
17299}
17300
17301void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17302 // Leave the expression-evaluation context.
17303 DiscardCleanupsInEvaluationContext();
17304 PopExpressionEvaluationContext();
17305
17306 // Pop off CurBlock, handle nested blocks.
17307 PopDeclContext();
17308 PopFunctionScopeInfo();
17309}
17310
17311ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17312 Stmt *Body, Scope *CurScope) {
17313 // If blocks are disabled, emit an error.
17314 if (!LangOpts.Blocks)
17315 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17316
17317 // Leave the expression-evaluation context.
17318 if (hasAnyUnrecoverableErrorsInThisFunction())
17319 DiscardCleanupsInEvaluationContext();
17320 assert(!Cleanup.exprNeedsCleanups() &&
17321 "cleanups within block not correctly bound!");
17322 PopExpressionEvaluationContext();
17323
17324 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17325 BlockDecl *BD = BSI->TheDecl;
17326
17327 maybeAddDeclWithEffects(D: BD);
17328
17329 if (BSI->HasImplicitReturnType)
17330 deduceClosureReturnType(CSI&: *BSI);
17331
17332 QualType RetTy = Context.VoidTy;
17333 if (!BSI->ReturnType.isNull())
17334 RetTy = BSI->ReturnType;
17335
17336 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17337 QualType BlockTy;
17338
17339 // If the user wrote a function type in some form, try to use that.
17340 if (!BSI->FunctionType.isNull()) {
17341 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17342
17343 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17344 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17345
17346 // Turn protoless block types into nullary block types.
17347 if (isa<FunctionNoProtoType>(Val: FTy)) {
17348 FunctionProtoType::ExtProtoInfo EPI;
17349 EPI.ExtInfo = Ext;
17350 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17351
17352 // Otherwise, if we don't need to change anything about the function type,
17353 // preserve its sugar structure.
17354 } else if (FTy->getReturnType() == RetTy &&
17355 (!NoReturn || FTy->getNoReturnAttr())) {
17356 BlockTy = BSI->FunctionType;
17357
17358 // Otherwise, make the minimal modifications to the function type.
17359 } else {
17360 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17361 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17362 EPI.TypeQuals = Qualifiers();
17363 EPI.ExtInfo = Ext;
17364 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17365 }
17366
17367 // If we don't have a function type, just build one from nothing.
17368 } else {
17369 FunctionProtoType::ExtProtoInfo EPI;
17370 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17371 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17372 }
17373
17374 DiagnoseUnusedParameters(Parameters: BD->parameters());
17375 BlockTy = Context.getBlockPointerType(T: BlockTy);
17376
17377 // If needed, diagnose invalid gotos and switches in the block.
17378 if (getCurFunction()->NeedsScopeChecking() &&
17379 !PP.isCodeCompletionEnabled())
17380 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17381
17382 BD->setBody(cast<CompoundStmt>(Val: Body));
17383
17384 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17385 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17386
17387 // Try to apply the named return value optimization. We have to check again
17388 // if we can do this, though, because blocks keep return statements around
17389 // to deduce an implicit return type.
17390 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17391 !BD->isDependentContext())
17392 computeNRVO(Body, Scope: BSI);
17393
17394 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17395 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17396 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17397 UseContext: NonTrivialCUnionContext::FunctionReturn,
17398 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17399
17400 PopDeclContext();
17401
17402 // Set the captured variables on the block.
17403 SmallVector<BlockDecl::Capture, 4> Captures;
17404 for (Capture &Cap : BSI->Captures) {
17405 if (Cap.isInvalid() || Cap.isThisCapture())
17406 continue;
17407 // Cap.getVariable() is always a VarDecl because
17408 // blocks cannot capture structured bindings or other ValueDecl kinds.
17409 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17410 Expr *CopyExpr = nullptr;
17411 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17412 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17413 // The capture logic needs the destructor, so make sure we mark it.
17414 // Usually this is unnecessary because most local variables have
17415 // their destructors marked at declaration time, but parameters are
17416 // an exception because it's technically only the call site that
17417 // actually requires the destructor.
17418 if (isa<ParmVarDecl>(Val: Var))
17419 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17420
17421 // Enter a separate potentially-evaluated context while building block
17422 // initializers to isolate their cleanups from those of the block
17423 // itself.
17424 // FIXME: Is this appropriate even when the block itself occurs in an
17425 // unevaluated operand?
17426 EnterExpressionEvaluationContext EvalContext(
17427 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17428
17429 SourceLocation Loc = Cap.getLocation();
17430
17431 ExprResult Result = BuildDeclarationNameExpr(
17432 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17433
17434 // According to the blocks spec, the capture of a variable from
17435 // the stack requires a const copy constructor. This is not true
17436 // of the copy/move done to move a __block variable to the heap.
17437 if (!Result.isInvalid() &&
17438 !Result.get()->getType().isConstQualified()) {
17439 Result = ImpCastExprToType(E: Result.get(),
17440 Type: Result.get()->getType().withConst(),
17441 CK: CK_NoOp, VK: VK_LValue);
17442 }
17443
17444 if (!Result.isInvalid()) {
17445 Result = PerformCopyInitialization(
17446 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17447 Type: Cap.getCaptureType()),
17448 EqualLoc: Loc, Init: Result.get());
17449 }
17450
17451 // Build a full-expression copy expression if initialization
17452 // succeeded and used a non-trivial constructor. Recover from
17453 // errors by pretending that the copy isn't necessary.
17454 if (!Result.isInvalid() &&
17455 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17456 ->isTrivial()) {
17457 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17458 CopyExpr = Result.get();
17459 }
17460 }
17461 }
17462
17463 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17464 CopyExpr);
17465 Captures.push_back(Elt: NewCap);
17466 }
17467 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17468
17469 // Pop the block scope now but keep it alive to the end of this function.
17470 AnalysisBasedWarnings::Policy WP =
17471 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17472 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17473
17474 BlockExpr *Result = new (Context)
17475 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17476
17477 // If the block isn't obviously global, i.e. it captures anything at
17478 // all, then we need to do a few things in the surrounding context:
17479 if (Result->getBlockDecl()->hasCaptures()) {
17480 // First, this expression has a new cleanup object.
17481 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17482 Cleanup.setExprNeedsCleanups(true);
17483
17484 // It also gets a branch-protected scope if any of the captured
17485 // variables needs destruction.
17486 for (const auto &CI : Result->getBlockDecl()->captures()) {
17487 const VarDecl *var = CI.getVariable();
17488 if (var->getType().isDestructedType() != QualType::DK_none) {
17489 setFunctionHasBranchProtectedScope();
17490 break;
17491 }
17492 }
17493 }
17494
17495 if (getCurFunction())
17496 getCurFunction()->addBlock(BD);
17497
17498 // This can happen if the block's return type is deduced, but
17499 // the return expression is invalid.
17500 if (BD->isInvalidDecl())
17501 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17502 SubExprs: {Result}, T: Result->getType());
17503 return Result;
17504}
17505
17506ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17507 SourceLocation RPLoc) {
17508 TypeSourceInfo *TInfo;
17509 GetTypeFromParser(Ty, TInfo: &TInfo);
17510 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17511}
17512
17513ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17514 Expr *E, TypeSourceInfo *TInfo,
17515 SourceLocation RPLoc) {
17516 Expr *OrigExpr = E;
17517 VAArgExpr::VarArgKind VAKind = VAArgExpr::VA_Std;
17518
17519 // CUDA device global function does not support varargs.
17520 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17521 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17522 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17523 if (T == CUDAFunctionTarget::Global)
17524 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17525 }
17526 }
17527
17528 // NVPTX does not support va_arg expression.
17529 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17530 Context.getTargetInfo().getTriple().isNVPTX())
17531 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17532
17533 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17534 // as Microsoft ABI on an actual Microsoft platform, where
17535 // __builtin_ms_va_list and __builtin_va_list are the same.)
17536 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17537 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17538 QualType MSVaListType = Context.getBuiltinMSVaListType();
17539 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17540 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17541 return ExprError();
17542 VAKind = VAArgExpr::VA_MS;
17543 }
17544 }
17545
17546 // Get the va_list type
17547 QualType VaListType = Context.getBuiltinVaListType();
17548
17549 // It might be a __builtin_zos_va_list!
17550 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17551 // E->getType() can be:
17552 // - va_list: equal to array (char*)[2] (inside function)
17553 // - char **: decayed array (va_list passed as parameter)
17554 // We need to check for both cases.
17555 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17556 assert(ZOSVaListType->isArrayType() &&
17557 "__builtin_zos_va_list must be an array type");
17558 QualType DecayedType = Context.getArrayDecayedType(T: ZOSVaListType);
17559 if (Context.hasSameType(T1: ZOSVaListType, T2: E->getType()) ||
17560 Context.hasSameType(T1: DecayedType, T2: E->getType())) {
17561 VAKind = VAArgExpr::VA_ZOS;
17562 VaListType = ZOSVaListType;
17563 }
17564 }
17565
17566 if (VAKind != VAArgExpr::VA_MS) {
17567 if (VaListType->isArrayType()) {
17568 // Deal with implicit array decay; for example, on x86-64,
17569 // va_list is an array, but it's supposed to decay to
17570 // a pointer for va_arg.
17571 VaListType = Context.getArrayDecayedType(T: VaListType);
17572 // Make sure the input expression also decays appropriately.
17573 ExprResult Result = UsualUnaryConversions(E);
17574 if (Result.isInvalid())
17575 return ExprError();
17576 E = Result.get();
17577 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17578 // If va_list is a record type and we are compiling in C++ mode,
17579 // check the argument using reference binding.
17580 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17581 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17582 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17583 if (Init.isInvalid())
17584 return ExprError();
17585 E = Init.getAs<Expr>();
17586 } else {
17587 // Otherwise, the va_list argument must be an l-value because
17588 // it is modified by va_arg.
17589 if (!E->isTypeDependent() &&
17590 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17591 return ExprError();
17592 }
17593 }
17594
17595 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17596 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17597 return ExprError(
17598 Diag(Loc: E->getBeginLoc(),
17599 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17600 << OrigExpr->getType() << E->getSourceRange());
17601
17602 if (!TInfo->getType()->isDependentType()) {
17603 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17604 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17605 Args: TInfo->getTypeLoc()))
17606 return ExprError();
17607
17608 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17609 T: TInfo->getType(),
17610 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17611 Args: TInfo->getTypeLoc()))
17612 return ExprError();
17613
17614 if (!TInfo->getType().isPODType(Context)) {
17615 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17616 DiagID: TInfo->getType()->isObjCLifetimeType()
17617 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17618 : diag::warn_second_parameter_to_va_arg_not_pod)
17619 << TInfo->getType()
17620 << TInfo->getTypeLoc().getSourceRange();
17621 }
17622
17623 if (TInfo->getType()->isArrayType()) {
17624 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17625 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17626 << TInfo->getType()
17627 << TInfo->getTypeLoc().getSourceRange());
17628 }
17629
17630 // Check for va_arg where arguments of the given type will be promoted
17631 // (i.e. this va_arg is guaranteed to have undefined behavior).
17632 QualType PromoteType;
17633 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17634 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17635 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17636 // and C23 7.16.1.1p2 says, in part:
17637 // If type is not compatible with the type of the actual next argument
17638 // (as promoted according to the default argument promotions), the
17639 // behavior is undefined, except for the following cases:
17640 // - both types are pointers to qualified or unqualified versions of
17641 // compatible types;
17642 // - one type is compatible with a signed integer type, the other
17643 // type is compatible with the corresponding unsigned integer type,
17644 // and the value is representable in both types;
17645 // - one type is pointer to qualified or unqualified void and the
17646 // other is a pointer to a qualified or unqualified character type;
17647 // - or, the type of the next argument is nullptr_t and type is a
17648 // pointer type that has the same representation and alignment
17649 // requirements as a pointer to a character type.
17650 // Given that type compatibility is the primary requirement (ignoring
17651 // qualifications), you would think we could call typesAreCompatible()
17652 // directly to test this. However, in C++, that checks for *same type*,
17653 // which causes false positives when passing an enumeration type to
17654 // va_arg. Instead, get the underlying type of the enumeration and pass
17655 // that.
17656 QualType UnderlyingType = TInfo->getType();
17657 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17658 UnderlyingType = ED->getIntegerType();
17659 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17660 /*CompareUnqualified*/ true))
17661 PromoteType = QualType();
17662
17663 // If the types are still not compatible, we need to test whether the
17664 // promoted type and the underlying type are the same except for
17665 // signedness. Ask the AST for the correctly corresponding type and see
17666 // if that's compatible.
17667 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17668 PromoteType->isUnsignedIntegerType() !=
17669 UnderlyingType->isUnsignedIntegerType()) {
17670 UnderlyingType =
17671 UnderlyingType->isUnsignedIntegerType()
17672 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17673 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17674 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17675 /*CompareUnqualified*/ true))
17676 PromoteType = QualType();
17677 }
17678 }
17679 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17680 PromoteType = Context.DoubleTy;
17681 if (!PromoteType.isNull())
17682 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17683 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17684 << TInfo->getType()
17685 << PromoteType
17686 << TInfo->getTypeLoc().getSourceRange());
17687 }
17688
17689 QualType T = TInfo->getType().getNonLValueExprType(Context);
17690 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17691}
17692
17693ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17694 // The type of __null will be int or long, depending on the size of
17695 // pointers on the target.
17696 QualType Ty;
17697 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17698 if (pw == Context.getTargetInfo().getIntWidth())
17699 Ty = Context.IntTy;
17700 else if (pw == Context.getTargetInfo().getLongWidth())
17701 Ty = Context.LongTy;
17702 else if (pw == Context.getTargetInfo().getLongLongWidth())
17703 Ty = Context.LongLongTy;
17704 else {
17705 llvm_unreachable("I don't know size of pointer!");
17706 }
17707
17708 return new (Context) GNUNullExpr(Ty, TokenLoc);
17709}
17710
17711static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17712 CXXRecordDecl *ImplDecl = nullptr;
17713
17714 // Fetch the std::source_location::__impl decl.
17715 if (NamespaceDecl *Std = S.getStdNamespace()) {
17716 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17717 Loc, Sema::LookupOrdinaryName);
17718 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17719 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17720 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17721 Loc, Sema::LookupOrdinaryName);
17722 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17723 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17724 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17725 }
17726 }
17727 }
17728 }
17729
17730 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17731 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17732 return nullptr;
17733 }
17734
17735 // Verify that __impl is a trivial struct type, with no base classes, and with
17736 // only the four expected fields.
17737 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17738 ImplDecl->getNumBases() != 0) {
17739 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17740 return nullptr;
17741 }
17742
17743 unsigned Count = 0;
17744 for (FieldDecl *F : ImplDecl->fields()) {
17745 StringRef Name = F->getName();
17746
17747 if (Name == "_M_file_name") {
17748 if (F->getType() !=
17749 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17750 break;
17751 Count++;
17752 } else if (Name == "_M_function_name") {
17753 if (F->getType() !=
17754 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17755 break;
17756 Count++;
17757 } else if (Name == "_M_line") {
17758 if (!F->getType()->isIntegerType())
17759 break;
17760 Count++;
17761 } else if (Name == "_M_column") {
17762 if (!F->getType()->isIntegerType())
17763 break;
17764 Count++;
17765 } else {
17766 Count = 100; // invalid
17767 break;
17768 }
17769 }
17770 if (Count != 4) {
17771 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17772 return nullptr;
17773 }
17774
17775 return ImplDecl;
17776}
17777
17778ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17779 SourceLocation BuiltinLoc,
17780 SourceLocation RPLoc) {
17781 QualType ResultTy;
17782 switch (Kind) {
17783 case SourceLocIdentKind::File:
17784 case SourceLocIdentKind::FileName:
17785 case SourceLocIdentKind::Function:
17786 case SourceLocIdentKind::FuncSig: {
17787 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17788 ResultTy =
17789 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17790 break;
17791 }
17792 case SourceLocIdentKind::Line:
17793 case SourceLocIdentKind::Column:
17794 ResultTy = Context.UnsignedIntTy;
17795 break;
17796 case SourceLocIdentKind::SourceLocStruct:
17797 if (!StdSourceLocationImplDecl) {
17798 StdSourceLocationImplDecl =
17799 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17800 if (!StdSourceLocationImplDecl)
17801 return ExprError();
17802 }
17803 ResultTy = Context.getPointerType(
17804 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17805 break;
17806 }
17807
17808 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17809}
17810
17811ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17812 SourceLocation BuiltinLoc,
17813 SourceLocation RPLoc,
17814 DeclContext *ParentContext) {
17815 return new (Context)
17816 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17817}
17818
17819ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17820 StringLiteral *BinaryData, StringRef FileName) {
17821 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17822 Data->BinaryData = BinaryData;
17823 Data->FileName = FileName;
17824 return new (Context)
17825 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17826 Data->getDataElementCount());
17827}
17828
17829static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17830 const Expr *SrcExpr) {
17831 if (!DstType->isFunctionPointerType() ||
17832 !SrcExpr->getType()->isFunctionType())
17833 return false;
17834
17835 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17836 if (!DRE)
17837 return false;
17838
17839 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17840 if (!FD)
17841 return false;
17842
17843 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17844 /*Complain=*/true,
17845 Loc: SrcExpr->getBeginLoc());
17846}
17847
17848bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17849 SourceLocation Loc,
17850 QualType DstType, QualType SrcType,
17851 Expr *SrcExpr, AssignmentAction Action,
17852 bool *Complained) {
17853 if (Complained)
17854 *Complained = false;
17855
17856 // Decode the result (notice that AST's are still created for extensions).
17857 bool CheckInferredResultType = false;
17858 bool isInvalid = false;
17859 unsigned DiagKind = 0;
17860 ConversionFixItGenerator ConvHints;
17861 bool MayHaveConvFixit = false;
17862 bool MayHaveFunctionDiff = false;
17863 const ObjCInterfaceDecl *IFace = nullptr;
17864 const ObjCProtocolDecl *PDecl = nullptr;
17865
17866 switch (ConvTy) {
17867 case AssignConvertType::Compatible:
17868 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17869 return false;
17870 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17871 // Still a valid conversion, but we may want to diagnose for C++
17872 // compatibility reasons.
17873 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17874 break;
17875 case AssignConvertType::PointerToInt:
17876 if (getLangOpts().CPlusPlus) {
17877 DiagKind = diag::err_typecheck_convert_pointer_int;
17878 isInvalid = true;
17879 } else {
17880 DiagKind = diag::ext_typecheck_convert_pointer_int;
17881 }
17882 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17883 MayHaveConvFixit = true;
17884 break;
17885 case AssignConvertType::IntToPointer:
17886 if (getLangOpts().CPlusPlus) {
17887 DiagKind = diag::err_typecheck_convert_int_pointer;
17888 isInvalid = true;
17889 } else {
17890 DiagKind = diag::ext_typecheck_convert_int_pointer;
17891 }
17892 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17893 MayHaveConvFixit = true;
17894 break;
17895 case AssignConvertType::IncompatibleFunctionPointerStrict:
17896 DiagKind =
17897 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17898 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17899 MayHaveConvFixit = true;
17900 break;
17901 case AssignConvertType::IncompatibleFunctionPointer:
17902 if (getLangOpts().CPlusPlus) {
17903 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17904 isInvalid = true;
17905 } else {
17906 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17907 }
17908 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17909 MayHaveConvFixit = true;
17910 break;
17911 case AssignConvertType::IncompatiblePointer:
17912 if (Action == AssignmentAction::Passing_CFAudited) {
17913 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17914 } else if (getLangOpts().CPlusPlus) {
17915 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17916 isInvalid = true;
17917 } else {
17918 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17919 }
17920 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17921 SrcType->isObjCObjectPointerType();
17922 if (CheckInferredResultType) {
17923 SrcType = SrcType.getUnqualifiedType();
17924 DstType = DstType.getUnqualifiedType();
17925 } else {
17926 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17927 }
17928 MayHaveConvFixit = true;
17929 break;
17930 case AssignConvertType::IncompatiblePointerSign:
17931 if (getLangOpts().CPlusPlus) {
17932 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17933 isInvalid = true;
17934 } else {
17935 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17936 }
17937 break;
17938 case AssignConvertType::FunctionVoidPointer:
17939 if (getLangOpts().CPlusPlus) {
17940 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17941 isInvalid = true;
17942 } else {
17943 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17944 }
17945 break;
17946 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17947 // Perform decay if necessary.
17948 if (SrcType->canDecayToPointerType())
17949 SrcType = Context.getDecayedType(T: SrcType);
17950
17951 isInvalid = true;
17952
17953 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17954 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17955 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17956 DiagKind = diag::err_typecheck_incompatible_address_space;
17957 break;
17958 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17959 DiagKind = diag::err_typecheck_incompatible_ownership;
17960 break;
17961 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17962 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17963 break;
17964 }
17965
17966 llvm_unreachable("unknown error case for discarding qualifiers!");
17967 // fallthrough
17968 }
17969 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17970 if (SrcType->isArrayType())
17971 SrcType = Context.getArrayDecayedType(T: SrcType);
17972
17973 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17974 break;
17975 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17976 // If the qualifiers lost were because we were applying the
17977 // (deprecated) C++ conversion from a string literal to a char*
17978 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17979 // Ideally, this check would be performed in
17980 // checkPointerTypesForAssignment. However, that would require a
17981 // bit of refactoring (so that the second argument is an
17982 // expression, rather than a type), which should be done as part
17983 // of a larger effort to fix checkPointerTypesForAssignment for
17984 // C++ semantics.
17985 if (getLangOpts().CPlusPlus &&
17986 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17987 return false;
17988 if (getLangOpts().CPlusPlus) {
17989 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17990 isInvalid = true;
17991 } else {
17992 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17993 }
17994
17995 break;
17996 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17997 if (getLangOpts().CPlusPlus) {
17998 isInvalid = true;
17999 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
18000 } else {
18001 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
18002 }
18003 break;
18004 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
18005 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
18006 isInvalid = true;
18007 break;
18008 case AssignConvertType::IntToBlockPointer:
18009 DiagKind = diag::err_int_to_block_pointer;
18010 isInvalid = true;
18011 break;
18012 case AssignConvertType::IncompatibleBlockPointer:
18013 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
18014 isInvalid = true;
18015 break;
18016 case AssignConvertType::IncompatibleObjCQualifiedId: {
18017 if (SrcType->isObjCQualifiedIdType()) {
18018 const ObjCObjectPointerType *srcOPT =
18019 SrcType->castAs<ObjCObjectPointerType>();
18020 for (auto *srcProto : srcOPT->quals()) {
18021 PDecl = srcProto;
18022 break;
18023 }
18024 if (const ObjCInterfaceType *IFaceT =
18025 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
18026 IFace = IFaceT->getDecl();
18027 }
18028 else if (DstType->isObjCQualifiedIdType()) {
18029 const ObjCObjectPointerType *dstOPT =
18030 DstType->castAs<ObjCObjectPointerType>();
18031 for (auto *dstProto : dstOPT->quals()) {
18032 PDecl = dstProto;
18033 break;
18034 }
18035 if (const ObjCInterfaceType *IFaceT =
18036 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
18037 IFace = IFaceT->getDecl();
18038 }
18039 if (getLangOpts().CPlusPlus) {
18040 DiagKind = diag::err_incompatible_qualified_id;
18041 isInvalid = true;
18042 } else {
18043 DiagKind = diag::warn_incompatible_qualified_id;
18044 }
18045 break;
18046 }
18047 case AssignConvertType::IncompatibleVectors:
18048 if (getLangOpts().CPlusPlus) {
18049 DiagKind = diag::err_incompatible_vectors;
18050 isInvalid = true;
18051 } else {
18052 DiagKind = diag::warn_incompatible_vectors;
18053 }
18054 break;
18055 case AssignConvertType::IncompatibleObjCWeakRef:
18056 DiagKind = diag::err_arc_weak_unavailable_assign;
18057 isInvalid = true;
18058 break;
18059 case AssignConvertType::CompatibleOBTDiscards:
18060 return false;
18061 case AssignConvertType::IncompatibleOBTKinds: {
18062 assert(!SrcType->isFunctionType() &&
18063 "Unexpected function type found in IncompatibleOBTKinds assignment");
18064 if (SrcType->canDecayToPointerType())
18065 SrcType = Context.getDecayedType(T: SrcType);
18066
18067 auto getOBTKindName = [](QualType Ty) -> StringRef {
18068 if (Ty->isPointerType())
18069 Ty = Ty->getPointeeType();
18070 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18071 return OBT->getBehaviorKind() ==
18072 OverflowBehaviorType::OverflowBehaviorKind::Trap
18073 ? "__ob_trap"
18074 : "__ob_wrap";
18075 }
18076 llvm_unreachable("OBT kind unhandled");
18077 };
18078
18079 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
18080 << DstType << SrcType << getOBTKindName(DstType)
18081 << getOBTKindName(SrcType);
18082 isInvalid = true;
18083 return true;
18084 }
18085 case AssignConvertType::Incompatible:
18086 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
18087 if (Complained)
18088 *Complained = true;
18089 return true;
18090 }
18091
18092 DiagKind = diag::err_typecheck_convert_incompatible;
18093 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18094 MayHaveConvFixit = true;
18095 isInvalid = true;
18096 MayHaveFunctionDiff = true;
18097 break;
18098 }
18099
18100 QualType FirstType, SecondType;
18101 switch (Action) {
18102 case AssignmentAction::Assigning:
18103 case AssignmentAction::Initializing:
18104 // The destination type comes first.
18105 FirstType = DstType;
18106 SecondType = SrcType;
18107 break;
18108
18109 case AssignmentAction::Returning:
18110 case AssignmentAction::Passing:
18111 case AssignmentAction::Passing_CFAudited:
18112 case AssignmentAction::Converting:
18113 case AssignmentAction::Sending:
18114 case AssignmentAction::Casting:
18115 // The source type comes first.
18116 FirstType = SrcType;
18117 SecondType = DstType;
18118 break;
18119 }
18120
18121 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
18122 AssignmentAction ActionForDiag = Action;
18123 if (Action == AssignmentAction::Passing_CFAudited)
18124 ActionForDiag = AssignmentAction::Passing;
18125
18126 FDiag << FirstType << SecondType << ActionForDiag
18127 << SrcExpr->getSourceRange();
18128
18129 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18130 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18131 auto isPlainChar = [](const clang::Type *Type) {
18132 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
18133 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
18134 };
18135 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18136 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18137 }
18138
18139 // If we can fix the conversion, suggest the FixIts.
18140 if (!ConvHints.isNull()) {
18141 for (FixItHint &H : ConvHints.Hints)
18142 FDiag << H;
18143 }
18144
18145 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18146
18147 if (MayHaveFunctionDiff)
18148 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
18149
18150 Diag(Loc, PD: FDiag);
18151 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18152 DiagKind == diag::err_incompatible_qualified_id) &&
18153 PDecl && IFace && !IFace->hasDefinition())
18154 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
18155 << IFace << PDecl;
18156
18157 if (SecondType == Context.OverloadTy)
18158 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
18159 DestType: FirstType, /*TakingAddress=*/true);
18160
18161 if (CheckInferredResultType)
18162 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
18163
18164 if (Action == AssignmentAction::Returning &&
18165 ConvTy == AssignConvertType::IncompatiblePointer)
18166 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
18167
18168 if (Complained)
18169 *Complained = true;
18170 return isInvalid;
18171}
18172
18173ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18174 llvm::APSInt *Result,
18175 AllowFoldKind CanFold) {
18176 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18177 public:
18178 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18179 QualType T) override {
18180 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
18181 << T << S.LangOpts.CPlusPlus;
18182 }
18183 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18184 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18185 }
18186 } Diagnoser;
18187
18188 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18189}
18190
18191ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18192 llvm::APSInt *Result,
18193 unsigned DiagID,
18194 AllowFoldKind CanFold) {
18195 class IDDiagnoser : public VerifyICEDiagnoser {
18196 unsigned DiagID;
18197
18198 public:
18199 IDDiagnoser(unsigned DiagID)
18200 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18201
18202 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18203 return S.Diag(Loc, DiagID);
18204 }
18205 } Diagnoser(DiagID);
18206
18207 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18208}
18209
18210Sema::SemaDiagnosticBuilder
18211Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
18212 QualType T) {
18213 return diagnoseNotICE(S, Loc);
18214}
18215
18216Sema::SemaDiagnosticBuilder
18217Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
18218 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18219}
18220
18221ExprResult
18222Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
18223 VerifyICEDiagnoser &Diagnoser,
18224 AllowFoldKind CanFold) {
18225 SourceLocation DiagLoc = E->getBeginLoc();
18226
18227 if (getLangOpts().CPlusPlus11) {
18228 // C++11 [expr.const]p5:
18229 // If an expression of literal class type is used in a context where an
18230 // integral constant expression is required, then that class type shall
18231 // have a single non-explicit conversion function to an integral or
18232 // unscoped enumeration type
18233 ExprResult Converted;
18234 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18235 VerifyICEDiagnoser &BaseDiagnoser;
18236 public:
18237 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18238 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18239 BaseDiagnoser.Suppress, true),
18240 BaseDiagnoser(BaseDiagnoser) {}
18241
18242 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18243 QualType T) override {
18244 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18245 }
18246
18247 SemaDiagnosticBuilder diagnoseIncomplete(
18248 Sema &S, SourceLocation Loc, QualType T) override {
18249 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
18250 }
18251
18252 SemaDiagnosticBuilder diagnoseExplicitConv(
18253 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18254 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
18255 }
18256
18257 SemaDiagnosticBuilder noteExplicitConv(
18258 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18259 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18260 << ConvTy->isEnumeralType() << ConvTy;
18261 }
18262
18263 SemaDiagnosticBuilder diagnoseAmbiguous(
18264 Sema &S, SourceLocation Loc, QualType T) override {
18265 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
18266 }
18267
18268 SemaDiagnosticBuilder noteAmbiguous(
18269 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18270 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18271 << ConvTy->isEnumeralType() << ConvTy;
18272 }
18273
18274 SemaDiagnosticBuilder diagnoseConversion(
18275 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18276 llvm_unreachable("conversion functions are permitted");
18277 }
18278 } ConvertDiagnoser(Diagnoser);
18279
18280 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18281 Converter&: ConvertDiagnoser);
18282 if (Converted.isInvalid())
18283 return Converted;
18284 E = Converted.get();
18285 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18286 // don't try to evaluate it later. We also don't want to return the
18287 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18288 // this function will attempt to use 'Value'.
18289 if (isa<RecoveryExpr>(Val: E))
18290 return ExprError();
18291 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18292 return ExprError();
18293 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18294 // An ICE must be of integral or unscoped enumeration type.
18295 if (!Diagnoser.Suppress)
18296 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18297 << E->getSourceRange();
18298 return ExprError();
18299 }
18300
18301 ExprResult RValueExpr = DefaultLvalueConversion(E);
18302 if (RValueExpr.isInvalid())
18303 return ExprError();
18304
18305 E = RValueExpr.get();
18306
18307 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18308 // in the non-ICE case.
18309 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18310 SmallVector<PartialDiagnosticAt, 8> Notes;
18311 if (Result)
18312 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18313 if (!isa<ConstantExpr>(Val: E))
18314 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18315 : ConstantExpr::Create(Context, E);
18316
18317 if (Notes.empty())
18318 return E;
18319
18320 // If our only note is the usual "invalid subexpression" note, just point
18321 // the caret at its location rather than producing an essentially
18322 // redundant note.
18323 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18324 diag::note_invalid_subexpr_in_const_expr) {
18325 DiagLoc = Notes[0].first;
18326 Notes.clear();
18327 }
18328
18329 if (getLangOpts().CPlusPlus) {
18330 if (!Diagnoser.Suppress) {
18331 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18332 for (const PartialDiagnosticAt &Note : Notes)
18333 Diag(Loc: Note.first, PD: Note.second);
18334 }
18335 return ExprError();
18336 }
18337
18338 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18339 for (const PartialDiagnosticAt &Note : Notes)
18340 Diag(Loc: Note.first, PD: Note.second);
18341
18342 return E;
18343 }
18344
18345 Expr::EvalResult EvalResult;
18346 SmallVector<PartialDiagnosticAt, 8> Notes;
18347 SmallVector<PartialDiagnosticAt> MSWarning;
18348 EvalResult.Diag = &Notes;
18349 EvalResult.ExtendedDiag = &MSWarning;
18350
18351 // Try to evaluate the expression, and produce diagnostics explaining why it's
18352 // not a constant expression as a side-effect.
18353 bool Folded =
18354 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18355 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18356 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18357
18358 if (!isa<ConstantExpr>(Val: E))
18359 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18360
18361 // For -fms-compatibility mode we relax some requirements
18362 // for constant folding in non-SFINAE contexts
18363 if (!MSWarning.empty()) {
18364 if (isSFINAEContext()) {
18365 Folded = false;
18366 } else {
18367 for (auto &Info : MSWarning)
18368 Diag(Loc: Info.first, PD: Info.second);
18369 }
18370 }
18371
18372 // In C++11, we can rely on diagnostics being produced for any expression
18373 // which is not a constant expression. If no diagnostics were produced, then
18374 // this is a constant expression.
18375 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18376 if (Result)
18377 *Result = EvalResult.Val.getInt();
18378 return E;
18379 }
18380
18381 // If our only note is the usual "invalid subexpression" note, just point
18382 // the caret at its location rather than producing an essentially
18383 // redundant note.
18384 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18385 diag::note_invalid_subexpr_in_const_expr) {
18386 DiagLoc = Notes[0].first;
18387 Notes.clear();
18388 }
18389
18390 if (!Folded || CanFold == AllowFoldKind::No) {
18391 if (!Diagnoser.Suppress) {
18392 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18393 for (const PartialDiagnosticAt &Note : Notes)
18394 Diag(Loc: Note.first, PD: Note.second);
18395 }
18396
18397 return ExprError();
18398 }
18399
18400 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18401 for (const PartialDiagnosticAt &Note : Notes)
18402 Diag(Loc: Note.first, PD: Note.second);
18403
18404 if (Result)
18405 *Result = EvalResult.Val.getInt();
18406 return E;
18407}
18408
18409namespace {
18410 // Handle the case where we conclude a expression which we speculatively
18411 // considered to be unevaluated is actually evaluated.
18412 class TransformToPE : public TreeTransform<TransformToPE> {
18413 typedef TreeTransform<TransformToPE> BaseTransform;
18414
18415 public:
18416 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18417
18418 // Make sure we redo semantic analysis
18419 bool AlwaysRebuild() { return true; }
18420 bool ReplacingOriginal() { return true; }
18421
18422 // We need to special-case DeclRefExprs referring to FieldDecls which
18423 // are not part of a member pointer formation; normal TreeTransforming
18424 // doesn't catch this case because of the way we represent them in the AST.
18425 // FIXME: This is a bit ugly; is it really the best way to handle this
18426 // case?
18427 //
18428 // Error on DeclRefExprs referring to FieldDecls.
18429 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18430 if (isa<FieldDecl>(Val: E->getDecl()) &&
18431 !SemaRef.isUnevaluatedContext())
18432 return SemaRef.Diag(Loc: E->getLocation(),
18433 DiagID: diag::err_invalid_non_static_member_use)
18434 << E->getDecl() << E->getSourceRange();
18435
18436 return BaseTransform::TransformDeclRefExpr(E);
18437 }
18438
18439 // Exception: filter out member pointer formation
18440 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18441 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18442 return E;
18443
18444 return BaseTransform::TransformUnaryOperator(E);
18445 }
18446
18447 // The body of a lambda-expression is in a separate expression evaluation
18448 // context so never needs to be transformed.
18449 // FIXME: Ideally we wouldn't transform the closure type either, and would
18450 // just recreate the capture expressions and lambda expression.
18451 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18452 return SkipLambdaBody(E, S: Body);
18453 }
18454 };
18455}
18456
18457ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18458 assert(isUnevaluatedContext() &&
18459 "Should only transform unevaluated expressions");
18460 ExprEvalContexts.back().Context =
18461 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18462 if (isUnevaluatedContext())
18463 return E;
18464 return TransformToPE(*this).TransformExpr(E);
18465}
18466
18467TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18468 assert(isUnevaluatedContext() &&
18469 "Should only transform unevaluated expressions");
18470 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18471 if (isUnevaluatedContext())
18472 return TInfo;
18473 return TransformToPE(*this).TransformType(TSI: TInfo);
18474}
18475
18476void
18477Sema::PushExpressionEvaluationContext(
18478 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18479 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18480 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18481 Args&: LambdaContextDecl, Args&: ExprContext);
18482
18483 // Discarded statements and immediate contexts nested in other
18484 // discarded statements or immediate context are themselves
18485 // a discarded statement or an immediate context, respectively.
18486 ExprEvalContexts.back().InDiscardedStatement =
18487 parentEvaluationContext().isDiscardedStatementContext();
18488
18489 // C++23 [expr.const]/p15
18490 // An expression or conversion is in an immediate function context if [...]
18491 // it is a subexpression of a manifestly constant-evaluated expression or
18492 // conversion.
18493 const auto &Prev = parentEvaluationContext();
18494 ExprEvalContexts.back().InImmediateFunctionContext =
18495 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18496
18497 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18498 Prev.InImmediateEscalatingFunctionContext;
18499
18500 Cleanup.reset();
18501 if (!MaybeODRUseExprs.empty())
18502 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18503}
18504
18505void
18506Sema::PushExpressionEvaluationContext(
18507 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18508 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18509 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18510 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18511}
18512
18513void Sema::PushExpressionEvaluationContextForFunction(
18514 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18515 // [expr.const]/p14.1
18516 // An expression or conversion is in an immediate function context if it is
18517 // potentially evaluated and either: its innermost enclosing non-block scope
18518 // is a function parameter scope of an immediate function.
18519 PushExpressionEvaluationContext(
18520 NewContext: FD && FD->isConsteval()
18521 ? ExpressionEvaluationContext::ImmediateFunctionContext
18522 : NewContext);
18523 const Sema::ExpressionEvaluationContextRecord &Parent =
18524 parentEvaluationContext();
18525 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18526
18527 Current.InDiscardedStatement = false;
18528
18529 if (FD) {
18530
18531 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18532 // context is nested in an immediate function context, so smaller contexts
18533 // that appear inside immediate functions (like variable initializers) are
18534 // considered to be inside an immediate function context even though by
18535 // themselves they are not immediate function contexts. But when a new
18536 // function is entered, we need to reset this tracking, since the entered
18537 // function might be not an immediate function.
18538
18539 Current.InImmediateEscalatingFunctionContext =
18540 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18541
18542 if (isLambdaMethod(DC: FD))
18543 Current.InImmediateFunctionContext =
18544 FD->isConsteval() ||
18545 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18546 Parent.isImmediateFunctionContext()));
18547 else
18548 Current.InImmediateFunctionContext = FD->isConsteval();
18549 }
18550}
18551
18552ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18553 TypeSourceInfo *TSI) {
18554 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18555}
18556
18557ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18558 TypeSourceInfo *TSI) {
18559 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TSI);
18560}
18561
18562namespace {
18563
18564const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18565 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18566 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18567 if (E->getOpcode() == UO_Deref)
18568 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18569 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18570 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18571 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18572 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18573 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18574 QualType Inner;
18575 QualType Ty = E->getType();
18576 if (const auto *Ptr = Ty->getAs<PointerType>())
18577 Inner = Ptr->getPointeeType();
18578 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18579 Inner = Arr->getElementType();
18580 else
18581 return nullptr;
18582
18583 if (Inner->hasAttr(AK: attr::NoDeref))
18584 return E;
18585 }
18586 return nullptr;
18587}
18588
18589} // namespace
18590
18591void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18592 for (const Expr *E : Rec.PossibleDerefs) {
18593 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18594 if (DeclRef) {
18595 const ValueDecl *Decl = DeclRef->getDecl();
18596 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18597 << Decl->getName() << E->getSourceRange();
18598 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18599 } else {
18600 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18601 << E->getSourceRange();
18602 }
18603 }
18604 Rec.PossibleDerefs.clear();
18605}
18606
18607void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18608 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18609 return;
18610
18611 // Note: ignoring parens here is not justified by the standard rules, but
18612 // ignoring parentheses seems like a more reasonable approach, and this only
18613 // drives a deprecation warning so doesn't affect conformance.
18614 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18615 if (BO->getOpcode() == BO_Assign) {
18616 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18617 llvm::erase(C&: LHSs, V: BO->getLHS());
18618 }
18619 }
18620}
18621
18622void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18623 assert(getLangOpts().CPlusPlus20 &&
18624 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18625 "Cannot mark an immediate escalating expression outside of an "
18626 "immediate escalating context");
18627 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18628 Call && Call->getCallee()) {
18629 if (auto *DeclRef =
18630 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18631 DeclRef->setIsImmediateEscalating(true);
18632 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18633 Ctr->setIsImmediateEscalating(true);
18634 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18635 DeclRef->setIsImmediateEscalating(true);
18636 } else {
18637 assert(false && "expected an immediately escalating expression");
18638 }
18639 if (FunctionScopeInfo *FI = getCurFunction())
18640 FI->FoundImmediateEscalatingExpression = true;
18641}
18642
18643ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18644 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18645 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18646 isCheckingDefaultArgumentOrInitializer() ||
18647 RebuildingImmediateInvocation || isImmediateFunctionContext())
18648 return E;
18649
18650 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18651 /// It's OK if this fails; we'll also remove this in
18652 /// HandleImmediateInvocations, but catching it here allows us to avoid
18653 /// walking the AST looking for it in simple cases.
18654 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18655 if (auto *DeclRef =
18656 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18657 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18658
18659 // C++23 [expr.const]/p16
18660 // An expression or conversion is immediate-escalating if it is not initially
18661 // in an immediate function context and it is [...] an immediate invocation
18662 // that is not a constant expression and is not a subexpression of an
18663 // immediate invocation.
18664 APValue Cached;
18665 auto CheckConstantExpressionAndKeepResult = [&]() {
18666 Expr::EvalResult Eval;
18667 bool Res = E.get()->EvaluateAsConstantExpr(
18668 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18669 if (Res && !Eval.DiagEmitted) {
18670 Cached = std::move(Eval.Val);
18671 return true;
18672 }
18673 return false;
18674 };
18675
18676 if (!E.get()->isValueDependent() &&
18677 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18678 !CheckConstantExpressionAndKeepResult()) {
18679 MarkExpressionAsImmediateEscalating(E: E.get());
18680 return E;
18681 }
18682
18683 if (Cleanup.exprNeedsCleanups()) {
18684 // Since an immediate invocation is a full expression itself - it requires
18685 // an additional ExprWithCleanups node, but it can participate to a bigger
18686 // full expression which actually requires cleanups to be run after so
18687 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18688 // may discard cleanups for outer expression too early.
18689
18690 // Note that ExprWithCleanups created here must always have empty cleanup
18691 // objects:
18692 // - compound literals do not create cleanup objects in C++ and immediate
18693 // invocations are C++-only.
18694 // - blocks are not allowed inside constant expressions and compiler will
18695 // issue an error if they appear there.
18696 //
18697 // Hence, in correct code any cleanup objects created inside current
18698 // evaluation context must be outside the immediate invocation.
18699 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18700 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18701 }
18702
18703 ConstantExpr *Res = ConstantExpr::Create(
18704 Context: getASTContext(), E: E.get(),
18705 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18706 Context: getASTContext()),
18707 /*IsImmediateInvocation*/ true);
18708 if (Cached.hasValue())
18709 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18710 /// Value-dependent constant expressions should not be immediately
18711 /// evaluated until they are instantiated.
18712 if (!Res->isValueDependent())
18713 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18714 return Res;
18715}
18716
18717static void EvaluateAndDiagnoseImmediateInvocation(
18718 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18719 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18720 Expr::EvalResult Eval;
18721 Eval.Diag = &Notes;
18722 ConstantExpr *CE = Candidate.getPointer();
18723 bool Result = CE->EvaluateAsConstantExpr(
18724 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18725 if (!Result || !Notes.empty()) {
18726 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18727 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18728 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18729 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18730 FunctionDecl *FD = nullptr;
18731 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18732 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18733 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18734 FD = Call->getConstructor();
18735 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18736 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18737
18738 assert(FD && FD->isImmediateFunction() &&
18739 "could not find an immediate function in this expression");
18740 if (FD->isInvalidDecl())
18741 return;
18742 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18743 << FD << FD->isConsteval();
18744 if (auto Context =
18745 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18746 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18747 << Context->Decl;
18748 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18749 }
18750 if (!FD->isConsteval())
18751 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18752 for (auto &Note : Notes)
18753 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18754 return;
18755 }
18756 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18757}
18758
18759static void RemoveNestedImmediateInvocation(
18760 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18761 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18762 struct ComplexRemove : TreeTransform<ComplexRemove> {
18763 using Base = TreeTransform<ComplexRemove>;
18764 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18765 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18766 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18767 CurrentII;
18768 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18769 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18770 SmallVector<Sema::ImmediateInvocationCandidate,
18771 4>::reverse_iterator Current)
18772 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18773 void RemoveImmediateInvocation(ConstantExpr* E) {
18774 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18775 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18776 return Elem.getPointer() == E;
18777 });
18778 // It is possible that some subexpression of the current immediate
18779 // invocation was handled from another expression evaluation context. Do
18780 // not handle the current immediate invocation if some of its
18781 // subexpressions failed before.
18782 if (It == IISet.rend()) {
18783 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18784 CurrentII->setInt(1);
18785 } else {
18786 It->setInt(1); // Mark as deleted
18787 }
18788 }
18789 ExprResult TransformConstantExpr(ConstantExpr *E) {
18790 if (!E->isImmediateInvocation())
18791 return Base::TransformConstantExpr(E);
18792 RemoveImmediateInvocation(E);
18793 return Base::TransformExpr(E: E->getSubExpr());
18794 }
18795 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18796 /// we need to remove its DeclRefExpr from the DRSet.
18797 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18798 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18799 return Base::TransformCXXOperatorCallExpr(E);
18800 }
18801 /// Base::TransformUserDefinedLiteral doesn't preserve the
18802 /// UserDefinedLiteral node.
18803 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18804 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18805 /// here.
18806 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18807 if (!Init)
18808 return Init;
18809
18810 // We cannot use IgnoreImpCasts because we need to preserve
18811 // full expressions.
18812 while (true) {
18813 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18814 Init = ICE->getSubExpr();
18815 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18816 Init = ICE->getSubExpr();
18817 else
18818 break;
18819 }
18820 /// ConstantExprs are the first layer of implicit node to be removed so if
18821 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18822 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18823 CE && CE->isImmediateInvocation())
18824 RemoveImmediateInvocation(E: CE);
18825 return Base::TransformInitializer(Init, NotCopyInit);
18826 }
18827 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18828 DRSet.erase(Ptr: E);
18829 return E;
18830 }
18831 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18832 // Do not rebuild lambdas to avoid creating a new type.
18833 // Lambdas have already been processed inside their eval contexts.
18834 return E;
18835 }
18836
18837 // We do not have enough information to transform opaque expressions and
18838 // assume they do not contain immediate subexpressions.
18839 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18840
18841 bool AlwaysRebuild() { return false; }
18842 bool ReplacingOriginal() { return true; }
18843 bool AllowSkippingCXXConstructExpr() {
18844 bool Res = AllowSkippingFirstCXXConstructExpr;
18845 AllowSkippingFirstCXXConstructExpr = true;
18846 return Res;
18847 }
18848 bool AllowSkippingFirstCXXConstructExpr = true;
18849 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18850 Rec.ImmediateInvocationCandidates, It);
18851
18852 /// CXXConstructExpr with a single argument are getting skipped by
18853 /// TreeTransform in some situtation because they could be implicit. This
18854 /// can only occur for the top-level CXXConstructExpr because it is used
18855 /// nowhere in the expression being transformed therefore will not be rebuilt.
18856 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18857 /// skipping the first CXXConstructExpr.
18858 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18859 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18860
18861 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18862 // The result may not be usable in case of previous compilation errors.
18863 // In this case evaluation of the expression may result in crash so just
18864 // don't do anything further with the result.
18865 if (Res.isUsable()) {
18866 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18867 It->getPointer()->setSubExpr(Res.get());
18868 }
18869}
18870
18871static void
18872HandleImmediateInvocations(Sema &SemaRef,
18873 Sema::ExpressionEvaluationContextRecord &Rec) {
18874 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18875 Rec.ReferenceToConsteval.size() == 0) ||
18876 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18877 return;
18878
18879 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18880 // [...]
18881 // - the initializer of a variable that is usable in constant expressions or
18882 // has constant initialization.
18883 if (SemaRef.getLangOpts().CPlusPlus23 &&
18884 Rec.ExprContext ==
18885 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18886 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18887 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18888 VD->hasConstantInitialization())) {
18889 // An expression or conversion is in an 'immediate function context' if it
18890 // is potentially evaluated and either:
18891 // [...]
18892 // - it is a subexpression of a manifestly constant-evaluated expression
18893 // or conversion.
18894 return;
18895 }
18896 }
18897
18898 /// When we have more than 1 ImmediateInvocationCandidates or previously
18899 /// failed immediate invocations, we need to check for nested
18900 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18901 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18902 /// invocation.
18903 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18904 !SemaRef.FailedImmediateInvocations.empty()) {
18905
18906 /// Prevent sema calls during the tree transform from adding pointers that
18907 /// are already in the sets.
18908 llvm::SaveAndRestore DisableIITracking(
18909 SemaRef.RebuildingImmediateInvocation, true);
18910
18911 /// Prevent diagnostic during tree transfrom as they are duplicates
18912 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18913
18914 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18915 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18916 if (!It->getInt())
18917 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18918 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18919 Rec.ReferenceToConsteval.size()) {
18920 struct SimpleRemove : DynamicRecursiveASTVisitor {
18921 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18922 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18923 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18924 DRSet.erase(Ptr: E);
18925 return DRSet.size();
18926 }
18927 } Visitor(Rec.ReferenceToConsteval);
18928 Visitor.TraverseStmt(
18929 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18930 }
18931 for (auto CE : Rec.ImmediateInvocationCandidates)
18932 if (!CE.getInt())
18933 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18934 for (auto *DR : Rec.ReferenceToConsteval) {
18935 // If the expression is immediate escalating, it is not an error;
18936 // The outer context itself becomes immediate and further errors,
18937 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18938 if (DR->isImmediateEscalating())
18939 continue;
18940 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18941 const NamedDecl *ND = FD;
18942 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18943 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18944 ND = MD->getParent();
18945
18946 // C++23 [expr.const]/p16
18947 // An expression or conversion is immediate-escalating if it is not
18948 // initially in an immediate function context and it is [...] a
18949 // potentially-evaluated id-expression that denotes an immediate function
18950 // that is not a subexpression of an immediate invocation.
18951 bool ImmediateEscalating = false;
18952 bool IsPotentiallyEvaluated =
18953 Rec.Context ==
18954 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18955 Rec.Context ==
18956 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18957 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18958 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18959
18960 if (!Rec.InImmediateEscalatingFunctionContext ||
18961 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18962 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18963 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18964 if (!FD->getBuiltinID())
18965 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18966 if (auto Context =
18967 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18968 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18969 << Context->Decl;
18970 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18971 }
18972 if (FD->isImmediateEscalating() && !FD->isConsteval())
18973 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18974
18975 } else {
18976 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18977 }
18978 }
18979}
18980
18981void Sema::PopExpressionEvaluationContext() {
18982 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18983 if (!Rec.Lambdas.empty()) {
18984 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18985 if (!getLangOpts().CPlusPlus20 &&
18986 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18987 Rec.isUnevaluated() ||
18988 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18989 unsigned D;
18990 if (Rec.isUnevaluated()) {
18991 // C++11 [expr.prim.lambda]p2:
18992 // A lambda-expression shall not appear in an unevaluated operand
18993 // (Clause 5).
18994 D = diag::err_lambda_unevaluated_operand;
18995 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18996 // C++1y [expr.const]p2:
18997 // A conditional-expression e is a core constant expression unless the
18998 // evaluation of e, following the rules of the abstract machine, would
18999 // evaluate [...] a lambda-expression.
19000 D = diag::err_lambda_in_constant_expression;
19001 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
19002 // C++17 [expr.prim.lamda]p2:
19003 // A lambda-expression shall not appear [...] in a template-argument.
19004 D = diag::err_lambda_in_invalid_context;
19005 } else
19006 llvm_unreachable("Couldn't infer lambda error message.");
19007
19008 for (const auto *L : Rec.Lambdas)
19009 Diag(Loc: L->getBeginLoc(), DiagID: D);
19010 }
19011 }
19012
19013 // Append the collected materialized temporaries into previous context before
19014 // exit if the previous also is a lifetime extending context.
19015 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
19016 parentEvaluationContext().InLifetimeExtendingContext &&
19017 !Rec.ForRangeLifetimeExtendTemps.empty()) {
19018 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
19019 RHS: Rec.ForRangeLifetimeExtendTemps);
19020 }
19021
19022 WarnOnPendingNoDerefs(Rec);
19023 HandleImmediateInvocations(SemaRef&: *this, Rec);
19024
19025 // Warn on any volatile-qualified simple-assignments that are not discarded-
19026 // value expressions nor unevaluated operands (those cases get removed from
19027 // this list by CheckUnusedVolatileAssignment).
19028 for (auto *BO : Rec.VolatileAssignmentLHSs)
19029 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
19030 << BO->getType();
19031
19032 // When are coming out of an unevaluated context, clear out any
19033 // temporaries that we may have created as part of the evaluation of
19034 // the expression in that context: they aren't relevant because they
19035 // will never be constructed.
19036 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
19037 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
19038 CE: ExprCleanupObjects.end());
19039 Cleanup = Rec.ParentCleanup;
19040 CleanupVarDeclMarking();
19041 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
19042 // Otherwise, merge the contexts together.
19043 } else {
19044 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
19045 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
19046 }
19047
19048 DiagnoseMisalignedMembers();
19049
19050 // Pop the current expression evaluation context off the stack.
19051 ExprEvalContexts.pop_back();
19052}
19053
19054void Sema::DiscardCleanupsInEvaluationContext() {
19055 ExprCleanupObjects.erase(
19056 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19057 CE: ExprCleanupObjects.end());
19058 Cleanup.reset();
19059 MaybeODRUseExprs.clear();
19060}
19061
19062ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
19063 ExprResult Result = CheckPlaceholderExpr(E);
19064 if (Result.isInvalid())
19065 return ExprError();
19066 E = Result.get();
19067 if (!E->getType()->isVariablyModifiedType())
19068 return E;
19069 return TransformToPotentiallyEvaluated(E);
19070}
19071
19072/// Are we in a context that is potentially constant evaluated per C++20
19073/// [expr.const]p12?
19074static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
19075 /// C++2a [expr.const]p12:
19076 // An expression or conversion is potentially constant evaluated if it is
19077 switch (SemaRef.ExprEvalContexts.back().Context) {
19078 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
19079 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
19080
19081 // -- a manifestly constant-evaluated expression,
19082 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
19083 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19084 case Sema::ExpressionEvaluationContext::DiscardedStatement:
19085 // -- a potentially-evaluated expression,
19086 case Sema::ExpressionEvaluationContext::UnevaluatedList:
19087 // -- an immediate subexpression of a braced-init-list,
19088
19089 // -- [FIXME] an expression of the form & cast-expression that occurs
19090 // within a templated entity
19091 // -- a subexpression of one of the above that is not a subexpression of
19092 // a nested unevaluated operand.
19093 return true;
19094
19095 case Sema::ExpressionEvaluationContext::Unevaluated:
19096 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
19097 // Expressions in this context are never evaluated.
19098 return false;
19099 }
19100 llvm_unreachable("Invalid context");
19101}
19102
19103/// Return true if this function has a calling convention that requires mangling
19104/// in the size of the parameter pack.
19105static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
19106 // These manglings are only applicable for targets whcih use Microsoft
19107 // mangling scheme for C.
19108 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
19109 return false;
19110
19111 // If this is C++ and this isn't an extern "C" function, parameters do not
19112 // need to be complete. In this case, C++ mangling will apply, which doesn't
19113 // use the size of the parameters.
19114 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19115 return false;
19116
19117 // Stdcall, fastcall, and vectorcall need this special treatment.
19118 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19119 switch (CC) {
19120 case CC_X86StdCall:
19121 case CC_X86FastCall:
19122 case CC_X86VectorCall:
19123 return true;
19124 default:
19125 break;
19126 }
19127 return false;
19128}
19129
19130/// Require that all of the parameter types of function be complete. Normally,
19131/// parameter types are only required to be complete when a function is called
19132/// or defined, but to mangle functions with certain calling conventions, the
19133/// mangler needs to know the size of the parameter list. In this situation,
19134/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19135/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19136/// result in a linker error. Clang doesn't implement this behavior, and instead
19137/// attempts to error at compile time.
19138static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
19139 SourceLocation Loc) {
19140 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19141 FunctionDecl *FD;
19142 ParmVarDecl *Param;
19143
19144 public:
19145 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19146 : FD(FD), Param(Param) {}
19147
19148 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19149 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19150 StringRef CCName;
19151 switch (CC) {
19152 case CC_X86StdCall:
19153 CCName = "stdcall";
19154 break;
19155 case CC_X86FastCall:
19156 CCName = "fastcall";
19157 break;
19158 case CC_X86VectorCall:
19159 CCName = "vectorcall";
19160 break;
19161 default:
19162 llvm_unreachable("CC does not need mangling");
19163 }
19164
19165 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
19166 << Param->getDeclName() << FD->getDeclName() << CCName;
19167 }
19168 };
19169
19170 for (ParmVarDecl *Param : FD->parameters()) {
19171 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19172 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
19173 }
19174}
19175
19176namespace {
19177enum class OdrUseContext {
19178 /// Declarations in this context are not odr-used.
19179 None,
19180 /// Declarations in this context are formally odr-used, but this is a
19181 /// dependent context.
19182 Dependent,
19183 /// Declarations in this context are odr-used but not actually used (yet).
19184 FormallyOdrUsed,
19185 /// Declarations in this context are used.
19186 Used
19187};
19188}
19189
19190/// Are we within a context in which references to resolved functions or to
19191/// variables result in odr-use?
19192static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19193 const Sema::ExpressionEvaluationContextRecord &Context =
19194 SemaRef.currentEvaluationContext();
19195
19196 if (Context.isUnevaluated())
19197 return OdrUseContext::None;
19198
19199 if (SemaRef.CurContext->isDependentContext())
19200 return OdrUseContext::Dependent;
19201
19202 if (Context.isDiscardedStatementContext())
19203 return OdrUseContext::FormallyOdrUsed;
19204
19205 else if (Context.Context ==
19206 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
19207 return OdrUseContext::FormallyOdrUsed;
19208
19209 return OdrUseContext::Used;
19210}
19211
19212static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
19213 if (!Func->isConstexpr())
19214 return false;
19215
19216 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19217 return true;
19218
19219 // Lambda conversion operators are never user provided.
19220 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
19221 return isLambdaConversionOperator(C: Conv);
19222
19223 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
19224 return CCD && CCD->getInheritedConstructor();
19225}
19226
19227void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
19228 bool MightBeOdrUse) {
19229 assert(Func && "No function?");
19230
19231 Func->setReferenced();
19232
19233 // Recursive functions aren't really used until they're used from some other
19234 // context.
19235 bool IsRecursiveCall = CurContext == Func;
19236
19237 // C++11 [basic.def.odr]p3:
19238 // A function whose name appears as a potentially-evaluated expression is
19239 // odr-used if it is the unique lookup result or the selected member of a
19240 // set of overloaded functions [...].
19241 //
19242 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19243 // can just check that here.
19244 OdrUseContext OdrUse =
19245 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
19246 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19247 OdrUse = OdrUseContext::FormallyOdrUsed;
19248
19249 // Trivial default constructors and destructors are never actually used.
19250 // FIXME: What about other special members?
19251 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19252 OdrUse == OdrUseContext::Used) {
19253 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
19254 if (Constructor->isDefaultConstructor())
19255 OdrUse = OdrUseContext::FormallyOdrUsed;
19256 if (isa<CXXDestructorDecl>(Val: Func))
19257 OdrUse = OdrUseContext::FormallyOdrUsed;
19258 }
19259
19260 // C++20 [expr.const]p12:
19261 // A function [...] is needed for constant evaluation if it is [...] a
19262 // constexpr function that is named by an expression that is potentially
19263 // constant evaluated
19264 bool NeededForConstantEvaluation =
19265 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
19266 isImplicitlyDefinableConstexprFunction(Func);
19267
19268 // Determine whether we require a function definition to exist, per
19269 // C++11 [temp.inst]p3:
19270 // Unless a function template specialization has been explicitly
19271 // instantiated or explicitly specialized, the function template
19272 // specialization is implicitly instantiated when the specialization is
19273 // referenced in a context that requires a function definition to exist.
19274 // C++20 [temp.inst]p7:
19275 // The existence of a definition of a [...] function is considered to
19276 // affect the semantics of the program if the [...] function is needed for
19277 // constant evaluation by an expression
19278 // C++20 [basic.def.odr]p10:
19279 // Every program shall contain exactly one definition of every non-inline
19280 // function or variable that is odr-used in that program outside of a
19281 // discarded statement
19282 // C++20 [special]p1:
19283 // The implementation will implicitly define [defaulted special members]
19284 // if they are odr-used or needed for constant evaluation.
19285 //
19286 // Note that we skip the implicit instantiation of templates that are only
19287 // used in unused default arguments or by recursive calls to themselves.
19288 // This is formally non-conforming, but seems reasonable in practice.
19289 bool NeedDefinition =
19290 !IsRecursiveCall &&
19291 (OdrUse == OdrUseContext::Used ||
19292 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19293
19294 // C++14 [temp.expl.spec]p6:
19295 // If a template [...] is explicitly specialized then that specialization
19296 // shall be declared before the first use of that specialization that would
19297 // cause an implicit instantiation to take place, in every translation unit
19298 // in which such a use occurs
19299 if (NeedDefinition &&
19300 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19301 Func->getMemberSpecializationInfo()))
19302 checkSpecializationReachability(Loc, Spec: Func);
19303
19304 if (getLangOpts().CUDA)
19305 CUDA().CheckCall(Loc, Callee: Func);
19306
19307 // If we need a definition, try to create one.
19308 if (NeedDefinition && !Func->getBody()) {
19309 runWithSufficientStackSpace(Loc, Fn: [&] {
19310 if (CXXConstructorDecl *Constructor =
19311 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19312 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19313 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19314 if (Constructor->isDefaultConstructor()) {
19315 if (Constructor->isTrivial() &&
19316 !Constructor->hasAttr<DLLExportAttr>())
19317 return;
19318 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19319 } else if (Constructor->isCopyConstructor()) {
19320 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19321 } else if (Constructor->isMoveConstructor()) {
19322 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19323 }
19324 } else if (Constructor->getInheritedConstructor()) {
19325 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19326 }
19327 } else if (CXXDestructorDecl *Destructor =
19328 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19329 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19330 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19331 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19332 return;
19333 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19334 }
19335 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19336 MarkVTableUsed(Loc, Class: Destructor->getParent());
19337 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19338 if (MethodDecl->isOverloadedOperator() &&
19339 MethodDecl->getOverloadedOperator() == OO_Equal) {
19340 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19341 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19342 if (MethodDecl->isCopyAssignmentOperator())
19343 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19344 else if (MethodDecl->isMoveAssignmentOperator())
19345 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19346 }
19347 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19348 MethodDecl->getParent()->isLambda()) {
19349 CXXConversionDecl *Conversion =
19350 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19351 if (Conversion->isLambdaToBlockPointerConversion())
19352 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19353 else
19354 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19355 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19356 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19357 }
19358
19359 if (Func->isDefaulted() && !Func->isDeleted()) {
19360 DefaultedComparisonKind DCK = Func->getDefaultedComparisonKind();
19361 if (DCK != DefaultedComparisonKind::None)
19362 DefineDefaultedComparison(Loc, FD: Func, DCK);
19363 }
19364
19365 // Implicit instantiation of function templates and member functions of
19366 // class templates.
19367 if (Func->isImplicitlyInstantiable()) {
19368 TemplateSpecializationKind TSK =
19369 Func->getTemplateSpecializationKindForInstantiation();
19370 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19371 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19372 if (FirstInstantiation) {
19373 PointOfInstantiation = Loc;
19374 if (auto *MSI = Func->getMemberSpecializationInfo())
19375 MSI->setPointOfInstantiation(Loc);
19376 // FIXME: Notify listener.
19377 else
19378 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19379 } else if (TSK != TSK_ImplicitInstantiation) {
19380 // Use the point of use as the point of instantiation, instead of the
19381 // point of explicit instantiation (which we track as the actual point
19382 // of instantiation). This gives better backtraces in diagnostics.
19383 PointOfInstantiation = Loc;
19384 }
19385
19386 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19387 Func->isConstexpr()) {
19388 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19389 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19390 CodeSynthesisContexts.size())
19391 PendingLocalImplicitInstantiations.push_back(
19392 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19393 else if (Func->isConstexpr())
19394 // Do not defer instantiations of constexpr functions, to avoid the
19395 // expression evaluator needing to call back into Sema if it sees a
19396 // call to such a function.
19397 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19398 else {
19399 Func->setInstantiationIsPending(true);
19400 PendingInstantiations.push_back(
19401 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19402 if (llvm::isTimeTraceVerbose()) {
19403 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19404 std::string Name;
19405 llvm::raw_string_ostream OS(Name);
19406 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19407 /*Qualified=*/true);
19408 return Name;
19409 });
19410 }
19411 // Notify the consumer that a function was implicitly instantiated.
19412 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19413 }
19414 }
19415 } else {
19416 // Walk redefinitions, as some of them may be instantiable.
19417 for (auto *i : Func->redecls()) {
19418 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19419 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19420 }
19421 }
19422 });
19423 }
19424
19425 // If a constructor was defined in the context of a default parameter
19426 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19427 // context), its initializers may not be referenced yet.
19428 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19429 EnterExpressionEvaluationContext EvalContext(
19430 *this,
19431 Constructor->isImmediateFunction()
19432 ? ExpressionEvaluationContext::ImmediateFunctionContext
19433 : ExpressionEvaluationContext::PotentiallyEvaluated,
19434 Constructor);
19435 for (CXXCtorInitializer *Init : Constructor->inits()) {
19436 if (Init->isInClassMemberInitializer())
19437 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19438 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19439 });
19440 }
19441 }
19442
19443 // C++14 [except.spec]p17:
19444 // An exception-specification is considered to be needed when:
19445 // - the function is odr-used or, if it appears in an unevaluated operand,
19446 // would be odr-used if the expression were potentially-evaluated;
19447 //
19448 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19449 // function is a pure virtual function we're calling, and in that case the
19450 // function was selected by overload resolution and we need to resolve its
19451 // exception specification for a different reason.
19452 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19453 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19454 ResolveExceptionSpec(Loc, FPT);
19455
19456 // A callee could be called by a host function then by a device function.
19457 // If we only try recording once, we will miss recording the use on device
19458 // side. Therefore keep trying until it is recorded.
19459 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19460 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19461 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19462
19463 // If this is the first "real" use, act on that.
19464 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19465 // Keep track of used but undefined functions.
19466 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19467 if (mightHaveNonExternalLinkage(FD: Func))
19468 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19469 else if (Func->getMostRecentDecl()->isInlined() &&
19470 !LangOpts.GNUInline &&
19471 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19472 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19473 else if (isExternalWithNoLinkageType(VD: Func))
19474 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19475 }
19476
19477 // Some x86 Windows calling conventions mangle the size of the parameter
19478 // pack into the name. Computing the size of the parameters requires the
19479 // parameter types to be complete. Check that now.
19480 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19481 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19482
19483 // In the MS C++ ABI, the compiler emits destructor variants where they are
19484 // used. If the destructor is used here but defined elsewhere, mark the
19485 // virtual base destructors referenced. If those virtual base destructors
19486 // are inline, this will ensure they are defined when emitting the complete
19487 // destructor variant. This checking may be redundant if the destructor is
19488 // provided later in this TU.
19489 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19490 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19491 CXXRecordDecl *Parent = Dtor->getParent();
19492 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19493 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19494 }
19495 }
19496
19497 Func->markUsed(C&: Context);
19498 }
19499}
19500
19501/// Directly mark a variable odr-used. Given a choice, prefer to use
19502/// MarkVariableReferenced since it does additional checks and then
19503/// calls MarkVarDeclODRUsed.
19504/// If the variable must be captured:
19505/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19506/// - else capture it in the DeclContext that maps to the
19507/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19508static void
19509MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19510 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19511 // Keep track of used but undefined variables.
19512 // FIXME: We shouldn't suppress this warning for static data members.
19513 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19514 assert(Var && "expected a capturable variable");
19515
19516 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19517 (!Var->isExternallyVisible() || Var->isInline() ||
19518 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19519 !(Var->isStaticDataMember() && Var->hasInit())) {
19520 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19521 if (old.isInvalid())
19522 old = Loc;
19523 }
19524 QualType CaptureType, DeclRefType;
19525 if (SemaRef.LangOpts.OpenMP)
19526 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19527 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19528 /*EllipsisLoc*/ SourceLocation(),
19529 /*BuildAndDiagnose*/ true, CaptureType,
19530 DeclRefType, FunctionScopeIndexToStopAt);
19531
19532 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19533 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19534 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19535 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19536 if (VarTarget == SemaCUDA::CVT_Host &&
19537 (UserTarget == CUDAFunctionTarget::Device ||
19538 UserTarget == CUDAFunctionTarget::HostDevice ||
19539 UserTarget == CUDAFunctionTarget::Global)) {
19540 // Diagnose ODR-use of host global variables in device functions.
19541 // Reference of device global variables in host functions is allowed
19542 // through shadow variables therefore it is not diagnosed.
19543 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19544 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19545 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19546 SemaRef.targetDiag(Loc: Var->getLocation(),
19547 DiagID: Var->getType().isConstQualified()
19548 ? diag::note_cuda_const_var_unpromoted
19549 : diag::note_cuda_host_var);
19550 }
19551 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19552 // Also capture __device__ const variables, which are classified
19553 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19554 // an explicit CUDADeviceAttr to distinguish them from plain
19555 // const variables (no __device__), which also get CVT_Both but
19556 // only have an implicit CUDADeviceAttr.
19557 (VarTarget == SemaCUDA::CVT_Both &&
19558 Var->hasAttr<CUDADeviceAttr>() &&
19559 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19560 !Var->hasAttr<CUDASharedAttr>() &&
19561 (UserTarget == CUDAFunctionTarget::Host ||
19562 UserTarget == CUDAFunctionTarget::HostDevice)) {
19563 // Record a CUDA/HIP device side variable if it is ODR-used
19564 // by host code. This is done conservatively, when the variable is
19565 // referenced in any of the following contexts:
19566 // - a non-function context
19567 // - a host function
19568 // - a host device function
19569 // This makes the ODR-use of the device side variable by host code to
19570 // be visible in the device compilation for the compiler to be able to
19571 // emit template variables instantiated by host code only and to
19572 // externalize the static device side variable ODR-used by host code.
19573 if (!Var->hasExternalStorage())
19574 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19575 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19576 (!FD || (!FD->getDescribedFunctionTemplate() &&
19577 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19578 GVA_StrongExternal)))
19579 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19580 }
19581 }
19582
19583 V->markUsed(C&: SemaRef.Context);
19584}
19585
19586void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19587 SourceLocation Loc,
19588 unsigned CapturingScopeIndex) {
19589 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19590}
19591
19592static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19593 SourceLocation loc,
19594 ValueDecl *var) {
19595 DeclContext *VarDC =
19596 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19597
19598 // If the parameter still belongs to the translation unit, then
19599 // we're actually just using one parameter in the declaration of
19600 // the next.
19601 if (isa<ParmVarDecl>(Val: var) &&
19602 isa<TranslationUnitDecl>(Val: VarDC))
19603 return;
19604
19605 // For C code, don't diagnose about capture if we're not actually in code
19606 // right now; it's impossible to write a non-constant expression outside of
19607 // function context, so we'll get other (more useful) diagnostics later.
19608 //
19609 // For C++, things get a bit more nasty... it would be nice to suppress this
19610 // diagnostic for certain cases like using a local variable in an array bound
19611 // for a member of a local class, but the correct predicate is not obvious.
19612 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19613 return;
19614
19615 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19616 unsigned ContextKind = 3; // unknown
19617 if (isa<CXXMethodDecl>(Val: VarDC) &&
19618 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19619 ContextKind = 2;
19620 } else if (isa<FunctionDecl>(Val: VarDC)) {
19621 ContextKind = 0;
19622 } else if (isa<BlockDecl>(Val: VarDC)) {
19623 ContextKind = 1;
19624 }
19625
19626 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19627 << var << ValueKind << ContextKind << VarDC;
19628 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19629 << var;
19630
19631 // FIXME: Add additional diagnostic info about class etc. which prevents
19632 // capture.
19633}
19634
19635static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19636 ValueDecl *Var,
19637 bool &SubCapturesAreNested,
19638 QualType &CaptureType,
19639 QualType &DeclRefType) {
19640 // Check whether we've already captured it.
19641 if (CSI->CaptureMap.count(Val: Var)) {
19642 // If we found a capture, any subcaptures are nested.
19643 SubCapturesAreNested = true;
19644
19645 // Retrieve the capture type for this variable.
19646 CaptureType = CSI->getCapture(Var).getCaptureType();
19647
19648 // Compute the type of an expression that refers to this variable.
19649 DeclRefType = CaptureType.getNonReferenceType();
19650
19651 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19652 // are mutable in the sense that user can change their value - they are
19653 // private instances of the captured declarations.
19654 const Capture &Cap = CSI->getCapture(Var);
19655 // C++ [expr.prim.lambda]p10:
19656 // The type of such a data member is [...] an lvalue reference to the
19657 // referenced function type if the entity is a reference to a function.
19658 // [...]
19659 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19660 !(isa<LambdaScopeInfo>(Val: CSI) &&
19661 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19662 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19663 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19664 DeclRefType.addConst();
19665 return true;
19666 }
19667 return false;
19668}
19669
19670// Only block literals, captured statements, and lambda expressions can
19671// capture; other scopes don't work.
19672static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19673 ValueDecl *Var,
19674 SourceLocation Loc,
19675 const bool Diagnose,
19676 Sema &S) {
19677 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19678 return getLambdaAwareParentOfDeclContext(DC);
19679
19680 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19681 if (Underlying) {
19682 if (Underlying->hasLocalStorage() && Diagnose)
19683 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19684 }
19685 return nullptr;
19686}
19687
19688// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19689// certain types of variables (unnamed, variably modified types etc.)
19690// so check for eligibility.
19691static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19692 SourceLocation Loc, const bool Diagnose,
19693 Sema &S) {
19694
19695 assert((isa<VarDecl, BindingDecl>(Var)) &&
19696 "Only variables and structured bindings can be captured");
19697
19698 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19699 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19700
19701 // Reject bindings referenced from a lambda or block that wraps an OpenMP
19702 // region.
19703 if ((IsLambda || IsBlock) && S.getLangOpts().OpenMP &&
19704 isa<DecompositionDecl>(Val: Var)) {
19705 if (Diagnose)
19706 S.Diag(Loc, DiagID: diag::err_omp_unsupported_on_binding) << 3;
19707 return false;
19708 }
19709
19710 // Lambdas are not allowed to capture unnamed variables
19711 // (e.g. anonymous unions).
19712 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19713 // assuming that's the intent.
19714 if (IsLambda && !Var->getDeclName()) {
19715 if (Diagnose) {
19716 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19717 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19718 }
19719 return false;
19720 }
19721
19722 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19723 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19724 if (Diagnose) {
19725 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19726 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19727 }
19728 return false;
19729 }
19730 // Prohibit structs with flexible array members too.
19731 // We cannot capture what is in the tail end of the struct.
19732 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19733 VTD && VTD->hasFlexibleArrayMember()) {
19734 if (Diagnose) {
19735 if (IsBlock)
19736 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19737 else
19738 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19739 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19740 }
19741 return false;
19742 }
19743 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19744 // Lambdas and captured statements are not allowed to capture __block
19745 // variables; they don't support the expected semantics.
19746 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19747 if (Diagnose) {
19748 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19749 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19750 }
19751 return false;
19752 }
19753 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19754 if (S.getLangOpts().OpenCL && IsBlock &&
19755 Var->getType()->isBlockPointerType()) {
19756 if (Diagnose)
19757 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19758 return false;
19759 }
19760
19761 if (auto *BD = dyn_cast<BindingDecl>(Val: Var)) {
19762 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19763 if (RSI->CapRegionKind == CR_OpenMP) {
19764 if (BD->getHoldingVar()) {
19765 if (Diagnose) {
19766 S.Diag(Loc, DiagID: diag::err_capture_tuple_binding_openmp) << Var;
19767 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19768 }
19769 return false;
19770 }
19771 if (Diagnose && S.getLangOpts().CPlusPlus) {
19772 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19773 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19774 }
19775 return true;
19776 }
19777 }
19778 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19779 if (Diagnose)
19780 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19781 return false;
19782 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19783 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19784 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19785 }
19786 }
19787
19788 return true;
19789}
19790
19791// Returns true if the capture by block was successful.
19792static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19793 SourceLocation Loc, const bool BuildAndDiagnose,
19794 QualType &CaptureType, QualType &DeclRefType,
19795 const bool Nested, Sema &S, bool Invalid) {
19796 bool ByRef = false;
19797
19798 // Blocks are not allowed to capture arrays, excepting OpenCL.
19799 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19800 // (decayed to pointers).
19801 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19802 if (BuildAndDiagnose) {
19803 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19804 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19805 Invalid = true;
19806 } else {
19807 return false;
19808 }
19809 }
19810
19811 // Forbid the block-capture of autoreleasing variables.
19812 if (!Invalid &&
19813 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19814 if (BuildAndDiagnose) {
19815 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19816 << /*block*/ 0;
19817 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19818 Invalid = true;
19819 } else {
19820 return false;
19821 }
19822 }
19823
19824 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19825 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19826 QualType PointeeTy = PT->getPointeeType();
19827
19828 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19829 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19830 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19831 if (BuildAndDiagnose) {
19832 SourceLocation VarLoc = Var->getLocation();
19833 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19834 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19835 }
19836 }
19837 }
19838
19839 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19840 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19841 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19842 // Block capture by reference does not change the capture or
19843 // declaration reference types.
19844 ByRef = true;
19845 } else {
19846 // Block capture by copy introduces 'const'.
19847 CaptureType = CaptureType.getNonReferenceType().withConst();
19848 DeclRefType = CaptureType;
19849 }
19850
19851 // Actually capture the variable.
19852 if (BuildAndDiagnose)
19853 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19854 CaptureType, Invalid);
19855
19856 return !Invalid;
19857}
19858
19859/// Capture the given variable in the captured region.
19860static bool captureInCapturedRegion(
19861 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19862 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19863 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19864 Sema &S, bool Invalid) {
19865 // By default, capture variables by reference.
19866 bool ByRef = true;
19867 bool IsBindingDecl = isa<BindingDecl>(Val: Var);
19868 ValueDecl *DSAVar = Var;
19869 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19870 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19871 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19872 // Using an LValue reference type is consistent with Lambdas (see below).
19873 if (VarDecl *VD = S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19874 Var = VD; // Capture the DecompositionDecl.
19875 bool HasConst = DeclRefType.isConstQualified();
19876 // Note: DeclRefType should remain the BindingDecl's type (e.g., int),
19877 // not the DecompositionDecl's type (e.g., Point). The variable being
19878 // captured is the DecompositionDecl, but expressions still reference
19879 // the individual binding's type.
19880 DeclRefType = DeclRefType.getUnqualifiedType();
19881 // Don't lose diagnostics about assignments to const.
19882 if (HasConst)
19883 DeclRefType.addConst();
19884 }
19885 // Do not capture firstprivates in tasks. For bindings the DSA is on the
19886 // binding, not on the DecompositionDecl; the task firstprivate path still
19887 // needs the DecompositionDecl capture, so skip only private.
19888 OpenMPClauseKind PrivateKind = S.OpenMP().isOpenMPPrivateDecl(
19889 D: IsBindingDecl ? DSAVar : Var, Level: RSI->OpenMPLevel,
19890 CapLevel: RSI->OpenMPCaptureLevel);
19891 if (IsBindingDecl ? PrivateKind == OMPC_private
19892 : PrivateKind != OMPC_unknown)
19893 return true;
19894 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: DSAVar, Level: RSI->OpenMPLevel,
19895 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19896 // Bindings share the DecompositionDecl storage; a second capture with
19897 // a different capture kind is not representable.
19898 if (BuildAndDiagnose && IsBindingDecl) {
19899 unsigned Idx = RSI->CaptureMap.lookup(Val: Var);
19900 if (Idx != 0 && RSI->Captures[Idx - 1].isReferenceCapture() != ByRef) {
19901 S.Diag(Loc,
19902 DiagID: diag::err_omp_decomposition_bindings_different_capture_kinds)
19903 << DSAVar;
19904 return false;
19905 }
19906 }
19907 }
19908
19909 if (ByRef)
19910 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19911 else
19912 CaptureType = DeclRefType;
19913
19914 // Actually capture the variable.
19915 if (BuildAndDiagnose)
19916 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19917 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19918
19919 if (BuildAndDiagnose && IsBindingDecl)
19920 // Key the binding to its own capture entry so repeated uses hit the
19921 // already-captured path.
19922 RSI->CaptureMap[DSAVar] = RSI->Captures.size();
19923
19924 return !Invalid;
19925}
19926
19927/// Capture the given variable in the lambda.
19928static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19929 SourceLocation Loc, const bool BuildAndDiagnose,
19930 QualType &CaptureType, QualType &DeclRefType,
19931 const bool RefersToCapturedVariable,
19932 const TryCaptureKind Kind,
19933 SourceLocation EllipsisLoc, const bool IsTopScope,
19934 Sema &S, bool Invalid) {
19935 // Determine whether we are capturing by reference or by value.
19936 bool ByRef = false;
19937 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19938 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19939 } else {
19940 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19941 }
19942
19943 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19944 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19945 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19946 Invalid = true;
19947 }
19948
19949 // Compute the type of the field that will capture this variable.
19950 if (ByRef) {
19951 // C++11 [expr.prim.lambda]p15:
19952 // An entity is captured by reference if it is implicitly or
19953 // explicitly captured but not captured by copy. It is
19954 // unspecified whether additional unnamed non-static data
19955 // members are declared in the closure type for entities
19956 // captured by reference.
19957 //
19958 // FIXME: It is not clear whether we want to build an lvalue reference
19959 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19960 // to do the former, while EDG does the latter. Core issue 1249 will
19961 // clarify, but for now we follow GCC because it's a more permissive and
19962 // easily defensible position.
19963 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19964 } else {
19965 // C++11 [expr.prim.lambda]p14:
19966 // For each entity captured by copy, an unnamed non-static
19967 // data member is declared in the closure type. The
19968 // declaration order of these members is unspecified. The type
19969 // of such a data member is the type of the corresponding
19970 // captured entity if the entity is not a reference to an
19971 // object, or the referenced type otherwise. [Note: If the
19972 // captured entity is a reference to a function, the
19973 // corresponding data member is also a reference to a
19974 // function. - end note ]
19975 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19976 if (!RefType->getPointeeType()->isFunctionType())
19977 CaptureType = RefType->getPointeeType();
19978 }
19979
19980 // Forbid the lambda copy-capture of autoreleasing variables.
19981 if (!Invalid &&
19982 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19983 if (BuildAndDiagnose) {
19984 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19985 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19986 << Var->getDeclName();
19987 Invalid = true;
19988 } else {
19989 return false;
19990 }
19991 }
19992
19993 // Make sure that by-copy captures are of a complete and non-abstract type.
19994 if (!Invalid && BuildAndDiagnose) {
19995 if (!CaptureType->isDependentType() &&
19996 S.RequireCompleteSizedType(
19997 Loc, T: CaptureType,
19998 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19999 Args: Var->getDeclName()))
20000 Invalid = true;
20001 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
20002 DiagID: diag::err_capture_of_abstract_type))
20003 Invalid = true;
20004 }
20005 }
20006
20007 // Compute the type of a reference to this captured variable.
20008 if (ByRef)
20009 DeclRefType = CaptureType.getNonReferenceType();
20010 else {
20011 // C++ [expr.prim.lambda]p5:
20012 // The closure type for a lambda-expression has a public inline
20013 // function call operator [...]. This function call operator is
20014 // declared const (9.3.1) if and only if the lambda-expression's
20015 // parameter-declaration-clause is not followed by mutable.
20016 DeclRefType = CaptureType.getNonReferenceType();
20017 bool Const = LSI->lambdaCaptureShouldBeConst();
20018 // C++ [expr.prim.lambda]p10:
20019 // The type of such a data member is [...] an lvalue reference to the
20020 // referenced function type if the entity is a reference to a function.
20021 // [...]
20022 if (Const && !CaptureType->isReferenceType() &&
20023 !DeclRefType->isFunctionType())
20024 DeclRefType.addConst();
20025 }
20026
20027 // Add the capture.
20028 if (BuildAndDiagnose)
20029 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
20030 Loc, EllipsisLoc, CaptureType, Invalid);
20031
20032 return !Invalid;
20033}
20034
20035static bool canCaptureVariableByCopy(ValueDecl *Var,
20036 const ASTContext &Context) {
20037 // Offer a Copy fix even if the type is dependent.
20038 if (Var->getType()->isDependentType())
20039 return true;
20040 QualType T = Var->getType().getNonReferenceType();
20041 if (T.isTriviallyCopyableType(Context))
20042 return true;
20043 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
20044
20045 if (!(RD = RD->getDefinition()))
20046 return false;
20047 if (RD->hasSimpleCopyConstructor())
20048 return true;
20049 if (RD->hasUserDeclaredCopyConstructor())
20050 for (CXXConstructorDecl *Ctor : RD->ctors())
20051 if (Ctor->isCopyConstructor())
20052 return !Ctor->isDeleted();
20053 }
20054 return false;
20055}
20056
20057/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
20058/// default capture. Fixes may be omitted if they aren't allowed by the
20059/// standard, for example we can't emit a default copy capture fix-it if we
20060/// already explicitly copy capture capture another variable.
20061static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
20062 ValueDecl *Var) {
20063 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
20064 // Don't offer Capture by copy of default capture by copy fixes if Var is
20065 // known not to be copy constructible.
20066 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
20067
20068 SmallString<32> FixBuffer;
20069 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
20070 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
20071 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
20072 if (ShouldOfferCopyFix) {
20073 // Offer fixes to insert an explicit capture for the variable.
20074 // [] -> [VarName]
20075 // [OtherCapture] -> [OtherCapture, VarName]
20076 FixBuffer.assign(Refs: {Separator, Var->getName()});
20077 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
20078 << Var << /*value*/ 0
20079 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
20080 }
20081 // As above but capture by reference.
20082 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
20083 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
20084 << Var << /*reference*/ 1
20085 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
20086 }
20087
20088 // Only try to offer default capture if there are no captures excluding this
20089 // and init captures.
20090 // [this]: OK.
20091 // [X = Y]: OK.
20092 // [&A, &B]: Don't offer.
20093 // [A, B]: Don't offer.
20094 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
20095 return !C.isThisCapture() && !C.isInitCapture();
20096 }))
20097 return;
20098
20099 // The default capture specifiers, '=' or '&', must appear first in the
20100 // capture body.
20101 SourceLocation DefaultInsertLoc =
20102 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
20103
20104 if (ShouldOfferCopyFix) {
20105 bool CanDefaultCopyCapture = true;
20106 // [=, *this] OK since c++17
20107 // [=, this] OK since c++20
20108 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20109 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20110 ? LSI->getCXXThisCapture().isCopyCapture()
20111 : false;
20112 // We can't use default capture by copy if any captures already specified
20113 // capture by copy.
20114 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20115 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20116 })) {
20117 FixBuffer.assign(Refs: {"=", Separator});
20118 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20119 << /*value*/ 0
20120 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20121 }
20122 }
20123
20124 // We can't use default capture by reference if any captures already specified
20125 // capture by reference.
20126 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20127 return !C.isInitCapture() && C.isReferenceCapture() &&
20128 !C.isThisCapture();
20129 })) {
20130 FixBuffer.assign(Refs: {"&", Separator});
20131 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20132 << /*reference*/ 1
20133 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20134 }
20135}
20136
20137bool Sema::tryCaptureVariable(
20138 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20139 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20140 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20141 // An init-capture is notionally from the context surrounding its
20142 // declaration, but its parent DC is the lambda class.
20143 DeclContext *VarDC =
20144 Var->getDeclContext()->getEnclosingNonExpansionStatementContext();
20145 DeclContext *DC = CurContext;
20146
20147 // Skip past RequiresExprBodys because they don't constitute function scopes.
20148 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20149 DC = DC->getParent();
20150
20151 // tryCaptureVariable is called every time a DeclRef is formed,
20152 // it can therefore have non-negigible impact on performances.
20153 // For local variables and when there is no capturing scope,
20154 // we can bailout early.
20155 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20156 return true;
20157
20158 // Exception: Function parameters are not tied to the function's DeclContext
20159 // until we enter the function definition. Capturing them anyway would result
20160 // in an out-of-bounds error while traversing DC and its parents.
20161 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
20162 return true;
20163
20164 const auto *VD = dyn_cast<VarDecl>(Val: Var);
20165 if (VD) {
20166 if (VD->isInitCapture())
20167 VarDC = VarDC->getParent();
20168 } else {
20169 VD = Var->getPotentiallyDecomposedVarDecl();
20170 }
20171 assert(VD && "Cannot capture a null variable");
20172
20173 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20174 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20175 // We need to sync up the Declaration Context with the
20176 // FunctionScopeIndexToStopAt
20177 if (FunctionScopeIndexToStopAt) {
20178 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20179 unsigned FSIndex = FunctionScopes.size() - 1;
20180 // When we're parsing the lambda parameter list, the current DeclContext is
20181 // NOT the lambda but its parent. So move away the current LSI before
20182 // aligning DC and FunctionScopeIndexToStopAt.
20183 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
20184 FSIndex && LSI && !LSI->AfterParameterList)
20185 --FSIndex;
20186 assert(MaxFunctionScopesIndex <= FSIndex &&
20187 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20188 "FunctionScopes.");
20189 while (FSIndex != MaxFunctionScopesIndex) {
20190 DC = getLambdaAwareParentOfDeclContext(DC);
20191 --FSIndex;
20192 }
20193 }
20194
20195 // Capture global variables if it is required to use private copy of this
20196 // variable.
20197 bool IsGlobal = !VD->hasLocalStorage();
20198 if (IsGlobal && !(LangOpts.OpenMP &&
20199 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
20200 StopAt: MaxFunctionScopesIndex)))
20201 return true;
20202
20203 if (isa<VarDecl>(Val: Var))
20204 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
20205
20206 // Walk up the stack to determine whether we can capture the variable,
20207 // performing the "simple" checks that don't depend on type. We stop when
20208 // we've either hit the declared scope of the variable or find an existing
20209 // capture of that variable. We start from the innermost capturing-entity
20210 // (the DC) and ensure that all intervening capturing-entities
20211 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20212 // declcontext can either capture the variable or have already captured
20213 // the variable.
20214 CaptureType = Var->getType();
20215 DeclRefType = CaptureType.getNonReferenceType();
20216 bool Nested = false;
20217 bool Explicit = (Kind != TryCaptureKind::Implicit);
20218 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20219 do {
20220
20221 LambdaScopeInfo *LSI = nullptr;
20222 if (!FunctionScopes.empty())
20223 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20224 Val: FunctionScopes[FunctionScopesIndex]);
20225
20226 bool IsInScopeDeclarationContext =
20227 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20228
20229 if (LSI && !LSI->AfterParameterList) {
20230 // This allows capturing parameters from a default value which does not
20231 // seems correct
20232 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
20233 return true;
20234 }
20235 // If the variable is declared in the current context, there is no need to
20236 // capture it.
20237 if (IsInScopeDeclarationContext &&
20238 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20239 return true;
20240
20241 // Only block literals, captured statements, and lambda expressions can
20242 // capture; other scopes don't work.
20243 DeclContext *ParentDC =
20244 !IsInScopeDeclarationContext
20245 ? DC->getParent()
20246 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
20247 Diagnose: BuildAndDiagnose, S&: *this);
20248 // We need to check for the parent *first* because, if we *have*
20249 // private-captured a global variable, we need to recursively capture it in
20250 // intermediate blocks, lambdas, etc.
20251 if (!ParentDC) {
20252 if (IsGlobal) {
20253 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20254 break;
20255 }
20256 return true;
20257 }
20258
20259 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20260 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
20261
20262 // Check whether we've already captured it.
20263 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
20264 DeclRefType)) {
20265 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
20266 break;
20267 }
20268
20269 // When evaluating some attributes (like enable_if) we might refer to a
20270 // function parameter appertaining to the same declaration as that
20271 // attribute.
20272 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
20273 Parm && Parm->getDeclContext() == DC)
20274 return true;
20275
20276 // If we are instantiating a generic lambda call operator body,
20277 // we do not want to capture new variables. What was captured
20278 // during either a lambdas transformation or initial parsing
20279 // should be used.
20280 if (isGenericLambdaCallOperatorSpecialization(DC)) {
20281 if (BuildAndDiagnose) {
20282 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20283 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
20284 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20285 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20286 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20287 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20288 } else
20289 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
20290 }
20291 return true;
20292 }
20293
20294 // Try to capture variable-length arrays types.
20295 if (Var->getType()->isVariablyModifiedType()) {
20296 // We're going to walk down into the type and look for VLA
20297 // expressions.
20298 QualType QTy = Var->getType();
20299 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20300 QTy = PVD->getOriginalType();
20301 captureVariablyModifiedType(Context, T: QTy, CSI);
20302 }
20303
20304 if (getLangOpts().OpenMP) {
20305 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20306 // OpenMP private variables should not be captured in outer scope, so
20307 // just break here. Similarly, global variables that are captured in a
20308 // target region should not be captured outside the scope of the region.
20309 if (RSI->CapRegionKind == CR_OpenMP) {
20310 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20311 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
20312 // If the variable is private (i.e. not captured) and has variably
20313 // modified type, we still need to capture the type for correct
20314 // codegen in all regions, associated with the construct. Currently,
20315 // it is captured in the innermost captured region only.
20316 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20317 Var->getType()->isVariablyModifiedType()) {
20318 QualType QTy = Var->getType();
20319 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20320 QTy = PVD->getOriginalType();
20321 for (int I = 1,
20322 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
20323 I < E; ++I) {
20324 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20325 Val: FunctionScopes[FunctionScopesIndex - I]);
20326 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20327 "Wrong number of captured regions associated with the "
20328 "OpenMP construct.");
20329 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
20330 }
20331 }
20332 bool IsTargetCap =
20333 IsOpenMPPrivateDecl != OMPC_private &&
20334 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
20335 CaptureLevel: RSI->OpenMPCaptureLevel);
20336 // Do not capture global if it is not privatized in outer regions.
20337 bool IsGlobalCap =
20338 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20339 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
20340
20341 // When we detect target captures we are looking from inside the
20342 // target region, therefore we need to propagate the capture from the
20343 // enclosing region. Therefore, the capture is not initially nested.
20344 if (IsTargetCap)
20345 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20346 Level: RSI->OpenMPLevel);
20347
20348 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20349 (IsGlobal && !IsGlobalCap)) {
20350 Nested = !IsTargetCap;
20351 bool HasConst = DeclRefType.isConstQualified();
20352 DeclRefType = DeclRefType.getUnqualifiedType();
20353 // Don't lose diagnostics about assignments to const.
20354 if (HasConst)
20355 DeclRefType.addConst();
20356 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20357 break;
20358 }
20359 }
20360 }
20361 }
20362 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20363 // No capture-default, and this is not an explicit capture
20364 // so cannot capture this variable.
20365 if (BuildAndDiagnose) {
20366 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20367 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20368 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20369 if (LSI->Lambda) {
20370 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20371 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20372 }
20373 // FIXME: If we error out because an outer lambda can not implicitly
20374 // capture a variable that an inner lambda explicitly captures, we
20375 // should have the inner lambda do the explicit capture - because
20376 // it makes for cleaner diagnostics later. This would purely be done
20377 // so that the diagnostic does not misleadingly claim that a variable
20378 // can not be captured by a lambda implicitly even though it is captured
20379 // explicitly. Suggestion:
20380 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20381 // at the function head
20382 // - cache the StartingDeclContext - this must be a lambda
20383 // - captureInLambda in the innermost lambda the variable.
20384 }
20385 return true;
20386 }
20387 Explicit = false;
20388 FunctionScopesIndex--;
20389 if (IsInScopeDeclarationContext)
20390 DC = ParentDC;
20391 } while (!VarDC->Equals(DC));
20392
20393 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20394 // computing the type of the capture at each step, checking type-specific
20395 // requirements, and adding captures if requested.
20396 // If the variable had already been captured previously, we start capturing
20397 // at the lambda nested within that one.
20398 bool Invalid = false;
20399 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20400 ++I) {
20401 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20402
20403 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20404 // certain types of variables (unnamed, variably modified types etc.)
20405 // so check for eligibility.
20406 if (!Invalid)
20407 Invalid =
20408 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20409
20410 // After encountering an error, if we're actually supposed to capture, keep
20411 // capturing in nested contexts to suppress any follow-on diagnostics.
20412 if (Invalid && !BuildAndDiagnose)
20413 return true;
20414
20415 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20416 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20417 DeclRefType, Nested, S&: *this, Invalid);
20418 Nested = true;
20419 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20420 Invalid = !captureInCapturedRegion(
20421 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20422 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20423 Nested = true;
20424 } else {
20425 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20426 Invalid =
20427 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20428 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20429 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20430 Nested = true;
20431 }
20432
20433 if (Invalid && !BuildAndDiagnose)
20434 return true;
20435 }
20436 return Invalid;
20437}
20438
20439bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20440 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20441 QualType CaptureType;
20442 QualType DeclRefType;
20443 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20444 /*BuildAndDiagnose=*/true, CaptureType,
20445 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20446}
20447
20448bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20449 QualType CaptureType;
20450 QualType DeclRefType;
20451 return !tryCaptureVariable(
20452 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20453 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20454}
20455
20456QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20457 assert(Var && "Null value cannot be captured");
20458
20459 QualType CaptureType;
20460 QualType DeclRefType;
20461
20462 // Determine whether we can capture this variable.
20463 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20464 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20465 FunctionScopeIndexToStopAt: nullptr))
20466 return QualType();
20467
20468 return DeclRefType;
20469}
20470
20471namespace {
20472// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20473// The produced TemplateArgumentListInfo* points to data stored within this
20474// object, so should only be used in contexts where the pointer will not be
20475// used after the CopiedTemplateArgs object is destroyed.
20476class CopiedTemplateArgs {
20477 bool HasArgs;
20478 TemplateArgumentListInfo TemplateArgStorage;
20479public:
20480 template<typename RefExpr>
20481 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20482 if (HasArgs)
20483 E->copyTemplateArgumentsInto(TemplateArgStorage);
20484 }
20485 operator TemplateArgumentListInfo*()
20486#ifdef __has_cpp_attribute
20487#if __has_cpp_attribute(clang::lifetimebound)
20488 [[clang::lifetimebound]]
20489#endif
20490#endif
20491 {
20492 return HasArgs ? &TemplateArgStorage : nullptr;
20493 }
20494};
20495}
20496
20497/// Walk the set of potential results of an expression and mark them all as
20498/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20499///
20500/// \return A new expression if we found any potential results, ExprEmpty() if
20501/// not, and ExprError() if we diagnosed an error.
20502static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20503 NonOdrUseReason NOUR) {
20504 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20505 // an object that satisfies the requirements for appearing in a
20506 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20507 // is immediately applied." This function handles the lvalue-to-rvalue
20508 // conversion part.
20509 //
20510 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20511 // transform it into the relevant kind of non-odr-use node and rebuild the
20512 // tree of nodes leading to it.
20513 //
20514 // This is a mini-TreeTransform that only transforms a restricted subset of
20515 // nodes (and only certain operands of them).
20516
20517 // Rebuild a subexpression.
20518 auto Rebuild = [&](Expr *Sub) {
20519 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20520 };
20521
20522 // Check whether a potential result satisfies the requirements of NOUR.
20523 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20524 // Any entity other than a VarDecl is always odr-used whenever it's named
20525 // in a potentially-evaluated expression.
20526 auto *VD = dyn_cast<VarDecl>(Val: D);
20527 if (!VD)
20528 return true;
20529
20530 // C++2a [basic.def.odr]p4:
20531 // A variable x whose name appears as a potentially-evalauted expression
20532 // e is odr-used by e unless
20533 // -- x is a reference that is usable in constant expressions, or
20534 // -- x is a variable of non-reference type that is usable in constant
20535 // expressions and has no mutable subobjects, and e is an element of
20536 // the set of potential results of an expression of
20537 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20538 // conversion is applied, or
20539 // -- x is a variable of non-reference type, and e is an element of the
20540 // set of potential results of a discarded-value expression to which
20541 // the lvalue-to-rvalue conversion is not applied
20542 //
20543 // We check the first bullet and the "potentially-evaluated" condition in
20544 // BuildDeclRefExpr. We check the type requirements in the second bullet
20545 // in CheckLValueToRValueConversionOperand below.
20546 switch (NOUR) {
20547 case NOUR_None:
20548 case NOUR_Unevaluated:
20549 llvm_unreachable("unexpected non-odr-use-reason");
20550
20551 case NOUR_Constant:
20552 // Constant references were handled when they were built.
20553 if (VD->getType()->isReferenceType())
20554 return true;
20555 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20556 if (RD->hasDefinition() && RD->hasMutableFields())
20557 return true;
20558 if (!VD->isUsableInConstantExpressions(C: S.Context))
20559 return true;
20560 break;
20561
20562 case NOUR_Discarded:
20563 if (VD->getType()->isReferenceType())
20564 return true;
20565 break;
20566 }
20567 return false;
20568 };
20569
20570 // Check whether this expression may be odr-used in CUDA/HIP.
20571 auto MaybeCUDAODRUsed = [&]() -> bool {
20572 if (!S.LangOpts.CUDA)
20573 return false;
20574 LambdaScopeInfo *LSI = S.getCurLambda();
20575 if (!LSI)
20576 return false;
20577 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20578 if (!DRE)
20579 return false;
20580 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20581 if (!VD)
20582 return false;
20583 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20584 };
20585
20586 // Mark that this expression does not constitute an odr-use.
20587 auto MarkNotOdrUsed = [&] {
20588 if (!MaybeCUDAODRUsed()) {
20589 S.MaybeODRUseExprs.remove(X: E);
20590 if (LambdaScopeInfo *LSI = S.getCurLambda())
20591 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20592 }
20593 };
20594
20595 // C++2a [basic.def.odr]p2:
20596 // The set of potential results of an expression e is defined as follows:
20597 switch (E->getStmtClass()) {
20598 // -- If e is an id-expression, ...
20599 case Expr::DeclRefExprClass: {
20600 auto *DRE = cast<DeclRefExpr>(Val: E);
20601 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20602 break;
20603
20604 // Rebuild as a non-odr-use DeclRefExpr.
20605 MarkNotOdrUsed();
20606 return DeclRefExpr::Create(
20607 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20608 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20609 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20610 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20611 }
20612
20613 case Expr::FunctionParmPackExprClass: {
20614 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20615 // If any of the declarations in the pack is odr-used, then the expression
20616 // as a whole constitutes an odr-use.
20617 for (ValueDecl *D : *FPPE)
20618 if (IsPotentialResultOdrUsed(D))
20619 return ExprEmpty();
20620
20621 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20622 // nothing cares about whether we marked this as an odr-use, but it might
20623 // be useful for non-compiler tools.
20624 MarkNotOdrUsed();
20625 break;
20626 }
20627
20628 // -- If e is a subscripting operation with an array operand...
20629 case Expr::ArraySubscriptExprClass: {
20630 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20631 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20632 if (!OldBase->getType()->isArrayType())
20633 break;
20634 ExprResult Base = Rebuild(OldBase);
20635 if (!Base.isUsable())
20636 return Base;
20637 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20638 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20639 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20640 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20641 rbLoc: ASE->getRBracketLoc());
20642 }
20643
20644 case Expr::MemberExprClass: {
20645 auto *ME = cast<MemberExpr>(Val: E);
20646 // -- If e is a class member access expression [...] naming a non-static
20647 // data member...
20648 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20649 ExprResult Base = Rebuild(ME->getBase());
20650 if (!Base.isUsable())
20651 return Base;
20652 return MemberExpr::Create(
20653 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20654 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20655 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20656 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20657 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20658 }
20659
20660 if (ME->getMemberDecl()->isCXXInstanceMember())
20661 break;
20662
20663 // -- If e is a class member access expression naming a static data member,
20664 // ...
20665 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20666 break;
20667
20668 // Rebuild as a non-odr-use MemberExpr.
20669 MarkNotOdrUsed();
20670 return MemberExpr::Create(
20671 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20672 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20673 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20674 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20675 }
20676
20677 case Expr::BinaryOperatorClass: {
20678 auto *BO = cast<BinaryOperator>(Val: E);
20679 Expr *LHS = BO->getLHS();
20680 Expr *RHS = BO->getRHS();
20681 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20682 if (BO->getOpcode() == BO_PtrMemD) {
20683 ExprResult Sub = Rebuild(LHS);
20684 if (!Sub.isUsable())
20685 return Sub;
20686 BO->setLHS(Sub.get());
20687 // -- If e is a comma expression, ...
20688 } else if (BO->getOpcode() == BO_Comma) {
20689 ExprResult Sub = Rebuild(RHS);
20690 if (!Sub.isUsable())
20691 return Sub;
20692 BO->setRHS(Sub.get());
20693 } else {
20694 break;
20695 }
20696 return ExprResult(BO);
20697 }
20698
20699 // -- If e has the form (e1)...
20700 case Expr::ParenExprClass: {
20701 auto *PE = cast<ParenExpr>(Val: E);
20702 ExprResult Sub = Rebuild(PE->getSubExpr());
20703 if (!Sub.isUsable())
20704 return Sub;
20705 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20706 }
20707
20708 // -- If e is a glvalue conditional expression, ...
20709 // We don't apply this to a binary conditional operator. FIXME: Should we?
20710 case Expr::ConditionalOperatorClass: {
20711 auto *CO = cast<ConditionalOperator>(Val: E);
20712 ExprResult LHS = Rebuild(CO->getLHS());
20713 if (LHS.isInvalid())
20714 return ExprError();
20715 ExprResult RHS = Rebuild(CO->getRHS());
20716 if (RHS.isInvalid())
20717 return ExprError();
20718 if (!LHS.isUsable() && !RHS.isUsable())
20719 return ExprEmpty();
20720 if (!LHS.isUsable())
20721 LHS = CO->getLHS();
20722 if (!RHS.isUsable())
20723 RHS = CO->getRHS();
20724 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20725 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20726 }
20727
20728 // [Clang extension]
20729 // -- If e has the form __extension__ e1...
20730 case Expr::UnaryOperatorClass: {
20731 auto *UO = cast<UnaryOperator>(Val: E);
20732 if (UO->getOpcode() != UO_Extension)
20733 break;
20734 ExprResult Sub = Rebuild(UO->getSubExpr());
20735 if (!Sub.isUsable())
20736 return Sub;
20737 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20738 Input: Sub.get());
20739 }
20740
20741 // [Clang extension]
20742 // -- If e has the form _Generic(...), the set of potential results is the
20743 // union of the sets of potential results of the associated expressions.
20744 case Expr::GenericSelectionExprClass: {
20745 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20746
20747 SmallVector<Expr *, 4> AssocExprs;
20748 bool AnyChanged = false;
20749 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20750 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20751 if (AssocExpr.isInvalid())
20752 return ExprError();
20753 if (AssocExpr.isUsable()) {
20754 AssocExprs.push_back(Elt: AssocExpr.get());
20755 AnyChanged = true;
20756 } else {
20757 AssocExprs.push_back(Elt: OrigAssocExpr);
20758 }
20759 }
20760
20761 void *ExOrTy = nullptr;
20762 bool IsExpr = GSE->isExprPredicate();
20763 if (IsExpr)
20764 ExOrTy = GSE->getControllingExpr();
20765 else
20766 ExOrTy = GSE->getControllingType();
20767 return AnyChanged ? S.CreateGenericSelectionExpr(
20768 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20769 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20770 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20771 : ExprEmpty();
20772 }
20773
20774 // [Clang extension]
20775 // -- If e has the form __builtin_choose_expr(...), the set of potential
20776 // results is the union of the sets of potential results of the
20777 // second and third subexpressions.
20778 case Expr::ChooseExprClass: {
20779 auto *CE = cast<ChooseExpr>(Val: E);
20780
20781 ExprResult LHS = Rebuild(CE->getLHS());
20782 if (LHS.isInvalid())
20783 return ExprError();
20784
20785 ExprResult RHS = Rebuild(CE->getLHS());
20786 if (RHS.isInvalid())
20787 return ExprError();
20788
20789 if (!LHS.get() && !RHS.get())
20790 return ExprEmpty();
20791 if (!LHS.isUsable())
20792 LHS = CE->getLHS();
20793 if (!RHS.isUsable())
20794 RHS = CE->getRHS();
20795
20796 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20797 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20798 }
20799
20800 // Step through non-syntactic nodes.
20801 case Expr::ConstantExprClass: {
20802 auto *CE = cast<ConstantExpr>(Val: E);
20803 ExprResult Sub = Rebuild(CE->getSubExpr());
20804 if (!Sub.isUsable())
20805 return Sub;
20806 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20807 }
20808
20809 // We could mostly rely on the recursive rebuilding to rebuild implicit
20810 // casts, but not at the top level, so rebuild them here.
20811 case Expr::ImplicitCastExprClass: {
20812 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20813 // Only step through the narrow set of cast kinds we expect to encounter.
20814 // Anything else suggests we've left the region in which potential results
20815 // can be found.
20816 switch (ICE->getCastKind()) {
20817 case CK_NoOp:
20818 case CK_DerivedToBase:
20819 case CK_UncheckedDerivedToBase: {
20820 ExprResult Sub = Rebuild(ICE->getSubExpr());
20821 if (!Sub.isUsable())
20822 return Sub;
20823 CXXCastPath Path(ICE->path());
20824 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20825 VK: ICE->getValueKind(), BasePath: &Path);
20826 }
20827
20828 default:
20829 break;
20830 }
20831 break;
20832 }
20833
20834 default:
20835 break;
20836 }
20837
20838 // Can't traverse through this node. Nothing to do.
20839 return ExprEmpty();
20840}
20841
20842ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20843 // Check whether the operand is or contains an object of non-trivial C union
20844 // type.
20845 if (E->getType().isVolatileQualified() &&
20846 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20847 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20848 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20849 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20850 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20851
20852 // C++2a [basic.def.odr]p4:
20853 // [...] an expression of non-volatile-qualified non-class type to which
20854 // the lvalue-to-rvalue conversion is applied [...]
20855 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20856 return E;
20857
20858 ExprResult Result =
20859 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20860 if (Result.isInvalid())
20861 return ExprError();
20862 return Result.get() ? Result : E;
20863}
20864
20865ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20866 if (!Res.isUsable())
20867 return Res;
20868
20869 // If a constant-expression is a reference to a variable where we delay
20870 // deciding whether it is an odr-use, just assume we will apply the
20871 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20872 // (a non-type template argument), we have special handling anyway.
20873 return CheckLValueToRValueConversionOperand(E: Res.get());
20874}
20875
20876void Sema::CleanupVarDeclMarking() {
20877 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20878 // call.
20879 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20880 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20881
20882 for (Expr *E : LocalMaybeODRUseExprs) {
20883 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20884 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20885 Loc: DRE->getLocation(), SemaRef&: *this);
20886 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20887 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20888 SemaRef&: *this);
20889 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20890 for (ValueDecl *VD : *FP)
20891 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20892 } else {
20893 llvm_unreachable("Unexpected expression");
20894 }
20895 }
20896
20897 assert(MaybeODRUseExprs.empty() &&
20898 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20899}
20900
20901static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20902 ValueDecl *Var, Expr *E) {
20903 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20904 if (!VD)
20905 return;
20906
20907 const bool RefersToEnclosingScope =
20908 (SemaRef.CurContext != VD->getDeclContext() &&
20909 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20910 if (RefersToEnclosingScope) {
20911 LambdaScopeInfo *const LSI =
20912 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20913 if (LSI && (!LSI->CallOperator ||
20914 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20915 // If a variable could potentially be odr-used, defer marking it so
20916 // until we finish analyzing the full expression for any
20917 // lvalue-to-rvalue
20918 // or discarded value conversions that would obviate odr-use.
20919 // Add it to the list of potential captures that will be analyzed
20920 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20921 // unless the variable is a reference that was initialized by a constant
20922 // expression (this will never need to be captured or odr-used).
20923 //
20924 // FIXME: We can simplify this a lot after implementing P0588R1.
20925 assert(E && "Capture variable should be used in an expression.");
20926 if (!Var->getType()->isReferenceType() ||
20927 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20928 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20929 }
20930 }
20931}
20932
20933static void DoMarkVarDeclReferenced(
20934 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20935 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20936 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20937 isa<FunctionParmPackExpr>(E)) &&
20938 "Invalid Expr argument to DoMarkVarDeclReferenced");
20939 Var->setReferenced();
20940
20941 if (Var->isInvalidDecl())
20942 return;
20943
20944 auto *MSI = Var->getMemberSpecializationInfo();
20945 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20946 : Var->getTemplateSpecializationKind();
20947
20948 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20949 bool UsableInConstantExpr =
20950 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20951
20952 // Only track variables with internal linkage or local scope.
20953 // Use canonical decl so in-class declarations and out-of-class definitions
20954 // of static data members in anonymous namespaces are tracked as a single
20955 // entry.
20956 const VarDecl *CanonVar = Var->getCanonicalDecl();
20957 if ((CanonVar->isLocalVarDeclOrParm() ||
20958 CanonVar->isInternalLinkageFileVar()) &&
20959 !CanonVar->hasExternalStorage()) {
20960 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20961 }
20962
20963 // C++20 [expr.const]p12:
20964 // A variable [...] is needed for constant evaluation if it is [...] a
20965 // variable whose name appears as a potentially constant evaluated
20966 // expression that is either a contexpr variable or is of non-volatile
20967 // const-qualified integral type or of reference type
20968 bool NeededForConstantEvaluation =
20969 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20970
20971 bool NeedDefinition =
20972 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20973 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20974 Var->getType()->isUndeducedType());
20975
20976 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20977 "Can't instantiate a partial template specialization.");
20978
20979 // If this might be a member specialization of a static data member, check
20980 // the specialization is visible. We already did the checks for variable
20981 // template specializations when we created them.
20982 if (NeedDefinition && TSK != TSK_Undeclared &&
20983 !isa<VarTemplateSpecializationDecl>(Val: Var))
20984 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20985
20986 // Perform implicit instantiation of static data members, static data member
20987 // templates of class templates, and variable template specializations. Delay
20988 // instantiations of variable templates, except for those that could be used
20989 // in a constant expression.
20990 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20991 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20992 // instantiation declaration if a variable is usable in a constant
20993 // expression (among other cases).
20994 bool TryInstantiating =
20995 TSK == TSK_ImplicitInstantiation ||
20996 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20997
20998 if (TryInstantiating) {
20999 SourceLocation PointOfInstantiation =
21000 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
21001 bool FirstInstantiation = PointOfInstantiation.isInvalid();
21002 if (FirstInstantiation) {
21003 PointOfInstantiation = Loc;
21004 if (MSI)
21005 MSI->setPointOfInstantiation(PointOfInstantiation);
21006 // FIXME: Notify listener.
21007 else
21008 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
21009 }
21010
21011 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
21012 // Do not defer instantiations of variables that could be used in a
21013 // constant expression.
21014 // The type deduction also needs a complete initializer.
21015 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
21016 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
21017 });
21018
21019 // The size of an incomplete array type can be updated by
21020 // instantiating the initializer. The DeclRefExpr's type should be
21021 // updated accordingly too, or users of it would be confused!
21022 if (E)
21023 SemaRef.getCompletedType(E);
21024
21025 // Re-set the member to trigger a recomputation of the dependence bits
21026 // for the expression.
21027 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
21028 DRE->setDecl(DRE->getDecl());
21029 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
21030 ME->setMemberDecl(ME->getMemberDecl());
21031 } else if (FirstInstantiation) {
21032 SemaRef.PendingInstantiations
21033 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
21034 } else {
21035 bool Inserted = false;
21036 for (auto &I : SemaRef.SavedPendingInstantiations) {
21037 auto Iter = llvm::find_if(
21038 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
21039 return P.first == Var;
21040 });
21041 if (Iter != I.end()) {
21042 SemaRef.PendingInstantiations.push_back(x: *Iter);
21043 I.erase(position: Iter);
21044 Inserted = true;
21045 break;
21046 }
21047 }
21048
21049 // FIXME: For a specialization of a variable template, we don't
21050 // distinguish between "declaration and type implicitly instantiated"
21051 // and "implicit instantiation of definition requested", so we have
21052 // no direct way to avoid enqueueing the pending instantiation
21053 // multiple times.
21054 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
21055 SemaRef.PendingInstantiations
21056 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
21057 }
21058 }
21059 }
21060
21061 // C++2a [basic.def.odr]p4:
21062 // A variable x whose name appears as a potentially-evaluated expression e
21063 // is odr-used by e unless
21064 // -- x is a reference that is usable in constant expressions
21065 // -- x is a variable of non-reference type that is usable in constant
21066 // expressions and has no mutable subobjects [FIXME], and e is an
21067 // element of the set of potential results of an expression of
21068 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
21069 // conversion is applied
21070 // -- x is a variable of non-reference type, and e is an element of the set
21071 // of potential results of a discarded-value expression to which the
21072 // lvalue-to-rvalue conversion is not applied [FIXME]
21073 //
21074 // We check the first part of the second bullet here, and
21075 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
21076 // FIXME: To get the third bullet right, we need to delay this even for
21077 // variables that are not usable in constant expressions.
21078
21079 // If we already know this isn't an odr-use, there's nothing more to do.
21080 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
21081 if (DRE->isNonOdrUse())
21082 return;
21083 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
21084 if (ME->isNonOdrUse())
21085 return;
21086
21087 switch (OdrUse) {
21088 case OdrUseContext::None:
21089 // In some cases, a variable may not have been marked unevaluated, if it
21090 // appears in a defaukt initializer.
21091 assert((!E || isa<FunctionParmPackExpr>(E) ||
21092 SemaRef.isUnevaluatedContext()) &&
21093 "missing non-odr-use marking for unevaluated decl ref");
21094 break;
21095
21096 case OdrUseContext::FormallyOdrUsed:
21097 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21098 // behavior.
21099 break;
21100
21101 case OdrUseContext::Used:
21102 // If we might later find that this expression isn't actually an odr-use,
21103 // delay the marking.
21104 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
21105 SemaRef.MaybeODRUseExprs.insert(X: E);
21106 else
21107 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
21108 break;
21109
21110 case OdrUseContext::Dependent:
21111 // If this is a dependent context, we don't need to mark variables as
21112 // odr-used, but we may still need to track them for lambda capture.
21113 // FIXME: Do we also need to do this inside dependent typeid expressions
21114 // (which are modeled as unevaluated at this point)?
21115 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21116 break;
21117 }
21118}
21119
21120static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
21121 BindingDecl *BD, Expr *E) {
21122 BD->setReferenced();
21123
21124 if (BD->isInvalidDecl())
21125 return;
21126
21127 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21128 if (OdrUse == OdrUseContext::Used) {
21129 QualType CaptureType, DeclRefType;
21130 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
21131 /*EllipsisLoc*/ SourceLocation(),
21132 /*BuildAndDiagnose*/ true, CaptureType,
21133 DeclRefType,
21134 /*FunctionScopeIndexToStopAt*/ nullptr);
21135 } else if (OdrUse == OdrUseContext::Dependent) {
21136 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
21137 }
21138}
21139
21140void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
21141 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
21142}
21143
21144// C++ [temp.dep.expr]p3:
21145// An id-expression is type-dependent if it contains:
21146// - an identifier associated by name lookup with an entity captured by copy
21147// in a lambda-expression that has an explicit object parameter whose type
21148// is dependent ([dcl.fct]),
21149static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
21150 Sema &SemaRef, ValueDecl *D, Expr *E) {
21151 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
21152 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21153 return;
21154
21155 // If any enclosing lambda with a dependent explicit object parameter either
21156 // explicitly captures the variable by value, or has a capture default of '='
21157 // and does not capture the variable by reference, then the type of the DRE
21158 // is dependent on the type of that lambda's explicit object parameter.
21159 auto IsDependent = [&]() {
21160 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
21161 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
21162 if (!LSI)
21163 continue;
21164
21165 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
21166 LSI->AfterParameterList)
21167 return false;
21168
21169 const auto *MD = LSI->CallOperator;
21170 if (MD->getType().isNull())
21171 continue;
21172
21173 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21174 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21175 !Ty->getParamType(i: 0)->isDependentType())
21176 continue;
21177
21178 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
21179 if (C->isCopyCapture())
21180 return true;
21181 continue;
21182 }
21183
21184 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21185 return true;
21186 }
21187 return false;
21188 }();
21189
21190 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21191 Set: IsDependent, Context: SemaRef.getASTContext());
21192}
21193
21194static void
21195MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
21196 bool MightBeOdrUse,
21197 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21198 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
21199 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
21200
21201 if (SemaRef.getLangOpts().OpenACC)
21202 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21203
21204 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
21205 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
21206 if (SemaRef.getLangOpts().CPlusPlus)
21207 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21208 D: Var, E);
21209 return;
21210 }
21211
21212 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
21213 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
21214 if (SemaRef.getLangOpts().CPlusPlus)
21215 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21216 D: Decl, E);
21217 return;
21218 }
21219 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21220
21221 // If this is a call to a method via a cast, also mark the method in the
21222 // derived class used in case codegen can devirtualize the call.
21223 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
21224 if (!ME)
21225 return;
21226 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
21227 if (!MD)
21228 return;
21229 // Only attempt to devirtualize if this is truly a virtual call.
21230 bool IsVirtualCall = MD->isVirtual() &&
21231 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
21232 if (!IsVirtualCall)
21233 return;
21234
21235 // If it's possible to devirtualize the call, mark the called function
21236 // referenced.
21237 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
21238 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
21239 if (DM)
21240 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
21241}
21242
21243void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
21244 // [basic.def.odr] (CWG 1614)
21245 // A function is named by an expression or conversion [...]
21246 // unless it is a pure virtual function and either the expression is not an
21247 // id-expression naming the function with an explicitly qualified name or
21248 // the expression forms a pointer to member
21249 bool OdrUse = true;
21250 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
21251 if (Method->isVirtual() &&
21252 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
21253 OdrUse = false;
21254
21255 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
21256 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
21257 !isImmediateFunctionContext() &&
21258 !isCheckingDefaultArgumentOrInitializer() &&
21259 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21260 !FD->isDependentContext())
21261 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
21262 }
21263 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
21264 RefsMinusAssignments);
21265}
21266
21267void Sema::MarkMemberReferenced(MemberExpr *E) {
21268 // C++11 [basic.def.odr]p2:
21269 // A non-overloaded function whose name appears as a potentially-evaluated
21270 // expression or a member of a set of candidate functions, if selected by
21271 // overload resolution when referred to from a potentially-evaluated
21272 // expression, is odr-used, unless it is a pure virtual function and its
21273 // name is not explicitly qualified.
21274 bool MightBeOdrUse = true;
21275 if (E->performsVirtualDispatch(LO: getLangOpts())) {
21276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
21277 if (Method->isPureVirtual())
21278 MightBeOdrUse = false;
21279 }
21280 SourceLocation Loc =
21281 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21282 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
21283 RefsMinusAssignments);
21284}
21285
21286void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
21287 for (ValueDecl *VD : *E)
21288 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
21289 RefsMinusAssignments);
21290}
21291
21292/// Perform marking for a reference to an arbitrary declaration. It
21293/// marks the declaration referenced, and performs odr-use checking for
21294/// functions and variables. This method should not be used when building a
21295/// normal expression which refers to a variable.
21296void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
21297 bool MightBeOdrUse) {
21298 if (MightBeOdrUse) {
21299 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
21300 MarkVariableReferenced(Loc, Var: VD);
21301 return;
21302 }
21303 }
21304 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
21305 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
21306 return;
21307 }
21308 D->setReferenced();
21309}
21310
21311namespace {
21312 // Mark all of the declarations used by a type as referenced.
21313 // FIXME: Not fully implemented yet! We need to have a better understanding
21314 // of when we're entering a context we should not recurse into.
21315 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21316 // TreeTransforms rebuilding the type in a new context. Rather than
21317 // duplicating the TreeTransform logic, we should consider reusing it here.
21318 // Currently that causes problems when rebuilding LambdaExprs.
21319class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21320 Sema &S;
21321 SourceLocation Loc;
21322
21323public:
21324 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21325
21326 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21327};
21328}
21329
21330bool MarkReferencedDecls::TraverseTemplateArgument(
21331 const TemplateArgument &Arg) {
21332 {
21333 // A non-type template argument is a constant-evaluated context.
21334 EnterExpressionEvaluationContext Evaluated(
21335 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
21336 if (Arg.getKind() == TemplateArgument::Declaration) {
21337 if (Decl *D = Arg.getAsDecl())
21338 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
21339 } else if (Arg.getKind() == TemplateArgument::Expression) {
21340 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
21341 }
21342 }
21343
21344 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
21345}
21346
21347void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
21348 MarkReferencedDecls Marker(*this, Loc);
21349 Marker.TraverseType(T);
21350}
21351
21352namespace {
21353/// Helper class that marks all of the declarations referenced by
21354/// potentially-evaluated subexpressions as "referenced".
21355class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21356public:
21357 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21358 bool SkipLocalVariables;
21359 ArrayRef<const Expr *> StopAt;
21360
21361 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21362 ArrayRef<const Expr *> StopAt)
21363 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21364
21365 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21366 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21367 }
21368
21369 void Visit(Expr *E) {
21370 if (llvm::is_contained(Range&: StopAt, Element: E))
21371 return;
21372 Inherited::Visit(S: E);
21373 }
21374
21375 void VisitConstantExpr(ConstantExpr *E) {
21376 // Don't mark declarations within a ConstantExpression, as this expression
21377 // will be evaluated and folded to a value.
21378 }
21379
21380 void VisitDeclRefExpr(DeclRefExpr *E) {
21381 // If we were asked not to visit local variables, don't.
21382 if (SkipLocalVariables) {
21383 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21384 if (VD->hasLocalStorage())
21385 return;
21386 }
21387
21388 // FIXME: This can trigger the instantiation of the initializer of a
21389 // variable, which can cause the expression to become value-dependent
21390 // or error-dependent. Do we need to propagate the new dependence bits?
21391 S.MarkDeclRefReferenced(E);
21392 }
21393
21394 void VisitMemberExpr(MemberExpr *E) {
21395 S.MarkMemberReferenced(E);
21396 Visit(E: E->getBase());
21397 }
21398};
21399} // namespace
21400
21401void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21402 bool SkipLocalVariables,
21403 ArrayRef<const Expr*> StopAt) {
21404 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21405}
21406
21407/// Emit a diagnostic when statements are reachable.
21408bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21409 const PartialDiagnostic &PD) {
21410 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21411 // The initializer of a constexpr variable or of the first declaration of a
21412 // static data member is not syntactically a constant evaluated constant,
21413 // but nonetheless is always required to be a constant expression, so we
21414 // can skip diagnosing.
21415 if (Decl &&
21416 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21417 Decl->isFirstDecl() && !Decl->isInline())))
21418 return false;
21419
21420 if (Stmts.empty()) {
21421 Diag(Loc, PD);
21422 return true;
21423 }
21424
21425 if (getCurFunction()) {
21426 // This queue flushes after the function is analyzed, by which time an
21427 // ignore-all-warnings region live here is gone, so sample it now. A note
21428 // is not error-class either, so this also drops the notes that accompany a
21429 // skipped warning. They arrive on their own call, out of reach of the
21430 // engine's rule that drops a note whose warning was ignored.
21431 if (Diags.getIgnoreAllWarnings() &&
21432 Diags.getDiagnosticIDs()->isWarningOrExtension(DiagID: PD.getDiagID()))
21433 return false;
21434 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21435 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21436 return true;
21437 }
21438
21439 // For non-constexpr file-scope variables with reachability context (non-empty
21440 // Stmts), build a CFG for the initializer and check whether the context in
21441 // question is reachable.
21442 if (Decl && Decl->isFileVarDecl()) {
21443 AnalysisWarnings.registerVarDeclWarning(
21444 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21445 return true;
21446 }
21447
21448 Diag(Loc, PD);
21449 return true;
21450}
21451
21452/// Emit a diagnostic that describes an effect on the run-time behavior
21453/// of the program being compiled.
21454///
21455/// This routine emits the given diagnostic when the code currently being
21456/// type-checked is "potentially evaluated", meaning that there is a
21457/// possibility that the code will actually be executable. Code in sizeof()
21458/// expressions, code used only during overload resolution, etc., are not
21459/// potentially evaluated. This routine will suppress such diagnostics or,
21460/// in the absolutely nutty case of potentially potentially evaluated
21461/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21462/// later.
21463///
21464/// This routine should be used for all diagnostics that describe the run-time
21465/// behavior of a program, such as passing a non-POD value through an ellipsis.
21466/// Failure to do so will likely result in spurious diagnostics or failures
21467/// during overload resolution or within sizeof/alignof/typeof/typeid.
21468bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21469 const PartialDiagnostic &PD) {
21470
21471 if (ExprEvalContexts.back().isDiscardedStatementContext())
21472 return false;
21473
21474 switch (ExprEvalContexts.back().Context) {
21475 case ExpressionEvaluationContext::Unevaluated:
21476 case ExpressionEvaluationContext::UnevaluatedList:
21477 case ExpressionEvaluationContext::UnevaluatedAbstract:
21478 case ExpressionEvaluationContext::DiscardedStatement:
21479 // The argument will never be evaluated, so don't complain.
21480 break;
21481
21482 case ExpressionEvaluationContext::ConstantEvaluated:
21483 case ExpressionEvaluationContext::ImmediateFunctionContext:
21484 // Relevant diagnostics should be produced by constant evaluation.
21485 break;
21486
21487 case ExpressionEvaluationContext::PotentiallyEvaluated:
21488 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21489 return DiagIfReachable(Loc, Stmts, PD);
21490 }
21491
21492 return false;
21493}
21494
21495bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21496 const PartialDiagnostic &PD) {
21497 return DiagRuntimeBehavior(
21498 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21499 PD);
21500}
21501
21502bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21503 CallExpr *CE, FunctionDecl *FD) {
21504 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21505 return false;
21506
21507 // If we're inside a decltype's expression, don't check for a valid return
21508 // type or construct temporaries until we know whether this is the last call.
21509 if (ExprEvalContexts.back().ExprContext ==
21510 ExpressionEvaluationContextRecord::EK_Decltype) {
21511 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21512 return false;
21513 }
21514
21515 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21516 FunctionDecl *FD;
21517 CallExpr *CE;
21518
21519 public:
21520 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21521 : FD(FD), CE(CE) { }
21522
21523 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21524 if (!FD) {
21525 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21526 << T << CE->getSourceRange();
21527 return;
21528 }
21529
21530 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21531 << CE->getSourceRange() << FD << T;
21532 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21533 << FD->getDeclName();
21534 }
21535 } Diagnoser(FD, CE);
21536
21537 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21538 return true;
21539
21540 return false;
21541}
21542
21543// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21544// will prevent this condition from triggering, which is what we want.
21545void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21546 SourceLocation Loc;
21547
21548 unsigned diagnostic = diag::warn_condition_is_assignment;
21549 bool IsOrAssign = false;
21550
21551 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21552 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21553 return;
21554
21555 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21556
21557 // Greylist some idioms by putting them into a warning subcategory.
21558 if (ObjCMessageExpr *ME
21559 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21560 Selector Sel = ME->getSelector();
21561
21562 // self = [<foo> init...]
21563 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21564 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21565
21566 // <foo> = [<bar> nextObject]
21567 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21568 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21569 }
21570
21571 Loc = Op->getOperatorLoc();
21572 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21573 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21574 return;
21575
21576 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21577 Loc = Op->getOperatorLoc();
21578 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21579 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21580 else {
21581 // Not an assignment.
21582 return;
21583 }
21584
21585 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21586
21587 SourceLocation Open = E->getBeginLoc();
21588 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21589 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21590 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21591 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21592
21593 if (IsOrAssign)
21594 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21595 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21596 else
21597 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21598 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21599}
21600
21601void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21602 // Don't warn if the parens came from a macro.
21603 SourceLocation parenLoc = ParenE->getBeginLoc();
21604 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21605 return;
21606 // Don't warn for dependent expressions.
21607 if (ParenE->isTypeDependent())
21608 return;
21609
21610 Expr *E = ParenE->IgnoreParens();
21611 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21612 return;
21613
21614 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21615 if (opE->getOpcode() == BO_EQ &&
21616 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21617 == Expr::MLV_Valid) {
21618 SourceLocation Loc = opE->getOperatorLoc();
21619
21620 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21621 SourceRange ParenERange = ParenE->getSourceRange();
21622 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21623 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21624 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21625 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21626 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21627 }
21628}
21629
21630ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21631 bool IsConstexpr) {
21632 DiagnoseAssignmentAsCondition(E);
21633 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21634 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21635
21636 ExprResult result = CheckPlaceholderExpr(E);
21637 if (result.isInvalid()) return ExprError();
21638 E = result.get();
21639
21640 if (!E->isTypeDependent()) {
21641 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21642 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21643
21644 if (getLangOpts().CPlusPlus)
21645 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21646
21647 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21648 if (ERes.isInvalid())
21649 return ExprError();
21650 E = ERes.get();
21651
21652 QualType T = E->getType();
21653 if (!T->isScalarType()) { // C99 6.8.4.1p1
21654 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21655 << T << E->getSourceRange();
21656 return ExprError();
21657 }
21658 CheckBoolLikeConversion(E, CC: Loc);
21659 }
21660
21661 return E;
21662}
21663
21664Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21665 Expr *SubExpr, ConditionKind CK,
21666 bool MissingOK) {
21667 // MissingOK indicates whether having no condition expression is valid
21668 // (for loop) or invalid (e.g. while loop).
21669 if (!SubExpr)
21670 return MissingOK ? ConditionResult() : ConditionError();
21671
21672 ExprResult Cond;
21673 switch (CK) {
21674 case ConditionKind::Boolean:
21675 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21676 break;
21677
21678 case ConditionKind::ConstexprIf:
21679 // Note: this might produce a FullExpr
21680 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21681 break;
21682
21683 case ConditionKind::Switch:
21684 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21685 break;
21686 }
21687 if (Cond.isInvalid()) {
21688 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21689 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21690 if (!Cond.get())
21691 return ConditionError();
21692 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21693 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21694
21695 if (!Cond.isUsable())
21696 return ConditionError();
21697
21698 return ConditionResult(*this, nullptr, Cond,
21699 CK == ConditionKind::ConstexprIf);
21700}
21701
21702namespace {
21703 /// A visitor for rebuilding a call to an __unknown_any expression
21704 /// to have an appropriate type.
21705 struct RebuildUnknownAnyFunction
21706 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21707
21708 Sema &S;
21709
21710 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21711
21712 ExprResult VisitStmt(Stmt *S) {
21713 llvm_unreachable("unexpected statement!");
21714 }
21715
21716 ExprResult VisitExpr(Expr *E) {
21717 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21718 << E->getSourceRange();
21719 return ExprError();
21720 }
21721
21722 /// Rebuild an expression which simply semantically wraps another
21723 /// expression which it shares the type and value kind of.
21724 template <class T> ExprResult rebuildSugarExpr(T *E) {
21725 ExprResult SubResult = Visit(S: E->getSubExpr());
21726 if (SubResult.isInvalid()) return ExprError();
21727
21728 Expr *SubExpr = SubResult.get();
21729 E->setSubExpr(SubExpr);
21730 E->setType(SubExpr->getType());
21731 E->setValueKind(SubExpr->getValueKind());
21732 assert(E->getObjectKind() == OK_Ordinary);
21733 return E;
21734 }
21735
21736 ExprResult VisitParenExpr(ParenExpr *E) {
21737 return rebuildSugarExpr(E);
21738 }
21739
21740 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21741 return rebuildSugarExpr(E);
21742 }
21743
21744 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21745 ExprResult SubResult = Visit(S: E->getSubExpr());
21746 if (SubResult.isInvalid()) return ExprError();
21747
21748 Expr *SubExpr = SubResult.get();
21749 E->setSubExpr(SubExpr);
21750 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21751 assert(E->isPRValue());
21752 assert(E->getObjectKind() == OK_Ordinary);
21753 return E;
21754 }
21755
21756 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21757 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21758
21759 E->setType(VD->getType());
21760
21761 assert(E->isPRValue());
21762 if (S.getLangOpts().CPlusPlus &&
21763 !(isa<CXXMethodDecl>(Val: VD) &&
21764 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21765 E->setValueKind(VK_LValue);
21766
21767 return E;
21768 }
21769
21770 ExprResult VisitMemberExpr(MemberExpr *E) {
21771 return resolveDecl(E, VD: E->getMemberDecl());
21772 }
21773
21774 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21775 return resolveDecl(E, VD: E->getDecl());
21776 }
21777 };
21778}
21779
21780/// Given a function expression of unknown-any type, try to rebuild it
21781/// to have a function type.
21782static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21783 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21784 if (Result.isInvalid()) return ExprError();
21785 return S.DefaultFunctionArrayConversion(E: Result.get());
21786}
21787
21788namespace {
21789 /// A visitor for rebuilding an expression of type __unknown_anytype
21790 /// into one which resolves the type directly on the referring
21791 /// expression. Strict preservation of the original source
21792 /// structure is not a goal.
21793 struct RebuildUnknownAnyExpr
21794 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21795
21796 Sema &S;
21797
21798 /// The current destination type.
21799 QualType DestType;
21800
21801 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21802 : S(S), DestType(CastType) {}
21803
21804 ExprResult VisitStmt(Stmt *S) {
21805 llvm_unreachable("unexpected statement!");
21806 }
21807
21808 ExprResult VisitExpr(Expr *E) {
21809 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21810 << E->getSourceRange();
21811 return ExprError();
21812 }
21813
21814 ExprResult VisitCallExpr(CallExpr *E);
21815 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21816
21817 /// Rebuild an expression which simply semantically wraps another
21818 /// expression which it shares the type and value kind of.
21819 template <class T> ExprResult rebuildSugarExpr(T *E) {
21820 ExprResult SubResult = Visit(S: E->getSubExpr());
21821 if (SubResult.isInvalid()) return ExprError();
21822 Expr *SubExpr = SubResult.get();
21823 E->setSubExpr(SubExpr);
21824 E->setType(SubExpr->getType());
21825 E->setValueKind(SubExpr->getValueKind());
21826 assert(E->getObjectKind() == OK_Ordinary);
21827 return E;
21828 }
21829
21830 ExprResult VisitParenExpr(ParenExpr *E) {
21831 return rebuildSugarExpr(E);
21832 }
21833
21834 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21835 return rebuildSugarExpr(E);
21836 }
21837
21838 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21839 const PointerType *Ptr = DestType->getAs<PointerType>();
21840 if (!Ptr) {
21841 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21842 << E->getSourceRange();
21843 return ExprError();
21844 }
21845
21846 if (isa<CallExpr>(Val: E->getSubExpr())) {
21847 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21848 << E->getSourceRange();
21849 return ExprError();
21850 }
21851
21852 assert(E->isPRValue());
21853 assert(E->getObjectKind() == OK_Ordinary);
21854 E->setType(DestType);
21855
21856 // Build the sub-expression as if it were an object of the pointee type.
21857 DestType = Ptr->getPointeeType();
21858 ExprResult SubResult = Visit(S: E->getSubExpr());
21859 if (SubResult.isInvalid()) return ExprError();
21860 E->setSubExpr(SubResult.get());
21861 return E;
21862 }
21863
21864 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21865
21866 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21867
21868 ExprResult VisitMemberExpr(MemberExpr *E) {
21869 return resolveDecl(E, VD: E->getMemberDecl());
21870 }
21871
21872 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21873 return resolveDecl(E, VD: E->getDecl());
21874 }
21875 };
21876}
21877
21878/// Rebuilds a call expression which yielded __unknown_anytype.
21879ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21880 Expr *CalleeExpr = E->getCallee();
21881
21882 enum FnKind {
21883 FK_MemberFunction,
21884 FK_FunctionPointer,
21885 FK_BlockPointer
21886 };
21887
21888 FnKind Kind;
21889 QualType CalleeType = CalleeExpr->getType();
21890 if (CalleeType == S.Context.BoundMemberTy) {
21891 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21892 Kind = FK_MemberFunction;
21893 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21894 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21895 CalleeType = Ptr->getPointeeType();
21896 Kind = FK_FunctionPointer;
21897 } else {
21898 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21899 Kind = FK_BlockPointer;
21900 }
21901 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21902
21903 // Verify that this is a legal result type of a function.
21904 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21905 DestType->isFunctionType()) {
21906 unsigned diagID = diag::err_func_returning_array_function;
21907 if (Kind == FK_BlockPointer)
21908 diagID = diag::err_block_returning_array_function;
21909
21910 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21911 << DestType->isFunctionType() << DestType;
21912 return ExprError();
21913 }
21914
21915 // Otherwise, go ahead and set DestType as the call's result.
21916 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21917 E->setValueKind(Expr::getValueKindForType(T: DestType));
21918 assert(E->getObjectKind() == OK_Ordinary);
21919
21920 // Rebuild the function type, replacing the result type with DestType.
21921 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21922 if (Proto) {
21923 // __unknown_anytype(...) is a special case used by the debugger when
21924 // it has no idea what a function's signature is.
21925 //
21926 // We want to build this call essentially under the K&R
21927 // unprototyped rules, but making a FunctionNoProtoType in C++
21928 // would foul up all sorts of assumptions. However, we cannot
21929 // simply pass all arguments as variadic arguments, nor can we
21930 // portably just call the function under a non-variadic type; see
21931 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21932 // However, it turns out that in practice it is generally safe to
21933 // call a function declared as "A foo(B,C,D);" under the prototype
21934 // "A foo(B,C,D,...);". The only known exception is with the
21935 // Windows ABI, where any variadic function is implicitly cdecl
21936 // regardless of its normal CC. Therefore we change the parameter
21937 // types to match the types of the arguments.
21938 //
21939 // This is a hack, but it is far superior to moving the
21940 // corresponding target-specific code from IR-gen to Sema/AST.
21941
21942 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21943 SmallVector<QualType, 8> ArgTypes;
21944 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21945 ArgTypes.reserve(N: E->getNumArgs());
21946 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21947 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21948 }
21949 ParamTypes = ArgTypes;
21950 }
21951 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21952 EPI: Proto->getExtProtoInfo());
21953 } else {
21954 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21955 Info: FnType->getExtInfo());
21956 }
21957
21958 // Rebuild the appropriate pointer-to-function type.
21959 switch (Kind) {
21960 case FK_MemberFunction:
21961 // Nothing to do.
21962 break;
21963
21964 case FK_FunctionPointer:
21965 DestType = S.Context.getPointerType(T: DestType);
21966 break;
21967
21968 case FK_BlockPointer:
21969 DestType = S.Context.getBlockPointerType(T: DestType);
21970 break;
21971 }
21972
21973 // Finally, we can recurse.
21974 ExprResult CalleeResult = Visit(S: CalleeExpr);
21975 if (!CalleeResult.isUsable()) return ExprError();
21976 E->setCallee(CalleeResult.get());
21977
21978 // Bind a temporary if necessary.
21979 return S.MaybeBindToTemporary(E);
21980}
21981
21982ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21983 // Verify that this is a legal result type of a call.
21984 if (DestType->isArrayType() || DestType->isFunctionType()) {
21985 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21986 << DestType->isFunctionType() << DestType;
21987 return ExprError();
21988 }
21989
21990 // Rewrite the method result type if available.
21991 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21992 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21993 Method->setReturnType(DestType);
21994 }
21995
21996 // Change the type of the message.
21997 E->setType(DestType.getNonReferenceType());
21998 E->setValueKind(Expr::getValueKindForType(T: DestType));
21999
22000 return S.MaybeBindToTemporary(E);
22001}
22002
22003ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
22004 // The only case we should ever see here is a function-to-pointer decay.
22005 if (E->getCastKind() == CK_FunctionToPointerDecay) {
22006 assert(E->isPRValue());
22007 assert(E->getObjectKind() == OK_Ordinary);
22008
22009 E->setType(DestType);
22010
22011 // Rebuild the sub-expression as the pointee (function) type.
22012 DestType = DestType->castAs<PointerType>()->getPointeeType();
22013
22014 ExprResult Result = Visit(S: E->getSubExpr());
22015 if (!Result.isUsable()) return ExprError();
22016
22017 E->setSubExpr(Result.get());
22018 return E;
22019 } else if (E->getCastKind() == CK_LValueToRValue) {
22020 assert(E->isPRValue());
22021 assert(E->getObjectKind() == OK_Ordinary);
22022
22023 assert(isa<BlockPointerType>(E->getType()));
22024
22025 E->setType(DestType);
22026
22027 // The sub-expression has to be a lvalue reference, so rebuild it as such.
22028 DestType = S.Context.getLValueReferenceType(T: DestType);
22029
22030 ExprResult Result = Visit(S: E->getSubExpr());
22031 if (!Result.isUsable()) return ExprError();
22032
22033 E->setSubExpr(Result.get());
22034 return E;
22035 } else {
22036 llvm_unreachable("Unhandled cast type!");
22037 }
22038}
22039
22040ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
22041 ExprValueKind ValueKind = VK_LValue;
22042 QualType Type = DestType;
22043
22044 // We know how to make this work for certain kinds of decls:
22045
22046 // - functions
22047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
22048 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
22049 DestType = Ptr->getPointeeType();
22050 ExprResult Result = resolveDecl(E, VD);
22051 if (Result.isInvalid()) return ExprError();
22052 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
22053 VK: VK_PRValue);
22054 }
22055
22056 if (!Type->isFunctionType()) {
22057 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
22058 << VD << E->getSourceRange();
22059 return ExprError();
22060 }
22061 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
22062 // We must match the FunctionDecl's type to the hack introduced in
22063 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
22064 // type. See the lengthy commentary in that routine.
22065 QualType FDT = FD->getType();
22066 const FunctionType *FnType = FDT->castAs<FunctionType>();
22067 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
22068 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
22069 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
22070 SourceLocation Loc = FD->getLocation();
22071 FunctionDecl *NewFD = FunctionDecl::Create(
22072 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
22073 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
22074 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
22075 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
22076 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
22077
22078 if (FD->getQualifier())
22079 NewFD->setQualifierInfo(FD->getQualifierLoc());
22080
22081 SmallVector<ParmVarDecl*, 16> Params;
22082 for (const auto &AI : FT->param_types()) {
22083 ParmVarDecl *Param =
22084 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
22085 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
22086 Params.push_back(Elt: Param);
22087 }
22088 NewFD->setParams(Params);
22089 DRE->setDecl(NewFD);
22090 VD = DRE->getDecl();
22091 }
22092 }
22093
22094 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
22095 if (MD->isInstance()) {
22096 ValueKind = VK_PRValue;
22097 Type = S.Context.BoundMemberTy;
22098 }
22099
22100 // Function references aren't l-values in C.
22101 if (!S.getLangOpts().CPlusPlus)
22102 ValueKind = VK_PRValue;
22103
22104 // - variables
22105 } else if (isa<VarDecl>(Val: VD)) {
22106 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22107 Type = RefTy->getPointeeType();
22108 } else if (Type->isFunctionType()) {
22109 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
22110 << VD << E->getSourceRange();
22111 return ExprError();
22112 }
22113
22114 // - nothing else
22115 } else {
22116 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
22117 << VD << E->getSourceRange();
22118 return ExprError();
22119 }
22120
22121 // Modifying the declaration like this is friendly to IR-gen but
22122 // also really dangerous.
22123 VD->setType(DestType);
22124 E->setType(Type);
22125 E->setValueKind(ValueKind);
22126 return E;
22127}
22128
22129ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
22130 Expr *CastExpr, CastKind &CastKind,
22131 ExprValueKind &VK, CXXCastPath &Path) {
22132 // The type we're casting to must be either void or complete.
22133 if (!CastType->isVoidType() &&
22134 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
22135 DiagID: diag::err_typecheck_cast_to_incomplete))
22136 return ExprError();
22137
22138 // Rewrite the casted expression from scratch.
22139 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
22140 if (!result.isUsable()) return ExprError();
22141
22142 CastExpr = result.get();
22143 VK = CastExpr->getValueKind();
22144 CastKind = CK_NoOp;
22145
22146 return CastExpr;
22147}
22148
22149ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
22150 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
22151}
22152
22153ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
22154 Expr *arg, QualType &paramType) {
22155 // If the syntactic form of the argument is not an explicit cast of
22156 // any sort, just do default argument promotion.
22157 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
22158 if (!castArg) {
22159 ExprResult result = DefaultArgumentPromotion(E: arg);
22160 if (result.isInvalid()) return ExprError();
22161 paramType = result.get()->getType();
22162 return result;
22163 }
22164
22165 // Otherwise, use the type that was written in the explicit cast.
22166 assert(!arg->hasPlaceholderType());
22167 paramType = castArg->getTypeAsWritten();
22168
22169 // Copy-initialize a parameter of that type.
22170 InitializedEntity entity =
22171 InitializedEntity::InitializeParameter(Context, Type: paramType,
22172 /*consumed*/ Consumed: false);
22173 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
22174}
22175
22176static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
22177 Expr *orig = E;
22178 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22179 while (true) {
22180 E = E->IgnoreParenImpCasts();
22181 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
22182 E = call->getCallee();
22183 diagID = diag::err_uncasted_call_of_unknown_any;
22184 } else {
22185 break;
22186 }
22187 }
22188
22189 SourceLocation loc;
22190 NamedDecl *d;
22191 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
22192 loc = ref->getLocation();
22193 d = ref->getDecl();
22194 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
22195 loc = mem->getMemberLoc();
22196 d = mem->getMemberDecl();
22197 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
22198 diagID = diag::err_uncasted_call_of_unknown_any;
22199 loc = msg->getSelectorStartLoc();
22200 d = msg->getMethodDecl();
22201 if (!d) {
22202 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
22203 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22204 << orig->getSourceRange();
22205 return ExprError();
22206 }
22207 } else {
22208 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
22209 << E->getSourceRange();
22210 return ExprError();
22211 }
22212
22213 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
22214
22215 // Never recoverable.
22216 return ExprError();
22217}
22218
22219ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
22220 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22221 if (!placeholderType) return E;
22222
22223 switch (placeholderType->getKind()) {
22224 case BuiltinType::UnresolvedTemplate: {
22225 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
22226 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22227 // There's only one FoundDecl for UnresolvedTemplate type. See
22228 // BuildTemplateIdExpr.
22229 NamedDecl *Temp = *ULE->decls_begin();
22230 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
22231
22232 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22233 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22234 // as it models only the unqualified-id case, where this case can clearly be
22235 // qualified. Thus we can't just qualify an assumed template.
22236 TemplateName TN;
22237 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
22238 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
22239 Template: TemplateName(TD));
22240 else
22241 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
22242
22243 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
22244 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22245 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
22246 << IsTypeAliasTemplateDecl;
22247
22248 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22249 bool HasAnyDependentTA = false;
22250 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22251 HasAnyDependentTA |= Arg.getArgument().isDependent();
22252 TAL.addArgument(Loc: Arg);
22253 }
22254
22255 QualType TST;
22256 {
22257 SFINAETrap Trap(*this);
22258 TST = CheckTemplateIdType(
22259 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
22260 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22261 }
22262 if (TST.isNull())
22263 TST = Context.getTemplateSpecializationType(
22264 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
22265 /*CanonicalArgs=*/{},
22266 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22267 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
22268 T: TST);
22269 }
22270
22271 // Overloaded expressions.
22272 case BuiltinType::Overload: {
22273 // Try to resolve a single function template specialization.
22274 // This is obligatory.
22275 ExprResult Result = E;
22276 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
22277 return Result;
22278
22279 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22280 // leaves Result unchanged on failure.
22281 Result = E;
22282 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
22283 return Result;
22284
22285 // If that failed, try to recover with a call.
22286 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
22287 /*complain*/ ForceComplain: true);
22288 return Result;
22289 }
22290
22291 // Bound member functions.
22292 case BuiltinType::BoundMember: {
22293 ExprResult result = E;
22294 const Expr *BME = E->IgnoreParens();
22295 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
22296 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22297 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
22298 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22299 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
22300 if (ME->getMemberNameInfo().getName().getNameKind() ==
22301 DeclarationName::CXXDestructorName)
22302 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22303 }
22304 tryToRecoverWithCall(E&: result, PD,
22305 /*complain*/ ForceComplain: true);
22306 return result;
22307 }
22308
22309 // ARC unbridged casts.
22310 case BuiltinType::ARCUnbridgedCast: {
22311 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
22312 ObjC().diagnoseARCUnbridgedCast(e: realCast);
22313 return realCast;
22314 }
22315
22316 // Expressions of unknown type.
22317 case BuiltinType::UnknownAny:
22318 return diagnoseUnknownAnyExpr(S&: *this, E);
22319
22320 // Pseudo-objects.
22321 case BuiltinType::PseudoObject:
22322 return PseudoObject().checkRValue(E);
22323
22324 case BuiltinType::BuiltinFn: {
22325 // Accept __noop without parens by implicitly converting it to a call expr.
22326 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
22327 if (DRE) {
22328 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
22329 unsigned BuiltinID = FD->getBuiltinID();
22330 if (BuiltinID == Builtin::BI__noop) {
22331 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
22332 CK: CK_BuiltinFnToFnPtr)
22333 .get();
22334 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
22335 VK: VK_PRValue, RParenLoc: SourceLocation(),
22336 FPFeatures: FPOptionsOverride());
22337 }
22338
22339 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
22340 // Any use of these other than a direct call is ill-formed as of C++20,
22341 // because they are not addressable functions. In earlier language
22342 // modes, warn and force an instantiation of the real body.
22343 Diag(Loc: E->getBeginLoc(),
22344 DiagID: getLangOpts().CPlusPlus20
22345 ? diag::err_use_of_unaddressable_function
22346 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22347 if (FD->isImplicitlyInstantiable()) {
22348 // Require a definition here because a normal attempt at
22349 // instantiation for a builtin will be ignored, and we won't try
22350 // again later. We assume that the definition of the template
22351 // precedes this use.
22352 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
22353 /*Recursive=*/false,
22354 /*DefinitionRequired=*/true,
22355 /*AtEndOfTU=*/false);
22356 }
22357 // Produce a properly-typed reference to the function.
22358 CXXScopeSpec SS;
22359 SS.Adopt(Other: DRE->getQualifierLoc());
22360 TemplateArgumentListInfo TemplateArgs;
22361 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22362 return BuildDeclRefExpr(
22363 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22364 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22365 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22366 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22367 }
22368 }
22369
22370 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22371 return ExprError();
22372 }
22373
22374 case BuiltinType::IncompleteMatrixIdx: {
22375 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22376 // At this point, we know there was no second [] to complete the operator.
22377 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22378 if (getLangOpts().HLSL) {
22379 return CreateBuiltinMatrixSingleSubscriptExpr(
22380 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22381 }
22382 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22383 return ExprError();
22384 }
22385
22386 // Expressions of unknown type.
22387 case BuiltinType::ArraySection:
22388 // If we've already diagnosed something on the array section type, we
22389 // shouldn't need to do any further diagnostic here.
22390 if (!E->containsErrors())
22391 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22392 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22393 return ExprError();
22394
22395 // Expressions of unknown type.
22396 case BuiltinType::OMPArrayShaping:
22397 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22398
22399 case BuiltinType::OMPIterator:
22400 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22401
22402 // Everything else should be impossible.
22403#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22404 case BuiltinType::Id:
22405#include "clang/Basic/OpenCLImageTypes.def"
22406#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22407 case BuiltinType::Id:
22408#include "clang/Basic/OpenCLExtensionTypes.def"
22409#define SVE_TYPE(Name, Id, SingletonId) \
22410 case BuiltinType::Id:
22411#include "clang/Basic/AArch64ACLETypes.def"
22412#define PPC_VECTOR_TYPE(Name, Id, Size) \
22413 case BuiltinType::Id:
22414#include "clang/Basic/PPCTypes.def"
22415#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22416#include "clang/Basic/RISCVVTypes.def"
22417#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22418#include "clang/Basic/WebAssemblyReferenceTypes.def"
22419#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22420#include "clang/Basic/AMDGPUTypes.def"
22421#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22422#include "clang/Basic/HLSLIntangibleTypes.def"
22423#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22424#include "clang/Basic/HLSLPackedTypes.def"
22425#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22426#include "clang/Basic/SPIRVTypes.def"
22427#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22428#define PLACEHOLDER_TYPE(Id, SingletonId)
22429#include "clang/AST/BuiltinTypes.def"
22430 break;
22431 }
22432
22433 llvm_unreachable("invalid placeholder type!");
22434}
22435
22436bool Sema::CheckCaseExpression(Expr *E) {
22437 if (E->isTypeDependent())
22438 return true;
22439 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22440 return E->getType()->isIntegralOrEnumerationType();
22441 return false;
22442}
22443
22444ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22445 ArrayRef<Expr *> SubExprs, QualType T) {
22446 if (!Context.getLangOpts().RecoveryAST)
22447 return ExprError();
22448
22449 if (isSFINAEContext())
22450 return ExprError();
22451
22452 if (T.isNull() || T->isUndeducedType() ||
22453 !Context.getLangOpts().RecoveryASTType)
22454 // We don't know the concrete type, fallback to dependent type.
22455 T = Context.DependentTy;
22456
22457 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22458}
22459