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/Builtins.h"
37#include "clang/Basic/DiagnosticSema.h"
38#include "clang/Basic/PartialDiagnostic.h"
39#include "clang/Basic/SourceManager.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TargetInfo.h"
42#include "clang/Basic/TypeTraits.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/Support/ConvertUTF.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/Support/TimeProfiler.h"
71#include "llvm/Support/TypeSize.h"
72#include <limits>
73#include <optional>
74
75using namespace clang;
76using namespace sema;
77
78bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
79 // See if this is an auto-typed variable whose initializer we are parsing.
80 if (ParsingInitForAutoVars.count(Ptr: D))
81 return false;
82
83 // See if this is a deleted function.
84 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
85 if (FD->isDeleted())
86 return false;
87
88 // If the function has a deduced return type, and we can't deduce it,
89 // then we can't use it either.
90 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
91 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
92 return false;
93
94 // See if this is an aligned allocation/deallocation function that is
95 // unavailable.
96 if (TreatUnavailableAsInvalid &&
97 isUnavailableAlignedAllocationFunction(FD: *FD))
98 return false;
99 }
100
101 // See if this function is unavailable.
102 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
103 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
104 return false;
105
106 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
107 return false;
108
109 return true;
110}
111
112static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
113 // Warn if this is used but marked unused.
114 if (const auto *A = D->getAttr<UnusedAttr>()) {
115 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
116 // should diagnose them.
117 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
118 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
119 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
120 if (DC && !DC->hasAttr<UnusedAttr>())
121 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
122 }
123 }
124}
125
126void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
127 assert(Decl && Decl->isDeleted());
128
129 if (Decl->isDefaulted()) {
130 // If the method was explicitly defaulted, point at that declaration.
131 if (!Decl->isImplicit())
132 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
133
134 // Try to diagnose why this special member function was implicitly
135 // deleted. This might fail, if that reason no longer applies.
136 DiagnoseDeletedDefaultedFunction(FD: Decl);
137 return;
138 }
139
140 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
141 if (Ctor && Ctor->isInheritingConstructor())
142 return NoteDeletedInheritingConstructor(CD: Ctor);
143
144 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
145 << Decl << 1;
146}
147
148/// Determine whether a FunctionDecl was ever declared with an
149/// explicit storage class.
150static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
151 for (auto *I : D->redecls()) {
152 if (I->getStorageClass() != SC_None)
153 return true;
154 }
155 return false;
156}
157
158/// Check whether we're in an extern inline function and referring to a
159/// variable or function with internal linkage (C11 6.7.4p3).
160///
161/// This is only a warning because we used to silently accept this code, but
162/// in many cases it will not behave correctly. This is not enabled in C++ mode
163/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
164/// and so while there may still be user mistakes, most of the time we can't
165/// prove that there are errors.
166static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
167 const NamedDecl *D,
168 SourceLocation Loc) {
169 // This is disabled under C++; there are too many ways for this to fire in
170 // contexts where the warning is a false positive, or where it is technically
171 // correct but benign.
172 //
173 // WG14 N3622 which removed the constraint entirely in C2y. It is left
174 // enabled in earlier language modes because this is a constraint in those
175 // language modes. But in C2y mode, we still want to issue the "incompatible
176 // with previous standards" diagnostic, too.
177 if (S.getLangOpts().CPlusPlus)
178 return;
179
180 // Check if this is an inlined function or method.
181 FunctionDecl *Current = S.getCurFunctionDecl();
182 if (!Current)
183 return;
184 if (!Current->isInlined())
185 return;
186 if (!Current->isExternallyVisible())
187 return;
188
189 // Check if the decl has internal linkage.
190 if (D->getFormalLinkage() != Linkage::Internal)
191 return;
192
193 // Downgrade from ExtWarn to Extension if
194 // (1) the supposedly external inline function is in the main file,
195 // and probably won't be included anywhere else.
196 // (2) the thing we're referencing is a pure function.
197 // (3) the thing we're referencing is another inline function.
198 // This last can give us false negatives, but it's better than warning on
199 // wrappers for simple C library functions.
200 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
201 unsigned DiagID;
202 if (S.getLangOpts().C2y)
203 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
204 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
205 S.getSourceManager().isInMainFile(Loc))
206 DiagID = diag::ext_internal_in_extern_inline_quiet;
207 else
208 DiagID = diag::ext_internal_in_extern_inline;
209
210 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
211 S.MaybeSuggestAddingStaticToDecl(D: Current);
212 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
213 << D;
214}
215
216void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
217 const FunctionDecl *First = Cur->getFirstDecl();
218
219 // Suggest "static" on the function, if possible.
220 if (!hasAnyExplicitStorageClass(D: First)) {
221 SourceLocation DeclBegin = First->getSourceRange().getBegin();
222 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
223 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
224 }
225}
226
227bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
228 const ObjCInterfaceDecl *UnknownObjCClass,
229 bool ObjCPropertyAccess,
230 bool AvoidPartialAvailabilityChecks,
231 ObjCInterfaceDecl *ClassReceiver,
232 bool SkipTrailingRequiresClause) {
233 SourceLocation Loc = Locs.front();
234 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
235 // If there were any diagnostics suppressed by template argument deduction,
236 // emit them now.
237 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
238 if (Pos != SuppressedDiagnostics.end()) {
239 for (const auto &[DiagLoc, PD] : Pos->second) {
240 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
241 PD.Emit(DB: Builder);
242 }
243 // Clear out the list of suppressed diagnostics, so that we don't emit
244 // them again for this specialization. However, we don't obsolete this
245 // entry from the table, because we want to avoid ever emitting these
246 // diagnostics again.
247 Pos->second.clear();
248 }
249
250 // C++ [basic.start.main]p3:
251 // The function 'main' shall not be used within a program.
252 if (cast<FunctionDecl>(Val: D)->isMain())
253 Diag(Loc, DiagID: diag::ext_main_used);
254
255 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
256 }
257
258 // See if this is an auto-typed variable whose initializer we are parsing.
259 if (ParsingInitForAutoVars.count(Ptr: D)) {
260 if (isa<BindingDecl>(Val: D)) {
261 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 } else {
264 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << diag::ParsingInitFor::Var << D->getDeclName()
266 << cast<VarDecl>(Val: D)->getType();
267 }
268 return true;
269 }
270
271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
272 // See if this is a deleted function.
273 if (FD->isDeleted()) {
274 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
275 if (Ctor && Ctor->isInheritingConstructor())
276 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
277 << Ctor->getParent()
278 << Ctor->getInheritedConstructor().getConstructor()->getParent();
279 else {
280 StringLiteral *Msg = FD->getDeletedMessage();
281 Diag(Loc, DiagID: diag::err_deleted_function_use)
282 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
283 }
284 NoteDeletedFunction(Decl: FD);
285 return true;
286 }
287
288 // [expr.prim.id]p4
289 // A program that refers explicitly or implicitly to a function with a
290 // trailing requires-clause whose constraint-expression is not satisfied,
291 // other than to declare it, is ill-formed. [...]
292 //
293 // See if this is a function with constraints that need to be satisfied.
294 // Check this before deducing the return type, as it might instantiate the
295 // definition.
296 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
297 ConstraintSatisfaction Satisfaction;
298 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
299 /*ForOverloadResolution*/ true))
300 // A diagnostic will have already been generated (non-constant
301 // constraint expression, for example)
302 return true;
303 if (!Satisfaction.IsSatisfied) {
304 Diag(Loc,
305 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
306 << D;
307 DiagnoseUnsatisfiedConstraint(Satisfaction);
308 return true;
309 }
310 }
311
312 // If the function has a deduced return type, and we can't deduce it,
313 // then we can't use it either.
314 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
315 DeduceReturnType(FD, Loc))
316 return true;
317
318 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
319 return true;
320
321 }
322
323 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
324 Concept && CheckConceptUseInDefinition(Concept, Loc))
325 return true;
326
327 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
328 // Lambdas are only default-constructible or assignable in C++2a onwards.
329 if (MD->getParent()->isLambda() &&
330 ((isa<CXXConstructorDecl>(Val: MD) &&
331 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
332 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
333 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
334 << !isa<CXXConstructorDecl>(Val: MD);
335 }
336 }
337
338 auto getReferencedObjCProp = [](const NamedDecl *D) ->
339 const ObjCPropertyDecl * {
340 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
341 return MD->findPropertyDecl();
342 return nullptr;
343 };
344 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
345 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
346 return true;
347 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
348 return true;
349 }
350
351 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
352 // Only the variables omp_in and omp_out are allowed in the combiner.
353 // Only the variables omp_priv and omp_orig are allowed in the
354 // initializer-clause.
355 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
356 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
357 isa<VarDecl>(Val: D)) {
358 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
359 << getCurFunction()->HasOMPDeclareReductionCombiner;
360 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
365 // List-items in map clauses on this construct may only refer to the declared
366 // variable var and entities that could be referenced by a procedure defined
367 // at the same location.
368 // [OpenMP 5.2] Also allow iterator declared variables.
369 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
370 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
371 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
372 << OpenMP().getOpenMPDeclareMapperVarName();
373 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
374 return true;
375 }
376
377 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
378 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
379 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
380 return true;
381 }
382
383 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
384 AvoidPartialAvailabilityChecks, ClassReceiver);
385
386 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
387
388 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
389
390 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
391 if (getLangOpts().getFPEvalMethod() !=
392 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
393 PP.getLastFPEvalPragmaLocation().isValid() &&
394 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
395 Diag(Loc: D->getLocation(),
396 DiagID: diag::err_type_available_only_in_default_eval_method)
397 << D->getName();
398 }
399
400 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
401 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
402
403 if (LangOpts.SYCLIsDevice ||
404 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
405 if (!Context.getTargetInfo().isTLSSupported())
406 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
407 if (VD->getTLSKind() != VarDecl::TLS_None)
408 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
409 }
410
411 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
412 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
413
414 return false;
415}
416
417void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
418 ArrayRef<Expr *> Args) {
419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420 if (!Attr)
421 return;
422
423 // The number of formal parameters of the declaration.
424 unsigned NumFormalParams;
425
426 // The kind of declaration. This is also an index into a %select in
427 // the diagnostic.
428 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
429
430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
431 NumFormalParams = MD->param_size();
432 CalleeKind = CK_Method;
433 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
434 NumFormalParams = FD->param_size();
435 CalleeKind = CK_Function;
436 if (FD->hasCXXExplicitFunctionObjectParameter())
437 NumFormalParams++;
438 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
439 QualType Ty = VD->getType();
440 const FunctionType *Fn = nullptr;
441 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
442 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
443 if (!Fn)
444 return;
445 CalleeKind = CK_Function;
446 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
447 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
448 CalleeKind = CK_Block;
449 } else {
450 return;
451 }
452
453 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
454 NumFormalParams = proto->getNumParams();
455 else
456 NumFormalParams = 0;
457 } else {
458 return;
459 }
460
461 // "NullPos" is the number of formal parameters at the end which
462 // effectively count as part of the variadic arguments. This is
463 // useful if you would prefer to not have *any* formal parameters,
464 // but the language forces you to have at least one.
465 unsigned NullPos = Attr->getNullPos();
466 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
467 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
468
469 // The number of arguments which should follow the sentinel.
470 unsigned NumArgsAfterSentinel = Attr->getSentinel();
471
472 // If there aren't enough arguments for all the formal parameters,
473 // the sentinel, and the args after the sentinel, complain.
474 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
475 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
476 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
477 return;
478 }
479
480 // Otherwise, find the sentinel expression.
481 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
482 if (!SentinelExpr)
483 return;
484 if (SentinelExpr->isValueDependent())
485 return;
486 if (Context.isSentinelNullExpr(E: SentinelExpr))
487 return;
488
489 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
490 // or 'NULL' if those are actually defined in the context. Only use
491 // 'nil' for ObjC methods, where it's much more likely that the
492 // variadic arguments form a list of object pointers.
493 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
494 std::string NullValue;
495 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
496 NullValue = "nil";
497 else if (getLangOpts().CPlusPlus11)
498 NullValue = "nullptr";
499 else if (PP.isMacroDefined(Id: "NULL"))
500 NullValue = "NULL";
501 else
502 NullValue = "(void*) 0";
503
504 if (MissingNilLoc.isInvalid())
505 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
506 else
507 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
508 << int(CalleeKind)
509 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
510 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
511 << int(CalleeKind) << Attr->getRange();
512}
513
514SourceRange Sema::getExprRange(Expr *E) const {
515 return E ? E->getSourceRange() : SourceRange();
516}
517
518//===----------------------------------------------------------------------===//
519// Standard Promotions and Conversions
520//===----------------------------------------------------------------------===//
521
522/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
523ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
524 // Handle any placeholder expressions which made it here.
525 if (E->hasPlaceholderType()) {
526 ExprResult result = CheckPlaceholderExpr(E);
527 if (result.isInvalid()) return ExprError();
528 E = result.get();
529 }
530
531 QualType Ty = E->getType();
532 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
533
534 if (Ty->isFunctionType()) {
535 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
536 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
537 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
538 return ExprError();
539
540 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
541 CK: CK_FunctionToPointerDecay).get();
542 } else if (Ty->isArrayType()) {
543 // In C90 mode, arrays only promote to pointers if the array expression is
544 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
545 // type 'array of type' is converted to an expression that has type 'pointer
546 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
547 // that has type 'array of type' ...". The relevant change is "an lvalue"
548 // (C90) to "an expression" (C99).
549 //
550 // C++ 4.2p1:
551 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
552 // T" can be converted to an rvalue of type "pointer to T".
553 //
554 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
555 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
556 CK: CK_ArrayToPointerDecay);
557 if (Res.isInvalid())
558 return ExprError();
559 E = Res.get();
560 }
561 }
562 return E;
563}
564
565static void CheckForNullPointerDereference(Sema &S, Expr *E) {
566 // Check to see if we are dereferencing a null pointer. If so,
567 // and if not volatile-qualified, this is undefined behavior that the
568 // optimizer will delete, so warn about it. People sometimes try to use this
569 // to get a deterministic trap and are surprised by clang's behavior. This
570 // only handles the pattern "*null", which is a very syntactic check.
571 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
572 if (UO && UO->getOpcode() == UO_Deref &&
573 UO->getSubExpr()->getType()->isPointerType()) {
574 const LangAS AS =
575 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
576 if ((!isTargetAddressSpace(AS) ||
577 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
578 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
579 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
580 !UO->getType().isVolatileQualified()) {
581 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
582 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
583 << UO->getSubExpr()->getSourceRange());
584 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
585 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
586 }
587 }
588}
589
590static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
591 SourceLocation AssignLoc,
592 const Expr* RHS) {
593 const ObjCIvarDecl *IV = OIRE->getDecl();
594 if (!IV)
595 return;
596
597 DeclarationName MemberName = IV->getDeclName();
598 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
599 if (!Member || !Member->isStr(Str: "isa"))
600 return;
601
602 const Expr *Base = OIRE->getBase();
603 QualType BaseType = Base->getType();
604 if (OIRE->isArrow())
605 BaseType = BaseType->getPointeeType();
606 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
607 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
608 ObjCInterfaceDecl *ClassDeclared = nullptr;
609 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
610 if (!ClassDeclared->getSuperClass()
611 && (*ClassDeclared->ivar_begin()) == IV) {
612 if (RHS) {
613 NamedDecl *ObjectSetClass =
614 S.LookupSingleName(S: S.TUScope,
615 Name: &S.Context.Idents.get(Name: "object_setClass"),
616 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
617 if (ObjectSetClass) {
618 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
619 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
620 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
621 Code: "object_setClass(")
622 << FixItHint::CreateReplacement(
623 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
624 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
625 }
626 else
627 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
628 } else {
629 NamedDecl *ObjectGetClass =
630 S.LookupSingleName(S: S.TUScope,
631 Name: &S.Context.Idents.get(Name: "object_getClass"),
632 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
633 if (ObjectGetClass)
634 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
635 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
636 Code: "object_getClass(")
637 << FixItHint::CreateReplacement(
638 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
639 else
640 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
641 }
642 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
643 }
644 }
645}
646
647ExprResult Sema::DefaultLvalueConversion(Expr *E) {
648 // Handle any placeholder expressions which made it here.
649 if (E->hasPlaceholderType()) {
650 ExprResult result = CheckPlaceholderExpr(E);
651 if (result.isInvalid()) return ExprError();
652 E = result.get();
653 }
654
655 // C++ [conv.lval]p1:
656 // A glvalue of a non-function, non-array type T can be
657 // converted to a prvalue.
658 if (!E->isGLValue()) return E;
659
660 QualType T = E->getType();
661 assert(!T.isNull() && "r-value conversion on typeless expression?");
662
663 // lvalue-to-rvalue conversion cannot be applied to types that decay to
664 // pointers (i.e. function or array types).
665 if (T->canDecayToPointerType())
666 return E;
667
668 // We don't want to throw lvalue-to-rvalue casts on top of
669 // expressions of certain types in C++.
670 // In HLSL LvaluetoRvalue conversion is allowed on records.
671 if (getLangOpts().CPlusPlus) {
672 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
673 (T->isDependentType() && !T->isAnyPointerType() &&
674 !T->isMemberPointerType()))
675 return E;
676 }
677
678 // The C standard is actually really unclear on this point, and
679 // DR106 tells us what the result should be but not why. It's
680 // generally best to say that void types just doesn't undergo
681 // lvalue-to-rvalue at all. Note that expressions of unqualified
682 // 'void' type are never l-values, but qualified void can be.
683 if (T->isVoidType())
684 return E;
685
686 // OpenCL usually rejects direct accesses to values of 'half' type.
687 if (getLangOpts().OpenCL &&
688 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
689 T->isHalfType()) {
690 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
691 << 0 << T;
692 return ExprError();
693 }
694
695 CheckForNullPointerDereference(S&: *this, E);
696 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
697 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
698 Name: &Context.Idents.get(Name: "object_getClass"),
699 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
700 if (ObjectGetClass)
701 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
702 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
703 << FixItHint::CreateReplacement(
704 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
705 else
706 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
707 }
708 else if (const ObjCIvarRefExpr *OIRE =
709 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
710 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
711
712 // C++ [conv.lval]p1:
713 // [...] If T is a non-class type, the type of the prvalue is the
714 // cv-unqualified version of T. Otherwise, the type of the
715 // rvalue is T.
716 //
717 // C99 6.3.2.1p2:
718 // If the lvalue has qualified type, the value has the unqualified
719 // version of the type of the lvalue; otherwise, the value has the
720 // type of the lvalue.
721 if (T.hasQualifiers())
722 T = T.getUnqualifiedType();
723
724 // Under the MS ABI, lock down the inheritance model now.
725 if (T->isMemberPointerType() &&
726 Context.getTargetInfo().getCXXABI().isMicrosoft())
727 (void)isCompleteType(Loc: E->getExprLoc(), T);
728
729 ExprResult Res = CheckLValueToRValueConversionOperand(E);
730 if (Res.isInvalid())
731 return Res;
732 E = Res.get();
733
734 // Loading a __weak object implicitly retains the value, so we need a cleanup to
735 // balance that.
736 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
737 Cleanup.setExprNeedsCleanups(true);
738
739 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
740 Cleanup.setExprNeedsCleanups(true);
741
742 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
743 return ExprError();
744
745 // C++ [conv.lval]p3:
746 // If T is cv std::nullptr_t, the result is a null pointer constant.
747 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
748 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
749 FPO: CurFPFeatureOverrides());
750
751 // C11 6.3.2.1p2:
752 // ... if the lvalue has atomic type, the value has the non-atomic version
753 // of the type of the lvalue ...
754 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
755 T = Atomic->getValueType().getUnqualifiedType();
756 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
757 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
758 }
759
760 return Res;
761}
762
763ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
764 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
765 if (Res.isInvalid())
766 return ExprError();
767 Res = DefaultLvalueConversion(E: Res.get());
768 if (Res.isInvalid())
769 return ExprError();
770 return Res;
771}
772
773ExprResult Sema::CallExprUnaryConversions(Expr *E) {
774 QualType Ty = E->getType();
775 ExprResult Res = E;
776 // Only do implicit cast for a function type, but not for a pointer
777 // to function type.
778 if (Ty->isFunctionType()) {
779 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
780 CK: CK_FunctionToPointerDecay);
781 if (Res.isInvalid())
782 return ExprError();
783 }
784 Res = DefaultLvalueConversion(E: Res.get());
785 if (Res.isInvalid())
786 return ExprError();
787 return Res.get();
788}
789
790/// UsualUnaryFPConversions - Promotes floating-point types according to the
791/// current language semantics.
792ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
793 QualType Ty = E->getType();
794 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
795
796 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
797 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
798 (getLangOpts().getFPEvalMethod() !=
799 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
800 PP.getLastFPEvalPragmaLocation().isValid())) {
801 switch (EvalMethod) {
802 default:
803 llvm_unreachable("Unrecognized float evaluation method");
804 break;
805 case LangOptions::FEM_UnsetOnCommandLine:
806 llvm_unreachable("Float evaluation method should be set by now");
807 break;
808 case LangOptions::FEM_Double:
809 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
810 // Widen the expression to double.
811 return Ty->isComplexType()
812 ? ImpCastExprToType(E,
813 Type: Context.getComplexType(T: Context.DoubleTy),
814 CK: CK_FloatingComplexCast)
815 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
816 break;
817 case LangOptions::FEM_Extended:
818 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
819 // Widen the expression to long double.
820 return Ty->isComplexType()
821 ? ImpCastExprToType(
822 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
823 CK: CK_FloatingComplexCast)
824 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
825 CK: CK_FloatingCast);
826 break;
827 }
828 }
829
830 // Half FP have to be promoted to float unless it is natively supported
831 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
832 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
833
834 return E;
835}
836
837/// UsualUnaryConversions - Performs various conversions that are common to most
838/// operators (C99 6.3). The conversions of array and function types are
839/// sometimes suppressed. For example, the array->pointer conversion doesn't
840/// apply if the array is an argument to the sizeof or address (&) operators.
841/// In these instances, this routine should *not* be called.
842ExprResult Sema::UsualUnaryConversions(Expr *E) {
843 // First, convert to an r-value.
844 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
845 if (Res.isInvalid())
846 return ExprError();
847
848 // Promote floating-point types.
849 Res = UsualUnaryFPConversions(E: Res.get());
850 if (Res.isInvalid())
851 return ExprError();
852 E = Res.get();
853
854 QualType Ty = E->getType();
855 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
856
857 // Try to perform integral promotions if the object has a theoretically
858 // promotable type.
859 if (Ty->isIntegralOrUnscopedEnumerationType()) {
860 // C99 6.3.1.1p2:
861 //
862 // The following may be used in an expression wherever an int or
863 // unsigned int may be used:
864 // - an object or expression with an integer type whose integer
865 // conversion rank is less than or equal to the rank of int
866 // and unsigned int.
867 // - A bit-field of type _Bool, int, signed int, or unsigned int.
868 //
869 // If an int can represent all values of the original type, the
870 // value is converted to an int; otherwise, it is converted to an
871 // unsigned int. These are called the integer promotions. All
872 // other types are unchanged by the integer promotions.
873
874 QualType PTy = Context.isPromotableBitField(E);
875 if (!PTy.isNull()) {
876 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
877 return E;
878 }
879 if (Context.isPromotableIntegerType(T: Ty)) {
880 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
881 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
882 return E;
883 }
884 }
885 return E;
886}
887
888/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
889/// do not have a prototype. Arguments that have type float or __fp16
890/// are promoted to double. All other argument types are converted by
891/// UsualUnaryConversions().
892ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
893 QualType Ty = E->getType();
894 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
895
896 ExprResult Res = UsualUnaryConversions(E);
897 if (Res.isInvalid())
898 return ExprError();
899 E = Res.get();
900
901 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
902 // promote to double.
903 // Note that default argument promotion applies only to float (and
904 // half/fp16); it does not apply to _Float16.
905 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
906 if (BTy && (BTy->getKind() == BuiltinType::Half ||
907 BTy->getKind() == BuiltinType::Float)) {
908 if (getLangOpts().OpenCL &&
909 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
910 if (BTy->getKind() == BuiltinType::Half) {
911 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
912 }
913 } else {
914 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
915 }
916 }
917 if (BTy &&
918 getLangOpts().getExtendIntArgs() ==
919 LangOptions::ExtendArgsKind::ExtendTo64 &&
920 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
921 Context.getTypeSizeInChars(T: BTy) <
922 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
923 E = (Ty->isUnsignedIntegerType())
924 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
925 .get()
926 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
927 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
928 "Unexpected typesize for LongLongTy");
929 }
930
931 // C++ performs lvalue-to-rvalue conversion as a default argument
932 // promotion, even on class types, but note:
933 // C++11 [conv.lval]p2:
934 // When an lvalue-to-rvalue conversion occurs in an unevaluated
935 // operand or a subexpression thereof the value contained in the
936 // referenced object is not accessed. Otherwise, if the glvalue
937 // has a class type, the conversion copy-initializes a temporary
938 // of type T from the glvalue and the result of the conversion
939 // is a prvalue for the temporary.
940 // FIXME: add some way to gate this entire thing for correctness in
941 // potentially potentially evaluated contexts.
942 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
943 ExprResult Temp = PerformCopyInitialization(
944 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
945 EqualLoc: E->getExprLoc(), Init: E);
946 if (Temp.isInvalid())
947 return ExprError();
948 E = Temp.get();
949 }
950
951 // C++ [expr.call]p7, per CWG722:
952 // An argument that has (possibly cv-qualified) type std::nullptr_t is
953 // converted to void* ([conv.ptr]).
954 // (This does not apply to C23 nullptr)
955 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
956 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
957
958 return E;
959}
960
961VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
962 if (Ty->isIncompleteType()) {
963 // C++11 [expr.call]p7:
964 // After these conversions, if the argument does not have arithmetic,
965 // enumeration, pointer, pointer to member, or class type, the program
966 // is ill-formed.
967 //
968 // Since we've already performed null pointer conversion, array-to-pointer
969 // decay and function-to-pointer decay, the only such type in C++ is cv
970 // void. This also handles initializer lists as variadic arguments.
971 if (Ty->isVoidType())
972 return VarArgKind::Invalid;
973
974 if (Ty->isObjCObjectType())
975 return VarArgKind::Invalid;
976 return VarArgKind::Valid;
977 }
978
979 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
980 return VarArgKind::Invalid;
981
982 if (Context.getTargetInfo().getTriple().isWasm() &&
983 Ty.isWebAssemblyReferenceType()) {
984 return VarArgKind::Invalid;
985 }
986
987 if (Ty.isCXX98PODType(Context))
988 return VarArgKind::Valid;
989
990 // C++11 [expr.call]p7:
991 // Passing a potentially-evaluated argument of class type (Clause 9)
992 // having a non-trivial copy constructor, a non-trivial move constructor,
993 // or a non-trivial destructor, with no corresponding parameter,
994 // is conditionally-supported with implementation-defined semantics.
995 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
996 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
997 if (!Record->hasNonTrivialCopyConstructor() &&
998 !Record->hasNonTrivialMoveConstructor() &&
999 !Record->hasNonTrivialDestructor())
1000 return VarArgKind::ValidInCXX11;
1001
1002 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1003 return VarArgKind::Valid;
1004
1005 if (Ty->isObjCObjectType())
1006 return VarArgKind::Invalid;
1007
1008 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1009 return VarArgKind::Valid;
1010
1011 if (getLangOpts().MSVCCompat)
1012 return VarArgKind::MSVCUndefined;
1013
1014 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1015 return VarArgKind::Valid;
1016
1017 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1018 // permitted to reject them. We should consider doing so.
1019 return VarArgKind::Undefined;
1020}
1021
1022void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1023 // Don't allow one to pass an Objective-C interface to a vararg.
1024 const QualType &Ty = E->getType();
1025 VarArgKind VAK = isValidVarArgType(Ty);
1026
1027 // Complain about passing non-POD types through varargs.
1028 switch (VAK) {
1029 case VarArgKind::ValidInCXX11:
1030 DiagRuntimeBehavior(
1031 Loc: E->getBeginLoc(), Statement: nullptr,
1032 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1033 [[fallthrough]];
1034 case VarArgKind::Valid:
1035 if (Ty->isRecordType()) {
1036 // This is unlikely to be what the user intended. If the class has a
1037 // 'c_str' member function, the user probably meant to call that.
1038 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1039 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1040 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1041 }
1042 break;
1043
1044 case VarArgKind::Undefined:
1045 case VarArgKind::MSVCUndefined:
1046 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1047 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1048 << getLangOpts().CPlusPlus11 << Ty << CT);
1049 break;
1050
1051 case VarArgKind::Invalid:
1052 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1053 Diag(Loc: E->getBeginLoc(),
1054 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1055 << Ty << CT;
1056 else if (Ty->isObjCObjectType())
1057 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1058 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1059 << Ty << CT);
1060 else
1061 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1062 << isa<InitListExpr>(Val: E) << Ty << CT;
1063 break;
1064 }
1065}
1066
1067ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1068 FunctionDecl *FDecl) {
1069 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1070 // Strip the unbridged-cast placeholder expression off, if applicable.
1071 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1072 (CT == VariadicCallType::Method ||
1073 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1074 E = ObjC().stripARCUnbridgedCast(e: E);
1075
1076 // Otherwise, do normal placeholder checking.
1077 } else {
1078 ExprResult ExprRes = CheckPlaceholderExpr(E);
1079 if (ExprRes.isInvalid())
1080 return ExprError();
1081 E = ExprRes.get();
1082 }
1083 }
1084
1085 ExprResult ExprRes = DefaultArgumentPromotion(E);
1086 if (ExprRes.isInvalid())
1087 return ExprError();
1088
1089 // Copy blocks to the heap.
1090 if (ExprRes.get()->getType()->isBlockPointerType())
1091 maybeExtendBlockObject(E&: ExprRes);
1092
1093 E = ExprRes.get();
1094
1095 // Diagnostics regarding non-POD argument types are
1096 // emitted along with format string checking in Sema::CheckFunctionCall().
1097 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1098 // Turn this into a trap.
1099 CXXScopeSpec SS;
1100 SourceLocation TemplateKWLoc;
1101 UnqualifiedId Name;
1102 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1103 IdLoc: E->getBeginLoc());
1104 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1105 /*HasTrailingLParen=*/true,
1106 /*IsAddressOfOperand=*/false);
1107 if (TrapFn.isInvalid())
1108 return ExprError();
1109
1110 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1111 RParenLoc: E->getEndLoc());
1112 if (Call.isInvalid())
1113 return ExprError();
1114
1115 ExprResult Comma =
1116 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1117 if (Comma.isInvalid())
1118 return ExprError();
1119 return Comma.get();
1120 }
1121
1122 if (!getLangOpts().CPlusPlus &&
1123 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1124 DiagID: diag::err_call_incomplete_argument))
1125 return ExprError();
1126
1127 return E;
1128}
1129
1130/// Convert complex integers to complex floats and real integers to
1131/// real floats as required for complex arithmetic. Helper function of
1132/// UsualArithmeticConversions()
1133///
1134/// \return false if the integer expression is an integer type and is
1135/// successfully converted to the (complex) float type.
1136static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1137 ExprResult &ComplexExpr,
1138 QualType IntTy,
1139 QualType ComplexTy,
1140 bool SkipCast) {
1141 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1142 if (SkipCast) return false;
1143 if (IntTy->isIntegerType()) {
1144 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1145 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1146 } else {
1147 assert(IntTy->isComplexIntegerType());
1148 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1149 CK: CK_IntegralComplexToFloatingComplex);
1150 }
1151 return false;
1152}
1153
1154// This handles complex/complex, complex/float, or float/complex.
1155// When both operands are complex, the shorter operand is converted to the
1156// type of the longer, and that is the type of the result. This corresponds
1157// to what is done when combining two real floating-point operands.
1158// The fun begins when size promotion occur across type domains.
1159// From H&S 6.3.4: When one operand is complex and the other is a real
1160// floating-point type, the less precise type is converted, within it's
1161// real or complex domain, to the precision of the other type. For example,
1162// when combining a "long double" with a "double _Complex", the
1163// "double _Complex" is promoted to "long double _Complex".
1164static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1165 QualType ShorterType,
1166 QualType LongerType,
1167 bool PromotePrecision) {
1168 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1169 QualType Result =
1170 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1171
1172 if (PromotePrecision) {
1173 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1174 Shorter =
1175 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1176 } else {
1177 if (LongerIsComplex)
1178 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1179 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1180 }
1181 }
1182 return Result;
1183}
1184
1185/// Handle arithmetic conversion with complex types. Helper function of
1186/// UsualArithmeticConversions()
1187static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1188 ExprResult &RHS, QualType LHSType,
1189 QualType RHSType, bool IsCompAssign) {
1190 // Handle (complex) integer types.
1191 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1192 /*SkipCast=*/false))
1193 return LHSType;
1194 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1195 /*SkipCast=*/IsCompAssign))
1196 return RHSType;
1197
1198 // Compute the rank of the two types, regardless of whether they are complex.
1199 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1200 if (Order < 0)
1201 // Promote the precision of the LHS if not an assignment.
1202 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1203 /*PromotePrecision=*/!IsCompAssign);
1204 // Promote the precision of the RHS unless it is already the same as the LHS.
1205 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1206 /*PromotePrecision=*/Order > 0);
1207}
1208
1209/// Handle arithmetic conversion from integer to float. Helper function
1210/// of UsualArithmeticConversions()
1211static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1212 ExprResult &IntExpr,
1213 QualType FloatTy, QualType IntTy,
1214 bool ConvertFloat, bool ConvertInt) {
1215 if (IntTy->isIntegerType()) {
1216 if (ConvertInt)
1217 // Convert intExpr to the lhs floating point type.
1218 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1219 CK: CK_IntegralToFloating);
1220 return FloatTy;
1221 }
1222
1223 // Convert both sides to the appropriate complex float.
1224 assert(IntTy->isComplexIntegerType());
1225 QualType result = S.Context.getComplexType(T: FloatTy);
1226
1227 // _Complex int -> _Complex float
1228 if (ConvertInt)
1229 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1230 CK: CK_IntegralComplexToFloatingComplex);
1231
1232 // float -> _Complex float
1233 if (ConvertFloat)
1234 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1235 CK: CK_FloatingRealToComplex);
1236
1237 return result;
1238}
1239
1240/// Handle arithmethic conversion with floating point types. Helper
1241/// function of UsualArithmeticConversions()
1242static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1243 ExprResult &RHS, QualType LHSType,
1244 QualType RHSType, bool IsCompAssign) {
1245 bool LHSFloat = LHSType->isRealFloatingType();
1246 bool RHSFloat = RHSType->isRealFloatingType();
1247
1248 // N1169 4.1.4: If one of the operands has a floating type and the other
1249 // operand has a fixed-point type, the fixed-point operand
1250 // is converted to the floating type [...]
1251 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1252 if (LHSFloat)
1253 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1254 else if (!IsCompAssign)
1255 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1256 return LHSFloat ? LHSType : RHSType;
1257 }
1258
1259 // If we have two real floating types, convert the smaller operand
1260 // to the bigger result.
1261 if (LHSFloat && RHSFloat) {
1262 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1263 if (order > 0) {
1264 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1265 return LHSType;
1266 }
1267
1268 assert(order < 0 && "illegal float comparison");
1269 if (!IsCompAssign)
1270 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1271 return RHSType;
1272 }
1273
1274 if (LHSFloat) {
1275 // Half FP has to be promoted to float unless it is natively supported
1276 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1277 LHSType = S.Context.FloatTy;
1278
1279 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1280 /*ConvertFloat=*/!IsCompAssign,
1281 /*ConvertInt=*/ true);
1282 }
1283 assert(RHSFloat);
1284 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1285 /*ConvertFloat=*/ true,
1286 /*ConvertInt=*/!IsCompAssign);
1287}
1288
1289/// Diagnose attempts to convert between __float128, __ibm128 and
1290/// long double if there is no support for such conversion.
1291/// Helper function of UsualArithmeticConversions().
1292static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1293 QualType RHSType) {
1294 // No issue if either is not a floating point type.
1295 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1296 return false;
1297
1298 // No issue if both have the same 128-bit float semantics.
1299 auto *LHSComplex = LHSType->getAs<ComplexType>();
1300 auto *RHSComplex = RHSType->getAs<ComplexType>();
1301
1302 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1303 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1304
1305 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1306 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1307
1308 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1309 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1310 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1311 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1312 return false;
1313
1314 return true;
1315}
1316
1317typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1318
1319namespace {
1320/// These helper callbacks are placed in an anonymous namespace to
1321/// permit their use as function template parameters.
1322ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1323 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1324}
1325
1326ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1327 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1328 CK: CK_IntegralComplexCast);
1329}
1330}
1331
1332/// Handle integer arithmetic conversions. Helper function of
1333/// UsualArithmeticConversions()
1334template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1335static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1336 ExprResult &RHS, QualType LHSType,
1337 QualType RHSType, bool IsCompAssign) {
1338 // The rules for this case are in C99 6.3.1.8
1339 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1340 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1341 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1342 if (LHSSigned == RHSSigned) {
1343 // Same signedness; use the higher-ranked type
1344 if (order >= 0) {
1345 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1346 return LHSType;
1347 } else if (!IsCompAssign)
1348 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1349 return RHSType;
1350 } else if (order != (LHSSigned ? 1 : -1)) {
1351 // The unsigned type has greater than or equal rank to the
1352 // signed type, so use the unsigned type
1353 if (RHSSigned) {
1354 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1355 return LHSType;
1356 } else if (!IsCompAssign)
1357 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1358 return RHSType;
1359 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1360 // The two types are different widths; if we are here, that
1361 // means the signed type is larger than the unsigned type, so
1362 // use the signed type.
1363 if (LHSSigned) {
1364 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1365 return LHSType;
1366 } else if (!IsCompAssign)
1367 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1368 return RHSType;
1369 } else {
1370 // The signed type is higher-ranked than the unsigned type,
1371 // but isn't actually any bigger (like unsigned int and long
1372 // on most 32-bit systems). Use the unsigned type corresponding
1373 // to the signed type.
1374 QualType result =
1375 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1376 RHS = (*doRHSCast)(S, RHS.get(), result);
1377 if (!IsCompAssign)
1378 LHS = (*doLHSCast)(S, LHS.get(), result);
1379 return result;
1380 }
1381}
1382
1383/// Handle conversions with GCC complex int extension. Helper function
1384/// of UsualArithmeticConversions()
1385static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1386 ExprResult &RHS, QualType LHSType,
1387 QualType RHSType,
1388 bool IsCompAssign) {
1389 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1390 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1391
1392 if (LHSComplexInt && RHSComplexInt) {
1393 QualType LHSEltType = LHSComplexInt->getElementType();
1394 QualType RHSEltType = RHSComplexInt->getElementType();
1395 QualType ScalarType =
1396 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1397 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1398
1399 return S.Context.getComplexType(T: ScalarType);
1400 }
1401
1402 if (LHSComplexInt) {
1403 QualType LHSEltType = LHSComplexInt->getElementType();
1404 QualType ScalarType =
1405 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1406 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1407 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1408 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1409 CK: CK_IntegralRealToComplex);
1410
1411 return ComplexType;
1412 }
1413
1414 assert(RHSComplexInt);
1415
1416 QualType RHSEltType = RHSComplexInt->getElementType();
1417 QualType ScalarType =
1418 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1419 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1420 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1421
1422 if (!IsCompAssign)
1423 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1424 CK: CK_IntegralRealToComplex);
1425 return ComplexType;
1426}
1427
1428static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1429 ExprResult &RHS,
1430 QualType LHSType,
1431 QualType RHSType,
1432 bool IsCompAssign) {
1433
1434 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1435 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1436
1437 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1438 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1439
1440 bool LHSHasTrap =
1441 LhsOBT && LhsOBT->getBehaviorKind() ==
1442 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1443 bool RHSHasTrap =
1444 RhsOBT && RhsOBT->getBehaviorKind() ==
1445 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1446 bool LHSHasWrap =
1447 LhsOBT && LhsOBT->getBehaviorKind() ==
1448 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1449 bool RHSHasWrap =
1450 RhsOBT && RhsOBT->getBehaviorKind() ==
1451 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1452
1453 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1454 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1455
1456 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1457 if (LHSHasTrap || RHSHasTrap)
1458 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1459 else if (LHSHasWrap || RHSHasWrap)
1460 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1461
1462 QualType LHSConvType = LHSUnderlyingType;
1463 QualType RHSConvType = RHSUnderlyingType;
1464 if (DominantBehavior) {
1465 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1466 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1467 Wrapped: LHSUnderlyingType);
1468 else
1469 LHSConvType = LHSType;
1470
1471 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1472 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1473 Wrapped: RHSUnderlyingType);
1474 else
1475 RHSConvType = RHSType;
1476 }
1477
1478 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1479 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1480}
1481
1482/// Return the rank of a given fixed point or integer type. The value itself
1483/// doesn't matter, but the values must be increasing with proper increasing
1484/// rank as described in N1169 4.1.1.
1485static unsigned GetFixedPointRank(QualType Ty) {
1486 const auto *BTy = Ty->getAs<BuiltinType>();
1487 assert(BTy && "Expected a builtin type.");
1488
1489 switch (BTy->getKind()) {
1490 case BuiltinType::ShortFract:
1491 case BuiltinType::UShortFract:
1492 case BuiltinType::SatShortFract:
1493 case BuiltinType::SatUShortFract:
1494 return 1;
1495 case BuiltinType::Fract:
1496 case BuiltinType::UFract:
1497 case BuiltinType::SatFract:
1498 case BuiltinType::SatUFract:
1499 return 2;
1500 case BuiltinType::LongFract:
1501 case BuiltinType::ULongFract:
1502 case BuiltinType::SatLongFract:
1503 case BuiltinType::SatULongFract:
1504 return 3;
1505 case BuiltinType::ShortAccum:
1506 case BuiltinType::UShortAccum:
1507 case BuiltinType::SatShortAccum:
1508 case BuiltinType::SatUShortAccum:
1509 return 4;
1510 case BuiltinType::Accum:
1511 case BuiltinType::UAccum:
1512 case BuiltinType::SatAccum:
1513 case BuiltinType::SatUAccum:
1514 return 5;
1515 case BuiltinType::LongAccum:
1516 case BuiltinType::ULongAccum:
1517 case BuiltinType::SatLongAccum:
1518 case BuiltinType::SatULongAccum:
1519 return 6;
1520 default:
1521 if (BTy->isInteger())
1522 return 0;
1523 llvm_unreachable("Unexpected fixed point or integer type");
1524 }
1525}
1526
1527/// handleFixedPointConversion - Fixed point operations between fixed
1528/// point types and integers or other fixed point types do not fall under
1529/// usual arithmetic conversion since these conversions could result in loss
1530/// of precsision (N1169 4.1.4). These operations should be calculated with
1531/// the full precision of their result type (N1169 4.1.6.2.1).
1532static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1533 QualType RHSTy) {
1534 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1535 "Expected at least one of the operands to be a fixed point type");
1536 assert((LHSTy->isFixedPointOrIntegerType() ||
1537 RHSTy->isFixedPointOrIntegerType()) &&
1538 "Special fixed point arithmetic operation conversions are only "
1539 "applied to ints or other fixed point types");
1540
1541 // If one operand has signed fixed-point type and the other operand has
1542 // unsigned fixed-point type, then the unsigned fixed-point operand is
1543 // converted to its corresponding signed fixed-point type and the resulting
1544 // type is the type of the converted operand.
1545 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1546 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1547 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1548 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1549
1550 // The result type is the type with the highest rank, whereby a fixed-point
1551 // conversion rank is always greater than an integer conversion rank; if the
1552 // type of either of the operands is a saturating fixedpoint type, the result
1553 // type shall be the saturating fixed-point type corresponding to the type
1554 // with the highest rank; the resulting value is converted (taking into
1555 // account rounding and overflow) to the precision of the resulting type.
1556 // Same ranks between signed and unsigned types are resolved earlier, so both
1557 // types are either signed or both unsigned at this point.
1558 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1559 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1560
1561 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1562
1563 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1564 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1565
1566 return ResultTy;
1567}
1568
1569/// Check that the usual arithmetic conversions can be performed on this pair of
1570/// expressions that might be of enumeration type.
1571void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1572 SourceLocation Loc,
1573 ArithConvKind ACK) {
1574 // C++2a [expr.arith.conv]p1:
1575 // If one operand is of enumeration type and the other operand is of a
1576 // different enumeration type or a floating-point type, this behavior is
1577 // deprecated ([depr.arith.conv.enum]).
1578 //
1579 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1580 // Eventually we will presumably reject these cases (in C++23 onwards?).
1581 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1582 R = RHS->getEnumCoercedType(Ctx: Context);
1583 bool LEnum = L->isUnscopedEnumerationType(),
1584 REnum = R->isUnscopedEnumerationType();
1585 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1586 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1587 (REnum && L->isFloatingType())) {
1588 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1589 : getLangOpts().CPlusPlus20
1590 ? diag::warn_arith_conv_enum_float_cxx20
1591 : diag::warn_arith_conv_enum_float)
1592 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1593 << L << R;
1594 } else if (!IsCompAssign && LEnum && REnum &&
1595 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1596 unsigned DiagID;
1597 // In C++ 26, usual arithmetic conversions between 2 different enum types
1598 // are ill-formed.
1599 if (getLangOpts().CPlusPlus26)
1600 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1601 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1602 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1603 // If either enumeration type is unnamed, it's less likely that the
1604 // user cares about this, but this situation is still deprecated in
1605 // C++2a. Use a different warning group.
1606 DiagID = getLangOpts().CPlusPlus20
1607 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1608 : diag::warn_arith_conv_mixed_anon_enum_types;
1609 } else if (ACK == ArithConvKind::Conditional) {
1610 // Conditional expressions are separated out because they have
1611 // historically had a different warning flag.
1612 DiagID = getLangOpts().CPlusPlus20
1613 ? diag::warn_conditional_mixed_enum_types_cxx20
1614 : diag::warn_conditional_mixed_enum_types;
1615 } else if (ACK == ArithConvKind::Comparison) {
1616 // Comparison expressions are separated out because they have
1617 // historically had a different warning flag.
1618 DiagID = getLangOpts().CPlusPlus20
1619 ? diag::warn_comparison_mixed_enum_types_cxx20
1620 : diag::warn_comparison_mixed_enum_types;
1621 } else {
1622 DiagID = getLangOpts().CPlusPlus20
1623 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1624 : diag::warn_arith_conv_mixed_enum_types;
1625 }
1626 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1627 << (int)ACK << L << R;
1628 }
1629}
1630
1631static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1632 Expr *RHS, SourceLocation Loc,
1633 ArithConvKind ACK) {
1634 QualType LHSType = LHS->getType().getUnqualifiedType();
1635 QualType RHSType = RHS->getType().getUnqualifiedType();
1636
1637 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1638 !RHSType->isUnicodeCharacterType())
1639 return;
1640
1641 if (ACK == ArithConvKind::Comparison) {
1642 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1643 return;
1644
1645 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1646 if (T->isChar8Type())
1647 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1648 if (T->isChar16Type())
1649 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1650 assert(T->isChar32Type());
1651 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1652 };
1653
1654 Expr::EvalResult LHSRes, RHSRes;
1655 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1656 AllowSideEffects: Expr::SE_AllowSideEffects,
1657 InConstantContext: SemaRef.isConstantEvaluatedContext());
1658 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1659 AllowSideEffects: Expr::SE_AllowSideEffects,
1660 InConstantContext: SemaRef.isConstantEvaluatedContext());
1661
1662 // Don't warn if the one known value is a representable
1663 // in the type of both expressions.
1664 if (LHSSuccess != RHSuccess) {
1665 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1666 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1667 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1668 return;
1669 }
1670
1671 if (!LHSSuccess || !RHSuccess) {
1672 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1673 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1674 << RHSType;
1675 return;
1676 }
1677
1678 llvm::APSInt LHSValue(32);
1679 LHSValue = LHSRes.Val.getInt();
1680 llvm::APSInt RHSValue(32);
1681 RHSValue = RHSRes.Val.getInt();
1682
1683 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1684 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1685 if (LHSSafe && RHSSafe)
1686 return;
1687
1688 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1689 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1690 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1691 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1692 return;
1693 }
1694
1695 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1696 return;
1697
1698 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1699 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1700 << RHSType;
1701}
1702
1703/// UsualArithmeticConversions - Performs various conversions that are common to
1704/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1705/// routine returns the first non-arithmetic type found. The client is
1706/// responsible for emitting appropriate error diagnostics.
1707QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1708 SourceLocation Loc,
1709 ArithConvKind ACK) {
1710
1711 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1712
1713 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1714
1715 if (ACK != ArithConvKind::CompAssign) {
1716 LHS = UsualUnaryConversions(E: LHS.get());
1717 if (LHS.isInvalid())
1718 return QualType();
1719 }
1720
1721 RHS = UsualUnaryConversions(E: RHS.get());
1722 if (RHS.isInvalid())
1723 return QualType();
1724
1725 // For conversion purposes, we ignore any qualifiers.
1726 // For example, "const float" and "float" are equivalent.
1727 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1728 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1729
1730 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1731 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1732 LHSType = AtomicLHS->getValueType();
1733
1734 // If both types are identical, no conversion is needed.
1735 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1736 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1737
1738 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1739 // The caller can deal with this (e.g. pointer + int).
1740 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1741 return QualType();
1742
1743 // Apply unary and bitfield promotions to the LHS's type.
1744 QualType LHSUnpromotedType = LHSType;
1745 if (Context.isPromotableIntegerType(T: LHSType))
1746 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1747 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1748 if (!LHSBitfieldPromoteTy.isNull())
1749 LHSType = LHSBitfieldPromoteTy;
1750 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1751 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1752
1753 // If both types are identical, no conversion is needed.
1754 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1755 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1756
1757 // At this point, we have two different arithmetic types.
1758
1759 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1760 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1761 return QualType();
1762
1763 // Diagnose attempts to convert between __ibm128, __float128 and long double
1764 // where such conversions currently can't be handled.
1765 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1766 return QualType();
1767
1768 // Handle complex types first (C99 6.3.1.8p1).
1769 if (LHSType->isComplexType() || RHSType->isComplexType())
1770 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1771 IsCompAssign: ACK == ArithConvKind::CompAssign);
1772
1773 // Now handle "real" floating types (i.e. float, double, long double).
1774 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1775 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1776 IsCompAssign: ACK == ArithConvKind::CompAssign);
1777
1778 // Handle GCC complex int extension.
1779 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1780 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1781 IsCompAssign: ACK == ArithConvKind::CompAssign);
1782
1783 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1784 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1785
1786 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1787 return handleOverflowBehaviorTypeConversion(
1788 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1789
1790 // Finally, we have two differing integer types.
1791 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1792 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1793}
1794
1795//===----------------------------------------------------------------------===//
1796// Semantic Analysis for various Expression Types
1797//===----------------------------------------------------------------------===//
1798
1799
1800ExprResult Sema::ActOnGenericSelectionExpr(
1801 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1802 bool PredicateIsExpr, void *ControllingExprOrType,
1803 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1804 unsigned NumAssocs = ArgTypes.size();
1805 assert(NumAssocs == ArgExprs.size());
1806
1807 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1808 for (unsigned i = 0; i < NumAssocs; ++i) {
1809 if (ArgTypes[i])
1810 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1811 else
1812 Types[i] = nullptr;
1813 }
1814
1815 // If we have a controlling type, we need to convert it from a parsed type
1816 // into a semantic type and then pass that along.
1817 if (!PredicateIsExpr) {
1818 TypeSourceInfo *ControllingType;
1819 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1820 TInfo: &ControllingType);
1821 assert(ControllingType && "couldn't get the type out of the parser");
1822 ControllingExprOrType = ControllingType;
1823 }
1824
1825 ExprResult ER = CreateGenericSelectionExpr(
1826 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1827 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1828 delete [] Types;
1829 return ER;
1830}
1831
1832// Helper function to determine type compatibility for C _Generic expressions.
1833// Multiple compatible types within the same _Generic expression is ambiguous
1834// and not valid.
1835static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1836 QualType U) {
1837 // Try to handle special types like OverflowBehaviorTypes
1838 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1839 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1840
1841 if (TOBT || UOBT) {
1842 if (TOBT && UOBT) {
1843 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1844 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1845 T2: UOBT->getUnderlyingType());
1846 return false;
1847 }
1848 return false;
1849 }
1850
1851 // We're dealing with types that don't require special handling.
1852 return Ctx.typesAreCompatible(T1: T, T2: U);
1853}
1854
1855ExprResult Sema::CreateGenericSelectionExpr(
1856 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1857 bool PredicateIsExpr, void *ControllingExprOrType,
1858 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1859 unsigned NumAssocs = Types.size();
1860 assert(NumAssocs == Exprs.size());
1861 assert(ControllingExprOrType &&
1862 "Must have either a controlling expression or a controlling type");
1863
1864 Expr *ControllingExpr = nullptr;
1865 TypeSourceInfo *ControllingType = nullptr;
1866 if (PredicateIsExpr) {
1867 // Decay and strip qualifiers for the controlling expression type, and
1868 // handle placeholder type replacement. See committee discussion from WG14
1869 // DR423.
1870 EnterExpressionEvaluationContext Unevaluated(
1871 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1872 ExprResult R = DefaultFunctionArrayLvalueConversion(
1873 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1874 if (R.isInvalid())
1875 return ExprError();
1876 ControllingExpr = R.get();
1877 } else {
1878 // The extension form uses the type directly rather than converting it.
1879 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1880 if (!ControllingType)
1881 return ExprError();
1882 }
1883
1884 bool TypeErrorFound = false,
1885 IsResultDependent = ControllingExpr
1886 ? ControllingExpr->isTypeDependent()
1887 : ControllingType->getType()->isDependentType(),
1888 ContainsUnexpandedParameterPack =
1889 ControllingExpr
1890 ? ControllingExpr->containsUnexpandedParameterPack()
1891 : ControllingType->getType()->containsUnexpandedParameterPack();
1892
1893 // The controlling expression is an unevaluated operand, so side effects are
1894 // likely unintended.
1895 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1896 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1897 Diag(Loc: ControllingExpr->getExprLoc(),
1898 DiagID: diag::warn_side_effects_unevaluated_context);
1899
1900 for (unsigned i = 0; i < NumAssocs; ++i) {
1901 if (Exprs[i]->containsUnexpandedParameterPack())
1902 ContainsUnexpandedParameterPack = true;
1903
1904 if (Types[i]) {
1905 if (Types[i]->getType()->containsUnexpandedParameterPack())
1906 ContainsUnexpandedParameterPack = true;
1907
1908 if (Types[i]->getType()->isDependentType()) {
1909 IsResultDependent = true;
1910 } else {
1911 // We relax the restriction on use of incomplete types and non-object
1912 // types with the type-based extension of _Generic. Allowing incomplete
1913 // objects means those can be used as "tags" for a type-safe way to map
1914 // to a value. Similarly, matching on function types rather than
1915 // function pointer types can be useful. However, the restriction on VM
1916 // types makes sense to retain as there are open questions about how
1917 // the selection can be made at compile time.
1918 //
1919 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1920 // complete object type other than a variably modified type."
1921 // C2y removed the requirement that an expression form must
1922 // use a complete type, though it's still as-if the type has undergone
1923 // lvalue conversion. We support this as an extension in C23 and
1924 // earlier because GCC does so.
1925 unsigned D = 0;
1926 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1927 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1928 : diag::compat_pre_c2y_assoc_type_incomplete;
1929 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1930 D = diag::err_assoc_type_nonobject;
1931 else if (Types[i]->getType()->isVariablyModifiedType())
1932 D = diag::err_assoc_type_variably_modified;
1933 else if (ControllingExpr) {
1934 // Because the controlling expression undergoes lvalue conversion,
1935 // array conversion, and function conversion, an association which is
1936 // of array type, function type, or is qualified can never be
1937 // reached. We will warn about this so users are less surprised by
1938 // the unreachable association. However, we don't have to handle
1939 // function types; that's not an object type, so it's handled above.
1940 //
1941 // The logic is somewhat different for C++ because C++ has different
1942 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1943 // If T is a non-class type, the type of the prvalue is the cv-
1944 // unqualified version of T. Otherwise, the type of the prvalue is T.
1945 // The result of these rules is that all qualified types in an
1946 // association in C are unreachable, and in C++, only qualified non-
1947 // class types are unreachable.
1948 //
1949 // NB: this does not apply when the first operand is a type rather
1950 // than an expression, because the type form does not undergo
1951 // conversion.
1952 unsigned Reason = 0;
1953 QualType QT = Types[i]->getType();
1954 if (QT->isArrayType())
1955 Reason = 1;
1956 else if (QT.hasQualifiers() &&
1957 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1958 Reason = 2;
1959
1960 if (Reason)
1961 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1962 DiagID: diag::warn_unreachable_association)
1963 << QT << (Reason - 1);
1964 }
1965
1966 if (D != 0) {
1967 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1968 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1969 if (getDiagnostics().getDiagnosticLevel(
1970 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1971 DiagnosticsEngine::Error)
1972 TypeErrorFound = true;
1973 }
1974
1975 // C11 6.5.1.1p2 "No two generic associations in the same generic
1976 // selection shall specify compatible types."
1977 for (unsigned j = i+1; j < NumAssocs; ++j)
1978 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1979 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1980 U: Types[j]->getType())) {
1981 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1982 DiagID: diag::err_assoc_compatible_types)
1983 << Types[j]->getTypeLoc().getSourceRange()
1984 << Types[j]->getType()
1985 << Types[i]->getType();
1986 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1987 DiagID: diag::note_compat_assoc)
1988 << Types[i]->getTypeLoc().getSourceRange()
1989 << Types[i]->getType();
1990 TypeErrorFound = true;
1991 }
1992 }
1993 }
1994 }
1995 if (TypeErrorFound)
1996 return ExprError();
1997
1998 // If we determined that the generic selection is result-dependent, don't
1999 // try to compute the result expression.
2000 if (IsResultDependent) {
2001 if (ControllingExpr)
2002 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
2003 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2004 ContainsUnexpandedParameterPack);
2005 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
2006 AssocExprs: Exprs, DefaultLoc, RParenLoc,
2007 ContainsUnexpandedParameterPack);
2008 }
2009
2010 SmallVector<unsigned, 1> CompatIndices;
2011 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2012 // Look at the canonical type of the controlling expression in case it was a
2013 // deduced type like __auto_type. However, when issuing diagnostics, use the
2014 // type the user wrote in source rather than the canonical one.
2015 for (unsigned i = 0; i < NumAssocs; ++i) {
2016 if (!Types[i])
2017 DefaultIndex = i;
2018 else {
2019 bool Compatible;
2020 QualType ControllingQT =
2021 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2022 : ControllingType->getType().getCanonicalType();
2023 QualType AssocQT = Types[i]->getType();
2024
2025 Compatible =
2026 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2027
2028 if (Compatible)
2029 CompatIndices.push_back(Elt: i);
2030 }
2031 }
2032
2033 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2034 TypeSourceInfo *ControllingType) {
2035 // We strip parens here because the controlling expression is typically
2036 // parenthesized in macro definitions.
2037 if (ControllingExpr)
2038 ControllingExpr = ControllingExpr->IgnoreParens();
2039
2040 SourceRange SR = ControllingExpr
2041 ? ControllingExpr->getSourceRange()
2042 : ControllingType->getTypeLoc().getSourceRange();
2043 QualType QT = ControllingExpr ? ControllingExpr->getType()
2044 : ControllingType->getType();
2045
2046 return std::make_pair(x&: SR, y&: QT);
2047 };
2048
2049 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2050 // type compatible with at most one of the types named in its generic
2051 // association list."
2052 if (CompatIndices.size() > 1) {
2053 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2054 SourceRange SR = P.first;
2055 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2056 << SR << P.second << (unsigned)CompatIndices.size();
2057 for (unsigned I : CompatIndices) {
2058 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2059 DiagID: diag::note_compat_assoc)
2060 << Types[I]->getTypeLoc().getSourceRange()
2061 << Types[I]->getType();
2062 }
2063 return ExprError();
2064 }
2065
2066 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2067 // its controlling expression shall have type compatible with exactly one of
2068 // the types named in its generic association list."
2069 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2070 CompatIndices.size() == 0) {
2071 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2072 SourceRange SR = P.first;
2073 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2074 return ExprError();
2075 }
2076
2077 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2078 // type name that is compatible with the type of the controlling expression,
2079 // then the result expression of the generic selection is the expression
2080 // in that generic association. Otherwise, the result expression of the
2081 // generic selection is the expression in the default generic association."
2082 unsigned ResultIndex =
2083 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2084
2085 if (ControllingExpr) {
2086 return GenericSelectionExpr::Create(
2087 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2088 ContainsUnexpandedParameterPack, ResultIndex);
2089 }
2090 return GenericSelectionExpr::Create(
2091 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2092 ContainsUnexpandedParameterPack, ResultIndex);
2093}
2094
2095static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2096 switch (Kind) {
2097 default:
2098 llvm_unreachable("unexpected TokenKind");
2099 case tok::kw___func__:
2100 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2101 case tok::kw___FUNCTION__:
2102 return PredefinedIdentKind::Function;
2103 case tok::kw___FUNCDNAME__:
2104 return PredefinedIdentKind::FuncDName; // [MS]
2105 case tok::kw___FUNCSIG__:
2106 return PredefinedIdentKind::FuncSig; // [MS]
2107 case tok::kw_L__FUNCTION__:
2108 return PredefinedIdentKind::LFunction; // [MS]
2109 case tok::kw_L__FUNCSIG__:
2110 return PredefinedIdentKind::LFuncSig; // [MS]
2111 case tok::kw___PRETTY_FUNCTION__:
2112 return PredefinedIdentKind::PrettyFunction; // [GNU]
2113 }
2114}
2115
2116/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2117/// to determine the value of a PredefinedExpr. This can be either a
2118/// block, lambda, captured statement, function, otherwise a nullptr.
2119static Decl *getPredefinedExprDecl(DeclContext *DC) {
2120 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
2121 DC = DC->getParent();
2122 return cast_or_null<Decl>(Val: DC);
2123}
2124
2125/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2126/// location of the token and the offset of the ud-suffix within it.
2127static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2128 unsigned Offset) {
2129 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2130 LangOpts: S.getLangOpts());
2131}
2132
2133/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2134/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2135static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2136 IdentifierInfo *UDSuffix,
2137 SourceLocation UDSuffixLoc,
2138 ArrayRef<Expr*> Args,
2139 SourceLocation LitEndLoc) {
2140 assert(Args.size() <= 2 && "too many arguments for literal operator");
2141
2142 QualType ArgTy[2];
2143 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2144 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2145 if (ArgTy[ArgIdx]->isArrayType())
2146 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2147 }
2148
2149 DeclarationName OpName =
2150 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2151 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2152 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2153
2154 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2155 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2156 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2157 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2158 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2159 return ExprError();
2160
2161 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2162}
2163
2164ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2165 // StringToks needs backing storage as it doesn't hold array elements itself
2166 std::vector<Token> ExpandedToks;
2167 if (getLangOpts().MicrosoftExt)
2168 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2169
2170 StringLiteralParser Literal(StringToks, PP,
2171 StringLiteralEvalMethod::Unevaluated);
2172 if (Literal.hadError)
2173 return ExprError();
2174
2175 SmallVector<SourceLocation, 4> StringTokLocs;
2176 for (const Token &Tok : StringToks)
2177 StringTokLocs.push_back(Elt: Tok.getLocation());
2178
2179 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2180 Kind: StringLiteralKind::Unevaluated,
2181 Pascal: false, Ty: {}, Locs: StringTokLocs);
2182
2183 if (!Literal.getUDSuffix().empty()) {
2184 SourceLocation UDSuffixLoc =
2185 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2186 Offset: Literal.getUDSuffixOffset());
2187 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2188 }
2189
2190 return Lit;
2191}
2192
2193std::vector<Token>
2194Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2195 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2196 // local macros that expand to string literals that may be concatenated.
2197 // These macros are expanded here (in Sema), because StringLiteralParser
2198 // (in Lex) doesn't know the enclosing function (because it hasn't been
2199 // parsed yet).
2200 assert(getLangOpts().MicrosoftExt);
2201
2202 // Note: Although function local macros are defined only inside functions,
2203 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2204 // expansion of macros into empty string literals without additional checks.
2205 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2206 if (!CurrentDecl)
2207 CurrentDecl = Context.getTranslationUnitDecl();
2208
2209 std::vector<Token> ExpandedToks;
2210 ExpandedToks.reserve(n: Toks.size());
2211 for (const Token &Tok : Toks) {
2212 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2213 assert(tok::isStringLiteral(Tok.getKind()));
2214 ExpandedToks.emplace_back(args: Tok);
2215 continue;
2216 }
2217 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2218 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2219 // Stringify predefined expression
2220 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2221 << Tok.getKind();
2222 SmallString<64> Str;
2223 llvm::raw_svector_ostream OS(Str);
2224 Token &Exp = ExpandedToks.emplace_back();
2225 Exp.startToken();
2226 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2227 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2228 OS << 'L';
2229 Exp.setKind(tok::wide_string_literal);
2230 } else {
2231 Exp.setKind(tok::string_literal);
2232 }
2233 OS << '"'
2234 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2235 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2236 << '"';
2237 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2238 }
2239 return ExpandedToks;
2240}
2241
2242ExprResult
2243Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2244 assert(!StringToks.empty() && "Must have at least one string!");
2245
2246 // StringToks needs backing storage as it doesn't hold array elements itself
2247 std::vector<Token> ExpandedToks;
2248 if (getLangOpts().MicrosoftExt)
2249 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2250
2251 StringLiteralParser Literal(
2252 StringToks, PP, StringLiteralEvalMethod::Evaluated, CA_ToLiteralEncoding);
2253 if (Literal.hadError)
2254 return ExprError();
2255
2256 SmallVector<SourceLocation, 4> StringTokLocs;
2257 for (const Token &Tok : StringToks)
2258 StringTokLocs.push_back(Elt: Tok.getLocation());
2259
2260 QualType CharTy = Context.CharTy;
2261 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2262 if (Literal.isWide()) {
2263 CharTy = Context.getWideCharType();
2264 Kind = StringLiteralKind::Wide;
2265 } else if (Literal.isUTF8()) {
2266 if (getLangOpts().Char8)
2267 CharTy = Context.Char8Ty;
2268 else if (getLangOpts().C23)
2269 CharTy = Context.UnsignedCharTy;
2270 Kind = StringLiteralKind::UTF8;
2271 } else if (Literal.isUTF16()) {
2272 CharTy = Context.Char16Ty;
2273 Kind = StringLiteralKind::UTF16;
2274 } else if (Literal.isUTF32()) {
2275 CharTy = Context.Char32Ty;
2276 Kind = StringLiteralKind::UTF32;
2277 } else if (Literal.isPascal()) {
2278 CharTy = Context.UnsignedCharTy;
2279 }
2280
2281 // Warn on u8 string literals before C++20 and C23, whose type
2282 // was an array of char before but becomes an array of char8_t.
2283 // In C++20, it cannot be used where a pointer to char is expected.
2284 // In C23, it might have an unexpected value if char was signed.
2285 if (Kind == StringLiteralKind::UTF8 &&
2286 (getLangOpts().CPlusPlus
2287 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2288 : !getLangOpts().C23)) {
2289 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2290 ? diag::warn_cxx20_compat_utf8_string
2291 : diag::warn_c23_compat_utf8_string);
2292
2293 // Create removals for all 'u8' prefixes in the string literal(s). This
2294 // ensures C++20/C23 compatibility (but may change the program behavior when
2295 // built by non-Clang compilers for which the execution character set is
2296 // not always UTF-8).
2297 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2298 SourceLocation RemovalDiagLoc;
2299 for (const Token &Tok : StringToks) {
2300 if (Tok.getKind() == tok::utf8_string_literal) {
2301 if (RemovalDiagLoc.isInvalid())
2302 RemovalDiagLoc = Tok.getLocation();
2303 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2304 B: Tok.getLocation(),
2305 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2306 SM: getSourceManager(), LangOpts: getLangOpts())));
2307 }
2308 }
2309 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2310 }
2311
2312 QualType StrTy =
2313 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2314
2315 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2316 StringLiteral *Lit = StringLiteral::Create(
2317 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2318 if (Literal.getUDSuffix().empty())
2319 return Lit;
2320
2321 // We're building a user-defined literal.
2322 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2323 SourceLocation UDSuffixLoc =
2324 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2325 Offset: Literal.getUDSuffixOffset());
2326
2327 // Make sure we're allowed user-defined literals here.
2328 if (!UDLScope)
2329 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2330
2331 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2332 // operator "" X (str, len)
2333 QualType SizeType = Context.getSizeType();
2334
2335 DeclarationName OpName =
2336 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2337 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2338 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2339
2340 QualType ArgTy[] = {
2341 Context.getArrayDecayedType(T: StrTy), SizeType
2342 };
2343
2344 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2345 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2346 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2347 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2348 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2349
2350 case LOLR_Cooked: {
2351 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2352 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2353 l: StringTokLocs[0]);
2354 Expr *Args[] = { Lit, LenArg };
2355
2356 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2357 }
2358
2359 case LOLR_Template: {
2360 TemplateArgumentListInfo ExplicitArgs;
2361 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2362 TemplateArgumentLocInfo ArgInfo(Lit);
2363 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2364 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2365 ExplicitTemplateArgs: &ExplicitArgs);
2366 }
2367
2368 case LOLR_StringTemplatePack: {
2369 TemplateArgumentListInfo ExplicitArgs;
2370
2371 unsigned CharBits = Context.getIntWidth(T: CharTy);
2372 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2373 llvm::APSInt Value(CharBits, CharIsUnsigned);
2374
2375 TemplateArgument TypeArg(CharTy);
2376 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2377 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2378
2379 SourceLocation Loc = StringTokLocs.back();
2380 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2381 Value = Lit->getCodeUnit(i: I);
2382 TemplateArgument Arg(Context, Value, CharTy);
2383 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2384 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2385 }
2386 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2387 }
2388 case LOLR_Raw:
2389 case LOLR_ErrorNoDiagnostic:
2390 llvm_unreachable("unexpected literal operator lookup result");
2391 case LOLR_Error:
2392 return ExprError();
2393 }
2394 llvm_unreachable("unexpected literal operator lookup result");
2395}
2396
2397DeclRefExpr *
2398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2399 SourceLocation Loc,
2400 const CXXScopeSpec *SS) {
2401 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2402 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2403}
2404
2405DeclRefExpr *
2406Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2407 const DeclarationNameInfo &NameInfo,
2408 const CXXScopeSpec *SS, NamedDecl *FoundD,
2409 SourceLocation TemplateKWLoc,
2410 const TemplateArgumentListInfo *TemplateArgs) {
2411 NestedNameSpecifierLoc NNS =
2412 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2413 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2414 TemplateArgs);
2415}
2416
2417// CUDA/HIP: Check whether a captured reference variable is referencing a
2418// host variable in a device or host device lambda.
2419static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2420 VarDecl *VD) {
2421 if (!S.getLangOpts().CUDA || !VD->hasInit())
2422 return false;
2423 assert(VD->getType()->isReferenceType());
2424
2425 // Check whether the reference variable is referencing a host variable.
2426 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2427 if (!DRE)
2428 return false;
2429 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2430 if (!Referee || !Referee->hasGlobalStorage() ||
2431 Referee->hasAttr<CUDADeviceAttr>())
2432 return false;
2433
2434 // Check whether the current function is a device or host device lambda.
2435 // Check whether the reference variable is a capture by getDeclContext()
2436 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2437 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2438 if (MD && MD->getParent()->isLambda() &&
2439 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2440 VD->getDeclContext() != MD)
2441 return true;
2442
2443 return false;
2444}
2445
2446NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2447 // A declaration named in an unevaluated operand never constitutes an odr-use.
2448 if (isUnevaluatedContext())
2449 return NOUR_Unevaluated;
2450
2451 // C++2a [basic.def.odr]p4:
2452 // A variable x whose name appears as a potentially-evaluated expression e
2453 // is odr-used by e unless [...] x is a reference that is usable in
2454 // constant expressions.
2455 // CUDA/HIP:
2456 // If a reference variable referencing a host variable is captured in a
2457 // device or host device lambda, the value of the referee must be copied
2458 // to the capture and the reference variable must be treated as odr-use
2459 // since the value of the referee is not known at compile time and must
2460 // be loaded from the captured.
2461 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2462 if (VD->getType()->isReferenceType() &&
2463 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2464 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2465 VD->isUsableInConstantExpressions(C: Context))
2466 return NOUR_Constant;
2467 }
2468
2469 // All remaining non-variable cases constitute an odr-use. For variables, we
2470 // need to wait and see how the expression is used.
2471 return NOUR_None;
2472}
2473
2474DeclRefExpr *
2475Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2476 const DeclarationNameInfo &NameInfo,
2477 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2478 SourceLocation TemplateKWLoc,
2479 const TemplateArgumentListInfo *TemplateArgs) {
2480 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2481 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2482
2483 DeclRefExpr *E = DeclRefExpr::Create(
2484 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2485 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2486 MarkDeclRefReferenced(E);
2487
2488 // C++ [except.spec]p17:
2489 // An exception-specification is considered to be needed when:
2490 // - in an expression, the function is the unique lookup result or
2491 // the selected member of a set of overloaded functions.
2492 //
2493 // We delay doing this until after we've built the function reference and
2494 // marked it as used so that:
2495 // a) if the function is defaulted, we get errors from defining it before /
2496 // instead of errors from computing its exception specification, and
2497 // b) if the function is a defaulted comparison, we can use the body we
2498 // build when defining it as input to the exception specification
2499 // computation rather than computing a new body.
2500 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2501 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2502 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2503 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2504 }
2505 }
2506
2507 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2508 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2509 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2510 getCurFunction()->recordUseOfWeak(E);
2511
2512 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2513 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2514 FD = IFD->getAnonField();
2515 if (FD) {
2516 UnusedPrivateFields.remove(X: FD);
2517 // Just in case we're building an illegal pointer-to-member.
2518 if (FD->isBitField())
2519 E->setObjectKind(OK_BitField);
2520 }
2521
2522 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2523 // designates a bit-field.
2524 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2525 if (const auto *BE = BD->getBinding())
2526 E->setObjectKind(BE->getObjectKind());
2527
2528 return E;
2529}
2530
2531void
2532Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2533 TemplateArgumentListInfo &Buffer,
2534 DeclarationNameInfo &NameInfo,
2535 const TemplateArgumentListInfo *&TemplateArgs) {
2536 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2537 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2538 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2539
2540 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2541 Id.TemplateId->NumArgs);
2542 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2543
2544 TemplateName TName = Id.TemplateId->Template.get();
2545 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2546 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2547 TemplateArgs = &Buffer;
2548 } else {
2549 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2550 TemplateArgs = nullptr;
2551 }
2552}
2553
2554bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2555 // During a default argument instantiation the CurContext points
2556 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2557 // function parameter list, hence add an explicit check.
2558 bool isDefaultArgument =
2559 !CodeSynthesisContexts.empty() &&
2560 CodeSynthesisContexts.back().Kind ==
2561 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2562 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2563 bool isInstance = CurMethod && CurMethod->isInstance() &&
2564 R.getNamingClass() == CurMethod->getParent() &&
2565 !isDefaultArgument;
2566
2567 // There are two ways we can find a class-scope declaration during template
2568 // instantiation that we did not find in the template definition: if it is a
2569 // member of a dependent base class, or if it is declared after the point of
2570 // use in the same class. Distinguish these by comparing the class in which
2571 // the member was found to the naming class of the lookup.
2572 unsigned DiagID = diag::err_found_in_dependent_base;
2573 unsigned NoteID = diag::note_member_declared_at;
2574 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2575 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2576 : diag::err_found_later_in_class;
2577 } else if (getLangOpts().MSVCCompat) {
2578 DiagID = diag::ext_found_in_dependent_base;
2579 NoteID = diag::note_dependent_member_use;
2580 }
2581
2582 if (isInstance) {
2583 // Give a code modification hint to insert 'this->'.
2584 Diag(Loc: R.getNameLoc(), DiagID)
2585 << R.getLookupName()
2586 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2587 CheckCXXThisCapture(Loc: R.getNameLoc());
2588 } else {
2589 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2590 // they're not shadowed).
2591 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2592 }
2593
2594 for (const NamedDecl *D : R)
2595 Diag(Loc: D->getLocation(), DiagID: NoteID);
2596
2597 // Return true if we are inside a default argument instantiation
2598 // and the found name refers to an instance member function, otherwise
2599 // the caller will try to create an implicit member call and this is wrong
2600 // for default arguments.
2601 //
2602 // FIXME: Is this special case necessary? We could allow the caller to
2603 // diagnose this.
2604 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2605 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2606 return true;
2607 }
2608
2609 // Tell the callee to try to recover.
2610 return false;
2611}
2612
2613bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2614 CorrectionCandidateCallback &CCC,
2615 TemplateArgumentListInfo *ExplicitTemplateArgs,
2616 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2617 DeclarationName Name = R.getLookupName();
2618 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2619
2620 unsigned diagnostic = diag::err_undeclared_var_use;
2621 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2622 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2623 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2624 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2625 diagnostic = diag::err_undeclared_use;
2626 diagnostic_suggest = diag::err_undeclared_use_suggest;
2627 }
2628
2629 // If the original lookup was an unqualified lookup, fake an
2630 // unqualified lookup. This is useful when (for example) the
2631 // original lookup would not have found something because it was a
2632 // dependent name.
2633 DeclContext *DC =
2634 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2635 while (DC) {
2636 if (isa<CXXRecordDecl>(Val: DC)) {
2637 if (ExplicitTemplateArgs) {
2638 if (LookupTemplateName(
2639 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2640 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2641 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2642 return true;
2643 } else {
2644 LookupQualifiedName(R, LookupCtx: DC);
2645 }
2646
2647 if (!R.empty()) {
2648 // Don't give errors about ambiguities in this lookup.
2649 R.suppressDiagnostics();
2650
2651 // If there's a best viable function among the results, only mention
2652 // that one in the notes.
2653 OverloadCandidateSet Candidates(R.getNameLoc(),
2654 OverloadCandidateSet::CSK_Normal);
2655 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2656 OverloadCandidateSet::iterator Best;
2657 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2658 OR_Success) {
2659 R.clear();
2660 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2661 R.resolveKind();
2662 }
2663
2664 return DiagnoseDependentMemberLookup(R);
2665 }
2666
2667 R.clear();
2668 }
2669
2670 DC = DC->getLookupParent();
2671 }
2672
2673 // We didn't find anything, so try to correct for a typo.
2674 TypoCorrection Corrected;
2675 if (S && (Corrected =
2676 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2677 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2678 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2679 bool DroppedSpecifier =
2680 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2681 R.setLookupName(Corrected.getCorrection());
2682
2683 bool AcceptableWithRecovery = false;
2684 bool AcceptableWithoutRecovery = false;
2685 NamedDecl *ND = Corrected.getFoundDecl();
2686 if (ND) {
2687 if (Corrected.isOverloaded()) {
2688 OverloadCandidateSet OCS(R.getNameLoc(),
2689 OverloadCandidateSet::CSK_Normal);
2690 OverloadCandidateSet::iterator Best;
2691 for (NamedDecl *CD : Corrected) {
2692 if (FunctionTemplateDecl *FTD =
2693 dyn_cast<FunctionTemplateDecl>(Val: CD))
2694 AddTemplateOverloadCandidate(
2695 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2696 Args, CandidateSet&: OCS);
2697 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2698 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2699 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2700 Args, CandidateSet&: OCS);
2701 }
2702 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2703 case OR_Success:
2704 ND = Best->FoundDecl;
2705 Corrected.setCorrectionDecl(ND);
2706 break;
2707 default:
2708 // FIXME: Arbitrarily pick the first declaration for the note.
2709 Corrected.setCorrectionDecl(ND);
2710 break;
2711 }
2712 }
2713 R.addDecl(D: ND);
2714 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2715 CXXRecordDecl *Record =
2716 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2717 if (!Record)
2718 Record = cast<CXXRecordDecl>(
2719 Val: ND->getDeclContext()->getRedeclContext());
2720 R.setNamingClass(Record);
2721 }
2722
2723 auto *UnderlyingND = ND->getUnderlyingDecl();
2724 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2725 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2726 // FIXME: If we ended up with a typo for a type name or
2727 // Objective-C class name, we're in trouble because the parser
2728 // is in the wrong place to recover. Suggest the typo
2729 // correction, but don't make it a fix-it since we're not going
2730 // to recover well anyway.
2731 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2732 getAsTypeTemplateDecl(D: UnderlyingND) ||
2733 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2734 } else {
2735 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2736 // because we aren't able to recover.
2737 AcceptableWithoutRecovery = true;
2738 }
2739
2740 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2741 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2742 ? diag::note_implicit_param_decl
2743 : diag::note_previous_decl;
2744 if (SS.isEmpty())
2745 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2746 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2747 else
2748 diagnoseTypo(Correction: Corrected,
2749 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2750 << Name << computeDeclContext(SS, EnteringContext: false)
2751 << DroppedSpecifier << NameRange,
2752 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2753
2754 if (Corrected.WillReplaceSpecifier()) {
2755 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2756 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2757 SS.MakeTrivial(Context, Qualifier: NNS,
2758 R: NNS ? NameRange.getBegin() : SourceRange());
2759 }
2760
2761 // Tell the callee whether to try to recover.
2762 return !AcceptableWithRecovery;
2763 }
2764 }
2765 R.clear();
2766
2767 // Emit a special diagnostic for failed member lookups.
2768 // FIXME: computing the declaration context might fail here (?)
2769 if (!SS.isEmpty()) {
2770 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2771 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2772 return true;
2773 }
2774
2775 // Give up, we can't recover.
2776 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2777 return true;
2778}
2779
2780/// In Microsoft mode, if we are inside a template class whose parent class has
2781/// dependent base classes, and we can't resolve an unqualified identifier, then
2782/// assume the identifier is a member of a dependent base class. We can only
2783/// recover successfully in static methods, instance methods, and other contexts
2784/// where 'this' is available. This doesn't precisely match MSVC's
2785/// instantiation model, but it's close enough.
2786static Expr *
2787recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2788 DeclarationNameInfo &NameInfo,
2789 SourceLocation TemplateKWLoc,
2790 const TemplateArgumentListInfo *TemplateArgs) {
2791 // Only try to recover from lookup into dependent bases in static methods or
2792 // contexts where 'this' is available.
2793 QualType ThisType = S.getCurrentThisType();
2794 const CXXRecordDecl *RD = nullptr;
2795 if (!ThisType.isNull())
2796 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2797 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2798 RD = MD->getParent();
2799 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2800 return nullptr;
2801
2802 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2803 // is available, suggest inserting 'this->' as a fixit.
2804 SourceLocation Loc = NameInfo.getLoc();
2805 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2806 DB << NameInfo.getName() << RD;
2807
2808 if (!ThisType.isNull()) {
2809 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2810 return CXXDependentScopeMemberExpr::Create(
2811 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2812 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2813 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2814 }
2815
2816 // Synthesize a fake NNS that points to the derived class. This will
2817 // perform name lookup during template instantiation.
2818 CXXScopeSpec SS;
2819 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2820 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2821 return DependentScopeDeclRefExpr::Create(
2822 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2823 TemplateArgs);
2824}
2825
2826ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2827 SourceLocation TemplateKWLoc,
2828 UnqualifiedId &Id, bool HasTrailingLParen,
2829 bool IsAddressOfOperand,
2830 CorrectionCandidateCallback *CCC,
2831 bool IsInlineAsmIdentifier) {
2832 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2833 "cannot be direct & operand and have a trailing lparen");
2834 if (SS.isInvalid())
2835 return ExprError();
2836
2837 TemplateArgumentListInfo TemplateArgsBuffer;
2838
2839 // Decompose the UnqualifiedId into the following data.
2840 DeclarationNameInfo NameInfo;
2841 const TemplateArgumentListInfo *TemplateArgs;
2842 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2843
2844 DeclarationName Name = NameInfo.getName();
2845 IdentifierInfo *II = Name.getAsIdentifierInfo();
2846 SourceLocation NameLoc = NameInfo.getLoc();
2847
2848 if (II && II->isEditorPlaceholder()) {
2849 // FIXME: When typed placeholders are supported we can create a typed
2850 // placeholder expression node.
2851 return ExprError();
2852 }
2853
2854 // This specially handles arguments of attributes appertains to a type of C
2855 // struct field such that the name lookup within a struct finds the member
2856 // name, which is not the case for other contexts in C.
2857 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2858 // See if this is reference to a field of struct.
2859 LookupResult R(*this, NameInfo, LookupMemberName);
2860 // LookupName handles a name lookup from within anonymous struct.
2861 if (LookupName(R, S)) {
2862 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2863 QualType type = VD->getType().getNonReferenceType();
2864 // This will eventually be translated into MemberExpr upon
2865 // the use of instantiated struct fields.
2866 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2867 }
2868 }
2869 }
2870
2871 // Perform the required lookup.
2872 LookupResult R(*this, NameInfo,
2873 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2874 ? LookupObjCImplicitSelfParam
2875 : LookupOrdinaryName);
2876 if (TemplateKWLoc.isValid() || TemplateArgs) {
2877 // Lookup the template name again to correctly establish the context in
2878 // which it was found. This is really unfortunate as we already did the
2879 // lookup to determine that it was a template name in the first place. If
2880 // this becomes a performance hit, we can work harder to preserve those
2881 // results until we get here but it's likely not worth it.
2882 AssumedTemplateKind AssumedTemplate;
2883 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2884 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2885 ATK: &AssumedTemplate))
2886 return ExprError();
2887
2888 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2889 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2890 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2891 } else {
2892 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2893 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2894 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2895
2896 // If the result might be in a dependent base class, this is a dependent
2897 // id-expression.
2898 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2899 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2900 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2901
2902 // If this reference is in an Objective-C method, then we need to do
2903 // some special Objective-C lookup, too.
2904 if (IvarLookupFollowUp) {
2905 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2906 if (E.isInvalid())
2907 return ExprError();
2908
2909 if (Expr *Ex = E.getAs<Expr>())
2910 return Ex;
2911 }
2912 }
2913
2914 if (R.isAmbiguous())
2915 return ExprError();
2916
2917 // This could be an implicitly declared function reference if the language
2918 // mode allows it as a feature.
2919 if (R.empty() && HasTrailingLParen && II &&
2920 getLangOpts().implicitFunctionsAllowed()) {
2921 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2922 if (D) R.addDecl(D);
2923 }
2924
2925 // Determine whether this name might be a candidate for
2926 // argument-dependent lookup.
2927 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2928
2929 if (R.empty() && !ADL) {
2930 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2931 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2932 TemplateKWLoc, TemplateArgs))
2933 return E;
2934 }
2935
2936 // Don't diagnose an empty lookup for inline assembly.
2937 if (IsInlineAsmIdentifier)
2938 return ExprError();
2939
2940 // If this name wasn't predeclared and if this is not a function
2941 // call, diagnose the problem.
2942 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2943 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2944 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2945 "Typo correction callback misconfigured");
2946 if (CCC) {
2947 // Make sure the callback knows what the typo being diagnosed is.
2948 CCC->setTypoName(II);
2949 if (SS.isValid())
2950 CCC->setTypoNNS(SS.getScopeRep());
2951 }
2952 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2953 // a template name, but we happen to have always already looked up the name
2954 // before we get here if it must be a template name.
2955 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2956 Args: {}, LookupCtx: nullptr))
2957 return ExprError();
2958
2959 assert(!R.empty() &&
2960 "DiagnoseEmptyLookup returned false but added no results");
2961
2962 // If we found an Objective-C instance variable, let
2963 // LookupInObjCMethod build the appropriate expression to
2964 // reference the ivar.
2965 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2966 R.clear();
2967 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2968 // In a hopelessly buggy code, Objective-C instance variable
2969 // lookup fails and no expression will be built to reference it.
2970 if (!E.isInvalid() && !E.get())
2971 return ExprError();
2972 return E;
2973 }
2974 }
2975
2976 // This is guaranteed from this point on.
2977 assert(!R.empty() || ADL);
2978
2979 // Check whether this might be a C++ implicit instance member access.
2980 // C++ [class.mfct.non-static]p3:
2981 // When an id-expression that is not part of a class member access
2982 // syntax and not used to form a pointer to member is used in the
2983 // body of a non-static member function of class X, if name lookup
2984 // resolves the name in the id-expression to a non-static non-type
2985 // member of some class C, the id-expression is transformed into a
2986 // class member access expression using (*this) as the
2987 // postfix-expression to the left of the . operator.
2988 //
2989 // But we don't actually need to do this for '&' operands if R
2990 // resolved to a function or overloaded function set, because the
2991 // expression is ill-formed if it actually works out to be a
2992 // non-static member function:
2993 //
2994 // C++ [expr.ref]p4:
2995 // Otherwise, if E1.E2 refers to a non-static member function. . .
2996 // [t]he expression can be used only as the left-hand operand of a
2997 // member function call.
2998 //
2999 // There are other safeguards against such uses, but it's important
3000 // to get this right here so that we don't end up making a
3001 // spuriously dependent expression if we're inside a dependent
3002 // instance method.
3003 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3004 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3005 S);
3006
3007 if (TemplateArgs || TemplateKWLoc.isValid()) {
3008
3009 // In C++1y, if this is a variable template id, then check it
3010 // in BuildTemplateIdExpr().
3011 // The single lookup result must be a variable template declaration.
3012 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3013 (Id.TemplateId->Kind == TNK_Var_template ||
3014 Id.TemplateId->Kind == TNK_Concept_template)) {
3015 assert(R.getAsSingle<TemplateDecl>() &&
3016 "There should only be one declaration found.");
3017 }
3018
3019 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3020 }
3021
3022 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3023}
3024
3025ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3026 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3027 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3028 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3029 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3030
3031 if (R.isAmbiguous())
3032 return ExprError();
3033
3034 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3035 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3036 NameInfo, /*TemplateArgs=*/nullptr);
3037
3038 if (R.empty()) {
3039 // Don't diagnose problems with invalid record decl, the secondary no_member
3040 // diagnostic during template instantiation is likely bogus, e.g. if a class
3041 // is invalid because it's derived from an invalid base class, then missing
3042 // members were likely supposed to be inherited.
3043 DeclContext *DC = computeDeclContext(SS);
3044 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3045 if (CD->isInvalidDecl() || CD->isBeingDefined())
3046 return ExprError();
3047 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3048 << NameInfo.getName() << DC << SS.getRange();
3049 return ExprError();
3050 }
3051
3052 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3053 QualType ET;
3054 TypeLocBuilder TLB;
3055 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3056 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3057 Qualifier: SS.getScopeRep(), TD: TagD,
3058 /*OwnsTag=*/false);
3059 auto TL = TLB.push<TagTypeLoc>(T: ET);
3060 TL.setElaboratedKeywordLoc(SourceLocation());
3061 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3062 TL.setNameLoc(NameInfo.getLoc());
3063 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3064 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3065 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3066 TLB.push<TypedefTypeLoc>(T: ET).set(
3067 /*ElaboratedKeywordLoc=*/SourceLocation(),
3068 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3069 } else {
3070 // FIXME: What else can appear here?
3071 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3072 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3073 assert(SS.isEmpty());
3074 }
3075
3076 // Diagnose a missing typename if this resolved unambiguously to a type in
3077 // a dependent context. If we can recover with a type, downgrade this to
3078 // a warning in Microsoft compatibility mode.
3079 unsigned DiagID = diag::err_typename_missing;
3080 if (RecoveryTSI && getLangOpts().MSVCCompat)
3081 DiagID = diag::ext_typename_missing;
3082 SourceLocation Loc = SS.getBeginLoc();
3083 auto D = Diag(Loc, DiagID);
3084 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3085
3086 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3087 // context.
3088 if (!RecoveryTSI)
3089 return ExprError();
3090
3091 // Only issue the fixit if we're prepared to recover.
3092 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3093
3094 // Recover by pretending this was an elaborated type.
3095 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3096
3097 return ExprEmpty();
3098 }
3099
3100 // If necessary, build an implicit class member access.
3101 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3102 return BuildPossibleImplicitMemberExpr(SS,
3103 /*TemplateKWLoc=*/SourceLocation(),
3104 R, /*TemplateArgs=*/nullptr,
3105 /*S=*/nullptr);
3106
3107 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3108}
3109
3110ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3111 NestedNameSpecifier Qualifier,
3112 NamedDecl *FoundDecl,
3113 NamedDecl *Member) {
3114 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3115 if (!RD)
3116 return From;
3117
3118 QualType DestRecordType;
3119 QualType DestType;
3120 QualType FromRecordType;
3121 QualType FromType = From->getType();
3122 bool PointerConversions = false;
3123 if (isa<FieldDecl>(Val: Member)) {
3124 DestRecordType = Context.getCanonicalTagType(TD: RD);
3125 auto FromPtrType = FromType->getAs<PointerType>();
3126 DestRecordType = Context.getAddrSpaceQualType(
3127 T: DestRecordType, AddressSpace: FromPtrType
3128 ? FromType->getPointeeType().getAddressSpace()
3129 : FromType.getAddressSpace());
3130
3131 if (FromPtrType) {
3132 DestType = Context.getPointerType(T: DestRecordType);
3133 FromRecordType = FromPtrType->getPointeeType();
3134 PointerConversions = true;
3135 } else {
3136 DestType = DestRecordType;
3137 FromRecordType = FromType;
3138 }
3139 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3140 if (!Method->isImplicitObjectMemberFunction())
3141 return From;
3142
3143 DestType = Method->getThisType().getNonReferenceType();
3144 DestRecordType = Method->getFunctionObjectParameterType();
3145
3146 if (FromType->getAs<PointerType>()) {
3147 FromRecordType = FromType->getPointeeType();
3148 PointerConversions = true;
3149 } else {
3150 FromRecordType = FromType;
3151 DestType = DestRecordType;
3152 }
3153
3154 LangAS FromAS = FromRecordType.getAddressSpace();
3155 LangAS DestAS = DestRecordType.getAddressSpace();
3156 if (FromAS != DestAS) {
3157 QualType FromRecordTypeWithoutAS =
3158 Context.removeAddrSpaceQualType(T: FromRecordType);
3159 QualType FromTypeWithDestAS =
3160 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3161 if (PointerConversions)
3162 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3163 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3164 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3165 .get();
3166 }
3167 } else {
3168 // No conversion necessary.
3169 return From;
3170 }
3171
3172 if (DestType->isDependentType() || FromType->isDependentType())
3173 return From;
3174
3175 // If the unqualified types are the same, no conversion is necessary.
3176 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3177 return From;
3178
3179 SourceRange FromRange = From->getSourceRange();
3180 SourceLocation FromLoc = FromRange.getBegin();
3181
3182 ExprValueKind VK = From->getValueKind();
3183
3184 // C++ [class.member.lookup]p8:
3185 // [...] Ambiguities can often be resolved by qualifying a name with its
3186 // class name.
3187 //
3188 // If the member was a qualified name and the qualified referred to a
3189 // specific base subobject type, we'll cast to that intermediate type
3190 // first and then to the object in which the member is declared. That allows
3191 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3192 //
3193 // class Base { public: int x; };
3194 // class Derived1 : public Base { };
3195 // class Derived2 : public Base { };
3196 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3197 //
3198 // void VeryDerived::f() {
3199 // x = 17; // error: ambiguous base subobjects
3200 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3201 // }
3202 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3203 QualType QType = QualType(Qualifier.getAsType(), 0);
3204 assert(QType->isRecordType() && "lookup done with non-record type");
3205
3206 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3207
3208 // In C++98, the qualifier type doesn't actually have to be a base
3209 // type of the object type, in which case we just ignore it.
3210 // Otherwise build the appropriate casts.
3211 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3212 CXXCastPath BasePath;
3213 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3214 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3215 return ExprError();
3216
3217 if (PointerConversions)
3218 QType = Context.getPointerType(T: QType);
3219 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3220 VK, BasePath: &BasePath).get();
3221
3222 FromType = QType;
3223 FromRecordType = QRecordType;
3224
3225 // If the qualifier type was the same as the destination type,
3226 // we're done.
3227 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3228 return From;
3229 }
3230 }
3231
3232 CXXCastPath BasePath;
3233 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3234 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3235 /*IgnoreAccess=*/true))
3236 return ExprError();
3237
3238 // Propagate qualifiers to base subobjects as per:
3239 // C++ [basic.type.qualifier]p1.2:
3240 // A volatile object is [...] a subobject of a volatile object.
3241 Qualifiers FromTypeQuals = FromType.getQualifiers();
3242 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3243 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3244
3245 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3246 BasePath: &BasePath);
3247}
3248
3249bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3250 const LookupResult &R,
3251 bool HasTrailingLParen) {
3252 // Only when used directly as the postfix-expression of a call.
3253 if (!HasTrailingLParen)
3254 return false;
3255
3256 // Never if a scope specifier was provided.
3257 if (SS.isNotEmpty())
3258 return false;
3259
3260 // Only in C++ or ObjC++.
3261 if (!getLangOpts().CPlusPlus)
3262 return false;
3263
3264 // Turn off ADL when we find certain kinds of declarations during
3265 // normal lookup:
3266 for (const NamedDecl *D : R) {
3267 // C++0x [basic.lookup.argdep]p3:
3268 // -- a declaration of a class member
3269 // Since using decls preserve this property, we check this on the
3270 // original decl.
3271 if (D->isCXXClassMember())
3272 return false;
3273
3274 // C++0x [basic.lookup.argdep]p3:
3275 // -- a block-scope function declaration that is not a
3276 // using-declaration
3277 // NOTE: we also trigger this for function templates (in fact, we
3278 // don't check the decl type at all, since all other decl types
3279 // turn off ADL anyway).
3280 if (isa<UsingShadowDecl>(Val: D))
3281 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3282 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3283 return false;
3284
3285 // C++0x [basic.lookup.argdep]p3:
3286 // -- a declaration that is neither a function or a function
3287 // template
3288 // And also for builtin functions.
3289 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3290 // But also builtin functions.
3291 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3292 return false;
3293 } else if (!isa<FunctionTemplateDecl>(Val: D))
3294 return false;
3295 }
3296
3297 return true;
3298}
3299
3300
3301/// Diagnoses obvious problems with the use of the given declaration
3302/// as an expression. This is only actually called for lookups that
3303/// were not overloaded, and it doesn't promise that the declaration
3304/// will in fact be used.
3305static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3306 bool AcceptInvalid) {
3307 if (D->isInvalidDecl() && !AcceptInvalid)
3308 return true;
3309
3310 if (isa<TypedefNameDecl>(Val: D)) {
3311 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3312 return true;
3313 }
3314
3315 if (isa<ObjCInterfaceDecl>(Val: D)) {
3316 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3317 return true;
3318 }
3319
3320 if (isa<NamespaceDecl>(Val: D)) {
3321 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3322 return true;
3323 }
3324
3325 return false;
3326}
3327
3328// Certain multiversion types should be treated as overloaded even when there is
3329// only one result.
3330static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3331 assert(R.isSingleResult() && "Expected only a single result");
3332 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3333 return FD &&
3334 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3335}
3336
3337ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3338 LookupResult &R, bool NeedsADL,
3339 bool AcceptInvalidDecl) {
3340 // If this is a single, fully-resolved result and we don't need ADL,
3341 // just build an ordinary singleton decl ref.
3342 if (!NeedsADL && R.isSingleResult() &&
3343 !R.getAsSingle<FunctionTemplateDecl>() &&
3344 !ShouldLookupResultBeMultiVersionOverload(R))
3345 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3346 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3347 AcceptInvalidDecl);
3348
3349 // We only need to check the declaration if there's exactly one
3350 // result, because in the overloaded case the results can only be
3351 // functions and function templates.
3352 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3353 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3354 AcceptInvalid: AcceptInvalidDecl))
3355 return ExprError();
3356
3357 // Otherwise, just build an unresolved lookup expression. Suppress
3358 // any lookup-related diagnostics; we'll hash these out later, when
3359 // we've picked a target.
3360 R.suppressDiagnostics();
3361
3362 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3363 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3364 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3365 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3366
3367 return ULE;
3368}
3369
3370ExprResult Sema::BuildDeclarationNameExpr(
3371 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3372 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3373 bool AcceptInvalidDecl) {
3374 assert(D && "Cannot refer to a NULL declaration");
3375 assert(!isa<FunctionTemplateDecl>(D) &&
3376 "Cannot refer unambiguously to a function template");
3377
3378 SourceLocation Loc = NameInfo.getLoc();
3379 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3380 // Recovery from invalid cases (e.g. D is an invalid Decl).
3381 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3382 // diagnostics, as invalid decls use int as a fallback type.
3383 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3384 }
3385
3386 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3387 // Specifically diagnose references to class templates that are missing
3388 // a template argument list.
3389 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3390 return ExprError();
3391 }
3392
3393 // Make sure that we're referring to a value.
3394 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3395 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3396 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3397 return ExprError();
3398 }
3399
3400 // Check whether this declaration can be used. Note that we suppress
3401 // this check when we're going to perform argument-dependent lookup
3402 // on this function name, because this might not be the function
3403 // that overload resolution actually selects.
3404 if (DiagnoseUseOfDecl(D, Locs: Loc))
3405 return ExprError();
3406
3407 auto *VD = cast<ValueDecl>(Val: D);
3408
3409 // Only create DeclRefExpr's for valid Decl's.
3410 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3411 return ExprError();
3412
3413 // Handle members of anonymous structs and unions. If we got here,
3414 // and the reference is to a class member indirect field, then this
3415 // must be the subject of a pointer-to-member expression.
3416 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3417 IndirectField && !IndirectField->isCXXClassMember())
3418 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3419 indirectField: IndirectField);
3420
3421 QualType type = VD->getType();
3422 if (type.isNull())
3423 return ExprError();
3424 ExprValueKind valueKind = VK_PRValue;
3425
3426 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3427 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3428 // is expanded by some outer '...' in the context of the use.
3429 type = type.getNonPackExpansionType();
3430
3431 switch (D->getKind()) {
3432 // Ignore all the non-ValueDecl kinds.
3433#define ABSTRACT_DECL(kind)
3434#define VALUE(type, base)
3435#define DECL(type, base) case Decl::type:
3436#include "clang/AST/DeclNodes.inc"
3437 llvm_unreachable("invalid value decl kind");
3438
3439 // These shouldn't make it here.
3440 case Decl::ObjCAtDefsField:
3441 llvm_unreachable("forming non-member reference to ivar?");
3442
3443 // Enum constants are always r-values and never references.
3444 // Unresolved using declarations are dependent.
3445 case Decl::EnumConstant:
3446 case Decl::UnresolvedUsingValue:
3447 case Decl::OMPDeclareReduction:
3448 case Decl::OMPDeclareMapper:
3449 valueKind = VK_PRValue;
3450 break;
3451
3452 // Fields and indirect fields that got here must be for
3453 // pointer-to-member expressions; we just call them l-values for
3454 // internal consistency, because this subexpression doesn't really
3455 // exist in the high-level semantics.
3456 case Decl::Field:
3457 case Decl::IndirectField:
3458 case Decl::ObjCIvar:
3459 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3460 "building reference to field in C?");
3461
3462 // These can't have reference type in well-formed programs, but
3463 // for internal consistency we do this anyway.
3464 type = type.getNonReferenceType();
3465 valueKind = VK_LValue;
3466 break;
3467
3468 // Non-type template parameters are either l-values or r-values
3469 // depending on the type.
3470 case Decl::NonTypeTemplateParm: {
3471 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3472 type = reftype->getPointeeType();
3473 valueKind = VK_LValue; // even if the parameter is an r-value reference
3474 break;
3475 }
3476
3477 // [expr.prim.id.unqual]p2:
3478 // If the entity is a template parameter object for a template
3479 // parameter of type T, the type of the expression is const T.
3480 // [...] The expression is an lvalue if the entity is a [...] template
3481 // parameter object.
3482 if (type->isRecordType()) {
3483 type = type.getUnqualifiedType().withConst();
3484 valueKind = VK_LValue;
3485 break;
3486 }
3487
3488 // For non-references, we need to strip qualifiers just in case
3489 // the template parameter was declared as 'const int' or whatever.
3490 valueKind = VK_PRValue;
3491 type = type.getUnqualifiedType();
3492 break;
3493 }
3494
3495 case Decl::Var:
3496 case Decl::VarTemplateSpecialization:
3497 case Decl::VarTemplatePartialSpecialization:
3498 case Decl::Decomposition:
3499 case Decl::Binding:
3500 case Decl::OMPCapturedExpr:
3501 // In C, "extern void blah;" is valid and is an r-value.
3502 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3503 type->isVoidType()) {
3504 valueKind = VK_PRValue;
3505 break;
3506 }
3507 [[fallthrough]];
3508
3509 case Decl::ImplicitParam:
3510 case Decl::ParmVar: {
3511 // These are always l-values.
3512 valueKind = VK_LValue;
3513 type = type.getNonReferenceType();
3514
3515 // FIXME: Does the addition of const really only apply in
3516 // potentially-evaluated contexts? Since the variable isn't actually
3517 // captured in an unevaluated context, it seems that the answer is no.
3518 if (!isUnevaluatedContext()) {
3519 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3520 if (!CapturedType.isNull())
3521 type = CapturedType;
3522 }
3523 break;
3524 }
3525
3526 case Decl::Function: {
3527 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3528 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3529 type = Context.BuiltinFnTy;
3530 valueKind = VK_PRValue;
3531 break;
3532 }
3533 }
3534
3535 const FunctionType *fty = type->castAs<FunctionType>();
3536
3537 // If we're referring to a function with an __unknown_anytype
3538 // result type, make the entire expression __unknown_anytype.
3539 if (fty->getReturnType() == Context.UnknownAnyTy) {
3540 type = Context.UnknownAnyTy;
3541 valueKind = VK_PRValue;
3542 break;
3543 }
3544
3545 // Functions are l-values in C++.
3546 if (getLangOpts().CPlusPlus) {
3547 valueKind = VK_LValue;
3548 break;
3549 }
3550
3551 // C99 DR 316 says that, if a function type comes from a
3552 // function definition (without a prototype), that type is only
3553 // used for checking compatibility. Therefore, when referencing
3554 // the function, we pretend that we don't have the full function
3555 // type.
3556 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3557 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3558 Info: fty->getExtInfo());
3559
3560 // Functions are r-values in C.
3561 valueKind = VK_PRValue;
3562 break;
3563 }
3564
3565 case Decl::CXXDeductionGuide:
3566 llvm_unreachable("building reference to deduction guide");
3567
3568 case Decl::MSProperty:
3569 case Decl::MSGuid:
3570 case Decl::TemplateParamObject:
3571 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3572 // capture in OpenMP, or duplicated between host and device?
3573 valueKind = VK_LValue;
3574 break;
3575
3576 case Decl::UnnamedGlobalConstant:
3577 valueKind = VK_LValue;
3578 break;
3579
3580 case Decl::CXXMethod:
3581 // If we're referring to a method with an __unknown_anytype
3582 // result type, make the entire expression __unknown_anytype.
3583 // This should only be possible with a type written directly.
3584 if (const FunctionProtoType *proto =
3585 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3586 if (proto->getReturnType() == Context.UnknownAnyTy) {
3587 type = Context.UnknownAnyTy;
3588 valueKind = VK_PRValue;
3589 break;
3590 }
3591
3592 // C++ methods are l-values if static, r-values if non-static.
3593 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3594 valueKind = VK_LValue;
3595 break;
3596 }
3597 [[fallthrough]];
3598
3599 case Decl::CXXConversion:
3600 case Decl::CXXDestructor:
3601 case Decl::CXXConstructor:
3602 valueKind = VK_PRValue;
3603 break;
3604 }
3605
3606 auto *E =
3607 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3608 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3609 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3610 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3611 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3612 // diagnostics).
3613 if (VD->isInvalidDecl() && E)
3614 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3615 return E;
3616}
3617
3618static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3619 SmallString<32> &Target) {
3620 Target.resize(N: CharByteWidth * (Source.size() + 1));
3621 char *ResultPtr = &Target[0];
3622 const llvm::UTF8 *ErrorPtr;
3623 bool success =
3624 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3625 (void)success;
3626 assert(success);
3627 Target.resize(N: ResultPtr - &Target[0]);
3628}
3629
3630ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3631 PredefinedIdentKind IK) {
3632 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3633 if (!currentDecl) {
3634 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3635 currentDecl = Context.getTranslationUnitDecl();
3636 }
3637
3638 QualType ResTy;
3639 StringLiteral *SL = nullptr;
3640 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3641 ResTy = Context.DependentTy;
3642 else {
3643 // Pre-defined identifiers are of type char[x], where x is the length of
3644 // the string.
3645 bool ForceElaboratedPrinting =
3646 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3647 auto Str =
3648 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3649 unsigned Length = Str.length();
3650
3651 llvm::APInt LengthI(32, Length + 1);
3652 if (IK == PredefinedIdentKind::LFunction ||
3653 IK == PredefinedIdentKind::LFuncSig) {
3654 ResTy =
3655 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3656 SmallString<32> RawChars;
3657 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3658 Source: Str, Target&: RawChars);
3659 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3660 ASM: ArraySizeModifier::Normal,
3661 /*IndexTypeQuals*/ 0);
3662 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3663 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3664 } else {
3665 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3666 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3667 ASM: ArraySizeModifier::Normal,
3668 /*IndexTypeQuals*/ 0);
3669 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3670 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3671 }
3672 }
3673
3674 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3675 SL);
3676}
3677
3678ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3679 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3680}
3681
3682ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3683 SmallString<16> CharBuffer;
3684 bool Invalid = false;
3685 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3686 if (Invalid)
3687 return ExprError();
3688
3689 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3690 PP, Tok.getKind());
3691 if (Literal.hadError())
3692 return ExprError();
3693
3694 QualType Ty;
3695 if (Literal.isWide())
3696 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3697 else if (Literal.isUTF8() && getLangOpts().C23)
3698 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3699 else if (Literal.isUTF8() && getLangOpts().Char8)
3700 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3701 else if (Literal.isUTF16())
3702 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3703 else if (Literal.isUTF32())
3704 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3705 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3706 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3707 else
3708 Ty = Context.CharTy; // 'x' -> char in C++;
3709 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3710
3711 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3712 if (Literal.isWide())
3713 Kind = CharacterLiteralKind::Wide;
3714 else if (Literal.isUTF16())
3715 Kind = CharacterLiteralKind::UTF16;
3716 else if (Literal.isUTF32())
3717 Kind = CharacterLiteralKind::UTF32;
3718 else if (Literal.isUTF8())
3719 Kind = CharacterLiteralKind::UTF8;
3720
3721 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3722 Tok.getLocation());
3723
3724 if (Literal.getUDSuffix().empty())
3725 return Lit;
3726
3727 // We're building a user-defined literal.
3728 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3729 SourceLocation UDSuffixLoc =
3730 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3731
3732 // Make sure we're allowed user-defined literals here.
3733 if (!UDLScope)
3734 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3735
3736 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3737 // operator "" X (ch)
3738 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3739 Args: Lit, LitEndLoc: Tok.getLocation());
3740}
3741
3742ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3743 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3744 return IntegerLiteral::Create(C: Context,
3745 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3746 type: Context.IntTy, l: Loc);
3747}
3748
3749ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3750 ExprResult Inner;
3751 if (getLangOpts().CPlusPlus) {
3752 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3753 } else {
3754 // C doesn't actually have a way to represent literal values of type
3755 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3756 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3757 Inner =
3758 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3759 }
3760 return Inner;
3761}
3762
3763static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3764 QualType Ty, SourceLocation Loc) {
3765 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3766
3767 using llvm::APFloat;
3768 APFloat Val(Format);
3769
3770 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3771 if (RM == llvm::RoundingMode::Dynamic)
3772 RM = llvm::RoundingMode::NearestTiesToEven;
3773 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3774
3775 // Overflow is always an error, but underflow is only an error if
3776 // we underflowed to zero (APFloat reports denormals as underflow).
3777 if ((result & APFloat::opOverflow) ||
3778 ((result & APFloat::opUnderflow) && Val.isZero())) {
3779 unsigned diagnostic;
3780 SmallString<20> buffer;
3781 if (result & APFloat::opOverflow) {
3782 diagnostic = diag::warn_float_overflow;
3783 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3784 } else {
3785 diagnostic = diag::warn_float_underflow;
3786 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3787 }
3788
3789 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3790 }
3791
3792 bool isExact = (result == APFloat::opOK);
3793 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3794}
3795
3796bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3797 assert(E && "Invalid expression");
3798
3799 if (E->isValueDependent())
3800 return false;
3801
3802 QualType QT = E->getType();
3803 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3804 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3805 return true;
3806 }
3807
3808 llvm::APSInt ValueAPS;
3809 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3810
3811 if (R.isInvalid())
3812 return true;
3813
3814 // GCC allows the value of unroll count to be 0.
3815 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3816 // "The values of 0 and 1 block any unrolling of the loop."
3817 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3818 // '#pragma unroll' cases.
3819 bool ValueIsPositive =
3820 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3821 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3822 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3823 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3824 return true;
3825 }
3826
3827 return false;
3828}
3829
3830ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3831 // Fast path for a single digit (which is quite common). A single digit
3832 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3833 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3834 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3835 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3836 }
3837
3838 SmallString<128> SpellingBuffer;
3839 // NumericLiteralParser wants to overread by one character. Add padding to
3840 // the buffer in case the token is copied to the buffer. If getSpelling()
3841 // returns a StringRef to the memory buffer, it should have a null char at
3842 // the EOF, so it is also safe.
3843 SpellingBuffer.resize(N: Tok.getLength() + 1);
3844
3845 // Get the spelling of the token, which eliminates trigraphs, etc.
3846 bool Invalid = false;
3847 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3848 if (Invalid)
3849 return ExprError();
3850
3851 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3852 PP.getSourceManager(), PP.getLangOpts(),
3853 PP.getTargetInfo(), PP.getDiagnostics());
3854 if (Literal.hadError)
3855 return ExprError();
3856
3857 if (Literal.hasUDSuffix()) {
3858 // We're building a user-defined literal.
3859 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3860 SourceLocation UDSuffixLoc =
3861 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3862
3863 // Make sure we're allowed user-defined literals here.
3864 if (!UDLScope)
3865 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3866
3867 QualType CookedTy;
3868 if (Literal.isFloatingLiteral()) {
3869 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3870 // long double, the literal is treated as a call of the form
3871 // operator "" X (f L)
3872 CookedTy = Context.LongDoubleTy;
3873 } else {
3874 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3875 // unsigned long long, the literal is treated as a call of the form
3876 // operator "" X (n ULL)
3877 CookedTy = Context.UnsignedLongLongTy;
3878 }
3879
3880 DeclarationName OpName =
3881 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3882 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3883 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3884
3885 SourceLocation TokLoc = Tok.getLocation();
3886
3887 // Perform literal operator lookup to determine if we're building a raw
3888 // literal or a cooked one.
3889 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3890 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3891 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3892 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3893 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3894 case LOLR_ErrorNoDiagnostic:
3895 // Lookup failure for imaginary constants isn't fatal, there's still the
3896 // GNU extension producing _Complex types.
3897 break;
3898 case LOLR_Error:
3899 return ExprError();
3900 case LOLR_Cooked: {
3901 Expr *Lit;
3902 if (Literal.isFloatingLiteral()) {
3903 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3904 } else {
3905 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3906 if (Literal.GetIntegerValue(Val&: ResultVal))
3907 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3908 << /* Unsigned */ 1;
3909 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3910 l: Tok.getLocation());
3911 }
3912 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3913 }
3914
3915 case LOLR_Raw: {
3916 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3917 // literal is treated as a call of the form
3918 // operator "" X ("n")
3919 unsigned Length = Literal.getUDSuffixOffset();
3920 QualType StrTy = Context.getConstantArrayType(
3921 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3922 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3923 Expr *Lit =
3924 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3925 Kind: StringLiteralKind::Ordinary,
3926 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3927 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3928 }
3929
3930 case LOLR_Template: {
3931 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3932 // template), L is treated as a call fo the form
3933 // operator "" X <'c1', 'c2', ... 'ck'>()
3934 // where n is the source character sequence c1 c2 ... ck.
3935 TemplateArgumentListInfo ExplicitArgs;
3936 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3937 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3938 llvm::APSInt Value(CharBits, CharIsUnsigned);
3939 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3940 Value = TokSpelling[I];
3941 TemplateArgument Arg(Context, Value, Context.CharTy);
3942 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
3943 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3944 }
3945 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3946 }
3947 case LOLR_StringTemplatePack:
3948 llvm_unreachable("unexpected literal operator lookup result");
3949 }
3950 }
3951
3952 Expr *Res;
3953
3954 if (Literal.isFixedPointLiteral()) {
3955 QualType Ty;
3956
3957 if (Literal.isAccum) {
3958 if (Literal.isHalf) {
3959 Ty = Context.ShortAccumTy;
3960 } else if (Literal.isLong) {
3961 Ty = Context.LongAccumTy;
3962 } else {
3963 Ty = Context.AccumTy;
3964 }
3965 } else if (Literal.isFract) {
3966 if (Literal.isHalf) {
3967 Ty = Context.ShortFractTy;
3968 } else if (Literal.isLong) {
3969 Ty = Context.LongFractTy;
3970 } else {
3971 Ty = Context.FractTy;
3972 }
3973 }
3974
3975 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
3976
3977 bool isSigned = !Literal.isUnsigned;
3978 unsigned scale = Context.getFixedPointScale(Ty);
3979 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
3980
3981 llvm::APInt Val(bit_width, 0, isSigned);
3982 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
3983 bool ValIsZero = Val.isZero() && !Overflowed;
3984
3985 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3986 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3987 // Clause 6.4.4 - The value of a constant shall be in the range of
3988 // representable values for its type, with exception for constants of a
3989 // fract type with a value of exactly 1; such a constant shall denote
3990 // the maximal value for the type.
3991 --Val;
3992 else if (Val.ugt(RHS: MaxVal) || Overflowed)
3993 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
3994
3995 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
3996 l: Tok.getLocation(), Scale: scale);
3997 } else if (Literal.isFloatingLiteral()) {
3998 QualType Ty;
3999 if (Literal.isHalf){
4000 if (getLangOpts().HLSL ||
4001 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4002 Ty = Context.HalfTy;
4003 else {
4004 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4005 return ExprError();
4006 }
4007 } else if (Literal.isFloat)
4008 Ty = Context.FloatTy;
4009 else if (Literal.isLong)
4010 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4011 else if (Literal.isFloat16)
4012 Ty = Context.Float16Ty;
4013 else if (Literal.isFloat128)
4014 Ty = Context.Float128Ty;
4015 else if (getLangOpts().HLSL)
4016 Ty = Context.FloatTy;
4017 else
4018 Ty = Context.DoubleTy;
4019
4020 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4021
4022 if (Ty == Context.DoubleTy) {
4023 if (getLangOpts().SinglePrecisionConstants) {
4024 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4025 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4026 }
4027 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4028 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4029 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4030 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4031 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4032 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4033 }
4034 }
4035 } else if (!Literal.isIntegerLiteral()) {
4036 return ExprError();
4037 } else {
4038 QualType Ty;
4039
4040 // 'z/uz' literals are a C++23 feature.
4041 if (Literal.isSizeT)
4042 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
4043 ? getLangOpts().CPlusPlus23
4044 ? diag::warn_cxx20_compat_size_t_suffix
4045 : diag::ext_cxx23_size_t_suffix
4046 : diag::err_cxx23_size_t_suffix);
4047
4048 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4049 // but we do not currently support the suffix in C++ mode because it's not
4050 // entirely clear whether WG21 will prefer this suffix to return a library
4051 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4052 // literals are a C++ extension.
4053 if (Literal.isBitInt)
4054 PP.Diag(Loc: Tok.getLocation(),
4055 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4056 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4057 : diag::ext_c23_bitint_suffix);
4058
4059 // Get the value in the widest-possible width. What is "widest" depends on
4060 // whether the literal is a bit-precise integer or not. For a bit-precise
4061 // integer type, try to scan the source to determine how many bits are
4062 // needed to represent the value. This may seem a bit expensive, but trying
4063 // to get the integer value from an overly-wide APInt is *extremely*
4064 // expensive, so the naive approach of assuming
4065 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4066 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4067 if (Literal.isBitInt)
4068 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4069 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4070 if (Literal.MicrosoftInteger) {
4071 if (Literal.MicrosoftInteger == 128 &&
4072 !Context.getTargetInfo().hasInt128Type())
4073 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4074 << Literal.isUnsigned;
4075 BitsNeeded = Literal.MicrosoftInteger;
4076 }
4077
4078 llvm::APInt ResultVal(BitsNeeded, 0);
4079
4080 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4081 // If this value didn't fit into uintmax_t, error and force to ull.
4082 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4083 << /* Unsigned */ 1;
4084 Ty = Context.UnsignedLongLongTy;
4085 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4086 "long long is not intmax_t?");
4087 } else {
4088 // If this value fits into a ULL, try to figure out what else it fits into
4089 // according to the rules of C99 6.4.4.1p5.
4090
4091 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4092 // be an unsigned int.
4093 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4094
4095 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4096 // suffix for portability of code with C++, but both `l` and `ll` are
4097 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4098 // same.
4099 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4100 Literal.isLong = true;
4101 Literal.isLongLong = false;
4102 }
4103
4104 // Check from smallest to largest, picking the smallest type we can.
4105 unsigned Width = 0;
4106
4107 // Microsoft specific integer suffixes are explicitly sized.
4108 if (Literal.MicrosoftInteger) {
4109 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4110 Width = 8;
4111 Ty = Context.CharTy;
4112 } else {
4113 Width = Literal.MicrosoftInteger;
4114 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4115 /*Signed=*/!Literal.isUnsigned);
4116 }
4117 }
4118
4119 // Bit-precise integer literals are automagically-sized based on the
4120 // width required by the literal.
4121 if (Literal.isBitInt) {
4122 // The signed version has one more bit for the sign value. There are no
4123 // zero-width bit-precise integers, even if the literal value is 0.
4124 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4125 (Literal.isUnsigned ? 0u : 1u);
4126
4127 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4128 // and reset the type to the largest supported width.
4129 unsigned int MaxBitIntWidth =
4130 Context.getTargetInfo().getMaxBitIntWidth();
4131 if (Width > MaxBitIntWidth) {
4132 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4133 << Literal.isUnsigned;
4134 Width = MaxBitIntWidth;
4135 }
4136
4137 // Reset the result value to the smaller APInt and select the correct
4138 // type to be used. Note, we zext even for signed values because the
4139 // literal itself is always an unsigned value (a preceeding - is a
4140 // unary operator, not part of the literal).
4141 ResultVal = ResultVal.zextOrTrunc(width: Width);
4142 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4143 }
4144
4145 // Check C++23 size_t literals.
4146 if (Literal.isSizeT) {
4147 assert(!Literal.MicrosoftInteger &&
4148 "size_t literals can't be Microsoft literals");
4149 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4150 T: Context.getTargetInfo().getSizeType());
4151
4152 // Does it fit in size_t?
4153 if (ResultVal.isIntN(N: SizeTSize)) {
4154 // Does it fit in ssize_t?
4155 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4156 Ty = Context.getSignedSizeType();
4157 else if (AllowUnsigned)
4158 Ty = Context.getSizeType();
4159 Width = SizeTSize;
4160 }
4161 }
4162
4163 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4164 !Literal.isSizeT) {
4165 // Are int/unsigned possibilities?
4166 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4167
4168 // Does it fit in a unsigned int?
4169 if (ResultVal.isIntN(N: IntSize)) {
4170 // Does it fit in a signed int?
4171 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4172 Ty = Context.IntTy;
4173 else if (AllowUnsigned)
4174 Ty = Context.UnsignedIntTy;
4175 Width = IntSize;
4176 }
4177 }
4178
4179 // Are long/unsigned long possibilities?
4180 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4181 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4182
4183 // Does it fit in a unsigned long?
4184 if (ResultVal.isIntN(N: LongSize)) {
4185 // Does it fit in a signed long?
4186 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4187 Ty = Context.LongTy;
4188 else if (AllowUnsigned)
4189 Ty = Context.UnsignedLongTy;
4190 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4191 // is compatible.
4192 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4193 const unsigned LongLongSize =
4194 Context.getTargetInfo().getLongLongWidth();
4195 Diag(Loc: Tok.getLocation(),
4196 DiagID: getLangOpts().CPlusPlus
4197 ? Literal.isLong
4198 ? diag::warn_old_implicitly_unsigned_long_cxx
4199 : /*C++98 UB*/ diag::
4200 ext_old_implicitly_unsigned_long_cxx
4201 : diag::warn_old_implicitly_unsigned_long)
4202 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4203 : /*will be ill-formed*/ 1);
4204 Ty = Context.UnsignedLongTy;
4205 }
4206 Width = LongSize;
4207 }
4208 }
4209
4210 // Check long long if needed.
4211 if (Ty.isNull() && !Literal.isSizeT) {
4212 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4213
4214 // Does it fit in a unsigned long long?
4215 if (ResultVal.isIntN(N: LongLongSize)) {
4216 // Does it fit in a signed long long?
4217 // To be compatible with MSVC, hex integer literals ending with the
4218 // LL or i64 suffix are always signed in Microsoft mode.
4219 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4220 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4221 Ty = Context.LongLongTy;
4222 else if (AllowUnsigned)
4223 Ty = Context.UnsignedLongLongTy;
4224 Width = LongLongSize;
4225
4226 // 'long long' is a C99 or C++11 feature, whether the literal
4227 // explicitly specified 'long long' or we needed the extra width.
4228 if (getLangOpts().CPlusPlus)
4229 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4230 ? diag::warn_cxx98_compat_longlong
4231 : diag::ext_cxx11_longlong);
4232 else if (!getLangOpts().C99)
4233 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4234 }
4235 }
4236
4237 // If we still couldn't decide a type, we either have 'size_t' literal
4238 // that is out of range, or a decimal literal that does not fit in a
4239 // signed long long and has no U suffix.
4240 if (Ty.isNull()) {
4241 if (Literal.isSizeT)
4242 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4243 << Literal.isUnsigned;
4244 else
4245 Diag(Loc: Tok.getLocation(),
4246 DiagID: diag::ext_integer_literal_too_large_for_signed);
4247 Ty = Context.UnsignedLongLongTy;
4248 Width = Context.getTargetInfo().getLongLongWidth();
4249 }
4250
4251 if (ResultVal.getBitWidth() != Width)
4252 ResultVal = ResultVal.trunc(width: Width);
4253 }
4254 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4255 }
4256
4257 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4258 if (Literal.isImaginary) {
4259 Res = new (Context) ImaginaryLiteral(Res,
4260 Context.getComplexType(T: Res->getType()));
4261
4262 // In C++, this is a GNU extension. In C, it's a C2y extension.
4263 if (getLangOpts().CPlusPlus)
4264 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_gnu_imaginary_constant);
4265 else
4266 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::imaginary_constant);
4267 }
4268 return Res;
4269}
4270
4271ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4272 assert(E && "ActOnParenExpr() missing expr");
4273 QualType ExprTy = E->getType();
4274 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4275 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4276 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4277 return new (Context) ParenExpr(L, R, E);
4278}
4279
4280static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4281 SourceLocation Loc,
4282 SourceRange ArgRange) {
4283 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4284 // scalar or vector data type argument..."
4285 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4286 // type (C99 6.2.5p18) or void.
4287 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4288 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4289 << T << ArgRange;
4290 return true;
4291 }
4292
4293 assert((T->isVoidType() || !T->isIncompleteType()) &&
4294 "Scalar types should always be complete");
4295 return false;
4296}
4297
4298static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4299 SourceLocation Loc,
4300 SourceRange ArgRange) {
4301 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4302 if (!T->isVectorType() && !T->isSizelessVectorType())
4303 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4304 << ""
4305 << "__builtin_vectorelements" << T << ArgRange;
4306
4307 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4308 if (T->isSVESizelessBuiltinType()) {
4309 llvm::StringMap<bool> CallerFeatureMap;
4310 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4311 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4312 }
4313 }
4314
4315 return false;
4316}
4317
4318static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4319 SourceLocation Loc,
4320 SourceRange ArgRange) {
4321 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4322 return true;
4323
4324 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4325 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4326 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4327 return true;
4328 }
4329
4330 return false;
4331}
4332
4333static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4334 SourceLocation Loc,
4335 SourceRange ArgRange,
4336 UnaryExprOrTypeTrait TraitKind) {
4337 // Invalid types must be hard errors for SFINAE in C++.
4338 if (S.LangOpts.CPlusPlus)
4339 return true;
4340
4341 // C99 6.5.3.4p1:
4342 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4343 TraitKind == UETT_PreferredAlignOf) {
4344
4345 // sizeof(function)/alignof(function) is allowed as an extension.
4346 if (T->isFunctionType()) {
4347 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4348 << getTraitSpelling(T: TraitKind) << ArgRange;
4349 return false;
4350 }
4351
4352 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4353 // this is an error (OpenCL v1.1 s6.3.k)
4354 if (T->isVoidType()) {
4355 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4356 : diag::ext_sizeof_alignof_void_type;
4357 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4358 return false;
4359 }
4360 }
4361 return true;
4362}
4363
4364static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4365 SourceLocation Loc,
4366 SourceRange ArgRange,
4367 UnaryExprOrTypeTrait TraitKind) {
4368 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4369 // runtime doesn't allow it.
4370 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4371 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4372 << T << (TraitKind == UETT_SizeOf)
4373 << ArgRange;
4374 return true;
4375 }
4376
4377 return false;
4378}
4379
4380/// Check whether E is a pointer from a decayed array type (the decayed
4381/// pointer type is equal to T) and emit a warning if it is.
4382static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4383 const Expr *E) {
4384 // Don't warn if the operation changed the type.
4385 if (T != E->getType())
4386 return;
4387
4388 // Now look for array decays.
4389 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4390 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4391 return;
4392
4393 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4394 << ICE->getType()
4395 << ICE->getSubExpr()->getType();
4396}
4397
4398bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4399 UnaryExprOrTypeTrait ExprKind) {
4400 QualType ExprTy = E->getType();
4401 assert(!ExprTy->isReferenceType());
4402
4403 bool IsUnevaluatedOperand =
4404 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4405 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4406 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4407 if (IsUnevaluatedOperand) {
4408 ExprResult Result = CheckUnevaluatedOperand(E);
4409 if (Result.isInvalid())
4410 return true;
4411 E = Result.get();
4412 }
4413
4414 // The operand for sizeof and alignof is in an unevaluated expression context,
4415 // so side effects could result in unintended consequences.
4416 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4417 // used to build SFINAE gadgets.
4418 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4419 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4420 !E->isInstantiationDependent() &&
4421 !E->getType()->isVariableArrayType() &&
4422 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4423 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4424
4425 if (ExprKind == UETT_VecStep)
4426 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4427 ArgRange: E->getSourceRange());
4428
4429 if (ExprKind == UETT_VectorElements)
4430 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4431 ArgRange: E->getSourceRange());
4432
4433 // Explicitly list some types as extensions.
4434 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4435 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4436 return false;
4437
4438 // WebAssembly tables are always illegal operands to unary expressions and
4439 // type traits.
4440 if (Context.getTargetInfo().getTriple().isWasm() &&
4441 E->getType()->isWebAssemblyTableType()) {
4442 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4443 << getTraitSpelling(T: ExprKind);
4444 return true;
4445 }
4446
4447 // 'alignof' applied to an expression only requires the base element type of
4448 // the expression to be complete. 'sizeof' requires the expression's type to
4449 // be complete (and will attempt to complete it if it's an array of unknown
4450 // bound).
4451 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4452 if (RequireCompleteSizedType(
4453 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4454 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4455 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4456 return true;
4457 } else {
4458 if (RequireCompleteSizedExprType(
4459 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4460 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4461 return true;
4462 }
4463
4464 // Completing the expression's type may have changed it.
4465 ExprTy = E->getType();
4466 assert(!ExprTy->isReferenceType());
4467
4468 if (ExprTy->isFunctionType()) {
4469 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4470 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4471 return true;
4472 }
4473
4474 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4475 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4476 return true;
4477
4478 if (ExprKind == UETT_CountOf) {
4479 // The type has to be an array type. We already checked for incomplete
4480 // types above.
4481 QualType ExprType = E->IgnoreParens()->getType();
4482 if (!ExprType->isArrayType()) {
4483 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4484 return true;
4485 }
4486 // FIXME: warn on _Countof on an array parameter. Not warning on it
4487 // currently because there are papers in WG14 about array types which do
4488 // not decay that could impact this behavior, so we want to see if anything
4489 // changes here before coming up with a warning group for _Countof-related
4490 // diagnostics.
4491 }
4492
4493 if (ExprKind == UETT_SizeOf) {
4494 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4495 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4496 QualType OType = PVD->getOriginalType();
4497 QualType Type = PVD->getType();
4498 if (Type->isPointerType() && OType->isArrayType()) {
4499 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4500 << Type << OType;
4501 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4502 }
4503 }
4504 }
4505
4506 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4507 // decays into a pointer and returns an unintended result. This is most
4508 // likely a typo for "sizeof(array) op x".
4509 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4510 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4511 E: BO->getLHS());
4512 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4513 E: BO->getRHS());
4514 }
4515 }
4516
4517 return false;
4518}
4519
4520static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4521 // Cannot know anything else if the expression is dependent.
4522 if (E->isTypeDependent())
4523 return false;
4524
4525 if (E->getObjectKind() == OK_BitField) {
4526 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4527 << 1 << E->getSourceRange();
4528 return true;
4529 }
4530
4531 ValueDecl *D = nullptr;
4532 Expr *Inner = E->IgnoreParens();
4533 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4534 D = DRE->getDecl();
4535 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4536 D = ME->getMemberDecl();
4537 }
4538
4539 // If it's a field, require the containing struct to have a
4540 // complete definition so that we can compute the layout.
4541 //
4542 // This can happen in C++11 onwards, either by naming the member
4543 // in a way that is not transformed into a member access expression
4544 // (in an unevaluated operand, for instance), or by naming the member
4545 // in a trailing-return-type.
4546 //
4547 // For the record, since __alignof__ on expressions is a GCC
4548 // extension, GCC seems to permit this but always gives the
4549 // nonsensical answer 0.
4550 //
4551 // We don't really need the layout here --- we could instead just
4552 // directly check for all the appropriate alignment-lowing
4553 // attributes --- but that would require duplicating a lot of
4554 // logic that just isn't worth duplicating for such a marginal
4555 // use-case.
4556 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4557 // Fast path this check, since we at least know the record has a
4558 // definition if we can find a member of it.
4559 if (!FD->getParent()->isCompleteDefinition()) {
4560 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4561 << E->getSourceRange();
4562 return true;
4563 }
4564
4565 // Otherwise, if it's a field, and the field doesn't have
4566 // reference type, then it must have a complete type (or be a
4567 // flexible array member, which we explicitly want to
4568 // white-list anyway), which makes the following checks trivial.
4569 if (!FD->getType()->isReferenceType())
4570 return false;
4571 }
4572
4573 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4574}
4575
4576bool Sema::CheckVecStepExpr(Expr *E) {
4577 E = E->IgnoreParens();
4578
4579 // Cannot know anything else if the expression is dependent.
4580 if (E->isTypeDependent())
4581 return false;
4582
4583 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4584}
4585
4586static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4587 CapturingScopeInfo *CSI) {
4588 assert(T->isVariablyModifiedType());
4589 assert(CSI != nullptr);
4590
4591 // We're going to walk down into the type and look for VLA expressions.
4592 do {
4593 const Type *Ty = T.getTypePtr();
4594 switch (Ty->getTypeClass()) {
4595#define TYPE(Class, Base)
4596#define ABSTRACT_TYPE(Class, Base)
4597#define NON_CANONICAL_TYPE(Class, Base)
4598#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4599#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4600#include "clang/AST/TypeNodes.inc"
4601 T = QualType();
4602 break;
4603 // These types are never variably-modified.
4604 case Type::Builtin:
4605 case Type::Complex:
4606 case Type::Vector:
4607 case Type::ExtVector:
4608 case Type::ConstantMatrix:
4609 case Type::Record:
4610 case Type::Enum:
4611 case Type::TemplateSpecialization:
4612 case Type::ObjCObject:
4613 case Type::ObjCInterface:
4614 case Type::ObjCObjectPointer:
4615 case Type::ObjCTypeParam:
4616 case Type::Pipe:
4617 case Type::BitInt:
4618 case Type::HLSLInlineSpirv:
4619 llvm_unreachable("type class is never variably-modified!");
4620 case Type::Adjusted:
4621 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4622 break;
4623 case Type::Decayed:
4624 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4625 break;
4626 case Type::ArrayParameter:
4627 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4628 break;
4629 case Type::Pointer:
4630 T = cast<PointerType>(Val: Ty)->getPointeeType();
4631 break;
4632 case Type::BlockPointer:
4633 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4634 break;
4635 case Type::LValueReference:
4636 case Type::RValueReference:
4637 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4638 break;
4639 case Type::MemberPointer:
4640 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4641 break;
4642 case Type::ConstantArray:
4643 case Type::IncompleteArray:
4644 // Losing element qualification here is fine.
4645 T = cast<ArrayType>(Val: Ty)->getElementType();
4646 break;
4647 case Type::VariableArray: {
4648 // Losing element qualification here is fine.
4649 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4650
4651 // Unknown size indication requires no size computation.
4652 // Otherwise, evaluate and record it.
4653 auto Size = VAT->getSizeExpr();
4654 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4655 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4656 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4657
4658 T = VAT->getElementType();
4659 break;
4660 }
4661 case Type::FunctionProto:
4662 case Type::FunctionNoProto:
4663 T = cast<FunctionType>(Val: Ty)->getReturnType();
4664 break;
4665 case Type::Paren:
4666 case Type::TypeOf:
4667 case Type::UnaryTransform:
4668 case Type::Attributed:
4669 case Type::BTFTagAttributed:
4670 case Type::OverflowBehavior:
4671 case Type::HLSLAttributedResource:
4672 case Type::SubstTemplateTypeParm:
4673 case Type::MacroQualified:
4674 case Type::CountAttributed:
4675 // Keep walking after single level desugaring.
4676 T = T.getSingleStepDesugaredType(Context);
4677 break;
4678 case Type::Typedef:
4679 T = cast<TypedefType>(Val: Ty)->desugar();
4680 break;
4681 case Type::Decltype:
4682 T = cast<DecltypeType>(Val: Ty)->desugar();
4683 break;
4684 case Type::PackIndexing:
4685 T = cast<PackIndexingType>(Val: Ty)->desugar();
4686 break;
4687 case Type::Using:
4688 T = cast<UsingType>(Val: Ty)->desugar();
4689 break;
4690 case Type::Auto:
4691 case Type::DeducedTemplateSpecialization:
4692 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4693 break;
4694 case Type::TypeOfExpr:
4695 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4696 break;
4697 case Type::Atomic:
4698 T = cast<AtomicType>(Val: Ty)->getValueType();
4699 break;
4700 case Type::PredefinedSugar:
4701 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4702 break;
4703 }
4704 } while (!T.isNull() && T->isVariablyModifiedType());
4705}
4706
4707bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4708 SourceLocation OpLoc,
4709 SourceRange ExprRange,
4710 UnaryExprOrTypeTrait ExprKind,
4711 StringRef KWName) {
4712 if (ExprType->isDependentType())
4713 return false;
4714
4715 // C++ [expr.sizeof]p2:
4716 // When applied to a reference or a reference type, the result
4717 // is the size of the referenced type.
4718 // C++11 [expr.alignof]p3:
4719 // When alignof is applied to a reference type, the result
4720 // shall be the alignment of the referenced type.
4721 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4722 ExprType = Ref->getPointeeType();
4723
4724 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4725 // When alignof or _Alignof is applied to an array type, the result
4726 // is the alignment of the element type.
4727 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4728 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4729 // If the trait is 'alignof' in C before C2y, the ability to apply the
4730 // trait to an incomplete array is an extension.
4731 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4732 ExprType->isIncompleteArrayType())
4733 DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::alignof_incomplete_array);
4734 ExprType = Context.getBaseElementType(QT: ExprType);
4735 }
4736
4737 if (ExprKind == UETT_VecStep)
4738 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4739
4740 if (ExprKind == UETT_VectorElements)
4741 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4742 ArgRange: ExprRange);
4743
4744 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4745 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4746 ArgRange: ExprRange);
4747
4748 // Explicitly list some types as extensions.
4749 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4750 TraitKind: ExprKind))
4751 return false;
4752
4753 if (RequireCompleteSizedType(
4754 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4755 Args: KWName, Args: ExprRange))
4756 return true;
4757
4758 if (ExprType->isFunctionType()) {
4759 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4760 return true;
4761 }
4762
4763 if (ExprKind == UETT_CountOf) {
4764 // The type has to be an array type. We already checked for incomplete
4765 // types above.
4766 if (!ExprType->isArrayType()) {
4767 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4768 return true;
4769 }
4770 }
4771
4772 // WebAssembly tables are always illegal operands to unary expressions and
4773 // type traits.
4774 if (Context.getTargetInfo().getTriple().isWasm() &&
4775 ExprType->isWebAssemblyTableType()) {
4776 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4777 << getTraitSpelling(T: ExprKind);
4778 return true;
4779 }
4780
4781 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4782 TraitKind: ExprKind))
4783 return true;
4784
4785 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4786 if (auto *TT = ExprType->getAs<TypedefType>()) {
4787 for (auto I = FunctionScopes.rbegin(),
4788 E = std::prev(x: FunctionScopes.rend());
4789 I != E; ++I) {
4790 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4791 if (CSI == nullptr)
4792 break;
4793 DeclContext *DC = nullptr;
4794 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4795 DC = LSI->CallOperator;
4796 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4797 DC = CRSI->TheCapturedDecl;
4798 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4799 DC = BSI->TheDecl;
4800 if (DC) {
4801 if (DC->containsDecl(D: TT->getDecl()))
4802 break;
4803 captureVariablyModifiedType(Context, T: ExprType, CSI);
4804 }
4805 }
4806 }
4807 }
4808
4809 return false;
4810}
4811
4812ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4813 SourceLocation OpLoc,
4814 UnaryExprOrTypeTrait ExprKind,
4815 SourceRange R) {
4816 if (!TInfo)
4817 return ExprError();
4818
4819 QualType T = TInfo->getType();
4820
4821 if (!T->isDependentType() &&
4822 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4823 KWName: getTraitSpelling(T: ExprKind)))
4824 return ExprError();
4825
4826 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4827 // properly deal with VLAs in nested calls of sizeof and typeof.
4828 if (currentEvaluationContext().isUnevaluated() &&
4829 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4830 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4831 TInfo->getType()->isVariablyModifiedType())
4832 TInfo = TransformToPotentiallyEvaluated(TInfo);
4833
4834 // It's possible that the transformation above failed.
4835 if (!TInfo)
4836 return ExprError();
4837
4838 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4839 return new (Context) UnaryExprOrTypeTraitExpr(
4840 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4841}
4842
4843ExprResult
4844Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4845 UnaryExprOrTypeTrait ExprKind) {
4846 ExprResult PE = CheckPlaceholderExpr(E);
4847 if (PE.isInvalid())
4848 return ExprError();
4849
4850 E = PE.get();
4851
4852 // Verify that the operand is valid.
4853 bool isInvalid = false;
4854 if (E->isTypeDependent()) {
4855 // Delay type-checking for type-dependent expressions.
4856 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4857 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4858 } else if (ExprKind == UETT_VecStep) {
4859 isInvalid = CheckVecStepExpr(E);
4860 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4861 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4862 isInvalid = true;
4863 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4864 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4865 isInvalid = true;
4866 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4867 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4868 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4869 }
4870
4871 if (isInvalid)
4872 return ExprError();
4873
4874 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4875 E->getType()->isVariableArrayType()) {
4876 PE = TransformToPotentiallyEvaluated(E);
4877 if (PE.isInvalid()) return ExprError();
4878 E = PE.get();
4879 }
4880
4881 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4882 return new (Context) UnaryExprOrTypeTraitExpr(
4883 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4884}
4885
4886ExprResult
4887Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4888 UnaryExprOrTypeTrait ExprKind, bool IsType,
4889 void *TyOrEx, SourceRange ArgRange) {
4890 // If error parsing type, ignore.
4891 if (!TyOrEx) return ExprError();
4892
4893 if (IsType) {
4894 TypeSourceInfo *TInfo;
4895 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4896 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4897 }
4898
4899 Expr *ArgEx = (Expr *)TyOrEx;
4900 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4901 return Result;
4902}
4903
4904bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4905 SourceLocation OpLoc, SourceRange R) {
4906 if (!TInfo)
4907 return true;
4908 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4909 ExprKind: UETT_AlignOf, KWName);
4910}
4911
4912bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4913 SourceLocation OpLoc, SourceRange R) {
4914 TypeSourceInfo *TInfo;
4915 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4916 TInfo: &TInfo);
4917 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4918}
4919
4920static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4921 bool IsReal) {
4922 if (V.get()->isTypeDependent())
4923 return S.Context.DependentTy;
4924
4925 // _Real and _Imag are only l-values for normal l-values.
4926 if (V.get()->getObjectKind() != OK_Ordinary) {
4927 V = S.DefaultLvalueConversion(E: V.get());
4928 if (V.isInvalid())
4929 return QualType();
4930 }
4931
4932 // These operators return the element type of a complex type.
4933 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4934 return CT->getElementType();
4935
4936 // Otherwise they pass through real integer and floating point types here.
4937 if (V.get()->getType()->isArithmeticType())
4938 return V.get()->getType();
4939
4940 // Test for placeholders.
4941 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4942 if (PR.isInvalid()) return QualType();
4943 if (PR.get() != V.get()) {
4944 V = PR;
4945 return CheckRealImagOperand(S, V, Loc, IsReal);
4946 }
4947
4948 // Reject anything else.
4949 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4950 << (IsReal ? "__real" : "__imag");
4951 return QualType();
4952}
4953
4954
4955
4956ExprResult
4957Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4958 tok::TokenKind Kind, Expr *Input) {
4959 UnaryOperatorKind Opc;
4960 switch (Kind) {
4961 default: llvm_unreachable("Unknown unary op!");
4962 case tok::plusplus: Opc = UO_PostInc; break;
4963 case tok::minusminus: Opc = UO_PostDec; break;
4964 }
4965
4966 // Since this might is a postfix expression, get rid of ParenListExprs.
4967 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4968 if (Result.isInvalid()) return ExprError();
4969 Input = Result.get();
4970
4971 return BuildUnaryOp(S, OpLoc, Opc, Input);
4972}
4973
4974/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4975///
4976/// \return true on error
4977static bool checkArithmeticOnObjCPointer(Sema &S,
4978 SourceLocation opLoc,
4979 Expr *op) {
4980 assert(op->getType()->isObjCObjectPointerType());
4981 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4982 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4983 return false;
4984
4985 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
4986 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4987 << op->getSourceRange();
4988 return true;
4989}
4990
4991static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4992 auto *BaseNoParens = Base->IgnoreParens();
4993 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
4994 return MSProp->getPropertyDecl()->getType()->isArrayType();
4995 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
4996}
4997
4998// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4999// Typically this is DependentTy, but can sometimes be more precise.
5000//
5001// There are cases when we could determine a non-dependent type:
5002// - LHS and RHS may have non-dependent types despite being type-dependent
5003// (e.g. unbounded array static members of the current instantiation)
5004// - one may be a dependent-sized array with known element type
5005// - one may be a dependent-typed valid index (enum in current instantiation)
5006//
5007// We *always* return a dependent type, in such cases it is DependentTy.
5008// This avoids creating type-dependent expressions with non-dependent types.
5009// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5010static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5011 const ASTContext &Ctx) {
5012 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5013 QualType LTy = LHS->getType(), RTy = RHS->getType();
5014 QualType Result = Ctx.DependentTy;
5015 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5016 if (const PointerType *PT = LTy->getAs<PointerType>())
5017 Result = PT->getPointeeType();
5018 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5019 Result = AT->getElementType();
5020 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5021 if (const PointerType *PT = RTy->getAs<PointerType>())
5022 Result = PT->getPointeeType();
5023 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5024 Result = AT->getElementType();
5025 }
5026 // Ensure we return a dependent type.
5027 return Result->isDependentType() ? Result : Ctx.DependentTy;
5028}
5029
5030ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5031 SourceLocation lbLoc,
5032 MultiExprArg ArgExprs,
5033 SourceLocation rbLoc) {
5034
5035 if (base && !base->getType().isNull() &&
5036 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5037 auto *AS = cast<ArraySectionExpr>(Val: base);
5038 if (AS->isOMPArraySection())
5039 return OpenMP().ActOnOMPArraySectionExpr(
5040 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5041 /*Length*/ nullptr,
5042 /*Stride=*/nullptr, RBLoc: rbLoc);
5043
5044 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5045 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5046 RBLoc: rbLoc);
5047 }
5048
5049 // Since this might be a postfix expression, get rid of ParenListExprs.
5050 if (isa<ParenListExpr>(Val: base)) {
5051 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5052 if (result.isInvalid())
5053 return ExprError();
5054 base = result.get();
5055 }
5056
5057 // Check if base and idx form a MatrixSubscriptExpr.
5058 //
5059 // Helper to check for comma expressions, which are not allowed as indices for
5060 // matrix subscript expressions.
5061 //
5062 // In C++23, we get multiple arguments instead of a comma expression.
5063 auto CheckAndReportCommaError = [&](Expr *E) {
5064 if (ArgExprs.size() > 1 ||
5065 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5066 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5067 << SourceRange(base->getBeginLoc(), rbLoc);
5068 return true;
5069 }
5070 return false;
5071 };
5072 // The matrix subscript operator ([][])is considered a single operator.
5073 // Separating the index expressions by parenthesis is not allowed.
5074 if (base && !base->getType().isNull() &&
5075 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5076 !isa<MatrixSubscriptExpr>(Val: base)) {
5077 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5078 << SourceRange(base->getBeginLoc(), rbLoc);
5079 return ExprError();
5080 }
5081 // If the base is a MatrixSubscriptExpr, try to create a new
5082 // MatrixSubscriptExpr.
5083 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5084 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5085 if (CheckAndReportCommaError(ArgExprs.front()))
5086 return ExprError();
5087
5088 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5089 RowIdx: matSubscriptE->getRowIdx(),
5090 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5091 }
5092 if (base->getType()->isWebAssemblyTableType()) {
5093 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5094 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5095 return ExprError();
5096 }
5097
5098 CheckInvalidBuiltinCountedByRef(E: base,
5099 K: BuiltinCountedByRefKind::ArraySubscript);
5100
5101 // Handle any non-overload placeholder types in the base and index
5102 // expressions. We can't handle overloads here because the other
5103 // operand might be an overloadable type, in which case the overload
5104 // resolution for the operator overload should get the first crack
5105 // at the overload.
5106 bool IsMSPropertySubscript = false;
5107 if (base->getType()->isNonOverloadPlaceholderType()) {
5108 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5109 if (!IsMSPropertySubscript) {
5110 ExprResult result = CheckPlaceholderExpr(E: base);
5111 if (result.isInvalid())
5112 return ExprError();
5113 base = result.get();
5114 }
5115 }
5116
5117 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5118 if (base->getType()->isMatrixType()) {
5119 if (CheckAndReportCommaError(ArgExprs.front()))
5120 return ExprError();
5121
5122 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5123 RBLoc: rbLoc);
5124 }
5125
5126 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5127 Expr *idx = ArgExprs[0];
5128 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5129 (isa<CXXOperatorCallExpr>(Val: idx) &&
5130 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5131 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5132 << SourceRange(base->getBeginLoc(), rbLoc);
5133 }
5134 }
5135
5136 if (ArgExprs.size() == 1 &&
5137 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5138 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5139 if (result.isInvalid())
5140 return ExprError();
5141 ArgExprs[0] = result.get();
5142 } else {
5143 if (CheckArgsForPlaceholders(args: ArgExprs))
5144 return ExprError();
5145 }
5146
5147 // Build an unanalyzed expression if either operand is type-dependent.
5148 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5149 (base->isTypeDependent() ||
5150 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5151 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5152 return new (Context) ArraySubscriptExpr(
5153 base, ArgExprs.front(),
5154 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5155 VK_LValue, OK_Ordinary, rbLoc);
5156 }
5157
5158 // MSDN, property (C++)
5159 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5160 // This attribute can also be used in the declaration of an empty array in a
5161 // class or structure definition. For example:
5162 // __declspec(property(get=GetX, put=PutX)) int x[];
5163 // The above statement indicates that x[] can be used with one or more array
5164 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5165 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5166 if (IsMSPropertySubscript) {
5167 if (ArgExprs.size() > 1) {
5168 Diag(Loc: base->getExprLoc(),
5169 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5170 return ExprError();
5171 }
5172
5173 // Build MS property subscript expression if base is MS property reference
5174 // or MS property subscript.
5175 return new (Context)
5176 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5177 VK_LValue, OK_Ordinary, rbLoc);
5178 }
5179
5180 // Use C++ overloaded-operator rules if either operand has record
5181 // type. The spec says to do this if either type is *overloadable*,
5182 // but enum types can't declare subscript operators or conversion
5183 // operators, so there's nothing interesting for overload resolution
5184 // to do if there aren't any record types involved.
5185 //
5186 // ObjC pointers have their own subscripting logic that is not tied
5187 // to overload resolution and so should not take this path.
5188 //
5189 // Issue a better diagnostic if we tried to pass multiple arguments to
5190 // a builtin subscript operator rather than diagnosing this as a generic
5191 // overload resolution failure.
5192 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5193 !base->getType()->isRecordType() &&
5194 !base->getType()->isObjCObjectPointerType()) {
5195 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5196 << base->getType() << base->getSourceRange();
5197 return ExprError();
5198 }
5199
5200 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5201 ((base->getType()->isRecordType() ||
5202 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5203 ArgExprs[0]->getType()->isRecordType())))) {
5204 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5205 }
5206
5207 ExprResult Res =
5208 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5209
5210 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5211 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5212
5213 return Res;
5214}
5215
5216ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5217 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5218 InitializationKind Kind =
5219 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5220 InitializationSequence InitSeq(*this, Entity, Kind, E);
5221 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5222}
5223
5224ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5225 Expr *RowIdx,
5226 SourceLocation RBLoc) {
5227 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5228 if (BaseR.isInvalid())
5229 return BaseR;
5230 Base = BaseR.get();
5231
5232 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5233 if (RowR.isInvalid())
5234 return RowR;
5235 RowIdx = RowR.get();
5236
5237 // Build an unanalyzed expression if any of the operands is type-dependent.
5238 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5239 return new (Context)
5240 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5241
5242 // Check that IndexExpr is an integer expression. If it is a constant
5243 // expression, check that it is less than Dim (= the number of elements in the
5244 // corresponding dimension).
5245 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5246 bool IsColumnIdx) -> Expr * {
5247 if (!IndexExpr->getType()->isIntegerType() &&
5248 !IndexExpr->isTypeDependent()) {
5249 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5250 << IsColumnIdx;
5251 return nullptr;
5252 }
5253
5254 if (std::optional<llvm::APSInt> Idx =
5255 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5256 if ((*Idx < 0 || *Idx >= Dim)) {
5257 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5258 << IsColumnIdx << Dim;
5259 return nullptr;
5260 }
5261 }
5262
5263 ExprResult ConvExpr = IndexExpr;
5264 assert(!ConvExpr.isInvalid() &&
5265 "should be able to convert any integer type to size type");
5266 return ConvExpr.get();
5267 };
5268
5269 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5270 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5271 if (!RowIdx)
5272 return ExprError();
5273
5274 QualType RowVecQT =
5275 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5276
5277 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5278}
5279
5280ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5281 Expr *ColumnIdx,
5282 SourceLocation RBLoc) {
5283 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5284 if (BaseR.isInvalid())
5285 return BaseR;
5286 Base = BaseR.get();
5287
5288 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5289 if (RowR.isInvalid())
5290 return RowR;
5291 RowIdx = RowR.get();
5292
5293 if (!ColumnIdx)
5294 return new (Context) MatrixSubscriptExpr(
5295 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5296
5297 // Build an unanalyzed expression if any of the operands is type-dependent.
5298 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5299 ColumnIdx->isTypeDependent())
5300 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5301 Context.DependentTy, RBLoc);
5302
5303 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5304 if (ColumnR.isInvalid())
5305 return ColumnR;
5306 ColumnIdx = ColumnR.get();
5307
5308 // Check that IndexExpr is an integer expression. If it is a constant
5309 // expression, check that it is less than Dim (= the number of elements in the
5310 // corresponding dimension).
5311 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5312 bool IsColumnIdx) -> Expr * {
5313 if (!IndexExpr->getType()->isIntegerType() &&
5314 !IndexExpr->isTypeDependent()) {
5315 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5316 << IsColumnIdx;
5317 return nullptr;
5318 }
5319
5320 if (std::optional<llvm::APSInt> Idx =
5321 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5322 if ((*Idx < 0 || *Idx >= Dim)) {
5323 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5324 << IsColumnIdx << Dim;
5325 return nullptr;
5326 }
5327 }
5328
5329 ExprResult ConvExpr = IndexExpr;
5330 assert(!ConvExpr.isInvalid() &&
5331 "should be able to convert any integer type to size type");
5332 return ConvExpr.get();
5333 };
5334
5335 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5336 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5337 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5338 if (!RowIdx || !ColumnIdx)
5339 return ExprError();
5340
5341 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5342 MTy->getElementType(), RBLoc);
5343}
5344
5345void Sema::CheckAddressOfNoDeref(const Expr *E) {
5346 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5347 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5348
5349 // For expressions like `&(*s).b`, the base is recorded and what should be
5350 // checked.
5351 const MemberExpr *Member = nullptr;
5352 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5353 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5354
5355 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5356}
5357
5358void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5359 if (isUnevaluatedContext())
5360 return;
5361
5362 QualType ResultTy = E->getType();
5363 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5364
5365 // Bail if the element is an array since it is not memory access.
5366 if (isa<ArrayType>(Val: ResultTy))
5367 return;
5368
5369 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5370 LastRecord.PossibleDerefs.insert(Ptr: E);
5371 return;
5372 }
5373
5374 // Check if the base type is a pointer to a member access of a struct
5375 // marked with noderef.
5376 const Expr *Base = E->getBase();
5377 QualType BaseTy = Base->getType();
5378 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5379 // Not a pointer access
5380 return;
5381
5382 const MemberExpr *Member = nullptr;
5383 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5384 Member->isArrow())
5385 Base = Member->getBase();
5386
5387 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5388 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5389 LastRecord.PossibleDerefs.insert(Ptr: E);
5390 }
5391}
5392
5393ExprResult
5394Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5395 Expr *Idx, SourceLocation RLoc) {
5396 Expr *LHSExp = Base;
5397 Expr *RHSExp = Idx;
5398
5399 ExprValueKind VK = VK_LValue;
5400 ExprObjectKind OK = OK_Ordinary;
5401
5402 // Per C++ core issue 1213, the result is an xvalue if either operand is
5403 // a non-lvalue array, and an lvalue otherwise.
5404 if (getLangOpts().CPlusPlus11) {
5405 for (auto *Op : {LHSExp, RHSExp}) {
5406 Op = Op->IgnoreImplicit();
5407 if (Op->getType()->isArrayType() && !Op->isLValue())
5408 VK = VK_XValue;
5409 }
5410 }
5411
5412 // Perform default conversions.
5413 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5414 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5415 if (Result.isInvalid())
5416 return ExprError();
5417 LHSExp = Result.get();
5418 }
5419 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5420 if (Result.isInvalid())
5421 return ExprError();
5422 RHSExp = Result.get();
5423
5424 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5425
5426 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5427 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5428 // in the subscript position. As a result, we need to derive the array base
5429 // and index from the expression types.
5430 Expr *BaseExpr, *IndexExpr;
5431 QualType ResultType;
5432 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5433 BaseExpr = LHSExp;
5434 IndexExpr = RHSExp;
5435 ResultType =
5436 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5437 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5438 BaseExpr = LHSExp;
5439 IndexExpr = RHSExp;
5440 ResultType = PTy->getPointeeType();
5441 } else if (const ObjCObjectPointerType *PTy =
5442 LHSTy->getAs<ObjCObjectPointerType>()) {
5443 BaseExpr = LHSExp;
5444 IndexExpr = RHSExp;
5445
5446 // Use custom logic if this should be the pseudo-object subscript
5447 // expression.
5448 if (!LangOpts.isSubscriptPointerArithmetic())
5449 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5450 getterMethod: nullptr, setterMethod: nullptr);
5451
5452 ResultType = PTy->getPointeeType();
5453 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5454 // Handle the uncommon case of "123[Ptr]".
5455 BaseExpr = RHSExp;
5456 IndexExpr = LHSExp;
5457 ResultType = PTy->getPointeeType();
5458 } else if (const ObjCObjectPointerType *PTy =
5459 RHSTy->getAs<ObjCObjectPointerType>()) {
5460 // Handle the uncommon case of "123[Ptr]".
5461 BaseExpr = RHSExp;
5462 IndexExpr = LHSExp;
5463 ResultType = PTy->getPointeeType();
5464 if (!LangOpts.isSubscriptPointerArithmetic()) {
5465 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5466 << ResultType << BaseExpr->getSourceRange();
5467 return ExprError();
5468 }
5469 } else if (LHSTy->isSubscriptableVectorType()) {
5470 if (LHSTy->isBuiltinType() &&
5471 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5472 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5473 if (BTy->isSVEBool())
5474 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5475 << LHSExp->getSourceRange()
5476 << RHSExp->getSourceRange());
5477 ResultType = BTy->getSveEltType(Ctx: Context);
5478 } else {
5479 const VectorType *VTy = LHSTy->getAs<VectorType>();
5480 ResultType = VTy->getElementType();
5481 }
5482 BaseExpr = LHSExp; // vectors: V[123]
5483 IndexExpr = RHSExp;
5484 // We apply C++ DR1213 to vector subscripting too.
5485 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5486 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5487 if (Materialized.isInvalid())
5488 return ExprError();
5489 LHSExp = Materialized.get();
5490 }
5491 VK = LHSExp->getValueKind();
5492 if (VK != VK_PRValue)
5493 OK = OK_VectorComponent;
5494
5495 QualType BaseType = BaseExpr->getType();
5496 Qualifiers BaseQuals = BaseType.getQualifiers();
5497 Qualifiers MemberQuals = ResultType.getQualifiers();
5498 Qualifiers Combined = BaseQuals + MemberQuals;
5499 if (Combined != MemberQuals)
5500 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5501 } else if (LHSTy->isArrayType()) {
5502 // If we see an array that wasn't promoted by
5503 // DefaultFunctionArrayLvalueConversion, it must be an array that
5504 // wasn't promoted because of the C90 rule that doesn't
5505 // allow promoting non-lvalue arrays. Warn, then
5506 // force the promotion here.
5507 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5508 << LHSExp->getSourceRange();
5509 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5510 CK: CK_ArrayToPointerDecay).get();
5511 LHSTy = LHSExp->getType();
5512
5513 BaseExpr = LHSExp;
5514 IndexExpr = RHSExp;
5515 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5516 } else if (RHSTy->isArrayType()) {
5517 // Same as previous, except for 123[f().a] case
5518 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5519 << RHSExp->getSourceRange();
5520 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5521 CK: CK_ArrayToPointerDecay).get();
5522 RHSTy = RHSExp->getType();
5523
5524 BaseExpr = RHSExp;
5525 IndexExpr = LHSExp;
5526 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5527 } else {
5528 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5529 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5530 }
5531 // C99 6.5.2.1p1
5532 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5533 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5534 << IndexExpr->getSourceRange());
5535
5536 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5537 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5538 !IndexExpr->isTypeDependent()) {
5539 std::optional<llvm::APSInt> IntegerContantExpr =
5540 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5541 if (!IntegerContantExpr.has_value() ||
5542 IntegerContantExpr.value().isNegative())
5543 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5544 }
5545
5546 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5547 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5548 // type. Note that Functions are not objects, and that (in C99 parlance)
5549 // incomplete types are not object types.
5550 if (ResultType->isFunctionType()) {
5551 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5552 << ResultType << BaseExpr->getSourceRange();
5553 return ExprError();
5554 }
5555
5556 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5557 // GNU extension: subscripting on pointer to void
5558 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5559 << BaseExpr->getSourceRange();
5560
5561 // C forbids expressions of unqualified void type from being l-values.
5562 // See IsCForbiddenLValueType.
5563 if (!ResultType.hasQualifiers())
5564 VK = VK_PRValue;
5565 } else if (!ResultType->isDependentType() &&
5566 !ResultType.isWebAssemblyReferenceType() &&
5567 RequireCompleteSizedType(
5568 Loc: LLoc, T: ResultType,
5569 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5570 return ExprError();
5571
5572 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5573 !ResultType.isCForbiddenLValueType());
5574
5575 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5576 FunctionScopes.size() > 1) {
5577 if (auto *TT =
5578 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5579 for (auto I = FunctionScopes.rbegin(),
5580 E = std::prev(x: FunctionScopes.rend());
5581 I != E; ++I) {
5582 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5583 if (CSI == nullptr)
5584 break;
5585 DeclContext *DC = nullptr;
5586 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5587 DC = LSI->CallOperator;
5588 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5589 DC = CRSI->TheCapturedDecl;
5590 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5591 DC = BSI->TheDecl;
5592 if (DC) {
5593 if (DC->containsDecl(D: TT->getDecl()))
5594 break;
5595 captureVariablyModifiedType(
5596 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5597 }
5598 }
5599 }
5600 }
5601
5602 return new (Context)
5603 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5604}
5605
5606bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5607 ParmVarDecl *Param, Expr *RewrittenInit,
5608 bool SkipImmediateInvocations) {
5609 if (Param->hasUnparsedDefaultArg()) {
5610 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5611 // If we've already cleared out the location for the default argument,
5612 // that means we're parsing it right now.
5613 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5614 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5615 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5616 Param->setInvalidDecl();
5617 return true;
5618 }
5619
5620 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5621 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5622 Diag(Loc: UnparsedDefaultArgLocs[Param],
5623 DiagID: diag::note_default_argument_declared_here);
5624 return true;
5625 }
5626
5627 if (Param->hasUninstantiatedDefaultArg()) {
5628 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5629 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5630 return true;
5631 }
5632
5633 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5634 assert(Init && "default argument but no initializer?");
5635
5636 // If the default expression creates temporaries, we need to
5637 // push them to the current stack of expression temporaries so they'll
5638 // be properly destroyed.
5639 // FIXME: We should really be rebuilding the default argument with new
5640 // bound temporaries; see the comment in PR5810.
5641 // We don't need to do that with block decls, though, because
5642 // blocks in default argument expression can never capture anything.
5643 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5644 // Set the "needs cleanups" bit regardless of whether there are
5645 // any explicit objects.
5646 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5647 // Append all the objects to the cleanup list. Right now, this
5648 // should always be a no-op, because blocks in default argument
5649 // expressions should never be able to capture anything.
5650 assert(!InitWithCleanup->getNumObjects() &&
5651 "default argument expression has capturing blocks?");
5652 }
5653 // C++ [expr.const]p15.1:
5654 // An expression or conversion is in an immediate function context if it is
5655 // potentially evaluated and [...] its innermost enclosing non-block scope
5656 // is a function parameter scope of an immediate function.
5657 EnterExpressionEvaluationContext EvalContext(
5658 *this,
5659 FD->isImmediateFunction()
5660 ? ExpressionEvaluationContext::ImmediateFunctionContext
5661 : ExpressionEvaluationContext::PotentiallyEvaluated,
5662 Param);
5663 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5664 SkipImmediateInvocations;
5665 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5666 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5667 });
5668 return false;
5669}
5670
5671struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5672 const ASTContext &Context;
5673 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5674 ShouldVisitImplicitCode = true;
5675 }
5676
5677 bool HasImmediateCalls = false;
5678
5679 bool VisitCallExpr(CallExpr *E) override {
5680 if (const FunctionDecl *FD = E->getDirectCallee())
5681 HasImmediateCalls |= FD->isImmediateFunction();
5682 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5683 }
5684
5685 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5686 if (const FunctionDecl *FD = E->getConstructor())
5687 HasImmediateCalls |= FD->isImmediateFunction();
5688 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5689 }
5690
5691 // SourceLocExpr are not immediate invocations
5692 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5693 // need to be rebuilt so that they refer to the correct SourceLocation and
5694 // DeclContext.
5695 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5696 HasImmediateCalls = true;
5697 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5698 }
5699
5700 // A nested lambda might have parameters with immediate invocations
5701 // in their default arguments, or init-captures that are evaluated in the
5702 // enclosing context.
5703 // The compound statement is not visited (as it does not constitute a
5704 // subexpression).
5705 bool VisitLambdaExpr(LambdaExpr *E) override {
5706 auto Init = E->capture_init_begin();
5707 for (auto C = E->capture_begin(), CEnd = E->capture_end(); C != CEnd;
5708 ++C, ++Init) {
5709 if (E->isInitCapture(Capture: C) && !TraverseLambdaCapture(LE: E, C, Init: *Init))
5710 return false;
5711 }
5712 return VisitCXXMethodDecl(D: E->getCallOperator());
5713 }
5714
5715 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5716 return TraverseStmt(S: E->getExpr());
5717 }
5718
5719 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5720 return TraverseStmt(S: E->getExpr());
5721 }
5722};
5723
5724struct EnsureImmediateInvocationInDefaultArgs
5725 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5726 using Base = TreeTransform<EnsureImmediateInvocationInDefaultArgs>;
5727
5728 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5729 : TreeTransform(SemaRef) {}
5730
5731 bool AlwaysRebuild() { return true; }
5732 bool ReplacingOriginal() { return true; }
5733
5734 // Lambda bodies are not subexpressions of the enclosing default initializer,
5735 // but init-capture expressions are evaluated in the enclosing context. Keep
5736 // the existing closure type and capture declarations so the existing body
5737 // still refers to the right declarations.
5738 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5739 SmallVector<Expr *, 4> CaptureInits(E->capture_inits());
5740
5741 bool Changed = false;
5742 for (unsigned I = 0, N = E->capture_size(); I != N; ++I) {
5743 const LambdaCapture *C = E->capture_begin() + I;
5744 if (!E->isInitCapture(Capture: C))
5745 continue;
5746
5747 auto *VD = cast<VarDecl>(Val: C->getCapturedVar());
5748 Expr *Init = CaptureInits[I];
5749 ExprResult NewInit =
5750 TransformInitializer(Init, NotCopyInit: VD->getInitStyle() == VarDecl::CallInit);
5751 if (NewInit.isInvalid())
5752 return ExprError();
5753 Changed |= NewInit.get() != Init;
5754 CaptureInits[I] = NewInit.get();
5755 }
5756
5757 LambdaExpr *Lambda = E;
5758 if (Changed) {
5759 // Reuse the existing closure class: it owns the capture declarations,
5760 // fields, and call operator body. Only the LambdaExpr's capture
5761 // initializer list is replaced.
5762 Lambda = LambdaExpr::Create(
5763 C: SemaRef.Context, Class: E->getLambdaClass(), IntroducerRange: E->getIntroducerRange(),
5764 CaptureDefault: E->getCaptureDefault(), CaptureDefaultLoc: E->getCaptureDefaultLoc(),
5765 ExplicitParams: E->hasExplicitParameters(), ExplicitResultType: E->hasExplicitResultType(), CaptureInits,
5766 ClosingBrace: E->getEndLoc(), ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack());
5767 }
5768
5769 return SemaRef.MaybeBindToTemporary(E: Lambda);
5770 }
5771 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5772
5773 // Make sure we don't rebuild the this pointer as it would
5774 // cause it to incorrectly point it to the outermost class
5775 // in the case of nested struct initialization.
5776 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5777
5778 // Rewrite to source location to refer to the context in which they are used.
5779 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5780 DeclContext *DC = E->getParentContext();
5781 if (DC == SemaRef.CurContext)
5782 return E;
5783
5784 // FIXME: During instantiation, because the rebuild of defaults arguments
5785 // is not always done in the context of the template instantiator,
5786 // we run the risk of producing a dependent source location
5787 // that would never be rebuilt.
5788 // This usually happens during overload resolution, or in contexts
5789 // where the value of the source location does not matter.
5790 // However, we should find a better way to deal with source location
5791 // of function templates.
5792 if (!SemaRef.CurrentInstantiationScope ||
5793 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5794 DC = SemaRef.CurContext;
5795
5796 return getDerived().RebuildSourceLocExpr(
5797 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5798 }
5799};
5800
5801ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5802 FunctionDecl *FD, ParmVarDecl *Param,
5803 Expr *Init) {
5804 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5805
5806 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5807 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5808 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5809 InitializationContext =
5810 OutermostDeclarationWithDelayedImmediateInvocations();
5811 if (!InitializationContext.has_value())
5812 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5813
5814 if (!Init && !Param->hasUnparsedDefaultArg()) {
5815 // Mark that we are replacing a default argument first.
5816 // If we are instantiating a template we won't have to
5817 // retransform immediate calls.
5818 // C++ [expr.const]p15.1:
5819 // An expression or conversion is in an immediate function context if it
5820 // is potentially evaluated and [...] its innermost enclosing non-block
5821 // scope is a function parameter scope of an immediate function.
5822 EnterExpressionEvaluationContext EvalContext(
5823 *this,
5824 FD->isImmediateFunction()
5825 ? ExpressionEvaluationContext::ImmediateFunctionContext
5826 : ExpressionEvaluationContext::PotentiallyEvaluated,
5827 Param);
5828
5829 if (Param->hasUninstantiatedDefaultArg()) {
5830 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5831 return ExprError();
5832 }
5833 // CWG2631
5834 // An immediate invocation that is not evaluated where it appears is
5835 // evaluated and checked for whether it is a constant expression at the
5836 // point where the enclosing initializer is used in a function call.
5837 ImmediateCallVisitor V(getASTContext());
5838 if (!NestedDefaultChecking)
5839 V.TraverseDecl(D: Param);
5840
5841 // Rewrite the call argument that was created from the corresponding
5842 // parameter's default argument.
5843 if (V.HasImmediateCalls ||
5844 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5845 if (V.HasImmediateCalls)
5846 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5847 CallLoc, Param, CurContext};
5848 // Pass down lifetime extending flag, and collect temporaries in
5849 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5850 currentEvaluationContext().InLifetimeExtendingContext =
5851 parentEvaluationContext().InLifetimeExtendingContext;
5852 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5853 ExprResult Res;
5854 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5855 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5856 /*NotCopy=*/NotCopyInit: false);
5857 });
5858 if (Res.isInvalid())
5859 return ExprError();
5860 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5861 EqualLoc: Res.get()->getBeginLoc());
5862 if (Res.isInvalid())
5863 return ExprError();
5864 Init = Res.get();
5865 }
5866 }
5867
5868 if (CheckCXXDefaultArgExpr(
5869 CallLoc, FD, Param, RewrittenInit: Init,
5870 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5871 return ExprError();
5872
5873 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5874 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5875}
5876
5877static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5878 FieldDecl *Field) {
5879 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5880 return Pattern;
5881 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5882 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5883 DeclContext::lookup_result Lookup =
5884 ClassPattern->lookup(Name: Field->getDeclName());
5885 auto Rng = llvm::make_filter_range(
5886 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5887 if (Rng.empty())
5888 return nullptr;
5889 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5890 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5891 // && "Duplicated instantiation pattern for field decl");
5892 return cast<FieldDecl>(Val: *Rng.begin());
5893}
5894
5895ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5896 assert(Field->hasInClassInitializer());
5897
5898 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5899
5900 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5901
5902 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5903 InitializationContext =
5904 OutermostDeclarationWithDelayedImmediateInvocations();
5905 if (!InitializationContext.has_value())
5906 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5907
5908 Expr *Init = nullptr;
5909
5910 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5911 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5912 EnterExpressionEvaluationContext EvalContext(
5913 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5914
5915 if (!Field->getInClassInitializer()) {
5916 // Maybe we haven't instantiated the in-class initializer. Go check the
5917 // pattern FieldDecl to see if it has one.
5918 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5919 FieldDecl *Pattern =
5920 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5921 assert(Pattern && "We must have set the Pattern!");
5922 if (!Pattern->hasInClassInitializer() ||
5923 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5924 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5925 Field->setInvalidDecl();
5926 return ExprError();
5927 }
5928 }
5929 }
5930
5931 // CWG2631
5932 // An immediate invocation that is not evaluated where it appears is
5933 // evaluated and checked for whether it is a constant expression at the
5934 // point where the enclosing initializer is used in a [...] a constructor
5935 // definition, or an aggregate initialization.
5936 ImmediateCallVisitor V(getASTContext());
5937 if (!NestedDefaultChecking)
5938 V.TraverseDecl(D: Field);
5939
5940 // CWG1815
5941 // Support lifetime extension of temporary created by aggregate
5942 // initialization using a default member initializer. We should rebuild
5943 // the initializer in a lifetime extension context if the initializer
5944 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5945 // extension code recurses into the default initializer and does lifetime
5946 // extension when warranted.
5947 bool ContainsAnyTemporaries =
5948 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5949 if (Field->getInClassInitializer() &&
5950 !Field->getInClassInitializer()->containsErrors() &&
5951 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5952 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5953 CurContext};
5954 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5955 NestedDefaultChecking;
5956 // Pass down lifetime extending flag, and collect temporaries in
5957 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5958 currentEvaluationContext().InLifetimeExtendingContext =
5959 parentEvaluationContext().InLifetimeExtendingContext;
5960 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5961 ExprResult Res;
5962 runWithSufficientStackSpace(Loc, Fn: [&] {
5963 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5964 /*CXXDirectInit=*/NotCopyInit: false);
5965 });
5966 if (!Res.isInvalid())
5967 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5968 if (Res.isInvalid()) {
5969 Field->setInvalidDecl();
5970 return ExprError();
5971 }
5972 Init = Res.get();
5973 }
5974
5975 if (Field->getInClassInitializer()) {
5976 Expr *E = Init ? Init : Field->getInClassInitializer();
5977 if (!NestedDefaultChecking)
5978 runWithSufficientStackSpace(Loc, Fn: [&] {
5979 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5980 });
5981 if (isInLifetimeExtendingContext())
5982 DiscardCleanupsInEvaluationContext();
5983 // C++11 [class.base.init]p7:
5984 // The initialization of each base and member constitutes a
5985 // full-expression.
5986 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5987 if (Res.isInvalid()) {
5988 Field->setInvalidDecl();
5989 return ExprError();
5990 }
5991 Init = Res.get();
5992
5993 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5994 Field, UsedContext: InitializationContext->Context,
5995 RewrittenInitExpr: Init);
5996 }
5997
5998 // DR1351:
5999 // If the brace-or-equal-initializer of a non-static data member
6000 // invokes a defaulted default constructor of its class or of an
6001 // enclosing class in a potentially evaluated subexpression, the
6002 // program is ill-formed.
6003 //
6004 // This resolution is unworkable: the exception specification of the
6005 // default constructor can be needed in an unevaluated context, in
6006 // particular, in the operand of a noexcept-expression, and we can be
6007 // unable to compute an exception specification for an enclosed class.
6008 //
6009 // Any attempt to resolve the exception specification of a defaulted default
6010 // constructor before the initializer is lexically complete will ultimately
6011 // come here at which point we can diagnose it.
6012 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6013 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
6014 << OutermostClass << Field;
6015 Diag(Loc: Field->getEndLoc(),
6016 DiagID: diag::note_default_member_initializer_not_yet_parsed);
6017 // Recover by marking the field invalid, unless we're in a SFINAE context.
6018 if (!isSFINAEContext())
6019 Field->setInvalidDecl();
6020 return ExprError();
6021}
6022
6023VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
6024 const FunctionProtoType *Proto,
6025 Expr *Fn) {
6026 if (Proto && Proto->isVariadic()) {
6027 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6028 return VariadicCallType::Constructor;
6029 else if (Fn && Fn->getType()->isBlockPointerType())
6030 return VariadicCallType::Block;
6031 else if (FDecl) {
6032 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6033 if (Method->isInstance())
6034 return VariadicCallType::Method;
6035 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6036 return VariadicCallType::Method;
6037 return VariadicCallType::Function;
6038 }
6039 return VariadicCallType::DoesNotApply;
6040}
6041
6042namespace {
6043class FunctionCallCCC final : public FunctionCallFilterCCC {
6044public:
6045 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6046 unsigned NumArgs, MemberExpr *ME)
6047 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6048 FunctionName(FuncName) {}
6049
6050 bool ValidateCandidate(const TypoCorrection &candidate) override {
6051 if (!candidate.getCorrectionSpecifier() ||
6052 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6053 return false;
6054 }
6055
6056 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6057 }
6058
6059 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6060 return std::make_unique<FunctionCallCCC>(args&: *this);
6061 }
6062
6063private:
6064 const IdentifierInfo *const FunctionName;
6065};
6066}
6067
6068static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6069 FunctionDecl *FDecl,
6070 ArrayRef<Expr *> Args) {
6071 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6072 DeclarationName FuncName = FDecl->getDeclName();
6073 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6074
6075 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6076 if (TypoCorrection Corrected = S.CorrectTypo(
6077 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6078 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6079 Mode: CorrectTypoKind::ErrorRecovery)) {
6080 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6081 if (Corrected.isOverloaded()) {
6082 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6083 OverloadCandidateSet::iterator Best;
6084 for (NamedDecl *CD : Corrected) {
6085 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6086 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6087 CandidateSet&: OCS);
6088 }
6089 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6090 case OR_Success:
6091 ND = Best->FoundDecl;
6092 Corrected.setCorrectionDecl(ND);
6093 break;
6094 default:
6095 break;
6096 }
6097 }
6098 ND = ND->getUnderlyingDecl();
6099 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6100 return Corrected;
6101 }
6102 }
6103 return TypoCorrection();
6104}
6105
6106// [C++26][[expr.unary.op]/p4
6107// A pointer to member is only formed when an explicit &
6108// is used and its operand is a qualified-id not enclosed in parentheses.
6109static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6110 if (!isa<ParenExpr>(Val: Fn))
6111 return false;
6112
6113 Fn = Fn->IgnoreParens();
6114
6115 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6116 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6117 return false;
6118 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6119 return DRE->hasQualifier();
6120 }
6121 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6122 return bool(OVL->getQualifier());
6123 return false;
6124}
6125
6126bool
6127Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6128 FunctionDecl *FDecl,
6129 const FunctionProtoType *Proto,
6130 ArrayRef<Expr *> Args,
6131 SourceLocation RParenLoc,
6132 bool IsExecConfig) {
6133 // Bail out early if calling a builtin with custom typechecking.
6134 // For HLSL builtin aliases, argument conversion is still needed because
6135 // overload resolution may have selected a conversion sequence (e.g.,
6136 // vector-to-scalar truncation) that must be applied before the custom
6137 // type checker runs.
6138 if (FDecl)
6139 if (unsigned ID = FDecl->getBuiltinID())
6140 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6141 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6142 return false;
6143
6144 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6145 // assignment, to the types of the corresponding parameter, ...
6146
6147 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6148 bool HasExplicitObjectParameter =
6149 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6150 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6151 unsigned NumParams = Proto->getNumParams();
6152 bool Invalid = false;
6153 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6154 unsigned FnKind = Fn->getType()->isBlockPointerType()
6155 ? 1 /* block */
6156 : (IsExecConfig ? 3 /* kernel function (exec config) */
6157 : 0 /* function */);
6158
6159 // If too few arguments are available (and we don't have default
6160 // arguments for the remaining parameters), don't make the call.
6161 if (Args.size() < NumParams) {
6162 if (Args.size() < MinArgs) {
6163 TypoCorrection TC;
6164 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6165 unsigned diag_id =
6166 MinArgs == NumParams && !Proto->isVariadic()
6167 ? diag::err_typecheck_call_too_few_args_suggest
6168 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6169 diagnoseTypo(
6170 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6171 << FnKind << MinArgs - ExplicitObjectParameterOffset
6172 << static_cast<unsigned>(Args.size()) -
6173 ExplicitObjectParameterOffset
6174 << HasExplicitObjectParameter << TC.getCorrectionRange());
6175 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6176 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6177 ->getDeclName())
6178 Diag(Loc: RParenLoc,
6179 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6180 ? diag::err_typecheck_call_too_few_args_one
6181 : diag::err_typecheck_call_too_few_args_at_least_one)
6182 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6183 << HasExplicitObjectParameter << Fn->getSourceRange();
6184 else
6185 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6186 ? diag::err_typecheck_call_too_few_args
6187 : diag::err_typecheck_call_too_few_args_at_least)
6188 << FnKind << MinArgs - ExplicitObjectParameterOffset
6189 << static_cast<unsigned>(Args.size()) -
6190 ExplicitObjectParameterOffset
6191 << HasExplicitObjectParameter << Fn->getSourceRange();
6192
6193 // Emit the location of the prototype.
6194 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6195 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6196 << FDecl << FDecl->getParametersSourceRange();
6197
6198 return true;
6199 }
6200 // We reserve space for the default arguments when we create
6201 // the call expression, before calling ConvertArgumentsForCall.
6202 assert((Call->getNumArgs() == NumParams) &&
6203 "We should have reserved space for the default arguments before!");
6204 }
6205
6206 // If too many are passed and not variadic, error on the extras and drop
6207 // them.
6208 if (Args.size() > NumParams) {
6209 if (!Proto->isVariadic()) {
6210 TypoCorrection TC;
6211 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6212 unsigned diag_id =
6213 MinArgs == NumParams && !Proto->isVariadic()
6214 ? diag::err_typecheck_call_too_many_args_suggest
6215 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6216 diagnoseTypo(
6217 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6218 << FnKind << NumParams - ExplicitObjectParameterOffset
6219 << static_cast<unsigned>(Args.size()) -
6220 ExplicitObjectParameterOffset
6221 << HasExplicitObjectParameter << TC.getCorrectionRange());
6222 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6223 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6224 ->getDeclName())
6225 Diag(Loc: Args[NumParams]->getBeginLoc(),
6226 DiagID: MinArgs == NumParams
6227 ? diag::err_typecheck_call_too_many_args_one
6228 : diag::err_typecheck_call_too_many_args_at_most_one)
6229 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6230 << static_cast<unsigned>(Args.size()) -
6231 ExplicitObjectParameterOffset
6232 << HasExplicitObjectParameter << Fn->getSourceRange()
6233 << SourceRange(Args[NumParams]->getBeginLoc(),
6234 Args.back()->getEndLoc());
6235 else
6236 Diag(Loc: Args[NumParams]->getBeginLoc(),
6237 DiagID: MinArgs == NumParams
6238 ? diag::err_typecheck_call_too_many_args
6239 : diag::err_typecheck_call_too_many_args_at_most)
6240 << FnKind << NumParams - ExplicitObjectParameterOffset
6241 << static_cast<unsigned>(Args.size()) -
6242 ExplicitObjectParameterOffset
6243 << HasExplicitObjectParameter << Fn->getSourceRange()
6244 << SourceRange(Args[NumParams]->getBeginLoc(),
6245 Args.back()->getEndLoc());
6246
6247 // Emit the location of the prototype.
6248 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6249 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6250 << FDecl << FDecl->getParametersSourceRange();
6251
6252 // This deletes the extra arguments.
6253 Call->shrinkNumArgs(NewNumArgs: NumParams);
6254 return true;
6255 }
6256 }
6257 SmallVector<Expr *, 8> AllArgs;
6258 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6259
6260 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6261 AllArgs, CallType);
6262 if (Invalid)
6263 return true;
6264 unsigned TotalNumArgs = AllArgs.size();
6265 for (unsigned i = 0; i < TotalNumArgs; ++i)
6266 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6267
6268 Call->computeDependence();
6269 return false;
6270}
6271
6272bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6273 const FunctionProtoType *Proto,
6274 unsigned FirstParam, ArrayRef<Expr *> Args,
6275 SmallVectorImpl<Expr *> &AllArgs,
6276 VariadicCallType CallType, bool AllowExplicit,
6277 bool IsListInitialization) {
6278 unsigned NumParams = Proto->getNumParams();
6279 bool Invalid = false;
6280 size_t ArgIx = 0;
6281 // Continue to check argument types (even if we have too few/many args).
6282 for (unsigned i = FirstParam; i < NumParams; i++) {
6283 QualType ProtoArgType = Proto->getParamType(i);
6284
6285 Expr *Arg;
6286 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6287 if (ArgIx < Args.size()) {
6288 Arg = Args[ArgIx++];
6289
6290 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6291 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6292 return true;
6293
6294 // Strip the unbridged-cast placeholder expression off, if applicable.
6295 bool CFAudited = false;
6296 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6297 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6298 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6299 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6300 else if (getLangOpts().ObjCAutoRefCount &&
6301 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6302 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6303 CFAudited = true;
6304
6305 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6306 ProtoArgType->isBlockPointerType())
6307 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6308 BE->getBlockDecl()->setDoesNotEscape();
6309 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6310 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6311 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6312 if (ArgExpr.isInvalid())
6313 return true;
6314 Arg = ArgExpr.getAs<Expr>();
6315 }
6316
6317 InitializedEntity Entity =
6318 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6319 Type: ProtoArgType)
6320 : InitializedEntity::InitializeParameter(
6321 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6322
6323 // Remember that parameter belongs to a CF audited API.
6324 if (CFAudited)
6325 Entity.setParameterCFAudited();
6326
6327 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6328 // function boundaries is a common oversight.
6329 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6330 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6331 bool isPedantic =
6332 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6333 Diag(Loc: Arg->getExprLoc(),
6334 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6335 : diag::warn_obt_discarded_at_function_boundary)
6336 << Arg->getType() << ProtoArgType;
6337 }
6338
6339 ExprResult ArgE = PerformCopyInitialization(
6340 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6341 if (ArgE.isInvalid())
6342 return true;
6343
6344 Arg = ArgE.getAs<Expr>();
6345 } else {
6346 assert(Param && "can't use default arguments without a known callee");
6347
6348 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6349 if (ArgExpr.isInvalid())
6350 return true;
6351
6352 Arg = ArgExpr.getAs<Expr>();
6353 }
6354
6355 // Check for array bounds violations for each argument to the call. This
6356 // check only triggers warnings when the argument isn't a more complex Expr
6357 // with its own checking, such as a BinaryOperator.
6358 CheckArrayAccess(E: Arg);
6359
6360 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6361 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6362
6363 AllArgs.push_back(Elt: Arg);
6364 }
6365
6366 // If this is a variadic call, handle args passed through "...".
6367 if (CallType != VariadicCallType::DoesNotApply) {
6368 // Assume that extern "C" functions with variadic arguments that
6369 // return __unknown_anytype aren't *really* variadic.
6370 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6371 FDecl->isExternC()) {
6372 for (Expr *A : Args.slice(N: ArgIx)) {
6373 QualType paramType; // ignored
6374 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6375 Invalid |= arg.isInvalid();
6376 AllArgs.push_back(Elt: arg.get());
6377 }
6378
6379 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6380 } else {
6381 for (Expr *A : Args.slice(N: ArgIx)) {
6382 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6383 Invalid |= Arg.isInvalid();
6384 AllArgs.push_back(Elt: Arg.get());
6385 }
6386 }
6387
6388 // Check for array bounds violations.
6389 for (Expr *A : Args.slice(N: ArgIx))
6390 CheckArrayAccess(E: A);
6391 }
6392 return Invalid;
6393}
6394
6395static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6396 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6397 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6398 TL = DTL.getOriginalLoc();
6399 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6400 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6401 << ATL.getLocalSourceRange();
6402}
6403
6404void
6405Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6406 ParmVarDecl *Param,
6407 const Expr *ArgExpr) {
6408 // Static array parameters are not supported in C++.
6409 if (!Param || getLangOpts().CPlusPlus)
6410 return;
6411
6412 QualType OrigTy = Param->getOriginalType();
6413
6414 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6415 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6416 return;
6417
6418 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6419 NPC: Expr::NPC_NeverValueDependent)) {
6420 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6421 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6422 return;
6423 }
6424
6425 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6426 if (!CAT)
6427 return;
6428
6429 const ConstantArrayType *ArgCAT =
6430 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6431 if (!ArgCAT)
6432 return;
6433
6434 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6435 T2: ArgCAT->getElementType())) {
6436 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6437 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6438 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6439 << (unsigned)CAT->getZExtSize() << 0;
6440 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6441 }
6442 return;
6443 }
6444
6445 std::optional<CharUnits> ArgSize =
6446 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6447 std::optional<CharUnits> ParmSize =
6448 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6449 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6450 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6451 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6452 << (unsigned)ParmSize->getQuantity() << 1;
6453 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6454 }
6455}
6456
6457/// Given a function expression of unknown-any type, try to rebuild it
6458/// to have a function type.
6459static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6460
6461/// Is the given type a placeholder that we need to lower out
6462/// immediately during argument processing?
6463static bool isPlaceholderToRemoveAsArg(QualType type) {
6464 // Placeholders are never sugared.
6465 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6466 if (!placeholder) return false;
6467
6468 switch (placeholder->getKind()) {
6469 // Ignore all the non-placeholder types.
6470#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6471 case BuiltinType::Id:
6472#include "clang/Basic/OpenCLImageTypes.def"
6473#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6474 case BuiltinType::Id:
6475#include "clang/Basic/OpenCLExtensionTypes.def"
6476 // In practice we'll never use this, since all SVE types are sugared
6477 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6478#define SVE_TYPE(Name, Id, SingletonId) \
6479 case BuiltinType::Id:
6480#include "clang/Basic/AArch64ACLETypes.def"
6481#define PPC_VECTOR_TYPE(Name, Id, Size) \
6482 case BuiltinType::Id:
6483#include "clang/Basic/PPCTypes.def"
6484#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6485#include "clang/Basic/RISCVVTypes.def"
6486#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6487#include "clang/Basic/WebAssemblyReferenceTypes.def"
6488#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6489#include "clang/Basic/AMDGPUTypes.def"
6490#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6491#include "clang/Basic/HLSLIntangibleTypes.def"
6492#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6493#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6494#include "clang/AST/BuiltinTypes.def"
6495 return false;
6496
6497 case BuiltinType::UnresolvedTemplate:
6498 // We cannot lower out overload sets; they might validly be resolved
6499 // by the call machinery.
6500 case BuiltinType::Overload:
6501 return false;
6502
6503 // Unbridged casts in ARC can be handled in some call positions and
6504 // should be left in place.
6505 case BuiltinType::ARCUnbridgedCast:
6506 return false;
6507
6508 // Pseudo-objects should be converted as soon as possible.
6509 case BuiltinType::PseudoObject:
6510 return true;
6511
6512 // The debugger mode could theoretically but currently does not try
6513 // to resolve unknown-typed arguments based on known parameter types.
6514 case BuiltinType::UnknownAny:
6515 return true;
6516
6517 // These are always invalid as call arguments and should be reported.
6518 case BuiltinType::BoundMember:
6519 case BuiltinType::BuiltinFn:
6520 case BuiltinType::IncompleteMatrixIdx:
6521 case BuiltinType::ArraySection:
6522 case BuiltinType::OMPArrayShaping:
6523 case BuiltinType::OMPIterator:
6524 return true;
6525
6526 }
6527 llvm_unreachable("bad builtin type kind");
6528}
6529
6530bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6531 // Apply this processing to all the arguments at once instead of
6532 // dying at the first failure.
6533 bool hasInvalid = false;
6534 for (size_t i = 0, e = args.size(); i != e; i++) {
6535 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6536 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6537 if (result.isInvalid()) hasInvalid = true;
6538 else args[i] = result.get();
6539 }
6540 }
6541 return hasInvalid;
6542}
6543
6544/// If a builtin function has a pointer argument with no explicit address
6545/// space, then it should be able to accept a pointer to any address
6546/// space as input. In order to do this, we need to replace the
6547/// standard builtin declaration with one that uses the same address space
6548/// as the call.
6549///
6550/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6551/// it does not contain any pointer arguments without
6552/// an address space qualifer. Otherwise the rewritten
6553/// FunctionDecl is returned.
6554/// TODO: Handle pointer return types.
6555static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6556 FunctionDecl *FDecl,
6557 MultiExprArg ArgExprs) {
6558
6559 QualType DeclType = FDecl->getType();
6560 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6561
6562 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6563 ArgExprs.size() < FT->getNumParams())
6564 return nullptr;
6565
6566 bool NeedsNewDecl = false;
6567 unsigned i = 0;
6568 SmallVector<QualType, 8> OverloadParams;
6569
6570 {
6571 // The lvalue conversions in this loop are only for type resolution and
6572 // don't actually occur.
6573 EnterExpressionEvaluationContext Unevaluated(
6574 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6575 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6576
6577 for (QualType ParamType : FT->param_types()) {
6578
6579 // Convert array arguments to pointer to simplify type lookup.
6580 ExprResult ArgRes =
6581 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6582 if (ArgRes.isInvalid())
6583 return nullptr;
6584 Expr *Arg = ArgRes.get();
6585 QualType ArgType = Arg->getType();
6586 if (!ParamType->isPointerType() ||
6587 ParamType->getPointeeType().hasAddressSpace() ||
6588 !ArgType->isPointerType() ||
6589 !ArgType->getPointeeType().hasAddressSpace() ||
6590 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6591 OverloadParams.push_back(Elt: ParamType);
6592 continue;
6593 }
6594
6595 QualType PointeeType = ParamType->getPointeeType();
6596 NeedsNewDecl = true;
6597 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6598
6599 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6600 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6601 }
6602 }
6603
6604 if (!NeedsNewDecl)
6605 return nullptr;
6606
6607 FunctionProtoType::ExtProtoInfo EPI;
6608 EPI.Variadic = FT->isVariadic();
6609 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6610 Args: OverloadParams, EPI);
6611 DeclContext *Parent = FDecl->getParent();
6612 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6613 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6614 N: FDecl->getIdentifier(), T: OverloadTy,
6615 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6616 isInlineSpecified: false,
6617 /*hasPrototype=*/hasWrittenPrototype: true);
6618 SmallVector<ParmVarDecl*, 16> Params;
6619 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6620 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6621 QualType ParamType = FT->getParamType(i);
6622 ParmVarDecl *Parm =
6623 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6624 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6625 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6626 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6627 Params.push_back(Elt: Parm);
6628 }
6629 OverloadDecl->setParams(Params);
6630 // We cannot merge host/device attributes of redeclarations. They have to
6631 // be consistent when created.
6632 if (Sema->LangOpts.CUDA) {
6633 if (FDecl->hasAttr<CUDAHostAttr>())
6634 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6635 if (FDecl->hasAttr<CUDADeviceAttr>())
6636 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6637 }
6638 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6639 return OverloadDecl;
6640}
6641
6642static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6643 FunctionDecl *Callee,
6644 MultiExprArg ArgExprs) {
6645 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6646 // similar attributes) really don't like it when functions are called with an
6647 // invalid number of args.
6648 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6649 /*PartialOverloading=*/false) &&
6650 !Callee->isVariadic())
6651 return;
6652 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6653 return;
6654
6655 if (const EnableIfAttr *Attr =
6656 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6657 S.Diag(Loc: Fn->getBeginLoc(),
6658 DiagID: isa<CXXMethodDecl>(Val: Callee)
6659 ? diag::err_ovl_no_viable_member_function_in_call
6660 : diag::err_ovl_no_viable_function_in_call)
6661 << Callee << Callee->getSourceRange();
6662 S.Diag(Loc: Callee->getLocation(),
6663 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6664 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6665 return;
6666 }
6667}
6668
6669static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6670 const UnresolvedMemberExpr *const UME, Sema &S) {
6671
6672 const auto GetFunctionLevelDCIfCXXClass =
6673 [](Sema &S) -> const CXXRecordDecl * {
6674 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6675 if (!DC || !DC->getParent())
6676 return nullptr;
6677
6678 // If the call to some member function was made from within a member
6679 // function body 'M' return return 'M's parent.
6680 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6681 return MD->getParent()->getCanonicalDecl();
6682 // else the call was made from within a default member initializer of a
6683 // class, so return the class.
6684 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6685 return RD->getCanonicalDecl();
6686 return nullptr;
6687 };
6688 // If our DeclContext is neither a member function nor a class (in the
6689 // case of a lambda in a default member initializer), we can't have an
6690 // enclosing 'this'.
6691
6692 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6693 if (!CurParentClass)
6694 return false;
6695
6696 // The naming class for implicit member functions call is the class in which
6697 // name lookup starts.
6698 const CXXRecordDecl *const NamingClass =
6699 UME->getNamingClass()->getCanonicalDecl();
6700 assert(NamingClass && "Must have naming class even for implicit access");
6701
6702 // If the unresolved member functions were found in a 'naming class' that is
6703 // related (either the same or derived from) to the class that contains the
6704 // member function that itself contained the implicit member access.
6705
6706 return CurParentClass == NamingClass ||
6707 CurParentClass->isDerivedFrom(Base: NamingClass);
6708}
6709
6710static void
6711tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6712 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6713
6714 if (!UME)
6715 return;
6716
6717 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6718 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6719 // already been captured, or if this is an implicit member function call (if
6720 // it isn't, an attempt to capture 'this' should already have been made).
6721 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6722 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6723 return;
6724
6725 // Check if the naming class in which the unresolved members were found is
6726 // related (same as or is a base of) to the enclosing class.
6727
6728 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6729 return;
6730
6731
6732 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6733 // If the enclosing function is not dependent, then this lambda is
6734 // capture ready, so if we can capture this, do so.
6735 if (!EnclosingFunctionCtx->isDependentContext()) {
6736 // If the current lambda and all enclosing lambdas can capture 'this' -
6737 // then go ahead and capture 'this' (since our unresolved overload set
6738 // contains at least one non-static member function).
6739 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6740 S.CheckCXXThisCapture(Loc: CallLoc);
6741 } else if (S.CurContext->isDependentContext()) {
6742 // ... since this is an implicit member reference, that might potentially
6743 // involve a 'this' capture, mark 'this' for potential capture in
6744 // enclosing lambdas.
6745 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6746 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6747 }
6748}
6749
6750// Once a call is fully resolved, warn for unqualified calls to specific
6751// C++ standard functions, like move and forward.
6752static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6753 const CallExpr *Call) {
6754 // We are only checking unary move and forward so exit early here.
6755 if (Call->getNumArgs() != 1)
6756 return;
6757
6758 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6759 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6760 return;
6761 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6762 if (!DRE || !DRE->getLocation().isValid())
6763 return;
6764
6765 if (DRE->getQualifier())
6766 return;
6767
6768 const FunctionDecl *FD = Call->getDirectCallee();
6769 if (!FD)
6770 return;
6771
6772 // Only warn for some functions deemed more frequent or problematic.
6773 unsigned BuiltinID = FD->getBuiltinID();
6774 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6775 return;
6776
6777 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6778 << FD->getQualifiedNameAsString()
6779 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6780}
6781
6782ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6783 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6784 Expr *ExecConfig) {
6785 ExprResult Call =
6786 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6787 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6788 if (Call.isInvalid())
6789 return Call;
6790
6791 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6792 // language modes.
6793 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6794 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6795 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6796 << ULE->getName();
6797 }
6798
6799 if (LangOpts.OpenMP)
6800 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6801 ExecConfig);
6802 if (LangOpts.CPlusPlus) {
6803 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6804 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6805
6806 // If we previously found that the id-expression of this call refers to a
6807 // consteval function but the call is dependent, we should not treat is an
6808 // an invalid immediate call.
6809 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6810 DRE && Call.get()->isValueDependent()) {
6811 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6812 }
6813 }
6814 return Call;
6815}
6816
6817// Any type that could be used to form a callable expression
6818static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6819 QualType T = E->getType();
6820 if (T->isDependentType())
6821 return true;
6822
6823 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6824 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6825 T->isFunctionType() || T->isFunctionReferenceType() ||
6826 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6827 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6828 return true;
6829
6830 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6831 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6832}
6833
6834ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6835 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6836 Expr *ExecConfig, bool IsExecConfig,
6837 bool AllowRecovery) {
6838 // Since this might be a postfix expression, get rid of ParenListExprs.
6839 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6840 if (Result.isInvalid()) return ExprError();
6841 Fn = Result.get();
6842
6843 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6844 // later, when we check boolean conditions, for now we merely forward it
6845 // without any additional checking.
6846 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6847 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6848 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6849
6850 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6851 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6852 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6853 return CallExpr::Create(
6854 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6855 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6856 }
6857 }
6858
6859 if (CheckArgsForPlaceholders(args: ArgExprs))
6860 return ExprError();
6861
6862 // The result of __builtin_counted_by_ref cannot be used as a function
6863 // argument. It allows leaking and modification of bounds safety information.
6864 for (const Expr *Arg : ArgExprs)
6865 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6866 K: BuiltinCountedByRefKind::FunctionArg))
6867 return ExprError();
6868
6869 if (getLangOpts().CPlusPlus) {
6870 // If this is a pseudo-destructor expression, build the call immediately.
6871 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6872 if (!ArgExprs.empty()) {
6873 // Pseudo-destructor calls should not have any arguments.
6874 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6875 << FixItHint::CreateRemoval(
6876 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6877 ArgExprs.back()->getEndLoc()));
6878 }
6879
6880 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6881 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6882 }
6883 if (Fn->getType() == Context.PseudoObjectTy) {
6884 ExprResult result = CheckPlaceholderExpr(E: Fn);
6885 if (result.isInvalid()) return ExprError();
6886 Fn = result.get();
6887 }
6888
6889 // Determine whether this is a dependent call inside a C++ template,
6890 // in which case we won't do any semantic analysis now.
6891 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6892 if (ExecConfig) {
6893 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6894 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6895 Ty: Context.DependentTy, VK: VK_PRValue,
6896 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6897 } else {
6898
6899 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6900 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6901 CallLoc: Fn->getBeginLoc());
6902
6903 // If the type of the function itself is not dependent
6904 // check that it is a reasonable as a function, as type deduction
6905 // later assume the CallExpr has a sensible TYPE.
6906 if (!MayBeFunctionType(Context, E: Fn))
6907 return ExprError(
6908 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6909 << Fn->getType() << Fn->getSourceRange());
6910
6911 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6912 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6913 }
6914 }
6915
6916 // Determine whether this is a call to an object (C++ [over.call.object]).
6917 if (Fn->getType()->isRecordType())
6918 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6919 RParenLoc);
6920
6921 if (Fn->getType() == Context.UnknownAnyTy) {
6922 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6923 if (result.isInvalid()) return ExprError();
6924 Fn = result.get();
6925 }
6926
6927 if (Fn->getType() == Context.BoundMemberTy) {
6928 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6929 RParenLoc, ExecConfig, IsExecConfig,
6930 AllowRecovery);
6931 }
6932 }
6933
6934 // Check for overloaded calls. This can happen even in C due to extensions.
6935 if (Fn->getType() == Context.OverloadTy) {
6936 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6937
6938 // We aren't supposed to apply this logic if there's an '&' involved.
6939 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6940 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6941 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6942 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6943 OverloadExpr *ovl = find.Expression;
6944 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6945 return BuildOverloadedCallExpr(
6946 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6947 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6948 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6949 RParenLoc, ExecConfig, IsExecConfig,
6950 AllowRecovery);
6951 }
6952 }
6953
6954 // If we're directly calling a function, get the appropriate declaration.
6955 if (Fn->getType() == Context.UnknownAnyTy) {
6956 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6957 if (result.isInvalid()) return ExprError();
6958 Fn = result.get();
6959 }
6960
6961 Expr *NakedFn = Fn->IgnoreParens();
6962
6963 bool CallingNDeclIndirectly = false;
6964 NamedDecl *NDecl = nullptr;
6965 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6966 if (UnOp->getOpcode() == UO_AddrOf) {
6967 CallingNDeclIndirectly = true;
6968 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6969 }
6970 }
6971
6972 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6973 NDecl = DRE->getDecl();
6974
6975 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6976 if (FDecl && FDecl->getBuiltinID()) {
6977 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6978 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6979 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
6980 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
6981 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
6982 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6983 }
6984 }
6985
6986 // Rewrite the function decl for this builtin by replacing parameters
6987 // with no explicit address space with the address space of the arguments
6988 // in ArgExprs.
6989 if ((FDecl =
6990 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6991 NDecl = FDecl;
6992 Fn = DeclRefExpr::Create(
6993 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6994 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
6995 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6996 }
6997 }
6998 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6999 NDecl = ME->getMemberDecl();
7000
7001 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
7002 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7003 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
7004 return ExprError();
7005
7006 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
7007
7008 // If this expression is a call to a builtin function in HIP compilation,
7009 // allow a pointer-type argument to default address space to be passed as a
7010 // pointer-type parameter to a non-default address space. If Arg is declared
7011 // in the default address space and Param is declared in a non-default
7012 // address space, perform an implicit address space cast to the parameter
7013 // type.
7014 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7015 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7016 ++Idx) {
7017 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7018 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7019 !ArgExprs[Idx]->getType()->isPointerType())
7020 continue;
7021
7022 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7023 auto ArgTy = ArgExprs[Idx]->getType();
7024 auto ArgPtTy = ArgTy->getPointeeType();
7025 auto ArgAS = ArgPtTy.getAddressSpace();
7026
7027 // Add address space cast if target address spaces are different
7028 bool NeedImplicitASC =
7029 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7030 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7031 // or from specific AS which has target AS matching that of Param.
7032 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7033 if (!NeedImplicitASC)
7034 continue;
7035
7036 // First, ensure that the Arg is an RValue.
7037 if (ArgExprs[Idx]->isGLValue()) {
7038 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7039 if (Res.isInvalid())
7040 return ExprError();
7041 ArgExprs[Idx] = Res.get();
7042 }
7043
7044 // Construct a new arg type with address space of Param
7045 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7046 ArgPtQuals.setAddressSpace(ParamAS);
7047 auto NewArgPtTy =
7048 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7049 auto NewArgTy =
7050 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7051 Qs: ArgTy.getQualifiers());
7052
7053 // Finally perform an implicit address space cast
7054 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7055 CK: CK_AddressSpaceConversion)
7056 .get();
7057 }
7058 }
7059 }
7060
7061 if (Context.isDependenceAllowed() &&
7062 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7063 assert(!getLangOpts().CPlusPlus);
7064 assert((Fn->containsErrors() ||
7065 llvm::any_of(ArgExprs,
7066 [](clang::Expr *E) { return E->containsErrors(); })) &&
7067 "should only occur in error-recovery path.");
7068 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7069 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7070 }
7071 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7072 Config: ExecConfig, IsExecConfig);
7073}
7074
7075Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7076 MultiExprArg CallArgs) {
7077 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7078 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7079 Sema::LookupOrdinaryName);
7080 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7081
7082 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7083 assert(BuiltInDecl && "failed to find builtin declaration");
7084
7085 ExprResult DeclRef =
7086 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7087 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7088
7089 ExprResult Call =
7090 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7091
7092 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7093 return Call.get();
7094}
7095
7096ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7097 SourceLocation BuiltinLoc,
7098 SourceLocation RParenLoc) {
7099 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7100 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7101}
7102
7103ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7104 SourceLocation BuiltinLoc,
7105 SourceLocation RParenLoc) {
7106 ExprValueKind VK = VK_PRValue;
7107 ExprObjectKind OK = OK_Ordinary;
7108 QualType SrcTy = E->getType();
7109 if (!SrcTy->isDependentType() &&
7110 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7111 return ExprError(
7112 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7113 << DestTy << SrcTy << E->getSourceRange());
7114 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7115}
7116
7117ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7118 SourceLocation BuiltinLoc,
7119 SourceLocation RParenLoc) {
7120 TypeSourceInfo *TInfo;
7121 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7122 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7123}
7124
7125ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7126 SourceLocation LParenLoc,
7127 ArrayRef<Expr *> Args,
7128 SourceLocation RParenLoc, Expr *Config,
7129 bool IsExecConfig, ADLCallKind UsesADL) {
7130 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7131 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7132
7133 auto IsSJLJ = [&] {
7134 switch (BuiltinID) {
7135 case Builtin::BI__builtin_longjmp:
7136 case Builtin::BI__builtin_setjmp:
7137 case Builtin::BI__sigsetjmp:
7138 case Builtin::BI_longjmp:
7139 case Builtin::BI_setjmp:
7140 case Builtin::BIlongjmp:
7141 case Builtin::BIsetjmp:
7142 case Builtin::BIsiglongjmp:
7143 case Builtin::BIsigsetjmp:
7144 return true;
7145 default:
7146 return false;
7147 }
7148 };
7149
7150 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7151 if (!CurrentDefer.empty() && IsSJLJ()) {
7152 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7153 // for more than just blocks (e.g. lambdas, nested classes...).
7154 Scope *DeferParent = CurrentDefer.back().first;
7155 Scope *Block = CurScope->getBlockParent();
7156 if (DeferParent->Contains(rhs: *CurScope) &&
7157 (!Block || !DeferParent->Contains(rhs: *Block)))
7158 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7159 }
7160
7161 // Functions with 'interrupt' attribute cannot be called directly.
7162 if (FDecl) {
7163 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7164 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7165 return ExprError();
7166 }
7167 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7168 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7169 return ExprError();
7170 }
7171 }
7172
7173 // X86 interrupt handlers may only call routines with attribute
7174 // no_caller_saved_registers since there is no efficient way to
7175 // save and restore the non-GPR state.
7176 if (auto *Caller = getCurFunctionDecl()) {
7177 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7178 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7179 const TargetInfo &TI = Context.getTargetInfo();
7180 bool HasNonGPRRegisters =
7181 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7182 if (HasNonGPRRegisters &&
7183 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7184 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7185 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7186 if (FDecl)
7187 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7188 }
7189 }
7190 }
7191
7192 // Extract the return type from the builtin function pointer type.
7193 QualType ResultTy;
7194 if (BuiltinID)
7195 ResultTy = FDecl->getCallResultType();
7196 else
7197 ResultTy = Context.BoolTy;
7198
7199 // Promote the function operand.
7200 // We special-case function promotion here because we only allow promoting
7201 // builtin functions to function pointers in the callee of a call.
7202 ExprResult Result;
7203 if (BuiltinID &&
7204 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7205 // FIXME Several builtins still have setType in
7206 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7207 // Builtins.td to ensure they are correct before removing setType calls.
7208 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7209 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7210 } else
7211 Result = CallExprUnaryConversions(E: Fn);
7212 if (Result.isInvalid())
7213 return ExprError();
7214 Fn = Result.get();
7215
7216 // Check for a valid function type, but only if it is not a builtin which
7217 // requires custom type checking. These will be handled by
7218 // CheckBuiltinFunctionCall below just after creation of the call expression.
7219 const FunctionType *FuncT = nullptr;
7220 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7221 retry:
7222 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7223 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7224 // have type pointer to function".
7225 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7226 if (!FuncT)
7227 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7228 << Fn->getType() << Fn->getSourceRange());
7229 } else if (const BlockPointerType *BPT =
7230 Fn->getType()->getAs<BlockPointerType>()) {
7231 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7232 } else {
7233 // Handle calls to expressions of unknown-any type.
7234 if (Fn->getType() == Context.UnknownAnyTy) {
7235 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7236 if (rewrite.isInvalid())
7237 return ExprError();
7238 Fn = rewrite.get();
7239 goto retry;
7240 }
7241
7242 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7243 << Fn->getType() << Fn->getSourceRange());
7244 }
7245 }
7246
7247 // Get the number of parameters in the function prototype, if any.
7248 // We will allocate space for max(Args.size(), NumParams) arguments
7249 // in the call expression.
7250 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7251 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7252
7253 CallExpr *TheCall;
7254 if (Config) {
7255 assert(UsesADL == ADLCallKind::NotADL &&
7256 "CUDAKernelCallExpr should not use ADL");
7257 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7258 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7259 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7260 } else {
7261 TheCall =
7262 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7263 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7264 }
7265
7266 // Bail out early if calling a builtin with custom type checking.
7267 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7268 // For HLSL builtin aliases, the call was resolved via overload resolution
7269 // which may have selected a conversion sequence (e.g., vector-to-scalar
7270 // truncation). Convert arguments to match the declared prototype before
7271 // the custom type checker runs, otherwise the builtin will operate on
7272 // the unconverted argument types.
7273 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7274 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7275 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7276 IsExecConfig))
7277 return ExprError();
7278 }
7279 }
7280 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7281 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7282 E = CheckForImmediateInvocation(E, Decl: FDecl);
7283 return E;
7284 }
7285
7286 if (getLangOpts().CUDA) {
7287 if (Config) {
7288 // CUDA: Kernel calls must be to global functions
7289 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7290 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7291 << FDecl << Fn->getSourceRange());
7292
7293 // CUDA: Kernel function must have 'void' return type
7294 if (!FuncT->getReturnType()->isVoidType() &&
7295 !FuncT->getReturnType()->getAs<AutoType>() &&
7296 !FuncT->getReturnType()->isInstantiationDependentType())
7297 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7298 << Fn->getType() << Fn->getSourceRange());
7299 } else {
7300 // CUDA: Calls to global functions must be configured
7301 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7302 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7303 << FDecl << Fn->getSourceRange());
7304 }
7305 }
7306
7307 // Check for a valid return type
7308 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7309 FD: FDecl))
7310 return ExprError();
7311
7312 // We know the result type of the call, set it.
7313 TheCall->setType(FuncT->getCallResultType(Context));
7314 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7315
7316 // WebAssembly tables can't be used as arguments.
7317 if (Context.getTargetInfo().getTriple().isWasm()) {
7318 for (const Expr *Arg : Args) {
7319 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7320 return ExprError(Diag(Loc: Arg->getExprLoc(),
7321 DiagID: diag::err_wasm_table_as_function_parameter));
7322 }
7323 }
7324 }
7325
7326 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7327 // replaces sampler DeclRefExprs with their integer initializers.
7328 if (getLangOpts().OpenCL && FDecl) {
7329 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7330 }
7331
7332 if (Proto) {
7333 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7334 IsExecConfig))
7335 return ExprError();
7336 } else {
7337 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7338
7339 if (FDecl) {
7340 // Check if we have too few/too many template arguments, based
7341 // on our knowledge of the function definition.
7342 const FunctionDecl *Def = nullptr;
7343 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7344 Proto = Def->getType()->getAs<FunctionProtoType>();
7345 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7346 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7347 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7348 }
7349
7350 // If the function we're calling isn't a function prototype, but we have
7351 // a function prototype from a prior declaratiom, use that prototype.
7352 if (!FDecl->hasPrototype())
7353 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7354 }
7355
7356 // If we still haven't found a prototype to use but there are arguments to
7357 // the call, diagnose this as calling a function without a prototype.
7358 // However, if we found a function declaration, check to see if
7359 // -Wdeprecated-non-prototype was disabled where the function was declared.
7360 // If so, we will silence the diagnostic here on the assumption that this
7361 // interface is intentional and the user knows what they're doing. We will
7362 // also silence the diagnostic if there is a function declaration but it
7363 // was implicitly defined (the user already gets diagnostics about the
7364 // creation of the implicit function declaration, so the additional warning
7365 // is not helpful).
7366 if (!Proto && !Args.empty() &&
7367 (!FDecl || (!FDecl->isImplicit() &&
7368 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7369 Loc: FDecl->getLocation()))))
7370 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7371 << (FDecl != nullptr) << FDecl;
7372
7373 // Promote the arguments (C99 6.5.2.2p6).
7374 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7375 Expr *Arg = Args[i];
7376
7377 if (Proto && i < Proto->getNumParams()) {
7378 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7379 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7380 ExprResult ArgE =
7381 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7382 if (ArgE.isInvalid())
7383 return true;
7384
7385 Arg = ArgE.getAs<Expr>();
7386
7387 } else {
7388 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7389
7390 if (ArgE.isInvalid())
7391 return true;
7392
7393 Arg = ArgE.getAs<Expr>();
7394 }
7395
7396 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7397 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7398 return ExprError();
7399
7400 TheCall->setArg(Arg: i, ArgExpr: Arg);
7401 }
7402 TheCall->computeDependence();
7403 }
7404
7405 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7406 if (Method->isImplicitObjectMemberFunction())
7407 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7408 << Fn->getSourceRange() << 0);
7409
7410 // Check for sentinels
7411 if (NDecl)
7412 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7413
7414 // Warn for unions passing across security boundary (CMSE).
7415 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7416 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7417 if (const auto *RT =
7418 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7419 if (RT->getDecl()->isOrContainsUnion())
7420 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7421 << 0 << i;
7422 }
7423 }
7424 }
7425
7426 // Do special checking on direct calls to functions.
7427 if (FDecl) {
7428 if (CheckFunctionCall(FDecl, TheCall, Proto))
7429 return ExprError();
7430
7431 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7432 checkFortifiedLibcArgument(FD: FDecl, TheCall);
7433
7434 if (BuiltinID)
7435 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7436 } else if (NDecl) {
7437 if (CheckPointerCall(NDecl, TheCall, Proto))
7438 return ExprError();
7439 } else {
7440 if (CheckOtherCall(TheCall, Proto))
7441 return ExprError();
7442 }
7443
7444 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7445}
7446
7447ExprResult
7448Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7449 SourceLocation RParenLoc, Expr *InitExpr) {
7450 assert(Ty && "ActOnCompoundLiteral(): missing type");
7451 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7452
7453 TypeSourceInfo *TInfo;
7454 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7455 if (!TInfo)
7456 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7457
7458 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7459}
7460
7461ExprResult
7462Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7463 SourceLocation RParenLoc, Expr *LiteralExpr) {
7464 QualType literalType = TInfo->getType();
7465
7466 if (literalType->isArrayType()) {
7467 if (RequireCompleteSizedType(
7468 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7469 DiagID: diag::err_array_incomplete_or_sizeless_type,
7470 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7471 return ExprError();
7472 if (literalType->isVariableArrayType()) {
7473 // C23 6.7.10p4: An entity of variable length array type shall not be
7474 // initialized except by an empty initializer.
7475 //
7476 // The C extension warnings are issued from ParseBraceInitializer() and
7477 // do not need to be issued here. However, we continue to issue an error
7478 // in the case there are initializers or we are compiling C++. We allow
7479 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7480 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7481 // FIXME: should we allow this construct in C++ when it makes sense to do
7482 // so?
7483 //
7484 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7485 // shall specify an object type or an array of unknown size, but not a
7486 // variable length array type. This seems odd, as it allows 'int a[size] =
7487 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7488 // says, this is what's implemented here for C (except for the extension
7489 // that permits constant foldable size arrays)
7490
7491 auto diagID = LangOpts.CPlusPlus
7492 ? diag::err_variable_object_no_init
7493 : diag::err_compound_literal_with_vla_type;
7494 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7495 FailedFoldDiagID: diagID))
7496 return ExprError();
7497 }
7498 } else if (!literalType->isDependentType() &&
7499 RequireCompleteType(Loc: LParenLoc, T: literalType,
7500 DiagID: diag::err_typecheck_decl_incomplete_type,
7501 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7502 return ExprError();
7503
7504 InitializedEntity Entity
7505 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7506 InitializationKind Kind
7507 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7508 TypeRange: SourceRange(LParenLoc, RParenLoc),
7509 /*InitList=*/true);
7510 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7511 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7512 ResultType: &literalType);
7513 if (Result.isInvalid())
7514 return ExprError();
7515 LiteralExpr = Result.get();
7516
7517 // We treat the compound literal as being at file scope if it's not in a
7518 // function or method body, or within the function's prototype scope. This
7519 // means the following compound literal is not at file scope:
7520 // void func(char *para[(int [1]){ 0 }[0]);
7521 const Scope *S = getCurScope();
7522 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7523 !S->isInCFunctionScope() &&
7524 (!S || !S->isFunctionPrototypeScope());
7525
7526 // In C, compound literals are l-values for some reason.
7527 // For GCC compatibility, in C++, file-scope array compound literals with
7528 // constant initializers are also l-values, and compound literals are
7529 // otherwise prvalues.
7530 //
7531 // (GCC also treats C++ list-initialized file-scope array prvalues with
7532 // constant initializers as l-values, but that's non-conforming, so we don't
7533 // follow it there.)
7534 //
7535 // FIXME: It would be better to handle the lvalue cases as materializing and
7536 // lifetime-extending a temporary object, but our materialized temporaries
7537 // representation only supports lifetime extension from a variable, not "out
7538 // of thin air".
7539 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7540 // is bound to the result of applying array-to-pointer decay to the compound
7541 // literal.
7542 // FIXME: GCC supports compound literals of reference type, which should
7543 // obviously have a value kind derived from the kind of reference involved.
7544 ExprValueKind VK =
7545 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7546 ? VK_PRValue
7547 : VK_LValue;
7548
7549 // C99 6.5.2.5
7550 // "If the compound literal occurs outside the body of a function, the
7551 // initializer list shall consist of constant expressions."
7552 if (IsFileScope)
7553 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7554 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7555 Expr *Init = ILE->getInit(Init: i);
7556 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7557 !Init->isConstantInitializer(Ctx&: Context)) {
7558 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7559 << Init->getSourceBitField();
7560 return ExprError();
7561 }
7562
7563 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7564 }
7565
7566 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7567 LiteralExpr, IsFileScope);
7568 if (IsFileScope) {
7569 if (!LiteralExpr->isTypeDependent() &&
7570 !LiteralExpr->isValueDependent() &&
7571 !literalType->isDependentType()) // C99 6.5.2.5p3
7572 if (CheckForConstantInitializer(Init: LiteralExpr))
7573 return ExprError();
7574 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7575 literalType.getAddressSpace() != LangAS::Default) {
7576 // Embedded-C extensions to C99 6.5.2.5:
7577 // "If the compound literal occurs inside the body of a function, the
7578 // type name shall not be qualified by an address-space qualifier."
7579 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7580 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7581 return ExprError();
7582 }
7583
7584 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7585 // Compound literals that have automatic storage duration are destroyed at
7586 // the end of the scope in C; in C++, they're just temporaries.
7587
7588 // Emit diagnostics if it is or contains a C union type that is non-trivial
7589 // to destruct.
7590 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7591 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7592 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7593 NonTrivialKind: NTCUK_Destruct);
7594
7595 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7596 if (literalType.isDestructedType()) {
7597 Cleanup.setExprNeedsCleanups(true);
7598 ExprCleanupObjects.push_back(Elt: E);
7599 getCurFunction()->setHasBranchProtectedScope();
7600 }
7601 }
7602
7603 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7604 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7605 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7606 Loc: E->getInitializer()->getExprLoc());
7607
7608 return MaybeBindToTemporary(E);
7609}
7610
7611ExprResult
7612Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7613 SourceLocation RBraceLoc) {
7614 // Only produce each kind of designated initialization diagnostic once.
7615 SourceLocation FirstDesignator;
7616 bool DiagnosedArrayDesignator = false;
7617 bool DiagnosedNestedDesignator = false;
7618 bool DiagnosedMixedDesignator = false;
7619
7620 // Check that any designated initializers are syntactically valid in the
7621 // current language mode.
7622 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7623 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7624 if (FirstDesignator.isInvalid())
7625 FirstDesignator = DIE->getBeginLoc();
7626
7627 if (!getLangOpts().CPlusPlus)
7628 break;
7629
7630 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7631 DiagnosedNestedDesignator = true;
7632 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7633 << DIE->getDesignatorsSourceRange();
7634 }
7635
7636 for (auto &Desig : DIE->designators()) {
7637 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7638 DiagnosedArrayDesignator = true;
7639 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7640 << Desig.getSourceRange();
7641 }
7642 }
7643
7644 if (!DiagnosedMixedDesignator &&
7645 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7646 DiagnosedMixedDesignator = true;
7647 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7648 << DIE->getSourceRange();
7649 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7650 << InitArgList[0]->getSourceRange();
7651 }
7652 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7653 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7654 DiagnosedMixedDesignator = true;
7655 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7656 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7657 << DIE->getSourceRange();
7658 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7659 << InitArgList[I]->getSourceRange();
7660 }
7661 }
7662
7663 if (FirstDesignator.isValid()) {
7664 // Only diagnose designated initiaization as a C++20 extension if we didn't
7665 // already diagnose use of (non-C++20) C99 designator syntax.
7666 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7667 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7668 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7669 ? diag::warn_cxx17_compat_designated_init
7670 : diag::ext_cxx_designated_init);
7671 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7672 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7673 }
7674 }
7675
7676 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7677}
7678
7679ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7680 MultiExprArg InitArgList,
7681 SourceLocation RBraceLoc, bool IsExplicit) {
7682 // Semantic analysis for initializers is done by ActOnDeclarator() and
7683 // CheckInitializer() - it requires knowledge of the object being initialized.
7684
7685 // Immediately handle non-overload placeholders. Overloads can be
7686 // resolved contextually, but everything else here can't.
7687 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7688 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7689 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7690
7691 // Ignore failures; dropping the entire initializer list because
7692 // of one failure would be terrible for indexing/etc.
7693 if (result.isInvalid()) continue;
7694
7695 InitArgList[I] = result.get();
7696 }
7697 }
7698
7699 InitListExpr *E = new (Context)
7700 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7701 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7702 return E;
7703}
7704
7705void Sema::maybeExtendBlockObject(ExprResult &E) {
7706 assert(E.get()->getType()->isBlockPointerType());
7707 assert(E.get()->isPRValue());
7708
7709 // Only do this in an r-value context.
7710 if (!getLangOpts().ObjCAutoRefCount) return;
7711
7712 E = ImplicitCastExpr::Create(
7713 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7714 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7715 Cleanup.setExprNeedsCleanups(true);
7716}
7717
7718CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7719 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7720 // Also, callers should have filtered out the invalid cases with
7721 // pointers. Everything else should be possible.
7722
7723 QualType SrcTy = Src.get()->getType();
7724 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7725 return CK_NoOp;
7726
7727 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7728 case Type::STK_MemberPointer:
7729 llvm_unreachable("member pointer type in C");
7730
7731 case Type::STK_CPointer:
7732 case Type::STK_BlockPointer:
7733 case Type::STK_ObjCObjectPointer:
7734 switch (DestTy->getScalarTypeKind()) {
7735 case Type::STK_CPointer: {
7736 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7737 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7738 if (SrcAS != DestAS)
7739 return CK_AddressSpaceConversion;
7740 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7741 return CK_NoOp;
7742 return CK_BitCast;
7743 }
7744 case Type::STK_BlockPointer:
7745 return (SrcKind == Type::STK_BlockPointer
7746 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7747 case Type::STK_ObjCObjectPointer:
7748 if (SrcKind == Type::STK_ObjCObjectPointer)
7749 return CK_BitCast;
7750 if (SrcKind == Type::STK_CPointer)
7751 return CK_CPointerToObjCPointerCast;
7752 maybeExtendBlockObject(E&: Src);
7753 return CK_BlockPointerToObjCPointerCast;
7754 case Type::STK_Bool:
7755 return CK_PointerToBoolean;
7756 case Type::STK_Integral:
7757 return CK_PointerToIntegral;
7758 case Type::STK_Floating:
7759 case Type::STK_FloatingComplex:
7760 case Type::STK_IntegralComplex:
7761 case Type::STK_MemberPointer:
7762 case Type::STK_FixedPoint:
7763 llvm_unreachable("illegal cast from pointer");
7764 }
7765 llvm_unreachable("Should have returned before this");
7766
7767 case Type::STK_FixedPoint:
7768 switch (DestTy->getScalarTypeKind()) {
7769 case Type::STK_FixedPoint:
7770 return CK_FixedPointCast;
7771 case Type::STK_Bool:
7772 return CK_FixedPointToBoolean;
7773 case Type::STK_Integral:
7774 return CK_FixedPointToIntegral;
7775 case Type::STK_Floating:
7776 return CK_FixedPointToFloating;
7777 case Type::STK_IntegralComplex:
7778 case Type::STK_FloatingComplex:
7779 Diag(Loc: Src.get()->getExprLoc(),
7780 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7781 << DestTy;
7782 return CK_IntegralCast;
7783 case Type::STK_CPointer:
7784 case Type::STK_ObjCObjectPointer:
7785 case Type::STK_BlockPointer:
7786 case Type::STK_MemberPointer:
7787 llvm_unreachable("illegal cast to pointer type");
7788 }
7789 llvm_unreachable("Should have returned before this");
7790
7791 case Type::STK_Bool: // casting from bool is like casting from an integer
7792 case Type::STK_Integral:
7793 switch (DestTy->getScalarTypeKind()) {
7794 case Type::STK_CPointer:
7795 case Type::STK_ObjCObjectPointer:
7796 case Type::STK_BlockPointer:
7797 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7798 NPC: Expr::NPC_ValueDependentIsNull))
7799 return CK_NullToPointer;
7800 return CK_IntegralToPointer;
7801 case Type::STK_Bool:
7802 return CK_IntegralToBoolean;
7803 case Type::STK_Integral:
7804 return CK_IntegralCast;
7805 case Type::STK_Floating:
7806 return CK_IntegralToFloating;
7807 case Type::STK_IntegralComplex:
7808 Src = ImpCastExprToType(E: Src.get(),
7809 Type: DestTy->castAs<ComplexType>()->getElementType(),
7810 CK: CK_IntegralCast);
7811 return CK_IntegralRealToComplex;
7812 case Type::STK_FloatingComplex:
7813 Src = ImpCastExprToType(E: Src.get(),
7814 Type: DestTy->castAs<ComplexType>()->getElementType(),
7815 CK: CK_IntegralToFloating);
7816 return CK_FloatingRealToComplex;
7817 case Type::STK_MemberPointer:
7818 llvm_unreachable("member pointer type in C");
7819 case Type::STK_FixedPoint:
7820 return CK_IntegralToFixedPoint;
7821 }
7822 llvm_unreachable("Should have returned before this");
7823
7824 case Type::STK_Floating:
7825 switch (DestTy->getScalarTypeKind()) {
7826 case Type::STK_Floating:
7827 return CK_FloatingCast;
7828 case Type::STK_Bool:
7829 return CK_FloatingToBoolean;
7830 case Type::STK_Integral:
7831 return CK_FloatingToIntegral;
7832 case Type::STK_FloatingComplex:
7833 Src = ImpCastExprToType(E: Src.get(),
7834 Type: DestTy->castAs<ComplexType>()->getElementType(),
7835 CK: CK_FloatingCast);
7836 return CK_FloatingRealToComplex;
7837 case Type::STK_IntegralComplex:
7838 Src = ImpCastExprToType(E: Src.get(),
7839 Type: DestTy->castAs<ComplexType>()->getElementType(),
7840 CK: CK_FloatingToIntegral);
7841 return CK_IntegralRealToComplex;
7842 case Type::STK_CPointer:
7843 case Type::STK_ObjCObjectPointer:
7844 case Type::STK_BlockPointer:
7845 llvm_unreachable("valid float->pointer cast?");
7846 case Type::STK_MemberPointer:
7847 llvm_unreachable("member pointer type in C");
7848 case Type::STK_FixedPoint:
7849 return CK_FloatingToFixedPoint;
7850 }
7851 llvm_unreachable("Should have returned before this");
7852
7853 case Type::STK_FloatingComplex:
7854 switch (DestTy->getScalarTypeKind()) {
7855 case Type::STK_FloatingComplex:
7856 return CK_FloatingComplexCast;
7857 case Type::STK_IntegralComplex:
7858 return CK_FloatingComplexToIntegralComplex;
7859 case Type::STK_Floating: {
7860 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7861 if (Context.hasSameType(T1: ET, T2: DestTy))
7862 return CK_FloatingComplexToReal;
7863 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7864 return CK_FloatingCast;
7865 }
7866 case Type::STK_Bool:
7867 return CK_FloatingComplexToBoolean;
7868 case Type::STK_Integral:
7869 Src = ImpCastExprToType(E: Src.get(),
7870 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7871 CK: CK_FloatingComplexToReal);
7872 return CK_FloatingToIntegral;
7873 case Type::STK_CPointer:
7874 case Type::STK_ObjCObjectPointer:
7875 case Type::STK_BlockPointer:
7876 llvm_unreachable("valid complex float->pointer cast?");
7877 case Type::STK_MemberPointer:
7878 llvm_unreachable("member pointer type in C");
7879 case Type::STK_FixedPoint:
7880 Diag(Loc: Src.get()->getExprLoc(),
7881 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7882 << SrcTy;
7883 return CK_IntegralCast;
7884 }
7885 llvm_unreachable("Should have returned before this");
7886
7887 case Type::STK_IntegralComplex:
7888 switch (DestTy->getScalarTypeKind()) {
7889 case Type::STK_FloatingComplex:
7890 return CK_IntegralComplexToFloatingComplex;
7891 case Type::STK_IntegralComplex:
7892 return CK_IntegralComplexCast;
7893 case Type::STK_Integral: {
7894 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7895 if (Context.hasSameType(T1: ET, T2: DestTy))
7896 return CK_IntegralComplexToReal;
7897 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7898 return CK_IntegralCast;
7899 }
7900 case Type::STK_Bool:
7901 return CK_IntegralComplexToBoolean;
7902 case Type::STK_Floating:
7903 Src = ImpCastExprToType(E: Src.get(),
7904 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7905 CK: CK_IntegralComplexToReal);
7906 return CK_IntegralToFloating;
7907 case Type::STK_CPointer:
7908 case Type::STK_ObjCObjectPointer:
7909 case Type::STK_BlockPointer:
7910 llvm_unreachable("valid complex int->pointer cast?");
7911 case Type::STK_MemberPointer:
7912 llvm_unreachable("member pointer type in C");
7913 case Type::STK_FixedPoint:
7914 Diag(Loc: Src.get()->getExprLoc(),
7915 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7916 << SrcTy;
7917 return CK_IntegralCast;
7918 }
7919 llvm_unreachable("Should have returned before this");
7920 }
7921
7922 llvm_unreachable("Unhandled scalar cast");
7923}
7924
7925static bool breakDownVectorType(QualType type, uint64_t &len,
7926 QualType &eltType) {
7927 // Vectors are simple.
7928 if (const VectorType *vecType = type->getAs<VectorType>()) {
7929 len = vecType->getNumElements();
7930 eltType = vecType->getElementType();
7931 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7932 return true;
7933 }
7934
7935 // We allow lax conversion to and from non-vector types, but only if
7936 // they're real types (i.e. non-complex, non-pointer scalar types).
7937 if (!type->isRealType()) return false;
7938
7939 len = 1;
7940 eltType = type;
7941 return true;
7942}
7943
7944bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7945 assert(srcTy->isVectorType() || destTy->isVectorType());
7946
7947 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7948 if (!FirstType->isSVESizelessBuiltinType())
7949 return false;
7950
7951 const auto *VecTy = SecondType->getAs<VectorType>();
7952 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7953 };
7954
7955 return ValidScalableConversion(srcTy, destTy) ||
7956 ValidScalableConversion(destTy, srcTy);
7957}
7958
7959bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7960 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7961 return false;
7962
7963 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7964 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7965
7966 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7967 matSrcType->getNumColumns() == matDestType->getNumColumns();
7968}
7969
7970bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7971 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7972
7973 uint64_t SrcLen, DestLen;
7974 QualType SrcEltTy, DestEltTy;
7975 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7976 return false;
7977 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7978 return false;
7979
7980 // ASTContext::getTypeSize will return the size rounded up to a
7981 // power of 2, so instead of using that, we need to use the raw
7982 // element size multiplied by the element count.
7983 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7984 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7985
7986 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7987}
7988
7989bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7990 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7991 "expected at least one type to be a vector here");
7992
7993 bool IsSrcTyAltivec =
7994 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7995 VectorKind::AltiVecVector) ||
7996 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7997 VectorKind::AltiVecBool) ||
7998 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7999 VectorKind::AltiVecPixel));
8000
8001 bool IsDestTyAltivec = DestTy->isVectorType() &&
8002 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8003 VectorKind::AltiVecVector) ||
8004 (DestTy->castAs<VectorType>()->getVectorKind() ==
8005 VectorKind::AltiVecBool) ||
8006 (DestTy->castAs<VectorType>()->getVectorKind() ==
8007 VectorKind::AltiVecPixel));
8008
8009 return (IsSrcTyAltivec || IsDestTyAltivec);
8010}
8011
8012bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8013 assert(destTy->isVectorType() || srcTy->isVectorType());
8014
8015 // Disallow lax conversions between scalars and ExtVectors (these
8016 // conversions are allowed for other vector types because common headers
8017 // depend on them). Most scalar OP ExtVector cases are handled by the
8018 // splat path anyway, which does what we want (convert, not bitcast).
8019 // What this rules out for ExtVectors is crazy things like char4*float.
8020 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8021 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8022
8023 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8024}
8025
8026bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8027 assert(destTy->isVectorType() || srcTy->isVectorType());
8028
8029 switch (Context.getLangOpts().getLaxVectorConversions()) {
8030 case LangOptions::LaxVectorConversionKind::None:
8031 return false;
8032
8033 case LangOptions::LaxVectorConversionKind::Integer:
8034 if (!srcTy->isIntegralOrEnumerationType()) {
8035 auto *Vec = srcTy->getAs<VectorType>();
8036 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8037 return false;
8038 }
8039 if (!destTy->isIntegralOrEnumerationType()) {
8040 auto *Vec = destTy->getAs<VectorType>();
8041 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8042 return false;
8043 }
8044 // OK, integer (vector) -> integer (vector) bitcast.
8045 break;
8046
8047 case LangOptions::LaxVectorConversionKind::All:
8048 break;
8049 }
8050
8051 return areLaxCompatibleVectorTypes(srcTy, destTy);
8052}
8053
8054bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8055 CastKind &Kind) {
8056 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8057 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8058 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8059 << DestTy << SrcTy << R;
8060 }
8061 } else if (SrcTy->isMatrixType()) {
8062 return Diag(Loc: R.getBegin(),
8063 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8064 << SrcTy << DestTy << R;
8065 } else if (DestTy->isMatrixType()) {
8066 return Diag(Loc: R.getBegin(),
8067 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8068 << DestTy << SrcTy << R;
8069 }
8070
8071 Kind = CK_MatrixCast;
8072 return false;
8073}
8074
8075bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8076 CastKind &Kind) {
8077 assert(VectorTy->isVectorType() && "Not a vector type!");
8078
8079 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8080 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8081 return Diag(Loc: R.getBegin(),
8082 DiagID: Ty->isVectorType() ?
8083 diag::err_invalid_conversion_between_vectors :
8084 diag::err_invalid_conversion_between_vector_and_integer)
8085 << VectorTy << Ty << R;
8086 } else
8087 return Diag(Loc: R.getBegin(),
8088 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8089 << VectorTy << Ty << R;
8090
8091 Kind = CK_BitCast;
8092 return false;
8093}
8094
8095ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8096 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8097
8098 if (DestElemTy == SplattedExpr->getType())
8099 return SplattedExpr;
8100
8101 assert(DestElemTy->isFloatingType() ||
8102 DestElemTy->isIntegralOrEnumerationType());
8103
8104 CastKind CK;
8105 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8106 // OpenCL requires that we convert `true` boolean expressions to -1, but
8107 // only when splatting vectors.
8108 if (DestElemTy->isFloatingType()) {
8109 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8110 // in two steps: boolean to signed integral, then to floating.
8111 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8112 CK: CK_BooleanToSignedIntegral);
8113 SplattedExpr = CastExprRes.get();
8114 CK = CK_IntegralToFloating;
8115 } else {
8116 CK = CK_BooleanToSignedIntegral;
8117 }
8118 } else {
8119 ExprResult CastExprRes = SplattedExpr;
8120 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8121 if (CastExprRes.isInvalid())
8122 return ExprError();
8123 SplattedExpr = CastExprRes.get();
8124 }
8125 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8126}
8127
8128ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8129 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8130
8131 if (DestElemTy == SplattedExpr->getType())
8132 return SplattedExpr;
8133
8134 assert(DestElemTy->isFloatingType() ||
8135 DestElemTy->isIntegralOrEnumerationType());
8136
8137 ExprResult CastExprRes = SplattedExpr;
8138 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8139 if (CastExprRes.isInvalid())
8140 return ExprError();
8141 SplattedExpr = CastExprRes.get();
8142
8143 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8144}
8145
8146ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8147 Expr *CastExpr, CastKind &Kind) {
8148 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8149
8150 QualType SrcTy = CastExpr->getType();
8151
8152 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8153 // an ExtVectorType.
8154 // In OpenCL, casts between vectors of different types are not allowed.
8155 // (See OpenCL 6.2).
8156 if (SrcTy->isVectorType()) {
8157 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8158 (getLangOpts().OpenCL &&
8159 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8160 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8161 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8162 << DestTy << SrcTy << R;
8163 return ExprError();
8164 }
8165 Kind = CK_BitCast;
8166 return CastExpr;
8167 }
8168
8169 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8170 // conversion will take place first from scalar to elt type, and then
8171 // splat from elt type to vector.
8172 if (SrcTy->isPointerType())
8173 return Diag(Loc: R.getBegin(),
8174 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8175 << DestTy << SrcTy << R;
8176
8177 Kind = CK_VectorSplat;
8178 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8179}
8180
8181/// Check that a call to alloc_size function specifies sufficient space for the
8182/// destination type.
8183static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8184 const Expr *E) {
8185 QualType SourceType = E->getType();
8186 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8187 DestType == SourceType)
8188 return;
8189
8190 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8191 if (!CE)
8192 return;
8193
8194 // Find the total size allocated by the function call.
8195 if (!CE->getCalleeAllocSizeAttr())
8196 return;
8197 std::optional<llvm::APInt> AllocSize =
8198 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8199 // Allocations of size zero are permitted as a special case. They are usually
8200 // done intentionally.
8201 if (!AllocSize || AllocSize->isZero())
8202 return;
8203 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8204
8205 QualType TargetType = DestType->getPointeeType();
8206 // Find the destination size. As a special case function types have size of
8207 // one byte to match the sizeof operator behavior.
8208 auto LhsSize = TargetType->isFunctionType()
8209 ? CharUnits::One()
8210 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8211 if (LhsSize && Size < LhsSize)
8212 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8213 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8214}
8215
8216ExprResult
8217Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8218 Declarator &D, ParsedType &Ty,
8219 SourceLocation RParenLoc, Expr *CastExpr) {
8220 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8221 "ActOnCastExpr(): missing type or expr");
8222
8223 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8224 if (D.isInvalidType())
8225 return ExprError();
8226
8227 if (getLangOpts().CPlusPlus) {
8228 // Check that there are no default arguments (C++ only).
8229 CheckExtraCXXDefaultArguments(D);
8230 }
8231
8232 checkUnusedDeclAttributes(D);
8233
8234 QualType castType = castTInfo->getType();
8235 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8236
8237 bool isVectorLiteral = false;
8238
8239 // Check for an altivec or OpenCL literal,
8240 // i.e. all the elements are integer constants.
8241 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8242 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8243 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8244 && castType->isVectorType() && (PE || PLE)) {
8245 if (PLE && PLE->getNumExprs() == 0) {
8246 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8247 return ExprError();
8248 }
8249 if (PE || PLE->getNumExprs() == 1) {
8250 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8251 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8252 isVectorLiteral = true;
8253 }
8254 else
8255 isVectorLiteral = true;
8256 }
8257
8258 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8259 // then handle it as such.
8260 if (isVectorLiteral)
8261 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8262
8263 // If the Expr being casted is a ParenListExpr, handle it specially.
8264 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8265 // sequence of BinOp comma operators.
8266 if (isa<ParenListExpr>(Val: CastExpr)) {
8267 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8268 if (Result.isInvalid()) return ExprError();
8269 CastExpr = Result.get();
8270 }
8271
8272 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8273 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8274
8275 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8276
8277 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8278
8279 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8280
8281 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8282
8283 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8284}
8285
8286ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8287 SourceLocation RParenLoc, Expr *E,
8288 TypeSourceInfo *TInfo) {
8289 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8290 "Expected paren or paren list expression");
8291
8292 Expr **exprs;
8293 unsigned numExprs;
8294 Expr *subExpr;
8295 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8296 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8297 LiteralLParenLoc = PE->getLParenLoc();
8298 LiteralRParenLoc = PE->getRParenLoc();
8299 exprs = PE->getExprs();
8300 numExprs = PE->getNumExprs();
8301 } else { // isa<ParenExpr> by assertion at function entrance
8302 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8303 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8304 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8305 exprs = &subExpr;
8306 numExprs = 1;
8307 }
8308
8309 QualType Ty = TInfo->getType();
8310 assert(Ty->isVectorType() && "Expected vector type");
8311
8312 SmallVector<Expr *, 8> initExprs;
8313 const VectorType *VTy = Ty->castAs<VectorType>();
8314 unsigned numElems = VTy->getNumElements();
8315
8316 // '(...)' form of vector initialization in AltiVec: the number of
8317 // initializers must be one or must match the size of the vector.
8318 // If a single value is specified in the initializer then it will be
8319 // replicated to all the components of the vector
8320 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8321 SrcTy: VTy->getElementType()))
8322 return ExprError();
8323 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8324 // The number of initializers must be one or must match the size of the
8325 // vector. If a single value is specified in the initializer then it will
8326 // be replicated to all the components of the vector
8327 if (numExprs == 1) {
8328 QualType ElemTy = VTy->getElementType();
8329 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8330 if (Literal.isInvalid())
8331 return ExprError();
8332 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8333 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8334 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8335 }
8336 else if (numExprs < numElems) {
8337 Diag(Loc: E->getExprLoc(),
8338 DiagID: diag::err_incorrect_number_of_vector_initializers);
8339 return ExprError();
8340 }
8341 else
8342 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8343 }
8344 else {
8345 // For OpenCL, when the number of initializers is a single value,
8346 // it will be replicated to all components of the vector.
8347 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8348 numExprs == 1) {
8349 QualType SrcTy = exprs[0]->getType();
8350 if (!SrcTy->isArithmeticType()) {
8351 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8352 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8353 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8354 return ExprError();
8355 }
8356 QualType ElemTy = VTy->getElementType();
8357 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8358 if (Literal.isInvalid())
8359 return ExprError();
8360 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8361 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8362 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8363 }
8364
8365 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8366 }
8367 // FIXME: This means that pretty-printing the final AST will produce curly
8368 // braces instead of the original commas.
8369 InitListExpr *initE =
8370 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8371 LiteralRParenLoc, /*isExplicit=*/false);
8372 initE->setType(Ty);
8373 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8374}
8375
8376ExprResult
8377Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8378 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8379 if (!E)
8380 return OrigExpr;
8381
8382 ExprResult Result(E->getExpr(Init: 0));
8383
8384 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8385 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8386 RHSExpr: E->getExpr(Init: i));
8387
8388 if (Result.isInvalid()) return ExprError();
8389
8390 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8391}
8392
8393ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8394 SourceLocation R,
8395 MultiExprArg Val) {
8396 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8397}
8398
8399ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8400 unsigned NumUserSpecifiedExprs,
8401 SourceLocation InitLoc,
8402 SourceLocation LParenLoc,
8403 SourceLocation RParenLoc) {
8404 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8405 InitLoc, LParenLoc, RParenLoc);
8406}
8407
8408bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8409 SourceLocation QuestionLoc) {
8410 const Expr *NullExpr = LHSExpr;
8411 const Expr *NonPointerExpr = RHSExpr;
8412 Expr::NullPointerConstantKind NullKind =
8413 NullExpr->isNullPointerConstant(Ctx&: Context,
8414 NPC: Expr::NPC_ValueDependentIsNotNull);
8415
8416 if (NullKind == Expr::NPCK_NotNull) {
8417 NullExpr = RHSExpr;
8418 NonPointerExpr = LHSExpr;
8419 NullKind =
8420 NullExpr->isNullPointerConstant(Ctx&: Context,
8421 NPC: Expr::NPC_ValueDependentIsNotNull);
8422 }
8423
8424 if (NullKind == Expr::NPCK_NotNull)
8425 return false;
8426
8427 if (NullKind == Expr::NPCK_ZeroExpression)
8428 return false;
8429
8430 if (NullKind == Expr::NPCK_ZeroLiteral) {
8431 // In this case, check to make sure that we got here from a "NULL"
8432 // string in the source code.
8433 NullExpr = NullExpr->IgnoreParenImpCasts();
8434 SourceLocation loc = NullExpr->getExprLoc();
8435 if (!findMacroSpelling(loc, name: "NULL"))
8436 return false;
8437 }
8438
8439 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8440 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8441 << NonPointerExpr->getType() << DiagType
8442 << NonPointerExpr->getSourceRange();
8443 return true;
8444}
8445
8446/// Return false if the condition expression is valid, true otherwise.
8447static bool checkCondition(Sema &S, const Expr *Cond,
8448 SourceLocation QuestionLoc) {
8449 QualType CondTy = Cond->getType();
8450
8451 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8452 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8453 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8454 << CondTy << Cond->getSourceRange();
8455 return true;
8456 }
8457
8458 // C99 6.5.15p2
8459 if (CondTy->isScalarType()) return false;
8460
8461 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8462 << CondTy << Cond->getSourceRange();
8463 return true;
8464}
8465
8466/// Return false if the NullExpr can be promoted to PointerTy,
8467/// true otherwise.
8468static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8469 QualType PointerTy) {
8470 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8471 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8472 NPC: Expr::NPC_ValueDependentIsNull))
8473 return true;
8474
8475 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8476 return false;
8477}
8478
8479/// Checks compatibility between two pointers and return the resulting
8480/// type.
8481static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8482 ExprResult &RHS,
8483 SourceLocation Loc) {
8484 QualType LHSTy = LHS.get()->getType();
8485 QualType RHSTy = RHS.get()->getType();
8486
8487 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8488 // Two identical pointers types are always compatible.
8489 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8490 }
8491
8492 QualType lhptee, rhptee;
8493
8494 // Get the pointee types.
8495 bool IsBlockPointer = false;
8496 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8497 lhptee = LHSBTy->getPointeeType();
8498 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8499 IsBlockPointer = true;
8500 } else {
8501 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8502 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8503 }
8504
8505 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8506 // differently qualified versions of compatible types, the result type is
8507 // a pointer to an appropriately qualified version of the composite
8508 // type.
8509
8510 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8511 // clause doesn't make sense for our extensions. E.g. address space 2 should
8512 // be incompatible with address space 3: they may live on different devices or
8513 // anything.
8514 Qualifiers lhQual = lhptee.getQualifiers();
8515 Qualifiers rhQual = rhptee.getQualifiers();
8516
8517 LangAS ResultAddrSpace = LangAS::Default;
8518 LangAS LAddrSpace = lhQual.getAddressSpace();
8519 LangAS RAddrSpace = rhQual.getAddressSpace();
8520
8521 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8522 // spaces is disallowed.
8523 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8524 ResultAddrSpace = LAddrSpace;
8525 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8526 ResultAddrSpace = RAddrSpace;
8527 else {
8528 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8529 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8530 << RHS.get()->getSourceRange();
8531 return QualType();
8532 }
8533
8534 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8535 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8536 lhQual.removeCVRQualifiers();
8537 rhQual.removeCVRQualifiers();
8538
8539 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8540 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8541 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8542 << RHS.get()->getSourceRange();
8543 return QualType();
8544 }
8545
8546 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8547 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8548 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8549 // qual types are compatible iff
8550 // * corresponded types are compatible
8551 // * CVR qualifiers are equal
8552 // * address spaces are equal
8553 // Thus for conditional operator we merge CVR and address space unqualified
8554 // pointees and if there is a composite type we return a pointer to it with
8555 // merged qualifiers.
8556 LHSCastKind =
8557 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8558 RHSCastKind =
8559 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8560 lhQual.removeAddressSpace();
8561 rhQual.removeAddressSpace();
8562
8563 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8564 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8565
8566 QualType CompositeTy = S.Context.mergeTypes(
8567 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8568 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8569
8570 if (CompositeTy.isNull()) {
8571 // In this situation, we assume void* type. No especially good
8572 // reason, but this is what gcc does, and we do have to pick
8573 // to get a consistent AST.
8574 QualType incompatTy;
8575 incompatTy = S.Context.getPointerType(
8576 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8577 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8578 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8579
8580 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8581 // for casts between types with incompatible address space qualifiers.
8582 // For the following code the compiler produces casts between global and
8583 // local address spaces of the corresponded innermost pointees:
8584 // local int *global *a;
8585 // global int *global *b;
8586 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8587 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8588 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8589 << RHS.get()->getSourceRange();
8590
8591 return incompatTy;
8592 }
8593
8594 // The pointer types are compatible.
8595 // In case of OpenCL ResultTy should have the address space qualifier
8596 // which is a superset of address spaces of both the 2nd and the 3rd
8597 // operands of the conditional operator.
8598 QualType ResultTy = [&, ResultAddrSpace]() {
8599 if (S.getLangOpts().OpenCL) {
8600 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8601 CompositeQuals.setAddressSpace(ResultAddrSpace);
8602 return S.Context
8603 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8604 .withCVRQualifiers(CVR: MergedCVRQual);
8605 }
8606 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8607 }();
8608 if (IsBlockPointer)
8609 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8610 else
8611 ResultTy = S.Context.getPointerType(T: ResultTy);
8612
8613 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8614 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8615 return ResultTy;
8616}
8617
8618/// Return the resulting type when the operands are both block pointers.
8619static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8620 ExprResult &LHS,
8621 ExprResult &RHS,
8622 SourceLocation Loc) {
8623 QualType LHSTy = LHS.get()->getType();
8624 QualType RHSTy = RHS.get()->getType();
8625
8626 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8627 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8628 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8629 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8630 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8631 return destType;
8632 }
8633 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8634 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8635 << RHS.get()->getSourceRange();
8636 return QualType();
8637 }
8638
8639 // We have 2 block pointer types.
8640 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8641}
8642
8643/// Return the resulting type when the operands are both pointers.
8644static QualType
8645checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8646 ExprResult &RHS,
8647 SourceLocation Loc) {
8648 // get the pointer types
8649 QualType LHSTy = LHS.get()->getType();
8650 QualType RHSTy = RHS.get()->getType();
8651
8652 // get the "pointed to" types
8653 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8654 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8655
8656 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8657 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8658 // Figure out necessary qualifiers (C99 6.5.15p6)
8659 QualType destPointee
8660 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8661 QualType destType = S.Context.getPointerType(T: destPointee);
8662 // Add qualifiers if necessary.
8663 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8664 // Promote to void*.
8665 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8666 return destType;
8667 }
8668 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8669 QualType destPointee
8670 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8671 QualType destType = S.Context.getPointerType(T: destPointee);
8672 // Add qualifiers if necessary.
8673 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8674 // Promote to void*.
8675 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8676 return destType;
8677 }
8678
8679 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8680}
8681
8682/// Return false if the first expression is not an integer and the second
8683/// expression is not a pointer, true otherwise.
8684static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8685 Expr* PointerExpr, SourceLocation Loc,
8686 bool IsIntFirstExpr) {
8687 if (!PointerExpr->getType()->isPointerType() ||
8688 !Int.get()->getType()->isIntegerType())
8689 return false;
8690
8691 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8692 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8693
8694 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8695 << Expr1->getType() << Expr2->getType()
8696 << Expr1->getSourceRange() << Expr2->getSourceRange();
8697 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8698 CK: CK_IntegralToPointer);
8699 return true;
8700}
8701
8702/// Simple conversion between integer and floating point types.
8703///
8704/// Used when handling the OpenCL conditional operator where the
8705/// condition is a vector while the other operands are scalar.
8706///
8707/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8708/// types are either integer or floating type. Between the two
8709/// operands, the type with the higher rank is defined as the "result
8710/// type". The other operand needs to be promoted to the same type. No
8711/// other type promotion is allowed. We cannot use
8712/// UsualArithmeticConversions() for this purpose, since it always
8713/// promotes promotable types.
8714static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8715 ExprResult &RHS,
8716 SourceLocation QuestionLoc) {
8717 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8718 if (LHS.isInvalid())
8719 return QualType();
8720 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8721 if (RHS.isInvalid())
8722 return QualType();
8723
8724 // For conversion purposes, we ignore any qualifiers.
8725 // For example, "const float" and "float" are equivalent.
8726 QualType LHSType =
8727 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8728 QualType RHSType =
8729 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8730
8731 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8732 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8733 << LHSType << LHS.get()->getSourceRange();
8734 return QualType();
8735 }
8736
8737 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8738 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8739 << RHSType << RHS.get()->getSourceRange();
8740 return QualType();
8741 }
8742
8743 // If both types are identical, no conversion is needed.
8744 if (LHSType == RHSType)
8745 return LHSType;
8746
8747 // Now handle "real" floating types (i.e. float, double, long double).
8748 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8749 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8750 /*IsCompAssign = */ false);
8751
8752 // Finally, we have two differing integer types.
8753 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8754 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8755}
8756
8757/// Convert scalar operands to a vector that matches the
8758/// condition in length.
8759///
8760/// Used when handling the OpenCL conditional operator where the
8761/// condition is a vector while the other operands are scalar.
8762///
8763/// We first compute the "result type" for the scalar operands
8764/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8765/// into a vector of that type where the length matches the condition
8766/// vector type. s6.11.6 requires that the element types of the result
8767/// and the condition must have the same number of bits.
8768static QualType
8769OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8770 QualType CondTy, SourceLocation QuestionLoc) {
8771 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8772 if (ResTy.isNull()) return QualType();
8773
8774 const VectorType *CV = CondTy->getAs<VectorType>();
8775 assert(CV);
8776
8777 // Determine the vector result type
8778 unsigned NumElements = CV->getNumElements();
8779 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8780
8781 // Ensure that all types have the same number of bits
8782 if (S.Context.getTypeSize(T: CV->getElementType())
8783 != S.Context.getTypeSize(T: ResTy)) {
8784 // Since VectorTy is created internally, it does not pretty print
8785 // with an OpenCL name. Instead, we just print a description.
8786 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8787 SmallString<64> Str;
8788 llvm::raw_svector_ostream OS(Str);
8789 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8790 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8791 << CondTy << OS.str();
8792 return QualType();
8793 }
8794
8795 // Convert operands to the vector result type
8796 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8797 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8798
8799 return VectorTy;
8800}
8801
8802/// Return false if this is a valid OpenCL condition vector
8803static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8804 SourceLocation QuestionLoc) {
8805 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8806 // integral type.
8807 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8808 assert(CondTy);
8809 QualType EleTy = CondTy->getElementType();
8810 if (EleTy->isIntegerType()) return false;
8811
8812 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8813 << Cond->getType() << Cond->getSourceRange();
8814 return true;
8815}
8816
8817/// Return false if the vector condition type and the vector
8818/// result type are compatible.
8819///
8820/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8821/// number of elements, and their element types have the same number
8822/// of bits.
8823static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8824 SourceLocation QuestionLoc) {
8825 const VectorType *CV = CondTy->getAs<VectorType>();
8826 const VectorType *RV = VecResTy->getAs<VectorType>();
8827 assert(CV && RV);
8828
8829 if (CV->getNumElements() != RV->getNumElements()) {
8830 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8831 << CondTy << VecResTy;
8832 return true;
8833 }
8834
8835 QualType CVE = CV->getElementType();
8836 QualType RVE = RV->getElementType();
8837
8838 // Boolean vectors are permitted outside of OpenCL mode.
8839 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8840 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8841 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8842 << CondTy << VecResTy;
8843 return true;
8844 }
8845
8846 return false;
8847}
8848
8849/// Return the resulting type for the conditional operator in
8850/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8851/// s6.3.i) when the condition is a vector type.
8852static QualType
8853OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8854 ExprResult &LHS, ExprResult &RHS,
8855 SourceLocation QuestionLoc) {
8856 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8857 if (Cond.isInvalid())
8858 return QualType();
8859 QualType CondTy = Cond.get()->getType();
8860
8861 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8862 return QualType();
8863
8864 // If either operand is a vector then find the vector type of the
8865 // result as specified in OpenCL v1.1 s6.3.i.
8866 if (LHS.get()->getType()->isVectorType() ||
8867 RHS.get()->getType()->isVectorType()) {
8868 bool IsBoolVecLang =
8869 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8870 QualType VecResTy =
8871 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8872 /*isCompAssign*/ IsCompAssign: false,
8873 /*AllowBothBool*/ true,
8874 /*AllowBoolConversions*/ AllowBoolConversion: false,
8875 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8876 /*ReportInvalid*/ true);
8877 if (VecResTy.isNull())
8878 return QualType();
8879 // The result type must match the condition type as specified in
8880 // OpenCL v1.1 s6.11.6.
8881 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8882 return QualType();
8883 return VecResTy;
8884 }
8885
8886 // Both operands are scalar.
8887 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8888}
8889
8890/// Return true if the Expr is block type
8891static bool checkBlockType(Sema &S, const Expr *E) {
8892 if (E->getType()->isBlockPointerType()) {
8893 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8894 return true;
8895 }
8896
8897 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8898 QualType Ty = CE->getCallee()->getType();
8899 if (Ty->isBlockPointerType()) {
8900 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8901 return true;
8902 }
8903 }
8904 return false;
8905}
8906
8907/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8908/// In that case, LHS = cond.
8909/// C99 6.5.15
8910QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8911 ExprResult &RHS, ExprValueKind &VK,
8912 ExprObjectKind &OK,
8913 SourceLocation QuestionLoc) {
8914
8915 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8916 if (!LHSResult.isUsable()) return QualType();
8917 LHS = LHSResult;
8918
8919 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8920 if (!RHSResult.isUsable()) return QualType();
8921 RHS = RHSResult;
8922
8923 // C++ is sufficiently different to merit its own checker.
8924 if (getLangOpts().CPlusPlus)
8925 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8926
8927 VK = VK_PRValue;
8928 OK = OK_Ordinary;
8929
8930 if (Context.isDependenceAllowed() &&
8931 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8932 RHS.get()->isTypeDependent())) {
8933 assert(!getLangOpts().CPlusPlus);
8934 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8935 RHS.get()->containsErrors()) &&
8936 "should only occur in error-recovery path.");
8937 return Context.DependentTy;
8938 }
8939
8940 // The OpenCL operator with a vector condition is sufficiently
8941 // different to merit its own checker.
8942 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8943 Cond.get()->getType()->isExtVectorType())
8944 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8945
8946 // First, check the condition.
8947 Cond = UsualUnaryConversions(E: Cond.get());
8948 if (Cond.isInvalid())
8949 return QualType();
8950 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8951 return QualType();
8952
8953 // Handle vectors.
8954 if (LHS.get()->getType()->isVectorType() ||
8955 RHS.get()->getType()->isVectorType())
8956 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8957 /*AllowBothBool*/ true,
8958 /*AllowBoolConversions*/ AllowBoolConversion: false,
8959 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8960 /*ReportInvalid*/ true);
8961
8962 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8963 ACK: ArithConvKind::Conditional);
8964 if (LHS.isInvalid() || RHS.isInvalid())
8965 return QualType();
8966
8967 // WebAssembly tables are not allowed as conditional LHS or RHS.
8968 QualType LHSTy = LHS.get()->getType();
8969 QualType RHSTy = RHS.get()->getType();
8970 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8971 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8973 return QualType();
8974 }
8975
8976 // Diagnose attempts to convert between __ibm128, __float128 and long double
8977 // where such conversions currently can't be handled.
8978 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8979 Diag(Loc: QuestionLoc,
8980 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8982 return QualType();
8983 }
8984
8985 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8986 // selection operator (?:).
8987 if (getLangOpts().OpenCL &&
8988 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8989 return QualType();
8990 }
8991
8992 // If both operands have arithmetic type, do the usual arithmetic conversions
8993 // to find a common type: C99 6.5.15p3,5.
8994 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8995 // Disallow invalid arithmetic conversions, such as those between bit-
8996 // precise integers types of different sizes, or between a bit-precise
8997 // integer and another type.
8998 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8999 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9000 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9001 << RHS.get()->getSourceRange();
9002 return QualType();
9003 }
9004
9005 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
9006 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
9007
9008 return ResTy;
9009 }
9010
9011 // If both operands are the same structure or union type, the result is that
9012 // type.
9013 // FIXME: Type of conditional expression must be complete in C mode.
9014 if (LHSTy->isRecordType() &&
9015 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
9016 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9017 Y: RHSTy.getUnqualifiedType());
9018
9019 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9020 // The following || allows only one side to be void (a GCC-ism).
9021 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9022 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9023 // UsualArithmeticConversions already handled the case where both sides
9024 // are the same type.
9025 } else if (RHSTy->isVoidType()) {
9026 ResTy = RHSTy;
9027 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9028 << RHS.get()->getSourceRange();
9029 } else {
9030 ResTy = LHSTy;
9031 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9032 << LHS.get()->getSourceRange();
9033 }
9034 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9035 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9036 return ResTy;
9037 }
9038
9039 // C23 6.5.15p7:
9040 // ... if both the second and third operands have nullptr_t type, the
9041 // result also has that type.
9042 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9043 return ResTy;
9044
9045 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9046 // the type of the other operand."
9047 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9048 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9049
9050 // All objective-c pointer type analysis is done here.
9051 QualType compositeType =
9052 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9053 if (LHS.isInvalid() || RHS.isInvalid())
9054 return QualType();
9055 if (!compositeType.isNull())
9056 return compositeType;
9057
9058
9059 // Handle block pointer types.
9060 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9061 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9062 Loc: QuestionLoc);
9063
9064 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9065 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9066 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9067 Loc: QuestionLoc);
9068
9069 // GCC compatibility: soften pointer/integer mismatch. Note that
9070 // null pointers have been filtered out by this point.
9071 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9072 /*IsIntFirstExpr=*/true))
9073 return RHSTy;
9074 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9075 /*IsIntFirstExpr=*/false))
9076 return LHSTy;
9077
9078 // Emit a better diagnostic if one of the expressions is a null pointer
9079 // constant and the other is not a pointer type. In this case, the user most
9080 // likely forgot to take the address of the other expression.
9081 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9082 return QualType();
9083
9084 // Finally, if the LHS and RHS types are canonically the same type, we can
9085 // use the common sugared type.
9086 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9087 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9088
9089 // Otherwise, the operands are not compatible.
9090 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9091 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9092 << RHS.get()->getSourceRange();
9093 return QualType();
9094}
9095
9096/// SuggestParentheses - Emit a note with a fixit hint that wraps
9097/// ParenRange in parentheses.
9098static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9099 const PartialDiagnostic &Note,
9100 SourceRange ParenRange) {
9101 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9102 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9103 EndLoc.isValid()) {
9104 Self.Diag(Loc, PD: Note)
9105 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9106 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9107 } else {
9108 // We can't display the parentheses, so just show the bare note.
9109 Self.Diag(Loc, PD: Note) << ParenRange;
9110 }
9111}
9112
9113static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9114 return BinaryOperator::isAdditiveOp(Opc) ||
9115 BinaryOperator::isMultiplicativeOp(Opc) ||
9116 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9117 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9118 // not any of the logical operators. Bitwise-xor is commonly used as a
9119 // logical-xor because there is no logical-xor operator. The logical
9120 // operators, including uses of xor, have a high false positive rate for
9121 // precedence warnings.
9122}
9123
9124/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9125/// expression, either using a built-in or overloaded operator,
9126/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9127/// expression.
9128static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9129 const Expr **RHSExprs) {
9130 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9131 E = E->IgnoreImpCasts();
9132 E = E->IgnoreConversionOperatorSingleStep();
9133 E = E->IgnoreImpCasts();
9134 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9135 E = MTE->getSubExpr();
9136 E = E->IgnoreImpCasts();
9137 }
9138
9139 // Built-in binary operator.
9140 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9141 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9142 *Opcode = OP->getOpcode();
9143 *RHSExprs = OP->getRHS();
9144 return true;
9145 }
9146
9147 // Overloaded operator.
9148 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9149 if (Call->getNumArgs() != 2)
9150 return false;
9151
9152 // Make sure this is really a binary operator that is safe to pass into
9153 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9154 OverloadedOperatorKind OO = Call->getOperator();
9155 if (OO < OO_Plus || OO > OO_Arrow ||
9156 OO == OO_PlusPlus || OO == OO_MinusMinus)
9157 return false;
9158
9159 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9160 if (IsArithmeticOp(Opc: OpKind)) {
9161 *Opcode = OpKind;
9162 *RHSExprs = Call->getArg(Arg: 1);
9163 return true;
9164 }
9165 }
9166
9167 return false;
9168}
9169
9170/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9171/// or is a logical expression such as (x==y) which has int type, but is
9172/// commonly interpreted as boolean.
9173static bool ExprLooksBoolean(const Expr *E) {
9174 E = E->IgnoreParenImpCasts();
9175
9176 if (E->getType()->isBooleanType())
9177 return true;
9178 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9179 return OP->isComparisonOp() || OP->isLogicalOp();
9180 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9181 return OP->getOpcode() == UO_LNot;
9182 if (E->getType()->isPointerType())
9183 return true;
9184 // FIXME: What about overloaded operator calls returning "unspecified boolean
9185 // type"s (commonly pointer-to-members)?
9186
9187 return false;
9188}
9189
9190/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9191/// and binary operator are mixed in a way that suggests the programmer assumed
9192/// the conditional operator has higher precedence, for example:
9193/// "int x = a + someBinaryCondition ? 1 : 2".
9194static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9195 Expr *Condition, const Expr *LHSExpr,
9196 const Expr *RHSExpr) {
9197 BinaryOperatorKind CondOpcode;
9198 const Expr *CondRHS;
9199
9200 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9201 return;
9202 if (!ExprLooksBoolean(E: CondRHS))
9203 return;
9204
9205 // The condition is an arithmetic binary expression, with a right-
9206 // hand side that looks boolean, so warn.
9207
9208 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9209 ? diag::warn_precedence_bitwise_conditional
9210 : diag::warn_precedence_conditional;
9211
9212 Self.Diag(Loc: OpLoc, DiagID)
9213 << Condition->getSourceRange()
9214 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9215
9216 SuggestParentheses(
9217 Self, Loc: OpLoc,
9218 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9219 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9220 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9221
9222 SuggestParentheses(Self, Loc: OpLoc,
9223 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9224 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9225}
9226
9227/// Compute the nullability of a conditional expression.
9228static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9229 QualType LHSTy, QualType RHSTy,
9230 ASTContext &Ctx) {
9231 if (!ResTy->isAnyPointerType())
9232 return ResTy;
9233
9234 auto GetNullability = [](QualType Ty) {
9235 NullabilityKindOrNone Kind = Ty->getNullability();
9236 if (Kind) {
9237 // For our purposes, treat _Nullable_result as _Nullable.
9238 if (*Kind == NullabilityKind::NullableResult)
9239 return NullabilityKind::Nullable;
9240 return *Kind;
9241 }
9242 return NullabilityKind::Unspecified;
9243 };
9244
9245 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9246 NullabilityKind MergedKind;
9247
9248 // Compute nullability of a binary conditional expression.
9249 if (IsBin) {
9250 if (LHSKind == NullabilityKind::NonNull)
9251 MergedKind = NullabilityKind::NonNull;
9252 else
9253 MergedKind = RHSKind;
9254 // Compute nullability of a normal conditional expression.
9255 } else {
9256 if (LHSKind == NullabilityKind::Nullable ||
9257 RHSKind == NullabilityKind::Nullable)
9258 MergedKind = NullabilityKind::Nullable;
9259 else if (LHSKind == NullabilityKind::NonNull)
9260 MergedKind = RHSKind;
9261 else if (RHSKind == NullabilityKind::NonNull)
9262 MergedKind = LHSKind;
9263 else
9264 MergedKind = NullabilityKind::Unspecified;
9265 }
9266
9267 // Return if ResTy already has the correct nullability.
9268 if (GetNullability(ResTy) == MergedKind)
9269 return ResTy;
9270
9271 // Strip all nullability from ResTy.
9272 while (ResTy->getNullability())
9273 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9274
9275 // Create a new AttributedType with the new nullability kind.
9276 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9277}
9278
9279ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9280 SourceLocation ColonLoc,
9281 Expr *CondExpr, Expr *LHSExpr,
9282 Expr *RHSExpr) {
9283 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9284 // was the condition.
9285 OpaqueValueExpr *opaqueValue = nullptr;
9286 Expr *commonExpr = nullptr;
9287 if (!LHSExpr) {
9288 commonExpr = CondExpr;
9289 // Lower out placeholder types first. This is important so that we don't
9290 // try to capture a placeholder. This happens in few cases in C++; such
9291 // as Objective-C++'s dictionary subscripting syntax.
9292 if (commonExpr->hasPlaceholderType()) {
9293 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9294 if (!result.isUsable()) return ExprError();
9295 commonExpr = result.get();
9296 }
9297 // We usually want to apply unary conversions *before* saving, except
9298 // in the special case of a C++ l-value conditional.
9299 if (!(getLangOpts().CPlusPlus
9300 && !commonExpr->isTypeDependent()
9301 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9302 && commonExpr->isGLValue()
9303 && commonExpr->isOrdinaryOrBitFieldObject()
9304 && RHSExpr->isOrdinaryOrBitFieldObject()
9305 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9306 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9307 if (commonRes.isInvalid())
9308 return ExprError();
9309 commonExpr = commonRes.get();
9310 }
9311
9312 // If the common expression is a class or array prvalue, materialize it
9313 // so that we can safely refer to it multiple times.
9314 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9315 commonExpr->getType()->isArrayType())) {
9316 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9317 if (MatExpr.isInvalid())
9318 return ExprError();
9319 commonExpr = MatExpr.get();
9320 }
9321
9322 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9323 commonExpr->getType(),
9324 commonExpr->getValueKind(),
9325 commonExpr->getObjectKind(),
9326 commonExpr);
9327 LHSExpr = CondExpr = opaqueValue;
9328 }
9329
9330 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9331 ExprValueKind VK = VK_PRValue;
9332 ExprObjectKind OK = OK_Ordinary;
9333 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9334 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9335 VK, OK, QuestionLoc);
9336 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9337 RHS.isInvalid())
9338 return ExprError();
9339
9340 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9341 RHSExpr: RHS.get());
9342
9343 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9344
9345 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9346 Ctx&: Context);
9347
9348 if (!commonExpr)
9349 return new (Context)
9350 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9351 RHS.get(), result, VK, OK);
9352
9353 return new (Context) BinaryConditionalOperator(
9354 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9355 ColonLoc, result, VK, OK);
9356}
9357
9358bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9359 unsigned FromAttributes = 0, ToAttributes = 0;
9360 if (const auto *FromFn =
9361 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9362 FromAttributes =
9363 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9364 if (const auto *ToFn =
9365 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9366 ToAttributes =
9367 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9368
9369 return FromAttributes != ToAttributes;
9370}
9371
9372// checkPointerTypesForAssignment - This is a very tricky routine (despite
9373// being closely modeled after the C99 spec:-). The odd characteristic of this
9374// routine is it effectively iqnores the qualifiers on the top level pointee.
9375// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9376// FIXME: add a couple examples in this comment.
9377static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9378 QualType LHSType,
9379 QualType RHSType,
9380 SourceLocation Loc) {
9381 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9382 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9383
9384 // get the "pointed to" type (ignoring qualifiers at the top level)
9385 const Type *lhptee, *rhptee;
9386 Qualifiers lhq, rhq;
9387 std::tie(args&: lhptee, args&: lhq) =
9388 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9389 std::tie(args&: rhptee, args&: rhq) =
9390 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9391
9392 AssignConvertType ConvTy = AssignConvertType::Compatible;
9393
9394 // C99 6.5.16.1p1: This following citation is common to constraints
9395 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9396 // qualifiers of the type *pointed to* by the right;
9397
9398 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9399 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9400 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9401 // Ignore lifetime for further calculation.
9402 lhq.removeObjCLifetime();
9403 rhq.removeObjCLifetime();
9404 }
9405
9406 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9407 // Treat address-space mismatches as fatal.
9408 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9409 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9410
9411 // It's okay to add or remove GC or lifetime qualifiers when converting to
9412 // and from void*.
9413 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9414 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9415 Ctx: S.getASTContext()) &&
9416 (lhptee->isVoidType() || rhptee->isVoidType()))
9417 ; // keep old
9418
9419 // Treat lifetime mismatches as fatal.
9420 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9421 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9422
9423 // Treat pointer-auth mismatches as fatal.
9424 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9425 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9426
9427 // For GCC/MS compatibility, other qualifier mismatches are treated
9428 // as still compatible in C.
9429 else
9430 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9431 }
9432
9433 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9434 // incomplete type and the other is a pointer to a qualified or unqualified
9435 // version of void...
9436 if (lhptee->isVoidType()) {
9437 if (rhptee->isIncompleteOrObjectType())
9438 return ConvTy;
9439
9440 // As an extension, we allow cast to/from void* to function pointer.
9441 assert(rhptee->isFunctionType());
9442 return AssignConvertType::FunctionVoidPointer;
9443 }
9444
9445 if (rhptee->isVoidType()) {
9446 // In C, void * to another pointer type is compatible, but we want to note
9447 // that there will be an implicit conversion happening here.
9448 if (lhptee->isIncompleteOrObjectType())
9449 return ConvTy == AssignConvertType::Compatible &&
9450 !S.getLangOpts().CPlusPlus
9451 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9452 : ConvTy;
9453
9454 // As an extension, we allow cast to/from void* to function pointer.
9455 assert(lhptee->isFunctionType());
9456 return AssignConvertType::FunctionVoidPointer;
9457 }
9458
9459 if (!S.Diags.isIgnored(
9460 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9461 Loc) &&
9462 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9463 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9464 return AssignConvertType::IncompatibleFunctionPointerStrict;
9465
9466 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9467 // unqualified versions of compatible types, ...
9468 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9469
9470 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9471 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9472 QualType LUnderlying =
9473 ltrans->isOverflowBehaviorType()
9474 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9475 : ltrans;
9476 QualType RUnderlying =
9477 rtrans->isOverflowBehaviorType()
9478 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9479 : rtrans;
9480
9481 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9482 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9483
9484 ltrans = LUnderlying;
9485 rtrans = RUnderlying;
9486 }
9487 }
9488
9489 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9490 // Check if the pointee types are compatible ignoring the sign.
9491 // We explicitly check for char so that we catch "char" vs
9492 // "unsigned char" on systems where "char" is unsigned.
9493 if (lhptee->isCharType())
9494 ltrans = S.Context.UnsignedCharTy;
9495 else if (lhptee->hasSignedIntegerRepresentation())
9496 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9497
9498 if (rhptee->isCharType())
9499 rtrans = S.Context.UnsignedCharTy;
9500 else if (rhptee->hasSignedIntegerRepresentation())
9501 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9502
9503 if (ltrans == rtrans) {
9504 // Types are compatible ignoring the sign. Qualifier incompatibility
9505 // takes priority over sign incompatibility because the sign
9506 // warning can be disabled.
9507 if (!S.IsAssignConvertCompatible(ConvTy))
9508 return ConvTy;
9509
9510 return AssignConvertType::IncompatiblePointerSign;
9511 }
9512
9513 // If we are a multi-level pointer, it's possible that our issue is simply
9514 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9515 // the eventual target type is the same and the pointers have the same
9516 // level of indirection, this must be the issue.
9517 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9518 do {
9519 std::tie(args&: lhptee, args&: lhq) =
9520 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9521 std::tie(args&: rhptee, args&: rhq) =
9522 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9523
9524 // Inconsistent address spaces at this point is invalid, even if the
9525 // address spaces would be compatible.
9526 // FIXME: This doesn't catch address space mismatches for pointers of
9527 // different nesting levels, like:
9528 // __local int *** a;
9529 // int ** b = a;
9530 // It's not clear how to actually determine when such pointers are
9531 // invalidly incompatible.
9532 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9533 return AssignConvertType::
9534 IncompatibleNestedPointerAddressSpaceMismatch;
9535
9536 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9537
9538 if (lhptee == rhptee)
9539 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9540 }
9541
9542 // General pointer incompatibility takes priority over qualifiers.
9543 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9544 return AssignConvertType::IncompatibleFunctionPointer;
9545 return AssignConvertType::IncompatiblePointer;
9546 }
9547 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9548 // hasSameType, so we can skip further checks.
9549 const auto *LFT = ltrans->getAs<FunctionType>();
9550 const auto *RFT = rtrans->getAs<FunctionType>();
9551 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9552 // The invocation of IsFunctionConversion below will try to transform rtrans
9553 // to obtain an exact match for ltrans. This should not fail because of
9554 // mismatches in result type and parameter types, they were already checked
9555 // by typesAreCompatible above. So we will recreate rtrans (or where
9556 // appropriate ltrans) using the result type and parameter types from ltrans
9557 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9558 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9559 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9560 if (LFPT && RFPT) {
9561 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9562 Args: LFPT->getParamTypes(),
9563 EPI: RFPT->getExtProtoInfo());
9564 } else if (LFPT) {
9565 FunctionProtoType::ExtProtoInfo EPI;
9566 EPI.ExtInfo = RFT->getExtInfo();
9567 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9568 Args: LFPT->getParamTypes(), EPI);
9569 } else if (RFPT) {
9570 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9571 // all of its ExtProtoInfo. Transform ltrans instead.
9572 FunctionProtoType::ExtProtoInfo EPI;
9573 EPI.ExtInfo = LFT->getExtInfo();
9574 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9575 Args: RFPT->getParamTypes(), EPI);
9576 } else {
9577 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9578 Info: RFT->getExtInfo());
9579 }
9580 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9581 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9582 return AssignConvertType::IncompatibleFunctionPointer;
9583 }
9584 return ConvTy;
9585}
9586
9587/// checkBlockPointerTypesForAssignment - This routine determines whether two
9588/// block pointer types are compatible or whether a block and normal pointer
9589/// are compatible. It is more restrict than comparing two function pointer
9590// types.
9591static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9592 QualType LHSType,
9593 QualType RHSType) {
9594 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9595 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9596
9597 QualType lhptee, rhptee;
9598
9599 // get the "pointed to" type (ignoring qualifiers at the top level)
9600 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9601 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9602
9603 // In C++, the types have to match exactly.
9604 if (S.getLangOpts().CPlusPlus)
9605 return AssignConvertType::IncompatibleBlockPointer;
9606
9607 AssignConvertType ConvTy = AssignConvertType::Compatible;
9608
9609 // For blocks we enforce that qualifiers are identical.
9610 Qualifiers LQuals = lhptee.getLocalQualifiers();
9611 Qualifiers RQuals = rhptee.getLocalQualifiers();
9612 if (S.getLangOpts().OpenCL) {
9613 LQuals.removeAddressSpace();
9614 RQuals.removeAddressSpace();
9615 }
9616 if (LQuals != RQuals)
9617 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9618
9619 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9620 // assignment.
9621 // The current behavior is similar to C++ lambdas. A block might be
9622 // assigned to a variable iff its return type and parameters are compatible
9623 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9624 // an assignment. Presumably it should behave in way that a function pointer
9625 // assignment does in C, so for each parameter and return type:
9626 // * CVR and address space of LHS should be a superset of CVR and address
9627 // space of RHS.
9628 // * unqualified types should be compatible.
9629 if (S.getLangOpts().OpenCL) {
9630 if (!S.Context.typesAreBlockPointerCompatible(
9631 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9632 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9633 return AssignConvertType::IncompatibleBlockPointer;
9634 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9635 return AssignConvertType::IncompatibleBlockPointer;
9636
9637 return ConvTy;
9638}
9639
9640/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9641/// for assignment compatibility.
9642static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9643 QualType LHSType,
9644 QualType RHSType) {
9645 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9646 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9647
9648 if (LHSType->isObjCBuiltinType()) {
9649 // Class is not compatible with ObjC object pointers.
9650 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9651 !RHSType->isObjCQualifiedClassType())
9652 return AssignConvertType::IncompatiblePointer;
9653 return AssignConvertType::Compatible;
9654 }
9655 if (RHSType->isObjCBuiltinType()) {
9656 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9657 !LHSType->isObjCQualifiedClassType())
9658 return AssignConvertType::IncompatiblePointer;
9659 return AssignConvertType::Compatible;
9660 }
9661 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9662 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9663
9664 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9665 // make an exception for id<P>
9666 !LHSType->isObjCQualifiedIdType())
9667 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9668
9669 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9670 return AssignConvertType::Compatible;
9671 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9672 return AssignConvertType::IncompatibleObjCQualifiedId;
9673 return AssignConvertType::IncompatiblePointer;
9674}
9675
9676AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9677 QualType LHSType,
9678 QualType RHSType) {
9679 // Fake up an opaque expression. We don't actually care about what
9680 // cast operations are required, so if CheckAssignmentConstraints
9681 // adds casts to this they'll be wasted, but fortunately that doesn't
9682 // usually happen on valid code.
9683 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9684 ExprResult RHSPtr = &RHSExpr;
9685 CastKind K;
9686
9687 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9688}
9689
9690/// This helper function returns true if QT is a vector type that has element
9691/// type ElementType.
9692static bool isVector(QualType QT, QualType ElementType) {
9693 if (const VectorType *VT = QT->getAs<VectorType>())
9694 return VT->getElementType().getCanonicalType() == ElementType;
9695 return false;
9696}
9697
9698/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9699/// has code to accommodate several GCC extensions when type checking
9700/// pointers. Here are some objectionable examples that GCC considers warnings:
9701///
9702/// int a, *pint;
9703/// short *pshort;
9704/// struct foo *pfoo;
9705///
9706/// pint = pshort; // warning: assignment from incompatible pointer type
9707/// a = pint; // warning: assignment makes integer from pointer without a cast
9708/// pint = a; // warning: assignment makes pointer from integer without a cast
9709/// pint = pfoo; // warning: assignment from incompatible pointer type
9710///
9711/// As a result, the code for dealing with pointers is more complex than the
9712/// C99 spec dictates.
9713///
9714/// Sets 'Kind' for any result kind except Incompatible.
9715AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9716 ExprResult &RHS,
9717 CastKind &Kind,
9718 bool ConvertRHS) {
9719 QualType RHSType = RHS.get()->getType();
9720 QualType OrigLHSType = LHSType;
9721
9722 // Get canonical types. We're not formatting these types, just comparing
9723 // them.
9724 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9725 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9726
9727 // Common case: no conversion required.
9728 if (LHSType == RHSType) {
9729 Kind = CK_NoOp;
9730 return AssignConvertType::Compatible;
9731 }
9732
9733 // If the LHS has an __auto_type, there are no additional type constraints
9734 // to be worried about.
9735 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9736 if (AT->isGNUAutoType()) {
9737 Kind = CK_NoOp;
9738 return AssignConvertType::Compatible;
9739 }
9740 }
9741
9742 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9743 switch (OBTResult) {
9744 case ASTContext::OBTAssignResult::IncompatibleKinds:
9745 Kind = CK_NoOp;
9746 return AssignConvertType::IncompatibleOBTKinds;
9747 case ASTContext::OBTAssignResult::Discards:
9748 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9749 return AssignConvertType::CompatibleOBTDiscards;
9750 case ASTContext::OBTAssignResult::Compatible:
9751 case ASTContext::OBTAssignResult::NotApplicable:
9752 break;
9753 }
9754
9755 // Check for incompatible OBT types in pointer pointee types
9756 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9757 QualType LHSPointee = LHSType->getPointeeType();
9758 QualType RHSPointee = RHSType->getPointeeType();
9759 if ((LHSPointee->isOverflowBehaviorType() ||
9760 RHSPointee->isOverflowBehaviorType()) &&
9761 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9762 Kind = CK_NoOp;
9763 return AssignConvertType::IncompatibleOBTKinds;
9764 }
9765 }
9766
9767 // If we have an atomic type, try a non-atomic assignment, then just add an
9768 // atomic qualification step.
9769 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9770 AssignConvertType Result =
9771 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9772 if (!IsAssignConvertCompatible(ConvTy: Result))
9773 return Result;
9774 if (Kind != CK_NoOp && ConvertRHS)
9775 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9776 Kind = CK_NonAtomicToAtomic;
9777 return Result;
9778 }
9779
9780 // If the left-hand side is a reference type, then we are in a
9781 // (rare!) case where we've allowed the use of references in C,
9782 // e.g., as a parameter type in a built-in function. In this case,
9783 // just make sure that the type referenced is compatible with the
9784 // right-hand side type. The caller is responsible for adjusting
9785 // LHSType so that the resulting expression does not have reference
9786 // type.
9787 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9788 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9789 Kind = CK_LValueBitCast;
9790 return AssignConvertType::Compatible;
9791 }
9792 return AssignConvertType::Incompatible;
9793 }
9794
9795 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9796 // of an ExtVector type to the same ExtVector type.
9797 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9798 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9799 // Implicit conversions require the same number of elements.
9800 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9801 return AssignConvertType::Incompatible;
9802
9803 if (LHSType->isExtVectorBoolType() &&
9804 RHSExtType->getElementType()->isIntegerType()) {
9805 Kind = CK_IntegralToBoolean;
9806 return AssignConvertType::Compatible;
9807 }
9808 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9809 if (Context.getLangOpts().OpenCL &&
9810 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9811 Kind = CK_BitCast;
9812 return AssignConvertType::Compatible;
9813 }
9814 return AssignConvertType::Incompatible;
9815 }
9816 if (RHSType->isArithmeticType()) {
9817 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9818 if (ConvertRHS)
9819 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9820 Kind = CK_VectorSplat;
9821 return AssignConvertType::Compatible;
9822 }
9823 }
9824
9825 // Conversions to or from vector type.
9826 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9827 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9828 // Allow assignments of an AltiVec vector type to an equivalent GCC
9829 // vector type and vice versa
9830 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9831 Kind = CK_BitCast;
9832 return AssignConvertType::Compatible;
9833 }
9834
9835 // If we are allowing lax vector conversions, and LHS and RHS are both
9836 // vectors, the total size only needs to be the same. This is a bitcast;
9837 // no bits are changed but the result type is different.
9838 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9839 // The default for lax vector conversions with Altivec vectors will
9840 // change, so if we are converting between vector types where
9841 // at least one is an Altivec vector, emit a warning.
9842 if (Context.getTargetInfo().getTriple().isPPC() &&
9843 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9844 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9845 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9846 << RHSType << LHSType;
9847 Kind = CK_BitCast;
9848 return AssignConvertType::IncompatibleVectors;
9849 }
9850 }
9851
9852 // When the RHS comes from another lax conversion (e.g. binops between
9853 // scalars and vectors) the result is canonicalized as a vector. When the
9854 // LHS is also a vector, the lax is allowed by the condition above. Handle
9855 // the case where LHS is a scalar.
9856 if (LHSType->isScalarType()) {
9857 const VectorType *VecType = RHSType->getAs<VectorType>();
9858 if (VecType && VecType->getNumElements() == 1 &&
9859 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9860 if (Context.getTargetInfo().getTriple().isPPC() &&
9861 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9862 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9863 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9864 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9865 << RHSType << LHSType;
9866 ExprResult *VecExpr = &RHS;
9867 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9868 Kind = CK_BitCast;
9869 return AssignConvertType::Compatible;
9870 }
9871 }
9872
9873 // Allow assignments between fixed-length and sizeless SVE vectors.
9874 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9875 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9876 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9877 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9878 Kind = CK_BitCast;
9879 return AssignConvertType::Compatible;
9880 }
9881
9882 // Allow assignments between fixed-length and sizeless RVV vectors.
9883 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9884 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9885 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9886 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9887 Kind = CK_BitCast;
9888 return AssignConvertType::Compatible;
9889 }
9890 }
9891
9892 return AssignConvertType::Incompatible;
9893 }
9894
9895 // Diagnose attempts to convert between __ibm128, __float128 and long double
9896 // where such conversions currently can't be handled.
9897 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9898 return AssignConvertType::Incompatible;
9899
9900 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9901 // discards the imaginary part.
9902 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9903 !LHSType->getAs<ComplexType>())
9904 return AssignConvertType::Incompatible;
9905
9906 // Arithmetic conversions.
9907 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9908 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9909 if (ConvertRHS)
9910 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9911 return AssignConvertType::Compatible;
9912 }
9913
9914 // Conversions to normal pointers.
9915 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9916 // U* -> T*
9917 if (isa<PointerType>(Val: RHSType)) {
9918 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9919 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9920 if (AddrSpaceL != AddrSpaceR)
9921 Kind = CK_AddressSpaceConversion;
9922 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9923 Kind = CK_NoOp;
9924 else
9925 Kind = CK_BitCast;
9926 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9927 Loc: RHS.get()->getBeginLoc());
9928 }
9929
9930 // int -> T*
9931 if (RHSType->isIntegerType()) {
9932 Kind = CK_IntegralToPointer; // FIXME: null?
9933 return AssignConvertType::IntToPointer;
9934 }
9935
9936 // C pointers are not compatible with ObjC object pointers,
9937 // with two exceptions:
9938 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9939 // - conversions to void*
9940 if (LHSPointer->getPointeeType()->isVoidType()) {
9941 Kind = CK_BitCast;
9942 return AssignConvertType::Compatible;
9943 }
9944
9945 // - conversions from 'Class' to the redefinition type
9946 if (RHSType->isObjCClassType() &&
9947 Context.hasSameType(T1: LHSType,
9948 T2: Context.getObjCClassRedefinitionType())) {
9949 Kind = CK_BitCast;
9950 return AssignConvertType::Compatible;
9951 }
9952
9953 Kind = CK_BitCast;
9954 return AssignConvertType::IncompatiblePointer;
9955 }
9956
9957 // U^ -> void*
9958 if (RHSType->getAs<BlockPointerType>()) {
9959 if (LHSPointer->getPointeeType()->isVoidType()) {
9960 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9961 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9962 ->getPointeeType()
9963 .getAddressSpace();
9964 Kind =
9965 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9966 return AssignConvertType::Compatible;
9967 }
9968 }
9969
9970 return AssignConvertType::Incompatible;
9971 }
9972
9973 // Conversions to block pointers.
9974 if (isa<BlockPointerType>(Val: LHSType)) {
9975 // U^ -> T^
9976 if (RHSType->isBlockPointerType()) {
9977 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9978 ->getPointeeType()
9979 .getAddressSpace();
9980 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9981 ->getPointeeType()
9982 .getAddressSpace();
9983 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9984 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9985 }
9986
9987 // int or null -> T^
9988 if (RHSType->isIntegerType()) {
9989 Kind = CK_IntegralToPointer; // FIXME: null
9990 return AssignConvertType::IntToBlockPointer;
9991 }
9992
9993 // id -> T^
9994 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9995 Kind = CK_AnyPointerToBlockPointerCast;
9996 return AssignConvertType::Compatible;
9997 }
9998
9999 // void* -> T^
10000 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10001 if (RHSPT->getPointeeType()->isVoidType()) {
10002 Kind = CK_AnyPointerToBlockPointerCast;
10003 return AssignConvertType::Compatible;
10004 }
10005
10006 return AssignConvertType::Incompatible;
10007 }
10008
10009 // Conversions to Objective-C pointers.
10010 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10011 // A* -> B*
10012 if (RHSType->isObjCObjectPointerType()) {
10013 Kind = CK_BitCast;
10014 AssignConvertType result =
10015 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10016 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10017 result == AssignConvertType::Compatible &&
10018 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10019 result = AssignConvertType::IncompatibleObjCWeakRef;
10020 return result;
10021 }
10022
10023 // int or null -> A*
10024 if (RHSType->isIntegerType()) {
10025 Kind = CK_IntegralToPointer; // FIXME: null
10026 return AssignConvertType::IntToPointer;
10027 }
10028
10029 // In general, C pointers are not compatible with ObjC object pointers,
10030 // with two exceptions:
10031 if (isa<PointerType>(Val: RHSType)) {
10032 Kind = CK_CPointerToObjCPointerCast;
10033
10034 // - conversions from 'void*'
10035 if (RHSType->isVoidPointerType()) {
10036 return AssignConvertType::Compatible;
10037 }
10038
10039 // - conversions to 'Class' from its redefinition type
10040 if (LHSType->isObjCClassType() &&
10041 Context.hasSameType(T1: RHSType,
10042 T2: Context.getObjCClassRedefinitionType())) {
10043 return AssignConvertType::Compatible;
10044 }
10045
10046 return AssignConvertType::IncompatiblePointer;
10047 }
10048
10049 // Only under strict condition T^ is compatible with an Objective-C pointer.
10050 if (RHSType->isBlockPointerType() &&
10051 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10052 if (ConvertRHS)
10053 maybeExtendBlockObject(E&: RHS);
10054 Kind = CK_BlockPointerToObjCPointerCast;
10055 return AssignConvertType::Compatible;
10056 }
10057
10058 return AssignConvertType::Incompatible;
10059 }
10060
10061 // Conversion to nullptr_t (C23 only)
10062 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10063 RHS.get()->isNullPointerConstant(Ctx&: Context,
10064 NPC: Expr::NPC_ValueDependentIsNull)) {
10065 // null -> nullptr_t
10066 Kind = CK_NullToPointer;
10067 return AssignConvertType::Compatible;
10068 }
10069
10070 // Conversions from pointers that are not covered by the above.
10071 if (isa<PointerType>(Val: RHSType)) {
10072 // T* -> _Bool
10073 if (LHSType == Context.BoolTy) {
10074 Kind = CK_PointerToBoolean;
10075 return AssignConvertType::Compatible;
10076 }
10077
10078 // T* -> int
10079 if (LHSType->isIntegerType()) {
10080 Kind = CK_PointerToIntegral;
10081 return AssignConvertType::PointerToInt;
10082 }
10083
10084 return AssignConvertType::Incompatible;
10085 }
10086
10087 // Conversions from Objective-C pointers that are not covered by the above.
10088 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10089 // T* -> _Bool
10090 if (LHSType == Context.BoolTy) {
10091 Kind = CK_PointerToBoolean;
10092 return AssignConvertType::Compatible;
10093 }
10094
10095 // T* -> int
10096 if (LHSType->isIntegerType()) {
10097 Kind = CK_PointerToIntegral;
10098 return AssignConvertType::PointerToInt;
10099 }
10100
10101 return AssignConvertType::Incompatible;
10102 }
10103
10104 // struct A -> struct B
10105 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10106 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10107 Kind = CK_NoOp;
10108 return AssignConvertType::Compatible;
10109 }
10110 }
10111
10112 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10113 Kind = CK_IntToOCLSampler;
10114 return AssignConvertType::Compatible;
10115 }
10116
10117 return AssignConvertType::Incompatible;
10118}
10119
10120/// Constructs a transparent union from an expression that is
10121/// used to initialize the transparent union.
10122static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10123 ExprResult &EResult, QualType UnionType,
10124 FieldDecl *Field) {
10125 // Build an initializer list that designates the appropriate member
10126 // of the transparent union.
10127 Expr *E = EResult.get();
10128 InitListExpr *Initializer = new (C) InitListExpr(
10129 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10130 Initializer->setType(UnionType);
10131 Initializer->setInitializedFieldInUnion(Field);
10132
10133 // Build a compound literal constructing a value of the transparent
10134 // union type from this initializer list.
10135 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10136 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10137 VK_PRValue, Initializer, false);
10138}
10139
10140AssignConvertType
10141Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10142 ExprResult &RHS) {
10143 QualType RHSType = RHS.get()->getType();
10144
10145 // If the ArgType is a Union type, we want to handle a potential
10146 // transparent_union GCC extension.
10147 const RecordType *UT = ArgType->getAsUnionType();
10148 if (!UT)
10149 return AssignConvertType::Incompatible;
10150
10151 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10152 if (!UD->hasAttr<TransparentUnionAttr>())
10153 return AssignConvertType::Incompatible;
10154
10155 // The field to initialize within the transparent union.
10156 FieldDecl *InitField = nullptr;
10157 // It's compatible if the expression matches any of the fields.
10158 for (auto *it : UD->fields()) {
10159 if (it->getType()->isPointerType()) {
10160 // If the transparent union contains a pointer type, we allow:
10161 // 1) void pointer
10162 // 2) null pointer constant
10163 if (RHSType->isPointerType())
10164 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10165 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10166 InitField = it;
10167 break;
10168 }
10169
10170 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10171 NPC: Expr::NPC_ValueDependentIsNull)) {
10172 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10173 CK: CK_NullToPointer);
10174 InitField = it;
10175 break;
10176 }
10177 }
10178
10179 CastKind Kind;
10180 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10181 AssignConvertType::Compatible) {
10182 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10183 InitField = it;
10184 break;
10185 }
10186 }
10187
10188 if (!InitField)
10189 return AssignConvertType::Incompatible;
10190
10191 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10192 return AssignConvertType::Compatible;
10193}
10194
10195AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10196 ExprResult &CallerRHS,
10197 bool Diagnose,
10198 bool DiagnoseCFAudited,
10199 bool ConvertRHS) {
10200 // We need to be able to tell the caller whether we diagnosed a problem, if
10201 // they ask us to issue diagnostics.
10202 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10203
10204 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10205 // we can't avoid *all* modifications at the moment, so we need some somewhere
10206 // to put the updated value.
10207 ExprResult LocalRHS = CallerRHS;
10208 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10209
10210 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10211 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10212 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10213 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10214 Diag(Loc: RHS.get()->getExprLoc(),
10215 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10216 << RHS.get()->getSourceRange();
10217 }
10218 }
10219 }
10220
10221 if (getLangOpts().CPlusPlus) {
10222 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10223 // C++ 5.17p3: If the left operand is not of class type, the
10224 // expression is implicitly converted (C++ 4) to the
10225 // cv-unqualified type of the left operand.
10226 QualType RHSType = RHS.get()->getType();
10227 if (Diagnose) {
10228 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10229 Action: AssignmentAction::Assigning);
10230 } else {
10231 ImplicitConversionSequence ICS =
10232 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10233 /*SuppressUserConversions=*/false,
10234 AllowExplicit: AllowedExplicit::None,
10235 /*InOverloadResolution=*/false,
10236 /*CStyle=*/false,
10237 /*AllowObjCWritebackConversion=*/false);
10238 if (ICS.isFailure())
10239 return AssignConvertType::Incompatible;
10240 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10241 ICS, Action: AssignmentAction::Assigning);
10242 }
10243 if (RHS.isInvalid())
10244 return AssignConvertType::Incompatible;
10245 AssignConvertType result = AssignConvertType::Compatible;
10246 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10247 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10248 result = AssignConvertType::IncompatibleObjCWeakRef;
10249
10250 // Check if OBT is being discarded during assignment
10251 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10252 if (RHSType->isOverflowBehaviorType() &&
10253 !LHSType->isOverflowBehaviorType()) {
10254 result = AssignConvertType::CompatibleOBTDiscards;
10255 }
10256
10257 return result;
10258 }
10259
10260 // FIXME: Currently, we fall through and treat C++ classes like C
10261 // structures.
10262 // FIXME: We also fall through for atomics; not sure what should
10263 // happen there, though.
10264 } else if (RHS.get()->getType() == Context.OverloadTy) {
10265 // As a set of extensions to C, we support overloading on functions. These
10266 // functions need to be resolved here.
10267 DeclAccessPair DAP;
10268 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10269 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10270 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10271 else
10272 return AssignConvertType::Incompatible;
10273 }
10274
10275 // For HLSL records, insert derived-to-base conversion if needed.
10276 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10277 QualType RHSType = RHS.get()->getType();
10278 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10279 CXXBasePaths Paths;
10280 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10281 CXXCastPath CastPath;
10282 BuildBasePathArray(Paths, BasePath&: CastPath);
10283 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10284 BasePath: &CastPath);
10285 }
10286 }
10287 }
10288
10289 // This check seems unnatural, however it is necessary to ensure the proper
10290 // conversion of functions/arrays. If the conversion were done for all
10291 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10292 // expressions that suppress this implicit conversion (&, sizeof). This needs
10293 // to happen before we check for null pointer conversions because C does not
10294 // undergo the same implicit conversions as C++ does above (by the calls to
10295 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10296 // lvalue to rvalue cast before checking for null pointer constraints. This
10297 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10298 //
10299 // Suppress this for references: C++ 8.5.3p5.
10300 if (!LHSType->isReferenceType()) {
10301 // FIXME: We potentially allocate here even if ConvertRHS is false.
10302 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10303 if (RHS.isInvalid())
10304 return AssignConvertType::Incompatible;
10305 }
10306
10307 // The constraints are expressed in terms of the atomic, qualified, or
10308 // unqualified type of the LHS.
10309 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10310
10311 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10312 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10313 if ((LHSTypeAfterConversion->isPointerType() ||
10314 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10315 LHSTypeAfterConversion->isBlockPointerType()) &&
10316 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10317 RHS.get()->isNullPointerConstant(Ctx&: Context,
10318 NPC: Expr::NPC_ValueDependentIsNull))) {
10319 AssignConvertType Ret = AssignConvertType::Compatible;
10320 if (Diagnose || ConvertRHS) {
10321 CastKind Kind;
10322 CXXCastPath Path;
10323 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10324 /*IgnoreBaseAccess=*/false, Diagnose);
10325
10326 // If there is a conversion of some kind, check to see what kind of
10327 // pointer conversion happened so we can diagnose a C++ compatibility
10328 // diagnostic if the conversion is invalid. This only matters if the RHS
10329 // is some kind of void pointer. We have a carve-out when the RHS is from
10330 // a macro expansion because the use of a macro may indicate different
10331 // code between C and C++. Consider: char *s = NULL; where NULL is
10332 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10333 // C++, which is valid in C++.
10334 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10335 !RHS.get()->getBeginLoc().isMacroID()) {
10336 QualType CanRHS =
10337 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10338 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10339 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10340 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10341 Loc: RHS.get()->getExprLoc());
10342 // Anything that's not considered perfectly compatible would be
10343 // incompatible in C++.
10344 if (Ret != AssignConvertType::Compatible)
10345 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10346 }
10347 }
10348
10349 if (ConvertRHS)
10350 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10351 }
10352 return Ret;
10353 }
10354 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10355 // unqualified bool, and the right operand is a pointer or its type is
10356 // nullptr_t.
10357 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10358 RHS.get()->getType()->isNullPtrType()) {
10359 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10360 // only handles nullptr -> _Bool due to needing an extra conversion
10361 // step.
10362 // We model this by converting from nullptr -> void * and then let the
10363 // conversion from void * -> _Bool happen naturally.
10364 if (Diagnose || ConvertRHS) {
10365 CastKind Kind;
10366 CXXCastPath Path;
10367 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10368 /*IgnoreBaseAccess=*/false, Diagnose);
10369 if (ConvertRHS)
10370 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10371 BasePath: &Path);
10372 }
10373 }
10374
10375 // OpenCL queue_t type assignment.
10376 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10377 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10378 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10379 return AssignConvertType::Compatible;
10380 }
10381
10382 CastKind Kind;
10383 AssignConvertType result =
10384 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10385
10386 // If assigning a void * created by an allocation function call to some other
10387 // type, check that the allocated size is sufficient for that type.
10388 if (result != AssignConvertType::Incompatible &&
10389 RHS.get()->getType()->isVoidPointerType())
10390 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10391
10392 // C99 6.5.16.1p2: The value of the right operand is converted to the
10393 // type of the assignment expression.
10394 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10395 // so that we can use references in built-in functions even in C.
10396 // The getNonReferenceType() call makes sure that the resulting expression
10397 // does not have reference type.
10398 if (result != AssignConvertType::Incompatible &&
10399 RHS.get()->getType() != LHSType) {
10400 QualType Ty = LHSType.getNonLValueExprType(Context);
10401 Expr *E = RHS.get();
10402
10403 // Check for various Objective-C errors. If we are not reporting
10404 // diagnostics and just checking for errors, e.g., during overload
10405 // resolution, return Incompatible to indicate the failure.
10406 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10407 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10408 CCK: CheckedConversionKind::Implicit, Diagnose,
10409 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10410 if (!Diagnose)
10411 return AssignConvertType::Incompatible;
10412 }
10413 if (getLangOpts().ObjC &&
10414 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10415 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10416 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10417 if (!Diagnose)
10418 return AssignConvertType::Incompatible;
10419 // Replace the expression with a corrected version and continue so we
10420 // can find further errors.
10421 RHS = E;
10422 return AssignConvertType::Compatible;
10423 }
10424
10425 if (ConvertRHS)
10426 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10427 }
10428
10429 return result;
10430}
10431
10432namespace {
10433/// The original operand to an operator, prior to the application of the usual
10434/// arithmetic conversions and converting the arguments of a builtin operator
10435/// candidate.
10436struct OriginalOperand {
10437 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10438 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10439 Op = MTE->getSubExpr();
10440 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10441 Op = BTE->getSubExpr();
10442 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10443 Orig = ICE->getSubExprAsWritten();
10444 Conversion = ICE->getConversionFunction();
10445 }
10446 }
10447
10448 QualType getType() const { return Orig->getType(); }
10449
10450 Expr *Orig;
10451 NamedDecl *Conversion;
10452};
10453}
10454
10455QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10456 ExprResult &RHS) {
10457 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10458
10459 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10460 << OrigLHS.getType() << OrigRHS.getType()
10461 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10462
10463 // If a user-defined conversion was applied to either of the operands prior
10464 // to applying the built-in operator rules, tell the user about it.
10465 if (OrigLHS.Conversion) {
10466 Diag(Loc: OrigLHS.Conversion->getLocation(),
10467 DiagID: diag::note_typecheck_invalid_operands_converted)
10468 << 0 << LHS.get()->getType();
10469 }
10470 if (OrigRHS.Conversion) {
10471 Diag(Loc: OrigRHS.Conversion->getLocation(),
10472 DiagID: diag::note_typecheck_invalid_operands_converted)
10473 << 1 << RHS.get()->getType();
10474 }
10475
10476 return QualType();
10477}
10478
10479QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10480 ExprResult &RHS) {
10481 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10482 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10483
10484 bool LHSNatVec = LHSType->isVectorType();
10485 bool RHSNatVec = RHSType->isVectorType();
10486
10487 if (!(LHSNatVec && RHSNatVec)) {
10488 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10489 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10490 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10491 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10492 << Vector->getSourceRange();
10493 return QualType();
10494 }
10495
10496 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10497 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10498 << RHS.get()->getSourceRange();
10499
10500 return QualType();
10501}
10502
10503/// Try to convert a value of non-vector type to a vector type by converting
10504/// the type to the element type of the vector and then performing a splat.
10505/// If the language is OpenCL, we only use conversions that promote scalar
10506/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10507/// for float->int.
10508///
10509/// OpenCL V2.0 6.2.6.p2:
10510/// An error shall occur if any scalar operand type has greater rank
10511/// than the type of the vector element.
10512///
10513/// \param scalar - if non-null, actually perform the conversions
10514/// \return true if the operation fails (but without diagnosing the failure)
10515static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10516 QualType scalarTy,
10517 QualType vectorEltTy,
10518 QualType vectorTy,
10519 unsigned &DiagID) {
10520 // The conversion to apply to the scalar before splatting it,
10521 // if necessary.
10522 CastKind scalarCast = CK_NoOp;
10523
10524 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10525 scalarCast = CK_IntegralToBoolean;
10526 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10527 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10528 (scalarTy->isIntegerType() &&
10529 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10530 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10531 return true;
10532 }
10533 if (!scalarTy->isIntegralType(Ctx: S.Context))
10534 return true;
10535 scalarCast = CK_IntegralCast;
10536 } else if (vectorEltTy->isRealFloatingType()) {
10537 if (scalarTy->isRealFloatingType()) {
10538 if (S.getLangOpts().OpenCL &&
10539 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10540 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10541 return true;
10542 }
10543 scalarCast = CK_FloatingCast;
10544 }
10545 else if (scalarTy->isIntegralType(Ctx: S.Context))
10546 scalarCast = CK_IntegralToFloating;
10547 else
10548 return true;
10549 } else {
10550 return true;
10551 }
10552
10553 // Adjust scalar if desired.
10554 if (scalar) {
10555 if (scalarCast != CK_NoOp)
10556 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10557 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10558 }
10559 return false;
10560}
10561
10562/// Convert vector E to a vector with the same number of elements but different
10563/// element type.
10564static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10565 const auto *VecTy = E->getType()->getAs<VectorType>();
10566 assert(VecTy && "Expression E must be a vector");
10567 QualType NewVecTy =
10568 VecTy->isExtVectorType()
10569 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10570 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10571 VecKind: VecTy->getVectorKind());
10572
10573 // Look through the implicit cast. Return the subexpression if its type is
10574 // NewVecTy.
10575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10576 if (ICE->getSubExpr()->getType() == NewVecTy)
10577 return ICE->getSubExpr();
10578
10579 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10580 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10581}
10582
10583/// Test if a (constant) integer Int can be casted to another integer type
10584/// IntTy without losing precision.
10585static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10586 QualType OtherIntTy) {
10587 Expr *E = Int->get();
10588 if (E->containsErrors() || E->isInstantiationDependent())
10589 return false;
10590
10591 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10592
10593 // Reject cases where the value of the Int is unknown as that would
10594 // possibly cause truncation, but accept cases where the scalar can be
10595 // demoted without loss of precision.
10596 Expr::EvalResult EVResult;
10597 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10598 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10599 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10600 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10601
10602 if (CstInt) {
10603 // If the scalar is constant and is of a higher order and has more active
10604 // bits that the vector element type, reject it.
10605 llvm::APSInt Result = EVResult.Val.getInt();
10606 unsigned NumBits = IntSigned
10607 ? (Result.isNegative() ? Result.getSignificantBits()
10608 : Result.getActiveBits())
10609 : Result.getActiveBits();
10610 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10611 return true;
10612
10613 // If the signedness of the scalar type and the vector element type
10614 // differs and the number of bits is greater than that of the vector
10615 // element reject it.
10616 return (IntSigned != OtherIntSigned &&
10617 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10618 }
10619
10620 // Reject cases where the value of the scalar is not constant and it's
10621 // order is greater than that of the vector element type.
10622 return (Order < 0);
10623}
10624
10625/// Test if a (constant) integer Int can be casted to floating point type
10626/// FloatTy without losing precision.
10627static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10628 QualType FloatTy) {
10629 if (Int->get()->containsErrors())
10630 return false;
10631
10632 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10633
10634 // Determine if the integer constant can be expressed as a floating point
10635 // number of the appropriate type.
10636 Expr::EvalResult EVResult;
10637 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10638
10639 uint64_t Bits = 0;
10640 if (CstInt) {
10641 // Reject constants that would be truncated if they were converted to
10642 // the floating point type. Test by simple to/from conversion.
10643 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10644 // could be avoided if there was a convertFromAPInt method
10645 // which could signal back if implicit truncation occurred.
10646 llvm::APSInt Result = EVResult.Val.getInt();
10647 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10648 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10649 RM: llvm::APFloat::rmTowardZero);
10650 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10651 !IntTy->hasSignedIntegerRepresentation());
10652 bool Ignored = false;
10653 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10654 IsExact: &Ignored);
10655 if (Result != ConvertBack)
10656 return true;
10657 } else {
10658 // Reject types that cannot be fully encoded into the mantissa of
10659 // the float.
10660 Bits = S.Context.getTypeSize(T: IntTy);
10661 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10662 S.Context.getFloatTypeSemantics(T: FloatTy));
10663 if (Bits > FloatPrec)
10664 return true;
10665 }
10666
10667 return false;
10668}
10669
10670/// Attempt to convert and splat Scalar into a vector whose types matches
10671/// Vector following GCC conversion rules. The rule is that implicit
10672/// conversion can occur when Scalar can be casted to match Vector's element
10673/// type without causing truncation of Scalar.
10674static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10675 ExprResult *Vector) {
10676 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10677 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10678 QualType VectorEltTy;
10679
10680 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10681 assert(!isa<ExtVectorType>(VT) &&
10682 "ExtVectorTypes should not be handled here!");
10683 VectorEltTy = VT->getElementType();
10684 } else if (VectorTy->isSveVLSBuiltinType()) {
10685 VectorEltTy =
10686 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10687 } else {
10688 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10689 }
10690
10691 // Reject cases where the vector element type or the scalar element type are
10692 // not integral or floating point types.
10693 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10694 return true;
10695
10696 // The conversion to apply to the scalar before splatting it,
10697 // if necessary.
10698 CastKind ScalarCast = CK_NoOp;
10699
10700 // Accept cases where the vector elements are integers and the scalar is
10701 // an integer.
10702 // FIXME: Notionally if the scalar was a floating point value with a precise
10703 // integral representation, we could cast it to an appropriate integer
10704 // type and then perform the rest of the checks here. GCC will perform
10705 // this conversion in some cases as determined by the input language.
10706 // We should accept it on a language independent basis.
10707 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10708 ScalarTy->isIntegralType(Ctx: S.Context) &&
10709 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10710
10711 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10712 return true;
10713
10714 ScalarCast = CK_IntegralCast;
10715 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10716 ScalarTy->isRealFloatingType()) {
10717 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10718 ScalarCast = CK_FloatingToIntegral;
10719 else
10720 return true;
10721 } else if (VectorEltTy->isRealFloatingType()) {
10722 if (ScalarTy->isRealFloatingType()) {
10723
10724 // Reject cases where the scalar type is not a constant and has a higher
10725 // Order than the vector element type.
10726 llvm::APFloat Result(0.0);
10727
10728 // Determine whether this is a constant scalar. In the event that the
10729 // value is dependent (and thus cannot be evaluated by the constant
10730 // evaluator), skip the evaluation. This will then diagnose once the
10731 // expression is instantiated.
10732 bool CstScalar = Scalar->get()->isValueDependent() ||
10733 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10734 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10735 if (!CstScalar && Order < 0)
10736 return true;
10737
10738 // If the scalar cannot be safely casted to the vector element type,
10739 // reject it.
10740 if (CstScalar) {
10741 bool Truncated = false;
10742 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10743 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10744 if (Truncated)
10745 return true;
10746 }
10747
10748 ScalarCast = CK_FloatingCast;
10749 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10750 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10751 return true;
10752
10753 ScalarCast = CK_IntegralToFloating;
10754 } else
10755 return true;
10756 } else if (ScalarTy->isEnumeralType())
10757 return true;
10758
10759 // Adjust scalar if desired.
10760 if (ScalarCast != CK_NoOp)
10761 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10762 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10763 return false;
10764}
10765
10766QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10767 SourceLocation Loc, bool IsCompAssign,
10768 bool AllowBothBool,
10769 bool AllowBoolConversions,
10770 bool AllowBoolOperation,
10771 bool ReportInvalid) {
10772 if (!IsCompAssign) {
10773 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10774 if (LHS.isInvalid())
10775 return QualType();
10776 }
10777 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10778 if (RHS.isInvalid())
10779 return QualType();
10780
10781 // For conversion purposes, we ignore any qualifiers.
10782 // For example, "const float" and "float" are equivalent.
10783 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10784 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10785
10786 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10787 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10788 assert(LHSVecType || RHSVecType);
10789
10790 if (getLangOpts().HLSL)
10791 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10792 IsCompAssign);
10793
10794 // Any operation with MFloat8 type is only possible with C intrinsics
10795 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10796 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10797 return InvalidOperands(Loc, LHS, RHS);
10798
10799 // AltiVec-style "vector bool op vector bool" combinations are allowed
10800 // for some operators but not others.
10801 if (!AllowBothBool && LHSVecType &&
10802 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10803 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10804 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10805
10806 // This operation may not be performed on boolean vectors.
10807 if (!AllowBoolOperation &&
10808 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10809 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10810
10811 // If the vector types are identical, return.
10812 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10813 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10814
10815 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10816 if (LHSVecType && RHSVecType &&
10817 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10818 if (isa<ExtVectorType>(Val: LHSVecType)) {
10819 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10820 return LHSType;
10821 }
10822
10823 if (!IsCompAssign)
10824 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10825 return RHSType;
10826 }
10827
10828 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10829 // can be mixed, with the result being the non-bool type. The non-bool
10830 // operand must have integer element type.
10831 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10832 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10833 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10834 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10835 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10836 LHSVecType->getElementType()->isIntegerType() &&
10837 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10838 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10839 return LHSType;
10840 }
10841 if (!IsCompAssign &&
10842 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10843 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10844 RHSVecType->getElementType()->isIntegerType()) {
10845 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10846 return RHSType;
10847 }
10848 }
10849
10850 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10851 // invalid since the ambiguity can affect the ABI.
10852 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10853 unsigned &SVEorRVV) {
10854 const VectorType *VecType = SecondType->getAs<VectorType>();
10855 SVEorRVV = 0;
10856 if (FirstType->isSizelessBuiltinType() && VecType) {
10857 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10858 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10859 return true;
10860 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10861 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10862 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10863 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10864 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10865 SVEorRVV = 1;
10866 return true;
10867 }
10868 }
10869
10870 return false;
10871 };
10872
10873 unsigned SVEorRVV;
10874 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10875 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10876 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10877 << SVEorRVV << LHSType << RHSType;
10878 return QualType();
10879 }
10880
10881 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10882 // invalid since the ambiguity can affect the ABI.
10883 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10884 unsigned &SVEorRVV) {
10885 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10886 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10887
10888 SVEorRVV = 0;
10889 if (FirstVecType && SecondVecType) {
10890 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10891 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10892 SecondVecType->getVectorKind() ==
10893 VectorKind::SveFixedLengthPredicate)
10894 return true;
10895 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10896 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10897 SecondVecType->getVectorKind() ==
10898 VectorKind::RVVFixedLengthMask_1 ||
10899 SecondVecType->getVectorKind() ==
10900 VectorKind::RVVFixedLengthMask_2 ||
10901 SecondVecType->getVectorKind() ==
10902 VectorKind::RVVFixedLengthMask_4) {
10903 SVEorRVV = 1;
10904 return true;
10905 }
10906 }
10907 return false;
10908 }
10909
10910 if (SecondVecType &&
10911 SecondVecType->getVectorKind() == VectorKind::Generic) {
10912 if (FirstType->isSVESizelessBuiltinType())
10913 return true;
10914 if (FirstType->isRVVSizelessBuiltinType()) {
10915 SVEorRVV = 1;
10916 return true;
10917 }
10918 }
10919
10920 return false;
10921 };
10922
10923 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10924 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10925 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10926 << SVEorRVV << LHSType << RHSType;
10927 return QualType();
10928 }
10929
10930 // If there's a vector type and a scalar, try to convert the scalar to
10931 // the vector element type and splat.
10932 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10933 if (!RHSVecType) {
10934 if (isa<ExtVectorType>(Val: LHSVecType)) {
10935 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10936 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10937 DiagID))
10938 return LHSType;
10939 } else {
10940 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10941 return LHSType;
10942 }
10943 }
10944 if (!LHSVecType) {
10945 if (isa<ExtVectorType>(Val: RHSVecType)) {
10946 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10947 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10948 vectorTy: RHSType, DiagID))
10949 return RHSType;
10950 } else {
10951 if (LHS.get()->isLValue() ||
10952 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10953 return RHSType;
10954 }
10955 }
10956
10957 // FIXME: The code below also handles conversion between vectors and
10958 // non-scalars, we should break this down into fine grained specific checks
10959 // and emit proper diagnostics.
10960 QualType VecType = LHSVecType ? LHSType : RHSType;
10961 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10962 QualType OtherType = LHSVecType ? RHSType : LHSType;
10963 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10964 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10965 if (Context.getTargetInfo().getTriple().isPPC() &&
10966 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10967 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10968 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10969 // If we're allowing lax vector conversions, only the total (data) size
10970 // needs to be the same. For non compound assignment, if one of the types is
10971 // scalar, the result is always the vector type.
10972 if (!IsCompAssign) {
10973 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10974 return VecType;
10975 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10976 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10977 // type. Note that this is already done by non-compound assignments in
10978 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10979 // <1 x T> -> T. The result is also a vector type.
10980 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10981 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10982 ExprResult *RHSExpr = &RHS;
10983 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10984 return VecType;
10985 }
10986 }
10987
10988 // Okay, the expression is invalid.
10989
10990 // If there's a non-vector, non-real operand, diagnose that.
10991 if ((!RHSVecType && !RHSType->isRealType()) ||
10992 (!LHSVecType && !LHSType->isRealType())) {
10993 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10994 << LHSType << RHSType
10995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10996 return QualType();
10997 }
10998
10999 // OpenCL V1.1 6.2.6.p1:
11000 // If the operands are of more than one vector type, then an error shall
11001 // occur. Implicit conversions between vector types are not permitted, per
11002 // section 6.2.1.
11003 if (getLangOpts().OpenCL &&
11004 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
11005 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
11006 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
11007 << RHSType;
11008 return QualType();
11009 }
11010
11011
11012 // If there is a vector type that is not a ExtVector and a scalar, we reach
11013 // this point if scalar could not be converted to the vector's element type
11014 // without truncation.
11015 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11016 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11017 QualType Scalar = LHSVecType ? RHSType : LHSType;
11018 QualType Vector = LHSVecType ? LHSType : RHSType;
11019 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11020 Diag(Loc,
11021 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11022 << ScalarOrVector << Scalar << Vector;
11023
11024 return QualType();
11025 }
11026
11027 // Otherwise, use the generic diagnostic.
11028 Diag(Loc, DiagID)
11029 << LHSType << RHSType
11030 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11031 return QualType();
11032}
11033
11034QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11035 SourceLocation Loc,
11036 bool IsCompAssign,
11037 ArithConvKind OperationKind) {
11038 if (!IsCompAssign) {
11039 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11040 if (LHS.isInvalid())
11041 return QualType();
11042 }
11043 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11044 if (RHS.isInvalid())
11045 return QualType();
11046
11047 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11048 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11049
11050 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11051 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11052
11053 unsigned DiagID = diag::err_typecheck_invalid_operands;
11054 if ((OperationKind == ArithConvKind::Arithmetic) &&
11055 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11056 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11057 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11058 << RHS.get()->getSourceRange();
11059 return QualType();
11060 }
11061
11062 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11063 return LHSType;
11064
11065 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11066 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11067 return LHSType;
11068 }
11069 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11070 if (LHS.get()->isLValue() ||
11071 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11072 return RHSType;
11073 }
11074
11075 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11076 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11077 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11078 << LHSType << RHSType << LHS.get()->getSourceRange()
11079 << RHS.get()->getSourceRange();
11080 return QualType();
11081 }
11082
11083 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11084 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11085 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11086 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11087 << LHSType << RHSType << LHS.get()->getSourceRange()
11088 << RHS.get()->getSourceRange();
11089 return QualType();
11090 }
11091
11092 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11093 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11094 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11095 bool ScalarOrVector =
11096 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11097
11098 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11099 << ScalarOrVector << Scalar << Vector;
11100
11101 return QualType();
11102 }
11103
11104 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11105 << RHS.get()->getSourceRange();
11106 return QualType();
11107}
11108
11109// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11110// expression. These are mainly cases where the null pointer is used as an
11111// integer instead of a pointer.
11112static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11113 SourceLocation Loc, bool IsCompare) {
11114 // The canonical way to check for a GNU null is with isNullPointerConstant,
11115 // but we use a bit of a hack here for speed; this is a relatively
11116 // hot path, and isNullPointerConstant is slow.
11117 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11118 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11119
11120 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11121
11122 // Avoid analyzing cases where the result will either be invalid (and
11123 // diagnosed as such) or entirely valid and not something to warn about.
11124 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11125 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11126 return;
11127
11128 // Comparison operations would not make sense with a null pointer no matter
11129 // what the other expression is.
11130 if (!IsCompare) {
11131 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11132 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11133 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11134 return;
11135 }
11136
11137 // The rest of the operations only make sense with a null pointer
11138 // if the other expression is a pointer.
11139 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11140 NonNullType->canDecayToPointerType())
11141 return;
11142
11143 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11144 << LHSNull /* LHS is NULL */ << NonNullType
11145 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11146}
11147
11148static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11149 SourceLocation OpLoc) {
11150 // If the divisor is real, then this is real/real or complex/real division.
11151 // Either way there can be no precision loss.
11152 auto *CT = DivisorTy->getAs<ComplexType>();
11153 if (!CT)
11154 return;
11155
11156 QualType ElementType = CT->getElementType().getCanonicalType();
11157 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11158 LangOptions::ComplexRangeKind::CX_Promoted;
11159 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11160 return;
11161
11162 ASTContext &Ctx = S.getASTContext();
11163 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11164 const llvm::fltSemantics &ElementTypeSemantics =
11165 Ctx.getFloatTypeSemantics(T: ElementType);
11166 const llvm::fltSemantics &HigherElementTypeSemantics =
11167 Ctx.getFloatTypeSemantics(T: HigherElementType);
11168
11169 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11170 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11171 (HigherElementType == Ctx.LongDoubleTy &&
11172 !Ctx.getTargetInfo().hasLongDoubleType())) {
11173 // Retain the location of the first use of higher precision type.
11174 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11175 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11176 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11177 if (Type == HigherElementType) {
11178 Num++;
11179 return;
11180 }
11181 }
11182 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11183 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11184 }
11185}
11186
11187static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11188 SourceLocation Loc) {
11189 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11190 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11191 if (!LUE || !RUE)
11192 return;
11193 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11194 RUE->getKind() != UETT_SizeOf)
11195 return;
11196
11197 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11198 QualType LHSTy = LHSArg->getType();
11199 QualType RHSTy;
11200
11201 if (RUE->isArgumentType())
11202 RHSTy = RUE->getArgumentType().getNonReferenceType();
11203 else
11204 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11205
11206 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11207 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11208 return;
11209
11210 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11211 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11212 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11213 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11214 << LHSArgDecl;
11215 }
11216 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11217 QualType ArrayElemTy = ArrayTy->getElementType();
11218 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11219 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11220 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11221 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11222 return;
11223 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11224 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11225 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11226 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11227 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11228 << LHSArgDecl;
11229 }
11230
11231 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11232 }
11233}
11234
11235static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11236 ExprResult &RHS,
11237 SourceLocation Loc, bool IsDiv) {
11238 // Check for division/remainder by zero.
11239 Expr::EvalResult RHSValue;
11240 if (!RHS.get()->isValueDependent() &&
11241 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11242 RHSValue.Val.getInt() == 0)
11243 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11244 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11245 << IsDiv << RHS.get()->getSourceRange());
11246}
11247
11248static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11249 const ExprResult &LHS, const ExprResult &RHS,
11250 BinaryOperatorKind Opc) {
11251 if (!LHS.isUsable() || !RHS.isUsable())
11252 return;
11253 const Expr *LHSExpr = LHS.get();
11254 const Expr *RHSExpr = RHS.get();
11255 const QualType LHSType = LHSExpr->getType();
11256 const QualType RHSType = RHSExpr->getType();
11257 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11258 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11259 if (!LHSIsScoped && !RHSIsScoped)
11260 return;
11261 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11262 return;
11263 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11264 return;
11265 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11266 return;
11267 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11268 SourceLocation BeginLoc = expr->getBeginLoc();
11269 QualType IntType = type->castAs<EnumType>()
11270 ->getDecl()
11271 ->getDefinitionOrSelf()
11272 ->getIntegerType();
11273 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11274 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11275 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11276 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11277 };
11278 if (LHSIsScoped) {
11279 DiagnosticHelper(LHSExpr, LHSType);
11280 }
11281 if (RHSIsScoped) {
11282 DiagnosticHelper(RHSExpr, RHSType);
11283 }
11284}
11285
11286QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11287 SourceLocation Loc,
11288 BinaryOperatorKind Opc) {
11289 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11290 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11291
11292 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11293
11294 QualType LHSTy = LHS.get()->getType();
11295 QualType RHSTy = RHS.get()->getType();
11296 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11297 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11298 /*AllowBothBool*/ getLangOpts().AltiVec,
11299 /*AllowBoolConversions*/ false,
11300 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11301 /*ReportInvalid*/ true);
11302 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11303 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11304 OperationKind: ArithConvKind::Arithmetic);
11305 if (!IsDiv &&
11306 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11307 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11308 // For division, only matrix-by-scalar is supported. Other combinations with
11309 // matrix types are invalid.
11310 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11311 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11312
11313 QualType compType = UsualArithmeticConversions(
11314 LHS, RHS, Loc,
11315 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11316 if (LHS.isInvalid() || RHS.isInvalid())
11317 return QualType();
11318
11319 if (compType.isNull() || !compType->isArithmeticType()) {
11320 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11321 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11322 return ResultTy;
11323 }
11324 if (IsDiv) {
11325 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11326 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11327 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11328 }
11329 return compType;
11330}
11331
11332QualType Sema::CheckRemainderOperands(
11333 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11334 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11335
11336 // Note: This check is here to simplify the double exclusions of
11337 // scalar and vector HLSL checks. No getLangOpts().HLSL
11338 // is needed since all languages exlcude doubles.
11339 if (LHS.get()->getType()->isDoubleType() ||
11340 RHS.get()->getType()->isDoubleType() ||
11341 (LHS.get()->getType()->isVectorType() && LHS.get()
11342 ->getType()
11343 ->getAs<VectorType>()
11344 ->getElementType()
11345 ->isDoubleType()) ||
11346 (RHS.get()->getType()->isVectorType() && RHS.get()
11347 ->getType()
11348 ->getAs<VectorType>()
11349 ->getElementType()
11350 ->isDoubleType()))
11351 return InvalidOperands(Loc, LHS, RHS);
11352
11353 if (LHS.get()->getType()->isVectorType() ||
11354 RHS.get()->getType()->isVectorType()) {
11355 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11356 RHS.get()->getType()->hasIntegerRepresentation()) ||
11357 (getLangOpts().HLSL &&
11358 (LHS.get()->getType()->hasFloatingRepresentation() ||
11359 RHS.get()->getType()->hasFloatingRepresentation())))
11360 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11361 /*AllowBothBool*/ getLangOpts().AltiVec,
11362 /*AllowBoolConversions*/ false,
11363 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11364 /*ReportInvalid*/ true);
11365 return InvalidOperands(Loc, LHS, RHS);
11366 }
11367
11368 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11369 RHS.get()->getType()->isSveVLSBuiltinType()) {
11370 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11371 RHS.get()->getType()->hasIntegerRepresentation())
11372 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11373 OperationKind: ArithConvKind::Arithmetic);
11374
11375 return InvalidOperands(Loc, LHS, RHS);
11376 }
11377
11378 QualType compType = UsualArithmeticConversions(
11379 LHS, RHS, Loc,
11380 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11381 if (LHS.isInvalid() || RHS.isInvalid())
11382 return QualType();
11383
11384 if (compType.isNull() ||
11385 (!compType->isIntegerType() &&
11386 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11387 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11388 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11389 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11390 return ResultTy;
11391 }
11392 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11393 return compType;
11394}
11395
11396/// Diagnose invalid arithmetic on two void pointers.
11397static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11398 Expr *LHSExpr, Expr *RHSExpr) {
11399 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11400 ? diag::err_typecheck_pointer_arith_void_type
11401 : diag::ext_gnu_void_ptr)
11402 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11403 << RHSExpr->getSourceRange();
11404}
11405
11406/// Diagnose invalid arithmetic on a void pointer.
11407static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11408 Expr *Pointer) {
11409 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11410 ? diag::err_typecheck_pointer_arith_void_type
11411 : diag::ext_gnu_void_ptr)
11412 << 0 /* one pointer */ << Pointer->getSourceRange();
11413}
11414
11415/// Diagnose invalid arithmetic on a null pointer.
11416///
11417/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11418/// idiom, which we recognize as a GNU extension.
11419///
11420static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11421 Expr *Pointer, bool IsGNUIdiom) {
11422 if (IsGNUIdiom)
11423 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11424 << Pointer->getSourceRange();
11425 else
11426 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11427 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11428}
11429
11430/// Diagnose invalid subraction on a null pointer.
11431///
11432static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11433 Expr *Pointer, bool BothNull) {
11434 // Null - null is valid in C++ [expr.add]p7
11435 if (BothNull && S.getLangOpts().CPlusPlus)
11436 return;
11437
11438 // Is this s a macro from a system header?
11439 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11440 return;
11441
11442 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11443 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11444 << S.getLangOpts().CPlusPlus
11445 << Pointer->getSourceRange());
11446}
11447
11448/// Diagnose invalid arithmetic on two function pointers.
11449static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11450 Expr *LHS, Expr *RHS) {
11451 assert(LHS->getType()->isAnyPointerType());
11452 assert(RHS->getType()->isAnyPointerType());
11453 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11454 ? diag::err_typecheck_pointer_arith_function_type
11455 : diag::ext_gnu_ptr_func_arith)
11456 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11457 // We only show the second type if it differs from the first.
11458 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11459 T2: RHS->getType())
11460 << RHS->getType()->getPointeeType()
11461 << LHS->getSourceRange() << RHS->getSourceRange();
11462}
11463
11464/// Diagnose invalid arithmetic on a function pointer.
11465static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11466 Expr *Pointer) {
11467 assert(Pointer->getType()->isAnyPointerType());
11468 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11469 ? diag::err_typecheck_pointer_arith_function_type
11470 : diag::ext_gnu_ptr_func_arith)
11471 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11472 << 0 /* one pointer, so only one type */
11473 << Pointer->getSourceRange();
11474}
11475
11476/// Emit error if Operand is incomplete pointer type
11477///
11478/// \returns True if pointer has incomplete type
11479static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11480 Expr *Operand) {
11481 QualType ResType = Operand->getType();
11482 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11483 ResType = ResAtomicType->getValueType();
11484
11485 assert(ResType->isAnyPointerType());
11486 QualType PointeeTy = ResType->getPointeeType();
11487 return S.RequireCompleteSizedType(
11488 Loc, T: PointeeTy,
11489 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11490 Args: Operand->getSourceRange());
11491}
11492
11493/// Check the validity of an arithmetic pointer operand.
11494///
11495/// If the operand has pointer type, this code will check for pointer types
11496/// which are invalid in arithmetic operations. These will be diagnosed
11497/// appropriately, including whether or not the use is supported as an
11498/// extension.
11499///
11500/// \returns True when the operand is valid to use (even if as an extension).
11501static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11502 Expr *Operand) {
11503 QualType ResType = Operand->getType();
11504 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11505 ResType = ResAtomicType->getValueType();
11506
11507 if (!ResType->isAnyPointerType()) return true;
11508
11509 QualType PointeeTy = ResType->getPointeeType();
11510 if (PointeeTy->isVoidType()) {
11511 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11512 return !S.getLangOpts().CPlusPlus;
11513 }
11514 if (PointeeTy->isFunctionType()) {
11515 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11516 return !S.getLangOpts().CPlusPlus;
11517 }
11518
11519 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11520
11521 return true;
11522}
11523
11524/// Check the validity of a binary arithmetic operation w.r.t. pointer
11525/// operands.
11526///
11527/// This routine will diagnose any invalid arithmetic on pointer operands much
11528/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11529/// for emitting a single diagnostic even for operations where both LHS and RHS
11530/// are (potentially problematic) pointers.
11531///
11532/// \returns True when the operand is valid to use (even if as an extension).
11533static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11534 Expr *LHSExpr, Expr *RHSExpr) {
11535 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11536 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11537 if (!isLHSPointer && !isRHSPointer) return true;
11538
11539 QualType LHSPointeeTy, RHSPointeeTy;
11540 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11541 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11542
11543 // if both are pointers check if operation is valid wrt address spaces
11544 if (isLHSPointer && isRHSPointer) {
11545 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11546 Ctx: S.getASTContext())) {
11547 S.Diag(Loc,
11548 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11549 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11550 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11551 return false;
11552 }
11553 }
11554
11555 // Check for arithmetic on pointers to incomplete types.
11556 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11557 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11558 if (isLHSVoidPtr || isRHSVoidPtr) {
11559 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11560 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11561 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11562
11563 return !S.getLangOpts().CPlusPlus;
11564 }
11565
11566 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11567 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11568 if (isLHSFuncPtr || isRHSFuncPtr) {
11569 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11570 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11571 Pointer: RHSExpr);
11572 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11573
11574 return !S.getLangOpts().CPlusPlus;
11575 }
11576
11577 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11578 return false;
11579 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11580 return false;
11581
11582 return true;
11583}
11584
11585/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11586/// literal.
11587static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11588 Expr *LHSExpr, Expr *RHSExpr) {
11589 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11590 Expr* IndexExpr = RHSExpr;
11591 if (!StrExpr) {
11592 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11593 IndexExpr = LHSExpr;
11594 }
11595
11596 bool IsStringPlusInt = StrExpr &&
11597 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11598 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11599 return;
11600
11601 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11602 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11603 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11604
11605 // Only print a fixit for "str" + int, not for int + "str".
11606 if (IndexExpr == RHSExpr) {
11607 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11608 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11609 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11610 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11611 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11612 } else
11613 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11614}
11615
11616/// Emit a warning when adding a char literal to a string.
11617static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11618 Expr *LHSExpr, Expr *RHSExpr) {
11619 const Expr *StringRefExpr = LHSExpr;
11620 const CharacterLiteral *CharExpr =
11621 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11622
11623 if (!CharExpr) {
11624 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11625 StringRefExpr = RHSExpr;
11626 }
11627
11628 if (!CharExpr || !StringRefExpr)
11629 return;
11630
11631 const QualType StringType = StringRefExpr->getType();
11632
11633 // Return if not a PointerType.
11634 if (!StringType->isAnyPointerType())
11635 return;
11636
11637 // Return if not a CharacterType.
11638 if (!StringType->getPointeeType()->isAnyCharacterType())
11639 return;
11640
11641 ASTContext &Ctx = Self.getASTContext();
11642 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11643
11644 const QualType CharType = CharExpr->getType();
11645 if (!CharType->isAnyCharacterType() &&
11646 CharType->isIntegerType() &&
11647 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11648 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11649 << DiagRange << Ctx.CharTy;
11650 } else {
11651 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11652 << DiagRange << CharExpr->getType();
11653 }
11654
11655 // Only print a fixit for str + char, not for char + str.
11656 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11657 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11658 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11659 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11660 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11661 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11662 } else {
11663 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11664 }
11665}
11666
11667/// Emit error when two pointers are incompatible.
11668static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11669 Expr *LHSExpr, Expr *RHSExpr) {
11670 assert(LHSExpr->getType()->isAnyPointerType());
11671 assert(RHSExpr->getType()->isAnyPointerType());
11672 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11673 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11674 << RHSExpr->getSourceRange();
11675}
11676
11677// C99 6.5.6
11678QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11679 SourceLocation Loc, BinaryOperatorKind Opc,
11680 QualType* CompLHSTy) {
11681 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11682
11683 if (LHS.get()->getType()->isVectorType() ||
11684 RHS.get()->getType()->isVectorType()) {
11685 QualType compType =
11686 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11687 /*AllowBothBool*/ getLangOpts().AltiVec,
11688 /*AllowBoolConversions*/ getLangOpts().ZVector,
11689 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11690 /*ReportInvalid*/ true);
11691 if (CompLHSTy) *CompLHSTy = compType;
11692 return compType;
11693 }
11694
11695 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11696 RHS.get()->getType()->isSveVLSBuiltinType()) {
11697 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11698 OperationKind: ArithConvKind::Arithmetic);
11699 if (CompLHSTy)
11700 *CompLHSTy = compType;
11701 return compType;
11702 }
11703
11704 if (LHS.get()->getType()->isConstantMatrixType() ||
11705 RHS.get()->getType()->isConstantMatrixType()) {
11706 QualType compType =
11707 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11708 if (CompLHSTy)
11709 *CompLHSTy = compType;
11710 return compType;
11711 }
11712
11713 QualType compType = UsualArithmeticConversions(
11714 LHS, RHS, Loc,
11715 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11716 if (LHS.isInvalid() || RHS.isInvalid())
11717 return QualType();
11718
11719 // Diagnose "string literal" '+' int and string '+' "char literal".
11720 if (Opc == BO_Add) {
11721 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11722 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11723 }
11724
11725 // handle the common case first (both operands are arithmetic).
11726 if (!compType.isNull() && compType->isArithmeticType()) {
11727 if (CompLHSTy) *CompLHSTy = compType;
11728 return compType;
11729 }
11730
11731 // Type-checking. Ultimately the pointer's going to be in PExp;
11732 // note that we bias towards the LHS being the pointer.
11733 Expr *PExp = LHS.get(), *IExp = RHS.get();
11734
11735 bool isObjCPointer;
11736 if (PExp->getType()->isPointerType()) {
11737 isObjCPointer = false;
11738 } else if (PExp->getType()->isObjCObjectPointerType()) {
11739 isObjCPointer = true;
11740 } else {
11741 std::swap(a&: PExp, b&: IExp);
11742 if (PExp->getType()->isPointerType()) {
11743 isObjCPointer = false;
11744 } else if (PExp->getType()->isObjCObjectPointerType()) {
11745 isObjCPointer = true;
11746 } else {
11747 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11748 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11749 return ResultTy;
11750 }
11751 }
11752 assert(PExp->getType()->isAnyPointerType());
11753
11754 if (!IExp->getType()->isIntegerType())
11755 return InvalidOperands(Loc, LHS, RHS);
11756
11757 // Adding to a null pointer results in undefined behavior.
11758 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11759 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11760 // In C++ adding zero to a null pointer is defined.
11761 Expr::EvalResult KnownVal;
11762 if (!getLangOpts().CPlusPlus ||
11763 (!IExp->isValueDependent() &&
11764 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11765 KnownVal.Val.getInt() != 0))) {
11766 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11767 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11768 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11769 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11770 }
11771 }
11772
11773 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11774 return QualType();
11775
11776 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11777 return QualType();
11778
11779 // Arithmetic on label addresses is normally allowed, except when we add
11780 // a ptrauth signature to the addresses.
11781 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11782 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11783 << /*addition*/ 1;
11784 return QualType();
11785 }
11786
11787 // Check array bounds for pointer arithemtic
11788 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11789
11790 if (CompLHSTy) {
11791 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11792 if (LHSTy.isNull()) {
11793 LHSTy = LHS.get()->getType();
11794 if (Context.isPromotableIntegerType(T: LHSTy))
11795 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11796 }
11797 *CompLHSTy = LHSTy;
11798 }
11799
11800 return PExp->getType();
11801}
11802
11803// C99 6.5.6
11804QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11805 SourceLocation Loc,
11806 BinaryOperatorKind Opc,
11807 QualType *CompLHSTy) {
11808 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11809
11810 if (LHS.get()->getType()->isVectorType() ||
11811 RHS.get()->getType()->isVectorType()) {
11812 QualType compType =
11813 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11814 /*AllowBothBool*/ getLangOpts().AltiVec,
11815 /*AllowBoolConversions*/ getLangOpts().ZVector,
11816 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11817 /*ReportInvalid*/ true);
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 // Enforce type constraints: C99 6.5.6p3.
11847
11848 // Handle the common case first (both operands are arithmetic).
11849 if (!compType.isNull() && compType->isArithmeticType()) {
11850 if (CompLHSTy) *CompLHSTy = compType;
11851 return compType;
11852 }
11853
11854 // Either ptr - int or ptr - ptr.
11855 if (LHS.get()->getType()->isAnyPointerType()) {
11856 QualType lpointee = LHS.get()->getType()->getPointeeType();
11857
11858 // Diagnose bad cases where we step over interface counts.
11859 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11860 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11861 return QualType();
11862
11863 // Arithmetic on label addresses is normally allowed, except when we add
11864 // a ptrauth signature to the addresses.
11865 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11866 getLangOpts().PointerAuthIndirectGotos) {
11867 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11868 << /*subtraction*/ 0;
11869 return QualType();
11870 }
11871
11872 // The result type of a pointer-int computation is the pointer type.
11873 if (RHS.get()->getType()->isIntegerType()) {
11874 // Subtracting from a null pointer should produce a warning.
11875 // The last argument to the diagnose call says this doesn't match the
11876 // GNU int-to-pointer idiom.
11877 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11878 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11879 // In C++ adding zero to a null pointer is defined.
11880 Expr::EvalResult KnownVal;
11881 if (!getLangOpts().CPlusPlus ||
11882 (!RHS.get()->isValueDependent() &&
11883 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11884 KnownVal.Val.getInt() != 0))) {
11885 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11886 }
11887 }
11888
11889 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11890 return QualType();
11891
11892 // Check array bounds for pointer arithemtic
11893 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11894 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11895
11896 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11897 return LHS.get()->getType();
11898 }
11899
11900 // Handle pointer-pointer subtractions.
11901 if (const PointerType *RHSPTy
11902 = RHS.get()->getType()->getAs<PointerType>()) {
11903 QualType rpointee = RHSPTy->getPointeeType();
11904
11905 if (getLangOpts().CPlusPlus) {
11906 // Pointee types must be the same: C++ [expr.add]
11907 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11908 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11909 }
11910 } else {
11911 // Pointee types must be compatible C99 6.5.6p3
11912 if (!Context.typesAreCompatible(
11913 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11914 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11915 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11916 return QualType();
11917 }
11918 }
11919
11920 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11921 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11922 return QualType();
11923
11924 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11925 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11926 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11927 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11928
11929 // Subtracting nullptr or from nullptr is suspect
11930 if (LHSIsNullPtr)
11931 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11932 if (RHSIsNullPtr)
11933 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11934
11935 // The pointee type may have zero size. As an extension, a structure or
11936 // union may have zero size or an array may have zero length. In this
11937 // case subtraction does not make sense.
11938 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11939 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11940 if (ElementSize.isZero()) {
11941 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11942 << rpointee.getUnqualifiedType()
11943 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11944 }
11945 }
11946
11947 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11948 return Context.getPointerDiffType();
11949 }
11950 }
11951
11952 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11953 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11954 return ResultTy;
11955}
11956
11957static bool isScopedEnumerationType(QualType T) {
11958 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11959 return ET->getDecl()->isScoped();
11960 return false;
11961}
11962
11963static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11964 SourceLocation Loc, BinaryOperatorKind Opc,
11965 QualType LHSType) {
11966 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11967 // so skip remaining warnings as we don't want to modify values within Sema.
11968 if (S.getLangOpts().OpenCL)
11969 return;
11970
11971 if (Opc == BO_Shr &&
11972 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11973 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11974
11975 // Check right/shifter operand
11976 Expr::EvalResult RHSResult;
11977 if (RHS.get()->isValueDependent() ||
11978 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11979 return;
11980 llvm::APSInt Right = RHSResult.Val.getInt();
11981
11982 if (Right.isNegative()) {
11983 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11984 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11985 << RHS.get()->getSourceRange());
11986 return;
11987 }
11988
11989 QualType LHSExprType = LHS.get()->getType();
11990 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11991 if (LHSExprType->isBitIntType())
11992 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11993 else if (LHSExprType->isFixedPointType()) {
11994 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11995 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11996 }
11997 if (Right.uge(RHS: LeftSize)) {
11998 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11999 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
12000 << RHS.get()->getSourceRange());
12001 return;
12002 }
12003
12004 // FIXME: We probably need to handle fixed point types specially here.
12005 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12006 return;
12007
12008 // When left shifting an ICE which is signed, we can check for overflow which
12009 // according to C++ standards prior to C++2a has undefined behavior
12010 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12011 // more than the maximum value representable in the result type, so never
12012 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12013 // expression is still probably a bug.)
12014 Expr::EvalResult LHSResult;
12015 if (LHS.get()->isValueDependent() ||
12016 LHSType->hasUnsignedIntegerRepresentation() ||
12017 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12018 return;
12019 llvm::APSInt Left = LHSResult.Val.getInt();
12020
12021 // Don't warn if signed overflow is defined, then all the rest of the
12022 // diagnostics will not be triggered because the behavior is defined.
12023 // Also don't warn in C++20 mode (and newer), as signed left shifts
12024 // always wrap and never overflow.
12025 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12026 return;
12027
12028 // If LHS does not have a non-negative value then, the
12029 // behavior is undefined before C++2a. Warn about it.
12030 if (Left.isNegative()) {
12031 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
12032 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
12033 << LHS.get()->getSourceRange());
12034 return;
12035 }
12036
12037 llvm::APInt ResultBits =
12038 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12039 if (ResultBits.ule(RHS: LeftSize))
12040 return;
12041 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12042 Result = Result.shl(ShiftAmt: Right);
12043
12044 // Print the bit representation of the signed integer as an unsigned
12045 // hexadecimal number.
12046 SmallString<40> HexResult;
12047 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12048
12049 // If we are only missing a sign bit, this is less likely to result in actual
12050 // bugs -- if the result is cast back to an unsigned type, it will have the
12051 // expected value. Thus we place this behind a different warning that can be
12052 // turned off separately if needed.
12053 if (ResultBits - 1 == LeftSize) {
12054 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12055 << HexResult << LHSType
12056 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12057 return;
12058 }
12059
12060 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12061 << HexResult.str() << Result.getSignificantBits() << LHSType
12062 << Left.getBitWidth() << LHS.get()->getSourceRange()
12063 << RHS.get()->getSourceRange();
12064}
12065
12066/// Return the resulting type when a vector is shifted
12067/// by a scalar or vector shift amount.
12068static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12069 SourceLocation Loc, bool IsCompAssign) {
12070 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12071 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12072 !LHS.get()->getType()->isVectorType()) {
12073 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12074 << RHS.get()->getType() << LHS.get()->getType()
12075 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12076 return QualType();
12077 }
12078
12079 if (!IsCompAssign) {
12080 LHS = S.UsualUnaryConversions(E: LHS.get());
12081 if (LHS.isInvalid()) return QualType();
12082 }
12083
12084 RHS = S.UsualUnaryConversions(E: RHS.get());
12085 if (RHS.isInvalid()) return QualType();
12086
12087 QualType LHSType = LHS.get()->getType();
12088 // Note that LHS might be a scalar because the routine calls not only in
12089 // OpenCL case.
12090 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12091 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12092
12093 // Note that RHS might not be a vector.
12094 QualType RHSType = RHS.get()->getType();
12095 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12096 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12097
12098 // Do not allow shifts for boolean vectors.
12099 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12100 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12101 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12102 << LHS.get()->getType() << RHS.get()->getType()
12103 << LHS.get()->getSourceRange();
12104 return QualType();
12105 }
12106
12107 // The operands need to be integers.
12108 if (!LHSEleType->isIntegerType()) {
12109 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12110 << LHS.get()->getType() << LHS.get()->getSourceRange();
12111 return QualType();
12112 }
12113
12114 if (!RHSEleType->isIntegerType()) {
12115 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12116 << RHS.get()->getType() << RHS.get()->getSourceRange();
12117 return QualType();
12118 }
12119
12120 if (!LHSVecTy) {
12121 assert(RHSVecTy);
12122 if (IsCompAssign)
12123 return RHSType;
12124 if (LHSEleType != RHSEleType) {
12125 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12126 LHSEleType = RHSEleType;
12127 }
12128 QualType VecTy =
12129 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12130 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12131 LHSType = VecTy;
12132 } else if (RHSVecTy) {
12133 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12134 // are applied component-wise. So if RHS is a vector, then ensure
12135 // that the number of elements is the same as LHS...
12136 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12137 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12138 << LHS.get()->getType() << RHS.get()->getType()
12139 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12140 return QualType();
12141 }
12142 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12143 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12144 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12145 if (LHSBT != RHSBT &&
12146 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12147 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12148 << LHS.get()->getType() << RHS.get()->getType()
12149 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12150 }
12151 }
12152 } else {
12153 // ...else expand RHS to match the number of elements in LHS.
12154 QualType VecTy =
12155 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12156 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12157 }
12158
12159 return LHSType;
12160}
12161
12162static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12163 ExprResult &RHS, SourceLocation Loc,
12164 bool IsCompAssign) {
12165 if (!IsCompAssign) {
12166 LHS = S.UsualUnaryConversions(E: LHS.get());
12167 if (LHS.isInvalid())
12168 return QualType();
12169 }
12170
12171 RHS = S.UsualUnaryConversions(E: RHS.get());
12172 if (RHS.isInvalid())
12173 return QualType();
12174
12175 QualType LHSType = LHS.get()->getType();
12176 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12177 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12178 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12179 : LHSType;
12180
12181 // Note that RHS might not be a vector
12182 QualType RHSType = RHS.get()->getType();
12183 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12184 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12185 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12186 : RHSType;
12187
12188 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12189 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12190 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12191 << LHSType << RHSType << LHS.get()->getSourceRange();
12192 return QualType();
12193 }
12194
12195 if (!LHSEleType->isIntegerType()) {
12196 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12197 << LHS.get()->getType() << LHS.get()->getSourceRange();
12198 return QualType();
12199 }
12200
12201 if (!RHSEleType->isIntegerType()) {
12202 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12203 << RHS.get()->getType() << RHS.get()->getSourceRange();
12204 return QualType();
12205 }
12206
12207 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12208 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12209 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12210 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12211 << LHSType << RHSType << LHS.get()->getSourceRange()
12212 << RHS.get()->getSourceRange();
12213 return QualType();
12214 }
12215
12216 if (!LHSType->isSveVLSBuiltinType()) {
12217 assert(RHSType->isSveVLSBuiltinType());
12218 if (IsCompAssign)
12219 return RHSType;
12220 if (LHSEleType != RHSEleType) {
12221 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12222 LHSEleType = RHSEleType;
12223 }
12224 const llvm::ElementCount VecSize =
12225 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12226 QualType VecTy =
12227 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12228 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12229 LHSType = VecTy;
12230 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12231 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12232 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12233 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12234 << LHSType << RHSType << LHS.get()->getSourceRange()
12235 << RHS.get()->getSourceRange();
12236 return QualType();
12237 }
12238 } else {
12239 const llvm::ElementCount VecSize =
12240 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12241 if (LHSEleType != RHSEleType) {
12242 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12243 RHSEleType = LHSEleType;
12244 }
12245 QualType VecTy =
12246 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12247 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12248 }
12249
12250 return LHSType;
12251}
12252
12253// C99 6.5.7
12254QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12255 SourceLocation Loc, BinaryOperatorKind Opc,
12256 bool IsCompAssign) {
12257 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12258
12259 // Vector shifts promote their scalar inputs to vector type.
12260 if (LHS.get()->getType()->isVectorType() ||
12261 RHS.get()->getType()->isVectorType()) {
12262 if (LangOpts.ZVector) {
12263 // The shift operators for the z vector extensions work basically
12264 // like general shifts, except that neither the LHS nor the RHS is
12265 // allowed to be a "vector bool".
12266 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12267 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12268 return InvalidOperands(Loc, LHS, RHS);
12269 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12270 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12271 return InvalidOperands(Loc, LHS, RHS);
12272 }
12273 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12274 }
12275
12276 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12277 RHS.get()->getType()->isSveVLSBuiltinType())
12278 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12279
12280 // Shifts don't perform usual arithmetic conversions, they just do integer
12281 // promotions on each operand. C99 6.5.7p3
12282
12283 // For the LHS, do usual unary conversions, but then reset them away
12284 // if this is a compound assignment.
12285 ExprResult OldLHS = LHS;
12286 LHS = UsualUnaryConversions(E: LHS.get());
12287 if (LHS.isInvalid())
12288 return QualType();
12289 QualType LHSType = LHS.get()->getType();
12290 if (IsCompAssign) LHS = OldLHS;
12291
12292 // The RHS is simpler.
12293 RHS = UsualUnaryConversions(E: RHS.get());
12294 if (RHS.isInvalid())
12295 return QualType();
12296 QualType RHSType = RHS.get()->getType();
12297
12298 // C99 6.5.7p2: Each of the operands shall have integer type.
12299 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12300 if ((!LHSType->isFixedPointOrIntegerType() &&
12301 !LHSType->hasIntegerRepresentation()) ||
12302 !RHSType->hasIntegerRepresentation()) {
12303 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12304 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12305 return ResultTy;
12306 }
12307
12308 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12309
12310 // "The type of the result is that of the promoted left operand."
12311 return LHSType;
12312}
12313
12314/// Diagnose bad pointer comparisons.
12315static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12316 ExprResult &LHS, ExprResult &RHS,
12317 bool IsError) {
12318 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12319 : diag::ext_typecheck_comparison_of_distinct_pointers)
12320 << LHS.get()->getType() << RHS.get()->getType()
12321 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12322}
12323
12324/// Returns false if the pointers are converted to a composite type,
12325/// true otherwise.
12326static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12327 ExprResult &LHS, ExprResult &RHS) {
12328 // C++ [expr.rel]p2:
12329 // [...] Pointer conversions (4.10) and qualification
12330 // conversions (4.4) are performed on pointer operands (or on
12331 // a pointer operand and a null pointer constant) to bring
12332 // them to their composite pointer type. [...]
12333 //
12334 // C++ [expr.eq]p1 uses the same notion for (in)equality
12335 // comparisons of pointers.
12336
12337 QualType LHSType = LHS.get()->getType();
12338 QualType RHSType = RHS.get()->getType();
12339 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12340 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12341
12342 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12343 if (T.isNull()) {
12344 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12345 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12346 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12347 else
12348 S.InvalidOperands(Loc, LHS, RHS);
12349 return true;
12350 }
12351
12352 return false;
12353}
12354
12355static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12356 ExprResult &LHS,
12357 ExprResult &RHS,
12358 bool IsError) {
12359 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12360 : diag::ext_typecheck_comparison_of_fptr_to_void)
12361 << LHS.get()->getType() << RHS.get()->getType()
12362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12363}
12364
12365static bool isObjCObjectLiteral(ExprResult &E) {
12366 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12367 case Stmt::ObjCArrayLiteralClass:
12368 case Stmt::ObjCDictionaryLiteralClass:
12369 case Stmt::ObjCStringLiteralClass:
12370 case Stmt::ObjCBoxedExprClass:
12371 return true;
12372 default:
12373 // Note that ObjCBoolLiteral is NOT an object literal!
12374 return false;
12375 }
12376}
12377
12378static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12379 const ObjCObjectPointerType *Type =
12380 LHS->getType()->getAs<ObjCObjectPointerType>();
12381
12382 // If this is not actually an Objective-C object, bail out.
12383 if (!Type)
12384 return false;
12385
12386 // Get the LHS object's interface type.
12387 QualType InterfaceType = Type->getPointeeType();
12388
12389 // If the RHS isn't an Objective-C object, bail out.
12390 if (!RHS->getType()->isObjCObjectPointerType())
12391 return false;
12392
12393 // Try to find the -isEqual: method.
12394 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12395 ObjCMethodDecl *Method =
12396 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12397 /*IsInstance=*/true);
12398 if (!Method) {
12399 if (Type->isObjCIdType()) {
12400 // For 'id', just check the global pool.
12401 Method =
12402 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12403 /*receiverId=*/receiverIdOrClass: true);
12404 } else {
12405 // Check protocols.
12406 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12407 /*IsInstance=*/true);
12408 }
12409 }
12410
12411 if (!Method)
12412 return false;
12413
12414 QualType T = Method->parameters()[0]->getType();
12415 if (!T->isObjCObjectPointerType())
12416 return false;
12417
12418 QualType R = Method->getReturnType();
12419 if (!R->isScalarType())
12420 return false;
12421
12422 return true;
12423}
12424
12425static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12426 ExprResult &LHS, ExprResult &RHS,
12427 BinaryOperator::Opcode Opc){
12428 Expr *Literal;
12429 Expr *Other;
12430 if (isObjCObjectLiteral(E&: LHS)) {
12431 Literal = LHS.get();
12432 Other = RHS.get();
12433 } else {
12434 Literal = RHS.get();
12435 Other = LHS.get();
12436 }
12437
12438 // Don't warn on comparisons against nil.
12439 Other = Other->IgnoreParenCasts();
12440 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12441 NPC: Expr::NPC_ValueDependentIsNotNull))
12442 return;
12443
12444 // This should be kept in sync with warn_objc_literal_comparison.
12445 // LK_String should always be after the other literals, since it has its own
12446 // warning flag.
12447 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12448 assert(LiteralKind != SemaObjC::LK_Block);
12449 if (LiteralKind == SemaObjC::LK_None) {
12450 llvm_unreachable("Unknown Objective-C object literal kind");
12451 }
12452
12453 if (LiteralKind == SemaObjC::LK_String)
12454 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12455 << Literal->getSourceRange();
12456 else
12457 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12458 << LiteralKind << Literal->getSourceRange();
12459
12460 if (BinaryOperator::isEqualityOp(Opc) &&
12461 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12462 SourceLocation Start = LHS.get()->getBeginLoc();
12463 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12464 CharSourceRange OpRange =
12465 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12466
12467 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12468 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12469 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12470 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12471 }
12472}
12473
12474/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12475static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12476 ExprResult &RHS, SourceLocation Loc,
12477 BinaryOperatorKind Opc) {
12478 // Check that left hand side is !something.
12479 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12480 if (!UO || UO->getOpcode() != UO_LNot) return;
12481
12482 // Only check if the right hand side is non-bool arithmetic type.
12483 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12484
12485 // Make sure that the something in !something is not bool.
12486 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12487 if (SubExpr->isKnownToHaveBooleanValue()) return;
12488
12489 // Emit warning.
12490 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12491 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12492 << Loc << IsBitwiseOp;
12493
12494 // First note suggest !(x < y)
12495 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12496 SourceLocation FirstClose = RHS.get()->getEndLoc();
12497 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12498 if (FirstClose.isInvalid())
12499 FirstOpen = SourceLocation();
12500 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12501 << IsBitwiseOp
12502 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12503 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12504
12505 // Second note suggests (!x) < y
12506 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12507 SourceLocation SecondClose = LHS.get()->getEndLoc();
12508 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12509 if (SecondClose.isInvalid())
12510 SecondOpen = SourceLocation();
12511 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12512 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12513 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12514}
12515
12516// Returns true if E refers to a non-weak array.
12517static bool checkForArray(const Expr *E) {
12518 const ValueDecl *D = nullptr;
12519 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12520 D = DR->getDecl();
12521 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12522 if (Mem->isImplicitAccess())
12523 D = Mem->getMemberDecl();
12524 }
12525 if (!D)
12526 return false;
12527 return D->getType()->isArrayType() && !D->isWeak();
12528}
12529
12530/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12531/// pointer and size is an unsigned integer. Return whether the result is
12532/// always true/false.
12533static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12534 const Expr *RHS,
12535 BinaryOperatorKind Opc) {
12536 if (!LHS->getType()->isPointerType() ||
12537 S.getLangOpts().PointerOverflowDefined)
12538 return std::nullopt;
12539
12540 // Canonicalize to >= or < predicate.
12541 switch (Opc) {
12542 case BO_GE:
12543 case BO_LT:
12544 break;
12545 case BO_GT:
12546 std::swap(a&: LHS, b&: RHS);
12547 Opc = BO_LT;
12548 break;
12549 case BO_LE:
12550 std::swap(a&: LHS, b&: RHS);
12551 Opc = BO_GE;
12552 break;
12553 default:
12554 return std::nullopt;
12555 }
12556
12557 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12558 if (!BO || BO->getOpcode() != BO_Add)
12559 return std::nullopt;
12560
12561 Expr *Other;
12562 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12563 Other = BO->getRHS();
12564 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12565 Other = BO->getLHS();
12566 else
12567 return std::nullopt;
12568
12569 if (!Other->getType()->isUnsignedIntegerType())
12570 return std::nullopt;
12571
12572 return Opc == BO_GE;
12573}
12574
12575/// Diagnose some forms of syntactically-obvious tautological comparison.
12576static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12577 Expr *LHS, Expr *RHS,
12578 BinaryOperatorKind Opc) {
12579 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12580 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12581
12582 QualType LHSType = LHS->getType();
12583 QualType RHSType = RHS->getType();
12584 if (LHSType->hasFloatingRepresentation() ||
12585 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12586 S.inTemplateInstantiation())
12587 return;
12588
12589 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12590 // Tautological diagnostics.
12591 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12592 return;
12593
12594 // Comparisons between two array types are ill-formed for operator<=>, so
12595 // we shouldn't emit any additional warnings about it.
12596 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12597 return;
12598
12599 // For non-floating point types, check for self-comparisons of the form
12600 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12601 // often indicate logic errors in the program.
12602 //
12603 // NOTE: Don't warn about comparison expressions resulting from macro
12604 // expansion. Also don't warn about comparisons which are only self
12605 // comparisons within a template instantiation. The warnings should catch
12606 // obvious cases in the definition of the template anyways. The idea is to
12607 // warn when the typed comparison operator will always evaluate to the same
12608 // result.
12609
12610 // Used for indexing into %select in warn_comparison_always
12611 enum {
12612 AlwaysConstant,
12613 AlwaysTrue,
12614 AlwaysFalse,
12615 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12616 };
12617
12618 // C++1a [array.comp]:
12619 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12620 // operands of array type.
12621 // C++2a [depr.array.comp]:
12622 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12623 // operands of array type are deprecated.
12624 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12625 RHSStripped->getType()->isArrayType()) {
12626 auto IsDeprArrayComparionIgnored =
12627 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12628 auto DiagID = S.getLangOpts().CPlusPlus26
12629 ? diag::warn_array_comparison_cxx26
12630 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12631 ? diag::warn_array_comparison
12632 : diag::warn_depr_array_comparison;
12633 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12634 << LHSStripped->getType() << RHSStripped->getType();
12635 // Carry on to produce the tautological comparison warning, if this
12636 // expression is potentially-evaluated, we can resolve the array to a
12637 // non-weak declaration, and so on.
12638 }
12639
12640 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12641 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12642 unsigned Result;
12643 switch (Opc) {
12644 case BO_EQ:
12645 case BO_LE:
12646 case BO_GE:
12647 Result = AlwaysTrue;
12648 break;
12649 case BO_NE:
12650 case BO_LT:
12651 case BO_GT:
12652 Result = AlwaysFalse;
12653 break;
12654 case BO_Cmp:
12655 Result = AlwaysEqual;
12656 break;
12657 default:
12658 Result = AlwaysConstant;
12659 break;
12660 }
12661 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12662 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12663 << 0 /*self-comparison*/
12664 << Result);
12665 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12666 // What is it always going to evaluate to?
12667 unsigned Result;
12668 switch (Opc) {
12669 case BO_EQ: // e.g. array1 == array2
12670 Result = AlwaysFalse;
12671 break;
12672 case BO_NE: // e.g. array1 != array2
12673 Result = AlwaysTrue;
12674 break;
12675 default: // e.g. array1 <= array2
12676 // The best we can say is 'a constant'
12677 Result = AlwaysConstant;
12678 break;
12679 }
12680 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12681 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12682 << 1 /*array comparison*/
12683 << Result);
12684 } else if (std::optional<bool> Res =
12685 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12686 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12687 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12688 << 2 /*pointer comparison*/
12689 << (*Res ? AlwaysTrue : AlwaysFalse));
12690 }
12691 }
12692
12693 if (isa<CastExpr>(Val: LHSStripped))
12694 LHSStripped = LHSStripped->IgnoreParenCasts();
12695 if (isa<CastExpr>(Val: RHSStripped))
12696 RHSStripped = RHSStripped->IgnoreParenCasts();
12697
12698 // Warn about comparisons against a string constant (unless the other
12699 // operand is null); the user probably wants string comparison function.
12700 Expr *LiteralString = nullptr;
12701 Expr *LiteralStringStripped = nullptr;
12702 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12703 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12704 NPC: Expr::NPC_ValueDependentIsNull)) {
12705 LiteralString = LHS;
12706 LiteralStringStripped = LHSStripped;
12707 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12708 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12709 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12710 NPC: Expr::NPC_ValueDependentIsNull)) {
12711 LiteralString = RHS;
12712 LiteralStringStripped = RHSStripped;
12713 }
12714
12715 if (LiteralString) {
12716 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12717 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12718 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12719 << LiteralString->getSourceRange());
12720 }
12721}
12722
12723static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12724 switch (CK) {
12725 default: {
12726#ifndef NDEBUG
12727 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12728 << "\n";
12729#endif
12730 llvm_unreachable("unhandled cast kind");
12731 }
12732 case CK_UserDefinedConversion:
12733 return ICK_Identity;
12734 case CK_LValueToRValue:
12735 return ICK_Lvalue_To_Rvalue;
12736 case CK_ArrayToPointerDecay:
12737 return ICK_Array_To_Pointer;
12738 case CK_FunctionToPointerDecay:
12739 return ICK_Function_To_Pointer;
12740 case CK_IntegralCast:
12741 return ICK_Integral_Conversion;
12742 case CK_FloatingCast:
12743 return ICK_Floating_Conversion;
12744 case CK_IntegralToFloating:
12745 case CK_FloatingToIntegral:
12746 return ICK_Floating_Integral;
12747 case CK_IntegralComplexCast:
12748 case CK_FloatingComplexCast:
12749 case CK_FloatingComplexToIntegralComplex:
12750 case CK_IntegralComplexToFloatingComplex:
12751 return ICK_Complex_Conversion;
12752 case CK_FloatingComplexToReal:
12753 case CK_FloatingRealToComplex:
12754 case CK_IntegralComplexToReal:
12755 case CK_IntegralRealToComplex:
12756 return ICK_Complex_Real;
12757 case CK_HLSLArrayRValue:
12758 return ICK_HLSL_Array_RValue;
12759 }
12760}
12761
12762static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12763 QualType FromType,
12764 SourceLocation Loc) {
12765 // Check for a narrowing implicit conversion.
12766 StandardConversionSequence SCS;
12767 SCS.setAsIdentityConversion();
12768 SCS.setToType(Idx: 0, T: FromType);
12769 SCS.setToType(Idx: 1, T: ToType);
12770 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12771 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12772
12773 APValue PreNarrowingValue;
12774 QualType PreNarrowingType;
12775 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12776 ConstantType&: PreNarrowingType,
12777 /*IgnoreFloatToIntegralConversion*/ true)) {
12778 case NK_Dependent_Narrowing:
12779 // Implicit conversion to a narrower type, but the expression is
12780 // value-dependent so we can't tell whether it's actually narrowing.
12781 case NK_Not_Narrowing:
12782 return false;
12783
12784 case NK_Constant_Narrowing:
12785 // Implicit conversion to a narrower type, and the value is not a constant
12786 // expression.
12787 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12788 << /*Constant*/ 1
12789 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12790 return true;
12791
12792 case NK_Variable_Narrowing:
12793 // Implicit conversion to a narrower type, and the value is not a constant
12794 // expression.
12795 case NK_Type_Narrowing:
12796 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12797 << /*Constant*/ 0 << FromType << ToType;
12798 // TODO: It's not a constant expression, but what if the user intended it
12799 // to be? Can we produce notes to help them figure out why it isn't?
12800 return true;
12801 }
12802 llvm_unreachable("unhandled case in switch");
12803}
12804
12805static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12806 ExprResult &LHS,
12807 ExprResult &RHS,
12808 SourceLocation Loc) {
12809 QualType LHSType = LHS.get()->getType();
12810 QualType RHSType = RHS.get()->getType();
12811 // Dig out the original argument type and expression before implicit casts
12812 // were applied. These are the types/expressions we need to check the
12813 // [expr.spaceship] requirements against.
12814 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12815 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12816 QualType LHSStrippedType = LHSStripped.get()->getType();
12817 QualType RHSStrippedType = RHSStripped.get()->getType();
12818
12819 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12820 // other is not, the program is ill-formed.
12821 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12822 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12823 return QualType();
12824 }
12825
12826 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12827 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12828 RHSStrippedType->isEnumeralType();
12829 if (NumEnumArgs == 1) {
12830 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12831 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12832 if (OtherTy->hasFloatingRepresentation()) {
12833 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12834 return QualType();
12835 }
12836 }
12837 if (NumEnumArgs == 2) {
12838 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12839 // type E, the operator yields the result of converting the operands
12840 // to the underlying type of E and applying <=> to the converted operands.
12841 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12842 S.InvalidOperands(Loc, LHS, RHS);
12843 return QualType();
12844 }
12845 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12846 assert(IntType->isArithmeticType());
12847
12848 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12849 // promote the boolean type, and all other promotable integer types, to
12850 // avoid this.
12851 if (S.Context.isPromotableIntegerType(T: IntType))
12852 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12853
12854 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12855 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12856 LHSType = RHSType = IntType;
12857 }
12858
12859 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12860 // usual arithmetic conversions are applied to the operands.
12861 QualType Type =
12862 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12863 if (LHS.isInvalid() || RHS.isInvalid())
12864 return QualType();
12865 if (Type.isNull()) {
12866 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12867 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12868 return ResultTy;
12869 }
12870
12871 std::optional<ComparisonCategoryType> CCT =
12872 getComparisonCategoryForBuiltinCmp(T: Type);
12873 if (!CCT)
12874 return S.InvalidOperands(Loc, LHS, RHS);
12875
12876 bool HasNarrowing = checkThreeWayNarrowingConversion(
12877 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12878 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12879 Loc: RHS.get()->getBeginLoc());
12880 if (HasNarrowing)
12881 return QualType();
12882
12883 assert(!Type.isNull() && "composite type for <=> has not been set");
12884
12885 return S.CheckComparisonCategoryType(
12886 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12887}
12888
12889static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12890 ExprResult &RHS,
12891 SourceLocation Loc,
12892 BinaryOperatorKind Opc) {
12893 if (Opc == BO_Cmp)
12894 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12895
12896 // C99 6.5.8p3 / C99 6.5.9p4
12897 QualType Type =
12898 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12899 if (LHS.isInvalid() || RHS.isInvalid())
12900 return QualType();
12901 if (Type.isNull()) {
12902 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12903 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12904 return ResultTy;
12905 }
12906 assert(Type->isArithmeticType() || Type->isEnumeralType());
12907
12908 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12909 return S.InvalidOperands(Loc, LHS, RHS);
12910
12911 // Check for comparisons of floating point operands using != and ==.
12912 if (Type->hasFloatingRepresentation())
12913 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12914
12915 // The result of comparisons is 'bool' in C++, 'int' in C.
12916 return S.Context.getLogicalOperationType();
12917}
12918
12919void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12920 if (!NullE.get()->getType()->isAnyPointerType())
12921 return;
12922 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12923 if (!E.get()->getType()->isAnyPointerType() &&
12924 E.get()->isNullPointerConstant(Ctx&: Context,
12925 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12926 Expr::NPCK_ZeroExpression) {
12927 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12928 if (CL->getValue() == 0)
12929 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12930 << NullValue
12931 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12932 Code: NullValue ? "NULL" : "(void *)0");
12933 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12934 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12935 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12936 if (T == Context.CharTy)
12937 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12938 << NullValue
12939 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12940 Code: NullValue ? "NULL" : "(void *)0");
12941 }
12942 }
12943}
12944
12945// C99 6.5.8, C++ [expr.rel]
12946QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12947 SourceLocation Loc,
12948 BinaryOperatorKind Opc) {
12949 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12950 bool IsThreeWay = Opc == BO_Cmp;
12951 bool IsOrdered = IsRelational || IsThreeWay;
12952 auto IsAnyPointerType = [](ExprResult E) {
12953 QualType Ty = E.get()->getType();
12954 return Ty->isPointerType() || Ty->isMemberPointerType();
12955 };
12956
12957 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12958 // type, array-to-pointer, ..., conversions are performed on both operands to
12959 // bring them to their composite type.
12960 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12961 // any type-related checks.
12962 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12963 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12964 if (LHS.isInvalid())
12965 return QualType();
12966 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12967 if (RHS.isInvalid())
12968 return QualType();
12969 } else {
12970 LHS = DefaultLvalueConversion(E: LHS.get());
12971 if (LHS.isInvalid())
12972 return QualType();
12973 RHS = DefaultLvalueConversion(E: RHS.get());
12974 if (RHS.isInvalid())
12975 return QualType();
12976 }
12977
12978 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12979 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12980 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12981 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12982 }
12983
12984 // Handle vector comparisons separately.
12985 if (LHS.get()->getType()->isVectorType() ||
12986 RHS.get()->getType()->isVectorType())
12987 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12988
12989 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12990 RHS.get()->getType()->isSveVLSBuiltinType())
12991 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12992
12993 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12994 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12995
12996 QualType LHSType = LHS.get()->getType();
12997 QualType RHSType = RHS.get()->getType();
12998 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12999 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13000 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
13001
13002 if ((LHSType->isPointerType() &&
13003 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13004 (RHSType->isPointerType() &&
13005 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13006 return InvalidOperands(Loc, LHS, RHS);
13007
13008 const Expr::NullPointerConstantKind LHSNullKind =
13009 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13010 const Expr::NullPointerConstantKind RHSNullKind =
13011 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13012 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13013 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13014
13015 auto computeResultTy = [&]() {
13016 if (Opc != BO_Cmp)
13017 return QualType(Context.getLogicalOperationType());
13018 assert(getLangOpts().CPlusPlus);
13019 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13020
13021 QualType CompositeTy = LHS.get()->getType();
13022 assert(!CompositeTy->isReferenceType());
13023
13024 std::optional<ComparisonCategoryType> CCT =
13025 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13026 if (!CCT)
13027 return InvalidOperands(Loc, LHS, RHS);
13028
13029 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13030 // P0946R0: Comparisons between a null pointer constant and an object
13031 // pointer result in std::strong_equality, which is ill-formed under
13032 // P1959R0.
13033 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13034 << (LHSIsNull ? LHS.get()->getSourceRange()
13035 : RHS.get()->getSourceRange());
13036 return QualType();
13037 }
13038
13039 return CheckComparisonCategoryType(
13040 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13041 };
13042
13043 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13044 bool IsEquality = Opc == BO_EQ;
13045 if (RHSIsNull)
13046 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13047 Range: RHS.get()->getSourceRange());
13048 else
13049 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13050 Range: LHS.get()->getSourceRange());
13051 }
13052
13053 if (IsOrdered && LHSType->isFunctionPointerType() &&
13054 RHSType->isFunctionPointerType()) {
13055 // Valid unless a relational comparison of function pointers
13056 bool IsError = Opc == BO_Cmp;
13057 auto DiagID =
13058 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13059 : getLangOpts().CPlusPlus
13060 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13061 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13062 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13063 << RHS.get()->getSourceRange();
13064 if (IsError)
13065 return QualType();
13066 }
13067
13068 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13069 (RHSType->isIntegerType() && !RHSIsNull)) {
13070 // Skip normal pointer conversion checks in this case; we have better
13071 // diagnostics for this below.
13072 } else if (getLangOpts().CPlusPlus) {
13073 // Equality comparison of a function pointer to a void pointer is invalid,
13074 // but we allow it as an extension.
13075 // FIXME: If we really want to allow this, should it be part of composite
13076 // pointer type computation so it works in conditionals too?
13077 if (!IsOrdered &&
13078 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13079 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13080 // This is a gcc extension compatibility comparison.
13081 // In a SFINAE context, we treat this as a hard error to maintain
13082 // conformance with the C++ standard.
13083 bool IsError = isSFINAEContext();
13084 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13085
13086 if (IsError)
13087 return QualType();
13088
13089 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13090 return computeResultTy();
13091 }
13092
13093 // C++ [expr.eq]p2:
13094 // If at least one operand is a pointer [...] bring them to their
13095 // composite pointer type.
13096 // C++ [expr.spaceship]p6
13097 // If at least one of the operands is of pointer type, [...] bring them
13098 // to their composite pointer type.
13099 // C++ [expr.rel]p2:
13100 // If both operands are pointers, [...] bring them to their composite
13101 // pointer type.
13102 // For <=>, the only valid non-pointer types are arrays and functions, and
13103 // we already decayed those, so this is really the same as the relational
13104 // comparison rule.
13105 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13106 (IsOrdered ? 2 : 1) &&
13107 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13108 RHSType->isObjCObjectPointerType()))) {
13109 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13110 return QualType();
13111 return computeResultTy();
13112 }
13113 } else if (LHSType->isPointerType() &&
13114 RHSType->isPointerType()) { // C99 6.5.8p2
13115 // All of the following pointer-related warnings are GCC extensions, except
13116 // when handling null pointer constants.
13117 QualType LCanPointeeTy =
13118 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13119 QualType RCanPointeeTy =
13120 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13121
13122 // C99 6.5.9p2 and C99 6.5.8p2
13123 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13124 T2: RCanPointeeTy.getUnqualifiedType())) {
13125 if (IsRelational) {
13126 // Pointers both need to point to complete or incomplete types
13127 if ((LCanPointeeTy->isIncompleteType() !=
13128 RCanPointeeTy->isIncompleteType()) &&
13129 !getLangOpts().C11) {
13130 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13131 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13132 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13133 << RCanPointeeTy->isIncompleteType();
13134 }
13135 }
13136 } else if (!IsRelational &&
13137 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13138 // Valid unless comparison between non-null pointer and function pointer
13139 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13140 && !LHSIsNull && !RHSIsNull)
13141 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13142 /*isError*/IsError: false);
13143 } else {
13144 // Invalid
13145 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13146 }
13147 if (LCanPointeeTy != RCanPointeeTy) {
13148 // Treat NULL constant as a special case in OpenCL.
13149 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13150 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13151 Ctx: getASTContext())) {
13152 Diag(Loc,
13153 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13154 << LHSType << RHSType << 0 /* comparison */
13155 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13156 }
13157 }
13158 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13159 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13160 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13161 : CK_BitCast;
13162
13163 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13164 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13165 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13166 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13167 bool ChangingCFIUncheckedCallee =
13168 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13169
13170 if (LHSIsNull && !RHSIsNull)
13171 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13172 else if (!ChangingCFIUncheckedCallee)
13173 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13174 }
13175 return computeResultTy();
13176 }
13177
13178
13179 // C++ [expr.eq]p4:
13180 // Two operands of type std::nullptr_t or one operand of type
13181 // std::nullptr_t and the other a null pointer constant compare
13182 // equal.
13183 // C23 6.5.9p5:
13184 // If both operands have type nullptr_t or one operand has type nullptr_t
13185 // and the other is a null pointer constant, they compare equal if the
13186 // former is a null pointer.
13187 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13188 if (LHSType->isNullPtrType()) {
13189 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13190 return computeResultTy();
13191 }
13192 if (RHSType->isNullPtrType()) {
13193 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13194 return computeResultTy();
13195 }
13196 }
13197
13198 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13199 // C23 6.5.9p6:
13200 // Otherwise, at least one operand is a pointer. If one is a pointer and
13201 // the other is a null pointer constant or has type nullptr_t, they
13202 // compare equal
13203 if (LHSIsNull && RHSType->isPointerType()) {
13204 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13205 return computeResultTy();
13206 }
13207 if (RHSIsNull && LHSType->isPointerType()) {
13208 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13209 return computeResultTy();
13210 }
13211 }
13212
13213 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13214 // These aren't covered by the composite pointer type rules.
13215 if (!IsOrdered && RHSType->isNullPtrType() &&
13216 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13217 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13218 return computeResultTy();
13219 }
13220 if (!IsOrdered && LHSType->isNullPtrType() &&
13221 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13222 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13223 return computeResultTy();
13224 }
13225
13226 if (getLangOpts().CPlusPlus) {
13227 if (IsRelational &&
13228 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13229 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13230 // HACK: Relational comparison of nullptr_t against a pointer type is
13231 // invalid per DR583, but we allow it within std::less<> and friends,
13232 // since otherwise common uses of it break.
13233 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13234 // friends to have std::nullptr_t overload candidates.
13235 DeclContext *DC = CurContext;
13236 if (isa<FunctionDecl>(Val: DC))
13237 DC = DC->getParent();
13238 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13239 if (CTSD->isInStdNamespace() &&
13240 llvm::StringSwitch<bool>(CTSD->getName())
13241 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13242 .Default(Value: false)) {
13243 if (RHSType->isNullPtrType())
13244 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13245 else
13246 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13247 return computeResultTy();
13248 }
13249 }
13250 }
13251
13252 // C++ [expr.eq]p2:
13253 // If at least one operand is a pointer to member, [...] bring them to
13254 // their composite pointer type.
13255 if (!IsOrdered &&
13256 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13257 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13258 return QualType();
13259 else
13260 return computeResultTy();
13261 }
13262 }
13263
13264 // Handle block pointer types.
13265 if (!IsOrdered && LHSType->isBlockPointerType() &&
13266 RHSType->isBlockPointerType()) {
13267 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13268 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13269
13270 if (!LHSIsNull && !RHSIsNull &&
13271 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13272 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13273 << LHSType << RHSType << LHS.get()->getSourceRange()
13274 << RHS.get()->getSourceRange();
13275 }
13276 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13277 return computeResultTy();
13278 }
13279
13280 // Allow block pointers to be compared with null pointer constants.
13281 if (!IsOrdered
13282 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13283 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13284 if (!LHSIsNull && !RHSIsNull) {
13285 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13286 ->getPointeeType()->isVoidType())
13287 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13288 ->getPointeeType()->isVoidType())))
13289 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13290 << LHSType << RHSType << LHS.get()->getSourceRange()
13291 << RHS.get()->getSourceRange();
13292 }
13293 if (LHSIsNull && !RHSIsNull)
13294 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13295 CK: RHSType->isPointerType() ? CK_BitCast
13296 : CK_AnyPointerToBlockPointerCast);
13297 else
13298 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13299 CK: LHSType->isPointerType() ? CK_BitCast
13300 : CK_AnyPointerToBlockPointerCast);
13301 return computeResultTy();
13302 }
13303
13304 if (LHSType->isObjCObjectPointerType() ||
13305 RHSType->isObjCObjectPointerType()) {
13306 const PointerType *LPT = LHSType->getAs<PointerType>();
13307 const PointerType *RPT = RHSType->getAs<PointerType>();
13308 if (LPT || RPT) {
13309 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13310 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13311
13312 if (!LPtrToVoid && !RPtrToVoid &&
13313 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13314 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13315 /*isError*/IsError: false);
13316 }
13317 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13318 // the RHS, but we have test coverage for this behavior.
13319 // FIXME: Consider using convertPointersToCompositeType in C++.
13320 if (LHSIsNull && !RHSIsNull) {
13321 Expr *E = LHS.get();
13322 if (getLangOpts().ObjCAutoRefCount)
13323 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13324 CCK: CheckedConversionKind::Implicit);
13325 LHS = ImpCastExprToType(E, Type: RHSType,
13326 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13327 }
13328 else {
13329 Expr *E = RHS.get();
13330 if (getLangOpts().ObjCAutoRefCount)
13331 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13332 CCK: CheckedConversionKind::Implicit,
13333 /*Diagnose=*/true,
13334 /*DiagnoseCFAudited=*/false, Opc);
13335 RHS = ImpCastExprToType(E, Type: LHSType,
13336 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13337 }
13338 return computeResultTy();
13339 }
13340 if (LHSType->isObjCObjectPointerType() &&
13341 RHSType->isObjCObjectPointerType()) {
13342 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13343 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13344 /*isError*/IsError: false);
13345 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13346 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13347
13348 if (LHSIsNull && !RHSIsNull)
13349 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13350 else
13351 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13352 return computeResultTy();
13353 }
13354
13355 if (!IsOrdered && LHSType->isBlockPointerType() &&
13356 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13357 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13358 CK: CK_BlockPointerToObjCPointerCast);
13359 return computeResultTy();
13360 } else if (!IsOrdered &&
13361 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13362 RHSType->isBlockPointerType()) {
13363 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13364 CK: CK_BlockPointerToObjCPointerCast);
13365 return computeResultTy();
13366 }
13367 }
13368 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13369 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13370 unsigned DiagID = 0;
13371 bool isError = false;
13372 if (LangOpts.DebuggerSupport) {
13373 // Under a debugger, allow the comparison of pointers to integers,
13374 // since users tend to want to compare addresses.
13375 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13376 (RHSIsNull && RHSType->isIntegerType())) {
13377 if (IsOrdered) {
13378 isError = getLangOpts().CPlusPlus;
13379 DiagID =
13380 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13381 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13382 }
13383 } else if (getLangOpts().CPlusPlus) {
13384 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13385 isError = true;
13386 } else if (IsOrdered)
13387 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13388 else
13389 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13390
13391 if (DiagID) {
13392 Diag(Loc, DiagID)
13393 << LHSType << RHSType << LHS.get()->getSourceRange()
13394 << RHS.get()->getSourceRange();
13395 if (isError)
13396 return QualType();
13397 }
13398
13399 if (LHSType->isIntegerType())
13400 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13401 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13402 else
13403 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13404 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13405 return computeResultTy();
13406 }
13407
13408 // Handle block pointers.
13409 if (!IsOrdered && RHSIsNull
13410 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13411 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13412 return computeResultTy();
13413 }
13414 if (!IsOrdered && LHSIsNull
13415 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13416 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13417 return computeResultTy();
13418 }
13419
13420 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13421 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13422 return computeResultTy();
13423 }
13424
13425 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13426 return computeResultTy();
13427 }
13428
13429 if (LHSIsNull && RHSType->isQueueT()) {
13430 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13431 return computeResultTy();
13432 }
13433
13434 if (LHSType->isQueueT() && RHSIsNull) {
13435 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13436 return computeResultTy();
13437 }
13438 }
13439
13440 return InvalidOperands(Loc, LHS, RHS);
13441}
13442
13443QualType Sema::GetSignedVectorType(QualType V) {
13444 const VectorType *VTy = V->castAs<VectorType>();
13445 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13446
13447 if (isa<ExtVectorType>(Val: VTy)) {
13448 if (VTy->isExtVectorBoolType())
13449 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13450 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13451 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13452 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13453 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13454 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13455 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13456 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13457 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13458 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13459 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13460 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13461 "Unhandled vector element size in vector compare");
13462 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13463 }
13464
13465 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13466 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13467 VecKind: VectorKind::Generic);
13468 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13469 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13470 VecKind: VectorKind::Generic);
13471 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13472 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13473 VecKind: VectorKind::Generic);
13474 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13475 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13476 VecKind: VectorKind::Generic);
13477 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13478 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13479 VecKind: VectorKind::Generic);
13480 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13481 "Unhandled vector element size in vector compare");
13482 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13483 VecKind: VectorKind::Generic);
13484}
13485
13486QualType Sema::GetSignedSizelessVectorType(QualType V) {
13487 const BuiltinType *VTy = V->castAs<BuiltinType>();
13488 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13489
13490 const QualType ETy = V->getSveEltType(Ctx: Context);
13491 const auto TypeSize = Context.getTypeSize(T: ETy);
13492
13493 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13494 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13495 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13496}
13497
13498QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13499 SourceLocation Loc,
13500 BinaryOperatorKind Opc) {
13501 if (Opc == BO_Cmp) {
13502 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13503 return QualType();
13504 }
13505
13506 // Check to make sure we're operating on vectors of the same type and width,
13507 // Allowing one side to be a scalar of element type.
13508 QualType vType =
13509 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13510 /*AllowBothBool*/ true,
13511 /*AllowBoolConversions*/ getLangOpts().ZVector,
13512 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13513 /*ReportInvalid*/ true);
13514 if (vType.isNull())
13515 return vType;
13516
13517 QualType LHSType = LHS.get()->getType();
13518
13519 // Determine the return type of a vector compare. By default clang will return
13520 // a scalar for all vector compares except vector bool and vector pixel.
13521 // With the gcc compiler we will always return a vector type and with the xl
13522 // compiler we will always return a scalar type. This switch allows choosing
13523 // which behavior is prefered.
13524 if (getLangOpts().AltiVec) {
13525 switch (getLangOpts().getAltivecSrcCompat()) {
13526 case LangOptions::AltivecSrcCompatKind::Mixed:
13527 // If AltiVec, the comparison results in a numeric type, i.e.
13528 // bool for C++, int for C
13529 if (vType->castAs<VectorType>()->getVectorKind() ==
13530 VectorKind::AltiVecVector)
13531 return Context.getLogicalOperationType();
13532 else
13533 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13534 break;
13535 case LangOptions::AltivecSrcCompatKind::GCC:
13536 // For GCC we always return the vector type.
13537 break;
13538 case LangOptions::AltivecSrcCompatKind::XL:
13539 return Context.getLogicalOperationType();
13540 break;
13541 }
13542 }
13543
13544 // For non-floating point types, check for self-comparisons of the form
13545 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13546 // often indicate logic errors in the program.
13547 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13548
13549 // Check for comparisons of floating point operands using != and ==.
13550 if (LHSType->hasFloatingRepresentation()) {
13551 assert(RHS.get()->getType()->hasFloatingRepresentation());
13552 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13553 }
13554
13555 // Return a signed type for the vector.
13556 return GetSignedVectorType(V: vType);
13557}
13558
13559QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13560 ExprResult &RHS,
13561 SourceLocation Loc,
13562 BinaryOperatorKind Opc) {
13563 if (Opc == BO_Cmp) {
13564 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13565 return QualType();
13566 }
13567
13568 // Check to make sure we're operating on vectors of the same type and width,
13569 // Allowing one side to be a scalar of element type.
13570 QualType vType = CheckSizelessVectorOperands(
13571 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13572
13573 if (vType.isNull())
13574 return vType;
13575
13576 QualType LHSType = LHS.get()->getType();
13577
13578 // For non-floating point types, check for self-comparisons of the form
13579 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13580 // often indicate logic errors in the program.
13581 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13582
13583 // Check for comparisons of floating point operands using != and ==.
13584 if (LHSType->hasFloatingRepresentation()) {
13585 assert(RHS.get()->getType()->hasFloatingRepresentation());
13586 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13587 }
13588
13589 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13590 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13591
13592 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13593 RHSBuiltinTy->isSVEBool())
13594 return LHSType;
13595
13596 // Return a signed type for the vector.
13597 return GetSignedSizelessVectorType(V: vType);
13598}
13599
13600static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13601 const ExprResult &XorRHS,
13602 const SourceLocation Loc) {
13603 // Do not diagnose macros.
13604 if (Loc.isMacroID())
13605 return;
13606
13607 // Do not diagnose if both LHS and RHS are macros.
13608 if (XorLHS.get()->getExprLoc().isMacroID() &&
13609 XorRHS.get()->getExprLoc().isMacroID())
13610 return;
13611
13612 bool Negative = false;
13613 bool ExplicitPlus = false;
13614 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13615 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13616
13617 if (!LHSInt)
13618 return;
13619 if (!RHSInt) {
13620 // Check negative literals.
13621 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13622 UnaryOperatorKind Opc = UO->getOpcode();
13623 if (Opc != UO_Minus && Opc != UO_Plus)
13624 return;
13625 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13626 if (!RHSInt)
13627 return;
13628 Negative = (Opc == UO_Minus);
13629 ExplicitPlus = !Negative;
13630 } else {
13631 return;
13632 }
13633 }
13634
13635 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13636 llvm::APInt RightSideValue = RHSInt->getValue();
13637 if (LeftSideValue != 2 && LeftSideValue != 10)
13638 return;
13639
13640 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13641 return;
13642
13643 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13644 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13645 llvm::StringRef ExprStr =
13646 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13647
13648 CharSourceRange XorRange =
13649 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13650 llvm::StringRef XorStr =
13651 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13652 // Do not diagnose if xor keyword/macro is used.
13653 if (XorStr == "xor")
13654 return;
13655
13656 std::string LHSStr = std::string(Lexer::getSourceText(
13657 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13658 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13659 std::string RHSStr = std::string(Lexer::getSourceText(
13660 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13661 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13662
13663 if (Negative) {
13664 RightSideValue = -RightSideValue;
13665 RHSStr = "-" + RHSStr;
13666 } else if (ExplicitPlus) {
13667 RHSStr = "+" + RHSStr;
13668 }
13669
13670 StringRef LHSStrRef = LHSStr;
13671 StringRef RHSStrRef = RHSStr;
13672 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13673 // literals.
13674 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13675 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13676 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13677 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13678 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13679 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13680 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13681 return;
13682
13683 bool SuggestXor =
13684 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13685 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13686 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13687 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13688 std::string SuggestedExpr = "1 << " + RHSStr;
13689 bool Overflow = false;
13690 llvm::APInt One = (LeftSideValue - 1);
13691 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13692 if (Overflow) {
13693 if (RightSideIntValue < 64)
13694 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13695 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13696 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13697 else if (RightSideIntValue == 64)
13698 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13699 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13700 else
13701 return;
13702 } else {
13703 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13704 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13705 << toString(I: PowValue, Radix: 10, Signed: true)
13706 << FixItHint::CreateReplacement(
13707 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13708 }
13709
13710 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13711 << ("0x2 ^ " + RHSStr) << SuggestXor;
13712 } else if (LeftSideValue == 10) {
13713 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13714 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13715 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13716 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13717 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13718 << ("0xA ^ " + RHSStr) << SuggestXor;
13719 }
13720}
13721
13722QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13723 SourceLocation Loc,
13724 BinaryOperatorKind Opc) {
13725 // Ensure that either both operands are of the same vector type, or
13726 // one operand is of a vector type and the other is of its element type.
13727 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13728 /*AllowBothBool*/ true,
13729 /*AllowBoolConversions*/ false,
13730 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13731 /*ReportInvalid*/ false);
13732 if (vType.isNull())
13733 return InvalidOperands(Loc, LHS, RHS);
13734 if (getLangOpts().OpenCL &&
13735 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13736 vType->hasFloatingRepresentation())
13737 return InvalidOperands(Loc, LHS, RHS);
13738 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13739 // usage of the logical operators && and || with vectors in C. This
13740 // check could be notionally dropped.
13741 if (!getLangOpts().CPlusPlus &&
13742 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13743 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13744 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13745 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13746 // `select` functions.
13747 if (getLangOpts().HLSL &&
13748 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13749 (void)InvalidOperands(Loc, LHS, RHS);
13750 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13751 return QualType();
13752 }
13753
13754 return GetSignedVectorType(V: LHS.get()->getType());
13755}
13756
13757QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13758 SourceLocation Loc,
13759 BinaryOperatorKind Opc) {
13760
13761 if (!getLangOpts().HLSL) {
13762 assert(false && "Logical operands are not supported in C\\C++");
13763 return QualType();
13764 }
13765
13766 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13767 (void)InvalidOperands(Loc, LHS, RHS);
13768 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13769 return QualType();
13770 }
13771 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13772 << getLangOpts().getHLSLVersion();
13773 return QualType();
13774}
13775
13776QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13777 SourceLocation Loc,
13778 bool IsCompAssign) {
13779 if (!IsCompAssign) {
13780 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13781 if (LHS.isInvalid())
13782 return QualType();
13783 }
13784 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13785 if (RHS.isInvalid())
13786 return QualType();
13787
13788 // For conversion purposes, we ignore any qualifiers.
13789 // For example, "const float" and "float" are equivalent.
13790 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13791 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13792
13793 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13794 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13795 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13796
13797 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13798 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13799
13800 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13801 // case we have to return InvalidOperands.
13802 ExprResult OriginalLHS = LHS;
13803 ExprResult OriginalRHS = RHS;
13804 if (LHSMatType && !RHSMatType) {
13805 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13806 if (!RHS.isInvalid())
13807 return LHSType;
13808
13809 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13810 }
13811
13812 if (!LHSMatType && RHSMatType) {
13813 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13814 if (!LHS.isInvalid())
13815 return RHSType;
13816 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13817 }
13818
13819 return InvalidOperands(Loc, LHS, RHS);
13820}
13821
13822QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13823 SourceLocation Loc,
13824 bool IsCompAssign) {
13825 if (!IsCompAssign) {
13826 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13827 if (LHS.isInvalid())
13828 return QualType();
13829 }
13830 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13831 if (RHS.isInvalid())
13832 return QualType();
13833
13834 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13835 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13836 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13837
13838 if (LHSMatType && RHSMatType) {
13839 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13840 return InvalidOperands(Loc, LHS, RHS);
13841
13842 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13843 return Context.getCommonSugaredType(
13844 X: LHS.get()->getType().getUnqualifiedType(),
13845 Y: RHS.get()->getType().getUnqualifiedType());
13846
13847 QualType LHSELTy = LHSMatType->getElementType(),
13848 RHSELTy = RHSMatType->getElementType();
13849 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13850 return InvalidOperands(Loc, LHS, RHS);
13851
13852 return Context.getConstantMatrixType(
13853 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13854 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13855 }
13856 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13857}
13858
13859static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13860 switch (Opc) {
13861 default:
13862 return false;
13863 case BO_And:
13864 case BO_AndAssign:
13865 case BO_Or:
13866 case BO_OrAssign:
13867 case BO_Xor:
13868 case BO_XorAssign:
13869 return true;
13870 }
13871}
13872
13873inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13874 SourceLocation Loc,
13875 BinaryOperatorKind Opc) {
13876 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13877
13878 bool IsCompAssign =
13879 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13880
13881 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13882
13883 if (LHS.get()->getType()->isVectorType() ||
13884 RHS.get()->getType()->isVectorType()) {
13885 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13886 RHS.get()->getType()->hasIntegerRepresentation())
13887 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13888 /*AllowBothBool*/ true,
13889 /*AllowBoolConversions*/ getLangOpts().ZVector,
13890 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13891 /*ReportInvalid*/ true);
13892 return InvalidOperands(Loc, LHS, RHS);
13893 }
13894
13895 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13896 RHS.get()->getType()->isSveVLSBuiltinType()) {
13897 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13898 RHS.get()->getType()->hasIntegerRepresentation())
13899 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13900 OperationKind: ArithConvKind::BitwiseOp);
13901 return InvalidOperands(Loc, LHS, RHS);
13902 }
13903
13904 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13905 RHS.get()->getType()->isSveVLSBuiltinType()) {
13906 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13907 RHS.get()->getType()->hasIntegerRepresentation())
13908 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13909 OperationKind: ArithConvKind::BitwiseOp);
13910 return InvalidOperands(Loc, LHS, RHS);
13911 }
13912
13913 if (Opc == BO_And)
13914 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13915
13916 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13917 RHS.get()->getType()->hasFloatingRepresentation())
13918 return InvalidOperands(Loc, LHS, RHS);
13919
13920 ExprResult LHSResult = LHS, RHSResult = RHS;
13921 QualType compType = UsualArithmeticConversions(
13922 LHS&: LHSResult, RHS&: RHSResult, Loc,
13923 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13924 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13925 return QualType();
13926 LHS = LHSResult.get();
13927 RHS = RHSResult.get();
13928
13929 if (Opc == BO_Xor)
13930 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13931
13932 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13933 return compType;
13934 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13935 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13936 return ResultTy;
13937}
13938
13939// C99 6.5.[13,14]
13940inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13941 SourceLocation Loc,
13942 BinaryOperatorKind Opc) {
13943 // Check vector operands differently.
13944 if (LHS.get()->getType()->isVectorType() ||
13945 RHS.get()->getType()->isVectorType())
13946 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13947
13948 if (LHS.get()->getType()->isConstantMatrixType() ||
13949 RHS.get()->getType()->isConstantMatrixType())
13950 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13951
13952 bool EnumConstantInBoolContext = false;
13953 for (const ExprResult &HS : {LHS, RHS}) {
13954 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13955 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13956 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13957 EnumConstantInBoolContext = true;
13958 }
13959 }
13960
13961 if (EnumConstantInBoolContext)
13962 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13963
13964 // WebAssembly tables can't be used with logical operators.
13965 QualType LHSTy = LHS.get()->getType();
13966 QualType RHSTy = RHS.get()->getType();
13967 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13968 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13969 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13970 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13971 return InvalidOperands(Loc, LHS, RHS);
13972 }
13973
13974 // Diagnose cases where the user write a logical and/or but probably meant a
13975 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13976 // is a constant.
13977 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13978 !LHS.get()->getType()->isBooleanType() &&
13979 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13980 // Don't warn in macros or template instantiations.
13981 !Loc.isMacroID() && !inTemplateInstantiation()) {
13982 // If the RHS can be constant folded, and if it constant folds to something
13983 // that isn't 0 or 1 (which indicate a potential logical operation that
13984 // happened to fold to true/false) then warn.
13985 // Parens on the RHS are ignored.
13986 Expr::EvalResult EVResult;
13987 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
13988 llvm::APSInt Result = EVResult.Val.getInt();
13989 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13990 !RHS.get()->getExprLoc().isMacroID()) ||
13991 (Result != 0 && Result != 1)) {
13992 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
13993 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13994 // Suggest replacing the logical operator with the bitwise version
13995 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
13996 << (Opc == BO_LAnd ? "&" : "|")
13997 << FixItHint::CreateReplacement(
13998 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
13999 Code: Opc == BO_LAnd ? "&" : "|");
14000 if (Opc == BO_LAnd)
14001 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14002 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
14003 << FixItHint::CreateRemoval(
14004 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
14005 RHS.get()->getEndLoc()));
14006 }
14007 }
14008 }
14009
14010 if (!Context.getLangOpts().CPlusPlus) {
14011 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14012 // not operate on the built-in scalar and vector float types.
14013 if (Context.getLangOpts().OpenCL &&
14014 Context.getLangOpts().OpenCLVersion < 120) {
14015 if (LHS.get()->getType()->isFloatingType() ||
14016 RHS.get()->getType()->isFloatingType())
14017 return InvalidOperands(Loc, LHS, RHS);
14018 }
14019
14020 LHS = UsualUnaryConversions(E: LHS.get());
14021 if (LHS.isInvalid())
14022 return QualType();
14023
14024 RHS = UsualUnaryConversions(E: RHS.get());
14025 if (RHS.isInvalid())
14026 return QualType();
14027
14028 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14029 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
14030 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14031 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
14032
14033 if (!LHS.get()->getType()->isScalarType() ||
14034 !RHS.get()->getType()->isScalarType())
14035 return InvalidOperands(Loc, LHS, RHS);
14036
14037 return Context.IntTy;
14038 }
14039
14040 // The following is safe because we only use this method for
14041 // non-overloadable operands.
14042
14043 // C++ [expr.log.and]p1
14044 // C++ [expr.log.or]p1
14045 // The operands are both contextually converted to type bool.
14046 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14047 if (LHSRes.isInvalid()) {
14048 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14049 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14050 return ResultTy;
14051 }
14052 LHS = LHSRes;
14053
14054 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14055 if (RHSRes.isInvalid()) {
14056 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14057 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14058 return ResultTy;
14059 }
14060 RHS = RHSRes;
14061
14062 // C++ [expr.log.and]p2
14063 // C++ [expr.log.or]p2
14064 // The result is a bool.
14065 return Context.BoolTy;
14066}
14067
14068static bool IsReadonlyMessage(Expr *E, Sema &S) {
14069 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14070 if (!ME) return false;
14071 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14072 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14073 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14074 if (!Base) return false;
14075 return Base->getMethodDecl() != nullptr;
14076}
14077
14078/// Is the given expression (which must be 'const') a reference to a
14079/// variable which was originally non-const, but which has become
14080/// 'const' due to being captured within a block?
14081enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14082static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14083 assert(E->isLValue() && E->getType().isConstQualified());
14084 E = E->IgnoreParens();
14085
14086 // Must be a reference to a declaration from an enclosing scope.
14087 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14088 if (!DRE) return NCCK_None;
14089 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14090
14091 ValueDecl *Value = DRE->getDecl();
14092
14093 // The declaration must be a value which is not declared 'const'.
14094 if (Value->getType().isConstQualified())
14095 return NCCK_None;
14096
14097 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14098 if (Binding) {
14099 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14100 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14101 return NCCK_Lambda;
14102 }
14103
14104 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14105 if (!Var)
14106 return NCCK_None;
14107 if (Var->getType()->isReferenceType())
14108 return NCCK_None;
14109
14110 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14111
14112 // Decide whether the first capture was for a block or a lambda.
14113 DeclContext *DC = S.CurContext, *Prev = nullptr;
14114 // Decide whether the first capture was for a block or a lambda.
14115 while (DC) {
14116 // For init-capture, it is possible that the variable belongs to the
14117 // template pattern of the current context.
14118 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14119 if (Var->isInitCapture() &&
14120 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14121 break;
14122 if (DC == Var->getDeclContext())
14123 break;
14124 Prev = DC;
14125 DC = DC->getParent();
14126 }
14127 // Unless we have an init-capture, we've gone one step too far.
14128 if (!Var->isInitCapture())
14129 DC = Prev;
14130 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14131}
14132
14133static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14134 Ty = Ty.getNonReferenceType();
14135 if (IsDereference && Ty->isPointerType())
14136 Ty = Ty->getPointeeType();
14137 return !Ty.isConstQualified();
14138}
14139
14140// Update err_typecheck_assign_const and note_typecheck_assign_const
14141// when this enum is changed.
14142enum {
14143 ConstFunction,
14144 ConstVariable,
14145 ConstMember,
14146 NestedConstMember,
14147 ConstUnknown, // Keep as last element
14148};
14149
14150/// Emit the "read-only variable not assignable" error and print notes to give
14151/// more information about why the variable is not assignable, such as pointing
14152/// to the declaration of a const variable, showing that a method is const, or
14153/// that the function is returning a const reference.
14154static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14155 SourceLocation Loc) {
14156 SourceRange ExprRange = E->getSourceRange();
14157
14158 // Only emit one error on the first const found. All other consts will emit
14159 // a note to the error.
14160 bool DiagnosticEmitted = false;
14161
14162 // Track if the current expression is the result of a dereference, and if the
14163 // next checked expression is the result of a dereference.
14164 bool IsDereference = false;
14165 bool NextIsDereference = false;
14166
14167 // Loop to process MemberExpr chains.
14168 while (true) {
14169 IsDereference = NextIsDereference;
14170
14171 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14172 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14173 NextIsDereference = ME->isArrow();
14174 const ValueDecl *VD = ME->getMemberDecl();
14175 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14176 // Mutable fields can be modified even if the class is const.
14177 if (Field->isMutable()) {
14178 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14179 break;
14180 }
14181
14182 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14183 if (!DiagnosticEmitted) {
14184 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14185 << ExprRange << ConstMember << false /*static*/ << Field
14186 << Field->getType();
14187 DiagnosticEmitted = true;
14188 }
14189 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14190 << ConstMember << false /*static*/ << Field << Field->getType()
14191 << Field->getSourceRange();
14192 }
14193 E = ME->getBase();
14194 continue;
14195 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14196 if (VDecl->getType().isConstQualified()) {
14197 if (!DiagnosticEmitted) {
14198 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14199 << ExprRange << ConstMember << true /*static*/ << VDecl
14200 << VDecl->getType();
14201 DiagnosticEmitted = true;
14202 }
14203 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14204 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14205 << VDecl->getSourceRange();
14206 }
14207 // Static fields do not inherit constness from parents.
14208 break;
14209 }
14210 break; // End MemberExpr
14211 } else if (const ArraySubscriptExpr *ASE =
14212 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14213 E = ASE->getBase()->IgnoreParenImpCasts();
14214 continue;
14215 } else if (const ExtVectorElementExpr *EVE =
14216 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14217 E = EVE->getBase()->IgnoreParenImpCasts();
14218 continue;
14219 }
14220 break;
14221 }
14222
14223 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14224 // Function calls
14225 const FunctionDecl *FD = CE->getDirectCallee();
14226 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14227 if (!DiagnosticEmitted) {
14228 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14229 << ConstFunction << FD;
14230 DiagnosticEmitted = true;
14231 }
14232 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14233 DiagID: diag::note_typecheck_assign_const)
14234 << ConstFunction << FD << FD->getReturnType()
14235 << FD->getReturnTypeSourceRange();
14236 }
14237 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14238 // Point to variable declaration.
14239 if (const ValueDecl *VD = DRE->getDecl()) {
14240 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14241 if (!DiagnosticEmitted) {
14242 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14243 << ExprRange << ConstVariable << VD << VD->getType();
14244 DiagnosticEmitted = true;
14245 }
14246 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14247 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14248 }
14249 }
14250 } else if (isa<CXXThisExpr>(Val: E)) {
14251 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14252 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14253 if (MD->isConst()) {
14254 if (!DiagnosticEmitted) {
14255 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14256 << ExprRange << MD;
14257 DiagnosticEmitted = true;
14258 }
14259 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14260 << MD << MD->getSourceRange();
14261 }
14262 }
14263 }
14264 }
14265
14266 if (DiagnosticEmitted)
14267 return;
14268
14269 // Can't determine a more specific message, so display the generic error.
14270 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14271}
14272
14273enum OriginalExprKind {
14274 OEK_Variable,
14275 OEK_Member,
14276 OEK_LValue
14277};
14278
14279static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14280 const RecordType *Ty,
14281 SourceLocation Loc, SourceRange Range,
14282 OriginalExprKind OEK,
14283 bool &DiagnosticEmitted) {
14284 std::vector<const RecordType *> RecordTypeList;
14285 RecordTypeList.push_back(x: Ty);
14286 unsigned NextToCheckIndex = 0;
14287 // We walk the record hierarchy breadth-first to ensure that we print
14288 // diagnostics in field nesting order.
14289 while (RecordTypeList.size() > NextToCheckIndex) {
14290 bool IsNested = NextToCheckIndex > 0;
14291 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14292 ->getDecl()
14293 ->getDefinitionOrSelf()
14294 ->fields()) {
14295 // First, check every field for constness.
14296 QualType FieldTy = Field->getType();
14297 if (FieldTy.isConstQualified()) {
14298 if (!DiagnosticEmitted) {
14299 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14300 << Range << NestedConstMember << OEK << VD
14301 << IsNested << Field;
14302 DiagnosticEmitted = true;
14303 }
14304 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14305 << NestedConstMember << IsNested << Field
14306 << FieldTy << Field->getSourceRange();
14307 }
14308
14309 // Then we append it to the list to check next in order.
14310 FieldTy = FieldTy.getCanonicalType();
14311 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14312 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14313 RecordTypeList.push_back(x: FieldRecTy);
14314 }
14315 }
14316 ++NextToCheckIndex;
14317 }
14318}
14319
14320/// Emit an error for the case where a record we are trying to assign to has a
14321/// const-qualified field somewhere in its hierarchy.
14322static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14323 SourceLocation Loc) {
14324 QualType Ty = E->getType();
14325 assert(Ty->isRecordType() && "lvalue was not record?");
14326 SourceRange Range = E->getSourceRange();
14327 const auto *RTy = Ty->getAsCanonical<RecordType>();
14328 bool DiagEmitted = false;
14329
14330 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14331 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14332 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14333 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14334 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14335 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14336 else
14337 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14338 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14339 if (!DiagEmitted)
14340 DiagnoseConstAssignment(S, E, Loc);
14341}
14342
14343/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14344/// emit an error and return true. If so, return false.
14345static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14346 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14347
14348 S.CheckShadowingDeclModification(E, Loc);
14349
14350 SourceLocation OrigLoc = Loc;
14351 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14352 Loc: &Loc);
14353 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14354 IsLV = Expr::MLV_InvalidMessageExpression;
14355 if (IsLV == Expr::MLV_Valid)
14356 return false;
14357
14358 unsigned DiagID = 0;
14359 bool NeedType = false;
14360 switch (IsLV) { // C99 6.5.16p2
14361 case Expr::MLV_ConstQualified:
14362 // Use a specialized diagnostic when we're assigning to an object
14363 // from an enclosing function or block.
14364 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14365 if (NCCK == NCCK_Block)
14366 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14367 else
14368 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14369 break;
14370 }
14371
14372 // In ARC, use some specialized diagnostics for occasions where we
14373 // infer 'const'. These are always pseudo-strong variables.
14374 if (S.getLangOpts().ObjCAutoRefCount) {
14375 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14376 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14377 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14378
14379 // Use the normal diagnostic if it's pseudo-__strong but the
14380 // user actually wrote 'const'.
14381 if (var->isARCPseudoStrong() &&
14382 (!var->getTypeSourceInfo() ||
14383 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14384 // There are three pseudo-strong cases:
14385 // - self
14386 ObjCMethodDecl *method = S.getCurMethodDecl();
14387 if (method && var == method->getSelfDecl()) {
14388 DiagID = method->isClassMethod()
14389 ? diag::err_typecheck_arc_assign_self_class_method
14390 : diag::err_typecheck_arc_assign_self;
14391
14392 // - Objective-C externally_retained attribute.
14393 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14394 isa<ParmVarDecl>(Val: var)) {
14395 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14396
14397 // - fast enumeration variables
14398 } else {
14399 DiagID = diag::err_typecheck_arr_assign_enumeration;
14400 }
14401
14402 SourceRange Assign;
14403 if (Loc != OrigLoc)
14404 Assign = SourceRange(OrigLoc, OrigLoc);
14405 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14406 // We need to preserve the AST regardless, so migration tool
14407 // can do its job.
14408 return false;
14409 }
14410 }
14411 }
14412
14413 // If none of the special cases above are triggered, then this is a
14414 // simple const assignment.
14415 if (DiagID == 0) {
14416 DiagnoseConstAssignment(S, E, Loc);
14417 return true;
14418 }
14419
14420 break;
14421 case Expr::MLV_ConstAddrSpace:
14422 DiagnoseConstAssignment(S, E, Loc);
14423 return true;
14424 case Expr::MLV_ConstQualifiedField:
14425 DiagnoseRecursiveConstFields(S, E, Loc);
14426 return true;
14427 case Expr::MLV_ArrayType:
14428 case Expr::MLV_ArrayTemporary:
14429 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14430 NeedType = true;
14431 break;
14432 case Expr::MLV_NotObjectType:
14433 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14434 NeedType = true;
14435 break;
14436 case Expr::MLV_LValueCast:
14437 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14438 break;
14439 case Expr::MLV_Valid:
14440 llvm_unreachable("did not take early return for MLV_Valid");
14441 case Expr::MLV_InvalidExpression:
14442 case Expr::MLV_MemberFunction:
14443 case Expr::MLV_ClassTemporary:
14444 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14445 break;
14446 case Expr::MLV_IncompleteType:
14447 case Expr::MLV_IncompleteVoidType:
14448 return S.RequireCompleteType(Loc, T: E->getType(),
14449 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14450 case Expr::MLV_DuplicateVectorComponents:
14451 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14452 break;
14453 case Expr::MLV_DuplicateMatrixComponents:
14454 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14455 break;
14456 case Expr::MLV_NoSetterProperty:
14457 llvm_unreachable("readonly properties should be processed differently");
14458 case Expr::MLV_InvalidMessageExpression:
14459 DiagID = diag::err_readonly_message_assignment;
14460 break;
14461 case Expr::MLV_SubObjCPropertySetting:
14462 DiagID = diag::err_no_subobject_property_setting;
14463 break;
14464 }
14465
14466 SourceRange Assign;
14467 if (Loc != OrigLoc)
14468 Assign = SourceRange(OrigLoc, OrigLoc);
14469 if (NeedType)
14470 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14471 else
14472 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14473 return true;
14474}
14475
14476static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14477 SourceLocation Loc,
14478 Sema &Sema) {
14479 if (Sema.inTemplateInstantiation())
14480 return;
14481 if (Sema.isUnevaluatedContext())
14482 return;
14483 if (Loc.isInvalid() || Loc.isMacroID())
14484 return;
14485 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14486 return;
14487
14488 // C / C++ fields
14489 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14490 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14491 if (ML && MR) {
14492 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14493 return;
14494 const ValueDecl *LHSDecl =
14495 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14496 const ValueDecl *RHSDecl =
14497 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14498 if (LHSDecl != RHSDecl)
14499 return;
14500 if (LHSDecl->getType().isVolatileQualified())
14501 return;
14502 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14503 if (RefTy->getPointeeType().isVolatileQualified())
14504 return;
14505
14506 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14507 }
14508
14509 // Objective-C instance variables
14510 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14511 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14512 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14513 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14514 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14515 if (RL && RR && RL->getDecl() == RR->getDecl())
14516 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14517 }
14518}
14519
14520// C99 6.5.16.1
14521QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14522 SourceLocation Loc,
14523 QualType CompoundType,
14524 BinaryOperatorKind Opc) {
14525 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14526
14527 // Verify that LHS is a modifiable lvalue, and emit error if not.
14528 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14529 return QualType();
14530
14531 QualType LHSType = LHSExpr->getType();
14532 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14533 CompoundType;
14534
14535 if (RHS.isUsable()) {
14536 // Even if this check fails don't return early to allow the best
14537 // possible error recovery and to allow any subsequent diagnostics to
14538 // work.
14539 const ValueDecl *Assignee = nullptr;
14540 bool ShowFullyQualifiedAssigneeName = false;
14541 // In simple cases describe what is being assigned to
14542 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14543 Assignee = DR->getDecl();
14544 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14545 Assignee = ME->getMemberDecl();
14546 ShowFullyQualifiedAssigneeName = true;
14547 }
14548
14549 BoundsSafetyCheckAssignmentToCountAttrPtr(
14550 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14551 ShowFullyQualifiedAssigneeName);
14552 }
14553
14554 // OpenCL v1.2 s6.1.1.1 p2:
14555 // The half data type can only be used to declare a pointer to a buffer that
14556 // contains half values
14557 if (getLangOpts().OpenCL &&
14558 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14559 LHSType->isHalfType()) {
14560 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14561 << LHSType.getUnqualifiedType();
14562 return QualType();
14563 }
14564
14565 // WebAssembly tables can't be used on RHS of an assignment expression.
14566 if (RHSType->isWebAssemblyTableType()) {
14567 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14568 return QualType();
14569 }
14570
14571 AssignConvertType ConvTy;
14572 if (CompoundType.isNull()) {
14573 Expr *RHSCheck = RHS.get();
14574
14575 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14576
14577 QualType LHSTy(LHSType);
14578 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14579 if (RHS.isInvalid())
14580 return QualType();
14581 // Special case of NSObject attributes on c-style pointer types.
14582 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14583 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14584 RHSType->isObjCObjectPointerType()) ||
14585 (Context.isObjCNSObjectType(Ty: RHSType) &&
14586 LHSType->isObjCObjectPointerType())))
14587 ConvTy = AssignConvertType::Compatible;
14588
14589 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14590 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14591
14592 // If the RHS is a unary plus or minus, check to see if they = and + are
14593 // right next to each other. If so, the user may have typo'd "x =+ 4"
14594 // instead of "x += 4".
14595 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14596 RHSCheck = ICE->getSubExpr();
14597 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14598 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14599 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14600 // Only if the two operators are exactly adjacent.
14601 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14602 // And there is a space or other character before the subexpr of the
14603 // unary +/-. We don't want to warn on "x=-1".
14604 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14605 UO->getSubExpr()->getBeginLoc().isFileID()) {
14606 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14607 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14608 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14609 }
14610 }
14611
14612 if (IsAssignConvertCompatible(ConvTy)) {
14613 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14614 // Warn about retain cycles where a block captures the LHS, but
14615 // not if the LHS is a simple variable into which the block is
14616 // being stored...unless that variable can be captured by reference!
14617 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14618 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14619 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14620 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14621 }
14622
14623 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14624 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14625 // It is safe to assign a weak reference into a strong variable.
14626 // Although this code can still have problems:
14627 // id x = self.weakProp;
14628 // id y = self.weakProp;
14629 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14630 // paths through the function. This should be revisited if
14631 // -Wrepeated-use-of-weak is made flow-sensitive.
14632 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14633 // variable, which will be valid for the current autorelease scope.
14634 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14635 Loc: RHS.get()->getBeginLoc()))
14636 getCurFunction()->markSafeWeakUse(E: RHS.get());
14637
14638 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14639 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14640 }
14641 }
14642 } else {
14643 // Compound assignment "x += y"
14644 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14645 }
14646
14647 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14648 Action: AssignmentAction::Assigning))
14649 return QualType();
14650
14651 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14652
14653 AssignedEntity AE{.LHS: LHSExpr};
14654 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14655
14656 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14657 if (CompoundType.isNull()) {
14658 // C++2a [expr.ass]p5:
14659 // A simple-assignment whose left operand is of a volatile-qualified
14660 // type is deprecated unless the assignment is either a discarded-value
14661 // expression or an unevaluated operand
14662 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14663 }
14664 }
14665
14666 // C11 6.5.16p3: The type of an assignment expression is the type of the
14667 // left operand would have after lvalue conversion.
14668 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14669 // qualified type, the value has the unqualified version of the type of the
14670 // lvalue; additionally, if the lvalue has atomic type, the value has the
14671 // non-atomic version of the type of the lvalue.
14672 // C++ 5.17p1: the type of the assignment expression is that of its left
14673 // operand.
14674 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14675}
14676
14677// Scenarios to ignore if expression E is:
14678// 1. an explicit cast expression into void
14679// 2. a function call expression that returns void
14680static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14681 E = E->IgnoreParens();
14682
14683 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14684 if (CE->getCastKind() == CK_ToVoid) {
14685 return true;
14686 }
14687
14688 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14689 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14690 CE->getSubExpr()->getType()->isDependentType()) {
14691 return true;
14692 }
14693 }
14694
14695 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14696 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14697 return false;
14698}
14699
14700void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14701 // No warnings in macros
14702 if (Loc.isMacroID())
14703 return;
14704
14705 // Don't warn in template instantiations.
14706 if (inTemplateInstantiation())
14707 return;
14708
14709 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14710 // instead, skip more than needed, then call back into here with the
14711 // CommaVisitor in SemaStmt.cpp.
14712 // The listed locations are the initialization and increment portions
14713 // of a for loop. The additional checks are on the condition of
14714 // if statements, do/while loops, and for loops.
14715 if (getCurScope()->isControlScope())
14716 return;
14717
14718 // If there are multiple comma operators used together, get the RHS of the
14719 // of the comma operator as the LHS.
14720 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14721 if (BO->getOpcode() != BO_Comma)
14722 break;
14723 LHS = BO->getRHS();
14724 }
14725
14726 // Only allow some expressions on LHS to not warn.
14727 if (IgnoreCommaOperand(E: LHS, Context))
14728 return;
14729
14730 Diag(Loc, DiagID: diag::warn_comma_operator);
14731 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14732 << LHS->getSourceRange()
14733 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14734 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14735 : "(void)(")
14736 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14737 Code: ")");
14738}
14739
14740// C99 6.5.17
14741static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14742 SourceLocation Loc) {
14743 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14744 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14745 if (LHS.isInvalid() || RHS.isInvalid())
14746 return QualType();
14747
14748 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14749 // operands, but not unary promotions.
14750 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14751
14752 // So we treat the LHS as a ignored value, and in C++ we allow the
14753 // containing site to determine what should be done with the RHS.
14754 LHS = S.IgnoredValueConversions(E: LHS.get());
14755 if (LHS.isInvalid())
14756 return QualType();
14757
14758 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14759
14760 if (!S.getLangOpts().CPlusPlus) {
14761 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14762 if (RHS.isInvalid())
14763 return QualType();
14764 if (!RHS.get()->getType()->isVoidType())
14765 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14766 DiagID: diag::err_incomplete_type);
14767 }
14768
14769 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14770 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14771
14772 return RHS.get()->getType();
14773}
14774
14775/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14776/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14777static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14778 ExprValueKind &VK,
14779 ExprObjectKind &OK,
14780 SourceLocation OpLoc, bool IsInc,
14781 bool IsPrefix) {
14782 QualType ResType = Op->getType();
14783 // Atomic types can be used for increment / decrement where the non-atomic
14784 // versions can, so ignore the _Atomic() specifier for the purpose of
14785 // checking.
14786 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14787 ResType = ResAtomicType->getValueType();
14788
14789 assert(!ResType.isNull() && "no type for increment/decrement expression");
14790
14791 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14792 // Decrement of bool is not allowed.
14793 if (!IsInc) {
14794 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14795 return QualType();
14796 }
14797 // Increment of bool sets it to true, but is deprecated.
14798 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14799 : diag::warn_increment_bool)
14800 << Op->getSourceRange();
14801 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14802 // Error on enum increments and decrements in C++ mode
14803 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14804 return QualType();
14805 } else if (ResType->isRealType()) {
14806 // OK!
14807 } else if (ResType->isPointerType()) {
14808 // C99 6.5.2.4p2, 6.5.6p2
14809 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14810 return QualType();
14811 } else if (ResType->isOverflowBehaviorType()) {
14812 // OK!
14813 } else if (ResType->isObjCObjectPointerType()) {
14814 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14815 // Otherwise, we just need a complete type.
14816 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14817 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14818 return QualType();
14819 } else if (ResType->isAnyComplexType()) {
14820 // C99 does not support ++/-- on complex types, we allow as an extension.
14821 S.DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::increment_complex)
14822 << IsInc << Op->getSourceRange();
14823 } else if (ResType->isPlaceholderType()) {
14824 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14825 if (PR.isInvalid()) return QualType();
14826 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14827 IsInc, IsPrefix);
14828 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14829 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14830 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14831 (ResType->castAs<VectorType>()->getVectorKind() !=
14832 VectorKind::AltiVecBool)) {
14833 // The z vector extensions allow ++ and -- for non-bool vectors.
14834 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14835 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14836 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14837 } else {
14838 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14839 << ResType << int(IsInc) << Op->getSourceRange();
14840 return QualType();
14841 }
14842 // At this point, we know we have a real, complex or pointer type.
14843 // Now make sure the operand is a modifiable lvalue.
14844 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14845 return QualType();
14846 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14847 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14848 // An operand with volatile-qualified type is deprecated
14849 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14850 << IsInc << ResType;
14851 }
14852 // In C++, a prefix increment is the same type as the operand. Otherwise
14853 // (in C or with postfix), the increment is the unqualified type of the
14854 // operand.
14855 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14856 VK = VK_LValue;
14857 OK = Op->getObjectKind();
14858 return ResType;
14859 } else {
14860 VK = VK_PRValue;
14861 return ResType.getUnqualifiedType();
14862 }
14863}
14864
14865/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14866/// This routine allows us to typecheck complex/recursive expressions
14867/// where the declaration is needed for type checking. We only need to
14868/// handle cases when the expression references a function designator
14869/// or is an lvalue. Here are some examples:
14870/// - &(x) => x
14871/// - &*****f => f for f a function designator.
14872/// - &s.xx => s
14873/// - &s.zz[1].yy -> s, if zz is an array
14874/// - *(x + 1) -> x, if x is an array
14875/// - &"123"[2] -> 0
14876/// - & __real__ x -> x
14877///
14878/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14879/// members.
14880static ValueDecl *getPrimaryDecl(Expr *E) {
14881 switch (E->getStmtClass()) {
14882 case Stmt::DeclRefExprClass:
14883 return cast<DeclRefExpr>(Val: E)->getDecl();
14884 case Stmt::MemberExprClass:
14885 // If this is an arrow operator, the address is an offset from
14886 // the base's value, so the object the base refers to is
14887 // irrelevant.
14888 if (cast<MemberExpr>(Val: E)->isArrow())
14889 return nullptr;
14890 // Otherwise, the expression refers to a part of the base
14891 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14892 case Stmt::ArraySubscriptExprClass: {
14893 // FIXME: This code shouldn't be necessary! We should catch the implicit
14894 // promotion of register arrays earlier.
14895 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14896 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14897 if (ICE->getSubExpr()->getType()->isArrayType())
14898 return getPrimaryDecl(E: ICE->getSubExpr());
14899 }
14900 return nullptr;
14901 }
14902 case Stmt::UnaryOperatorClass: {
14903 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14904
14905 switch(UO->getOpcode()) {
14906 case UO_Real:
14907 case UO_Imag:
14908 case UO_Extension:
14909 return getPrimaryDecl(E: UO->getSubExpr());
14910 default:
14911 return nullptr;
14912 }
14913 }
14914 case Stmt::ParenExprClass:
14915 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14916 case Stmt::ImplicitCastExprClass:
14917 // If the result of an implicit cast is an l-value, we care about
14918 // the sub-expression; otherwise, the result here doesn't matter.
14919 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14920 case Stmt::CXXUuidofExprClass:
14921 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14922 default:
14923 return nullptr;
14924 }
14925}
14926
14927namespace {
14928enum {
14929 AO_Bit_Field = 0,
14930 AO_Vector_Element = 1,
14931 AO_Property_Expansion = 2,
14932 AO_Register_Variable = 3,
14933 AO_Matrix_Element = 4,
14934 AO_No_Error = 5
14935};
14936}
14937/// Diagnose invalid operand for address of operations.
14938///
14939/// \param Type The type of operand which cannot have its address taken.
14940static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14941 Expr *E, unsigned Type) {
14942 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14943}
14944
14945bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14946 const Expr *Op,
14947 const CXXMethodDecl *MD) {
14948 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14949
14950 if (Op != DRE)
14951 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14952 << Op->getSourceRange();
14953
14954 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14955 if (isa<CXXDestructorDecl>(Val: MD))
14956 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14957 << DRE->getSourceRange();
14958
14959 if (DRE->getQualifier())
14960 return false;
14961
14962 if (MD->getParent()->getName().empty())
14963 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14964 << DRE->getSourceRange();
14965
14966 SmallString<32> Str;
14967 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14968 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14969 << DRE->getSourceRange()
14970 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14971}
14972
14973QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14974 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14975 if (PTy->getKind() == BuiltinType::Overload) {
14976 Expr *E = OrigOp.get()->IgnoreParens();
14977 if (!isa<OverloadExpr>(Val: E)) {
14978 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14979 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14980 << OrigOp.get()->getSourceRange();
14981 return QualType();
14982 }
14983
14984 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
14985 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14986 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
14987 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14988 << OrigOp.get()->getSourceRange();
14989 return QualType();
14990 }
14991
14992 return Context.OverloadTy;
14993 }
14994
14995 if (PTy->getKind() == BuiltinType::UnknownAny)
14996 return Context.UnknownAnyTy;
14997
14998 if (PTy->getKind() == BuiltinType::BoundMember) {
14999 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15000 << OrigOp.get()->getSourceRange();
15001 return QualType();
15002 }
15003
15004 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15005 if (OrigOp.isInvalid()) return QualType();
15006 }
15007
15008 if (OrigOp.get()->isTypeDependent())
15009 return Context.DependentTy;
15010
15011 assert(!OrigOp.get()->hasPlaceholderType());
15012
15013 // Make sure to ignore parentheses in subsequent checks
15014 Expr *op = OrigOp.get()->IgnoreParens();
15015
15016 // In OpenCL captures for blocks called as lambda functions
15017 // are located in the private address space. Blocks used in
15018 // enqueue_kernel can be located in a different address space
15019 // depending on a vendor implementation. Thus preventing
15020 // taking an address of the capture to avoid invalid AS casts.
15021 if (LangOpts.OpenCL) {
15022 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15023 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15024 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
15025 return QualType();
15026 }
15027 }
15028
15029 if (getLangOpts().C99) {
15030 // Implement C99-only parts of addressof rules.
15031 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15032 if (uOp->getOpcode() == UO_Deref)
15033 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15034 // (assuming the deref expression is valid).
15035 return uOp->getSubExpr()->getType();
15036 }
15037 // Technically, there should be a check for array subscript
15038 // expressions here, but the result of one is always an lvalue anyway.
15039 }
15040 ValueDecl *dcl = getPrimaryDecl(E: op);
15041
15042 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15043 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15044 Loc: op->getBeginLoc()))
15045 return QualType();
15046
15047 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15048 unsigned AddressOfError = AO_No_Error;
15049
15050 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15051 bool IsError = isSFINAEContext();
15052 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15053 : diag::ext_typecheck_addrof_temporary)
15054 << op->getType() << op->getSourceRange();
15055 if (IsError)
15056 return QualType();
15057 // Materialize the temporary as an lvalue so that we can take its address.
15058 OrigOp = op =
15059 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15060 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15061 return Context.getPointerType(T: op->getType());
15062 } else if (lval == Expr::LV_MemberFunction) {
15063 // If it's an instance method, make a member pointer.
15064 // The expression must have exactly the form &A::foo.
15065
15066 // If the underlying expression isn't a decl ref, give up.
15067 if (!isa<DeclRefExpr>(Val: op)) {
15068 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15069 << OrigOp.get()->getSourceRange();
15070 return QualType();
15071 }
15072 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15073 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15074
15075 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15076 QualType MPTy = Context.getMemberPointerType(
15077 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15078
15079 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15080 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15081 // When pointer authentication is enabled, argument and return types of
15082 // vitual member functions must be complete. This is because vitrual
15083 // member function pointers are implemented using virtual dispatch
15084 // thunks and the thunks cannot be emitted if the argument or return
15085 // types are incomplete.
15086 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15087 SourceLocation DeclRefLoc,
15088 SourceLocation RetArgTypeLoc) {
15089 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15090 Diag(Loc: DeclRefLoc,
15091 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15092 Diag(Loc: RetArgTypeLoc,
15093 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15094 << T;
15095 return true;
15096 }
15097 return false;
15098 };
15099 QualType RetTy = MD->getReturnType();
15100 bool IsIncomplete =
15101 !RetTy->isVoidType() &&
15102 ReturnOrParamTypeIsIncomplete(
15103 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15104 for (auto *PVD : MD->parameters())
15105 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15106 PVD->getBeginLoc());
15107 if (IsIncomplete)
15108 return QualType();
15109 }
15110
15111 // Under the MS ABI, lock down the inheritance model now.
15112 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15113 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15114 return MPTy;
15115 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15116 // C99 6.5.3.2p1
15117 // The operand must be either an l-value or a function designator
15118 if (!op->getType()->isFunctionType()) {
15119 // Use a special diagnostic for loads from property references.
15120 if (isa<PseudoObjectExpr>(Val: op)) {
15121 AddressOfError = AO_Property_Expansion;
15122 } else {
15123 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15124 << op->getType() << op->getSourceRange();
15125 return QualType();
15126 }
15127 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15128 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15129 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15130 }
15131
15132 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15133 // The operand cannot be a bit-field
15134 AddressOfError = AO_Bit_Field;
15135 } else if (op->getObjectKind() == OK_VectorComponent) {
15136 // The operand cannot be an element of a vector
15137 AddressOfError = AO_Vector_Element;
15138 } else if (op->getObjectKind() == OK_MatrixComponent) {
15139 // The operand cannot be an element of a matrix.
15140 AddressOfError = AO_Matrix_Element;
15141 } else if (dcl) { // C99 6.5.3.2p1
15142 // We have an lvalue with a decl. Make sure the decl is not declared
15143 // with the register storage-class specifier.
15144 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15145 // in C++ it is not error to take address of a register
15146 // variable (c++03 7.1.1P3)
15147 if (vd->getStorageClass() == SC_Register &&
15148 !getLangOpts().CPlusPlus) {
15149 AddressOfError = AO_Register_Variable;
15150 }
15151 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15152 AddressOfError = AO_Property_Expansion;
15153 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15154 return Context.OverloadTy;
15155 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15156 // Okay: we can take the address of a field.
15157 // Could be a pointer to member, though, if there is an explicit
15158 // scope qualifier for the class.
15159
15160 // [C++26] [expr.prim.id.general]
15161 // If an id-expression E denotes a non-static non-type member
15162 // of some class C [...] and if E is a qualified-id, E is
15163 // not the un-parenthesized operand of the unary & operator [...]
15164 // the id-expression is transformed into a class member access expression.
15165 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15166 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15167 DeclContext *Ctx = dcl->getDeclContext();
15168 if (Ctx && Ctx->isRecord()) {
15169 if (dcl->getType()->isReferenceType()) {
15170 Diag(Loc: OpLoc,
15171 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15172 << dcl->getDeclName() << dcl->getType();
15173 return QualType();
15174 }
15175
15176 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15177 Ctx = Ctx->getParent();
15178
15179 QualType MPTy = Context.getMemberPointerType(
15180 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15181 // Under the MS ABI, lock down the inheritance model now.
15182 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15183 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15184 return MPTy;
15185 }
15186 }
15187 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15188 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15189 UnnamedGlobalConstantDecl>(Val: dcl))
15190 llvm_unreachable("Unknown/unexpected decl type");
15191 }
15192
15193 if (AddressOfError != AO_No_Error) {
15194 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15195 return QualType();
15196 }
15197
15198 if (lval == Expr::LV_IncompleteVoidType) {
15199 // Taking the address of a void variable is technically illegal, but we
15200 // allow it in cases which are otherwise valid.
15201 // Example: "extern void x; void* y = &x;".
15202 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15203 }
15204
15205 // If the operand has type "type", the result has type "pointer to type".
15206 if (op->getType()->isObjCObjectType())
15207 return Context.getObjCObjectPointerType(OIT: op->getType());
15208
15209 // Cannot take the address of WebAssembly references or tables.
15210 if (Context.getTargetInfo().getTriple().isWasm()) {
15211 QualType OpTy = op->getType();
15212 if (OpTy.isWebAssemblyReferenceType()) {
15213 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15214 << 1 << OrigOp.get()->getSourceRange();
15215 return QualType();
15216 }
15217 if (OpTy->isWebAssemblyTableType()) {
15218 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15219 << 1 << OrigOp.get()->getSourceRange();
15220 return QualType();
15221 }
15222 }
15223
15224 CheckAddressOfPackedMember(rhs: op);
15225
15226 return Context.getPointerType(T: op->getType());
15227}
15228
15229static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15230 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15231 if (!DRE)
15232 return;
15233 const Decl *D = DRE->getDecl();
15234 if (!D)
15235 return;
15236 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15237 if (!Param)
15238 return;
15239 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15240 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15241 return;
15242 if (FunctionScopeInfo *FD = S.getCurFunction())
15243 FD->ModifiedNonNullParams.insert(Ptr: Param);
15244}
15245
15246/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15247static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15248 SourceLocation OpLoc,
15249 bool IsAfterAmp = false) {
15250 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15251 if (ConvResult.isInvalid())
15252 return QualType();
15253 Op = ConvResult.get();
15254 QualType OpTy = Op->getType();
15255 QualType Result;
15256
15257 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15258 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15259 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15260 Range: Op->getSourceRange());
15261 }
15262
15263 if (const PointerType *PT = OpTy->getAs<PointerType>())
15264 {
15265 Result = PT->getPointeeType();
15266 }
15267 else if (const ObjCObjectPointerType *OPT =
15268 OpTy->getAs<ObjCObjectPointerType>())
15269 Result = OPT->getPointeeType();
15270 else {
15271 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15272 if (PR.isInvalid()) return QualType();
15273 if (PR.get() != Op)
15274 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15275 }
15276
15277 if (Result.isNull()) {
15278 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15279 << OpTy << Op->getSourceRange();
15280 return QualType();
15281 }
15282
15283 if (Result->isVoidType()) {
15284 // C++ [expr.unary.op]p1:
15285 // [...] the expression to which [the unary * operator] is applied shall
15286 // be a pointer to an object type, or a pointer to a function type
15287 LangOptions LO = S.getLangOpts();
15288 if (LO.CPlusPlus)
15289 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15290 << OpTy << Op->getSourceRange();
15291 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15292 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15293 << OpTy << Op->getSourceRange();
15294 }
15295
15296 // Dereferences are usually l-values...
15297 VK = VK_LValue;
15298
15299 // ...except that certain expressions are never l-values in C.
15300 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15301 VK = VK_PRValue;
15302
15303 return Result;
15304}
15305
15306BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15307 BinaryOperatorKind Opc;
15308 switch (Kind) {
15309 default: llvm_unreachable("Unknown binop!");
15310 case tok::periodstar: Opc = BO_PtrMemD; break;
15311 case tok::arrowstar: Opc = BO_PtrMemI; break;
15312 case tok::star: Opc = BO_Mul; break;
15313 case tok::slash: Opc = BO_Div; break;
15314 case tok::percent: Opc = BO_Rem; break;
15315 case tok::plus: Opc = BO_Add; break;
15316 case tok::minus: Opc = BO_Sub; break;
15317 case tok::lessless: Opc = BO_Shl; break;
15318 case tok::greatergreater: Opc = BO_Shr; break;
15319 case tok::lessequal: Opc = BO_LE; break;
15320 case tok::less: Opc = BO_LT; break;
15321 case tok::greaterequal: Opc = BO_GE; break;
15322 case tok::greater: Opc = BO_GT; break;
15323 case tok::exclaimequal: Opc = BO_NE; break;
15324 case tok::equalequal: Opc = BO_EQ; break;
15325 case tok::spaceship: Opc = BO_Cmp; break;
15326 case tok::amp: Opc = BO_And; break;
15327 case tok::caret: Opc = BO_Xor; break;
15328 case tok::pipe: Opc = BO_Or; break;
15329 case tok::ampamp: Opc = BO_LAnd; break;
15330 case tok::pipepipe: Opc = BO_LOr; break;
15331 case tok::equal: Opc = BO_Assign; break;
15332 case tok::starequal: Opc = BO_MulAssign; break;
15333 case tok::slashequal: Opc = BO_DivAssign; break;
15334 case tok::percentequal: Opc = BO_RemAssign; break;
15335 case tok::plusequal: Opc = BO_AddAssign; break;
15336 case tok::minusequal: Opc = BO_SubAssign; break;
15337 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15338 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15339 case tok::ampequal: Opc = BO_AndAssign; break;
15340 case tok::caretequal: Opc = BO_XorAssign; break;
15341 case tok::pipeequal: Opc = BO_OrAssign; break;
15342 case tok::comma: Opc = BO_Comma; break;
15343 }
15344 return Opc;
15345}
15346
15347static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15348 tok::TokenKind Kind) {
15349 UnaryOperatorKind Opc;
15350 switch (Kind) {
15351 default: llvm_unreachable("Unknown unary op!");
15352 case tok::plusplus: Opc = UO_PreInc; break;
15353 case tok::minusminus: Opc = UO_PreDec; break;
15354 case tok::amp: Opc = UO_AddrOf; break;
15355 case tok::star: Opc = UO_Deref; break;
15356 case tok::plus: Opc = UO_Plus; break;
15357 case tok::minus: Opc = UO_Minus; break;
15358 case tok::tilde: Opc = UO_Not; break;
15359 case tok::exclaim: Opc = UO_LNot; break;
15360 case tok::kw___real: Opc = UO_Real; break;
15361 case tok::kw___imag: Opc = UO_Imag; break;
15362 case tok::kw___extension__: Opc = UO_Extension; break;
15363 }
15364 return Opc;
15365}
15366
15367const FieldDecl *
15368Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15369 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15370 // common for setters.
15371 // struct A {
15372 // int X;
15373 // -void setX(int X) { X = X; }
15374 // +void setX(int X) { this->X = X; }
15375 // };
15376
15377 // Only consider parameters for self assignment fixes.
15378 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15379 return nullptr;
15380 const auto *Method =
15381 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15382 if (!Method)
15383 return nullptr;
15384
15385 const CXXRecordDecl *Parent = Method->getParent();
15386 // In theory this is fixable if the lambda explicitly captures this, but
15387 // that's added complexity that's rarely going to be used.
15388 if (Parent->isLambda())
15389 return nullptr;
15390
15391 // FIXME: Use an actual Lookup operation instead of just traversing fields
15392 // in order to get base class fields.
15393 auto Field =
15394 llvm::find_if(Range: Parent->fields(),
15395 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15396 return F->getDeclName() == Name;
15397 });
15398 return (Field != Parent->field_end()) ? *Field : nullptr;
15399}
15400
15401/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15402/// This warning suppressed in the event of macro expansions.
15403static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15404 SourceLocation OpLoc, bool IsBuiltin) {
15405 if (S.inTemplateInstantiation())
15406 return;
15407 if (S.isUnevaluatedContext())
15408 return;
15409 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15410 return;
15411 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15412 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15413 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15414 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15415 if (!LHSDeclRef || !RHSDeclRef ||
15416 LHSDeclRef->getLocation().isMacroID() ||
15417 RHSDeclRef->getLocation().isMacroID())
15418 return;
15419 const ValueDecl *LHSDecl =
15420 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15421 const ValueDecl *RHSDecl =
15422 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15423 if (LHSDecl != RHSDecl)
15424 return;
15425 if (LHSDecl->getType().isVolatileQualified())
15426 return;
15427 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15428 if (RefTy->getPointeeType().isVolatileQualified())
15429 return;
15430
15431 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15432 : diag::warn_self_assignment_overloaded)
15433 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15434 << RHSExpr->getSourceRange();
15435 if (const FieldDecl *SelfAssignField =
15436 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15437 Diag << 1 << SelfAssignField
15438 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15439 else
15440 Diag << 0;
15441}
15442
15443/// Check if a bitwise-& is performed on an Objective-C pointer. This
15444/// is usually indicative of introspection within the Objective-C pointer.
15445static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15446 SourceLocation OpLoc) {
15447 if (!S.getLangOpts().ObjC)
15448 return;
15449
15450 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15451 const Expr *LHS = L.get();
15452 const Expr *RHS = R.get();
15453
15454 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15455 ObjCPointerExpr = LHS;
15456 OtherExpr = RHS;
15457 }
15458 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15459 ObjCPointerExpr = RHS;
15460 OtherExpr = LHS;
15461 }
15462
15463 // This warning is deliberately made very specific to reduce false
15464 // positives with logic that uses '&' for hashing. This logic mainly
15465 // looks for code trying to introspect into tagged pointers, which
15466 // code should generally never do.
15467 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15468 unsigned Diag = diag::warn_objc_pointer_masking;
15469 // Determine if we are introspecting the result of performSelectorXXX.
15470 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15471 // Special case messages to -performSelector and friends, which
15472 // can return non-pointer values boxed in a pointer value.
15473 // Some clients may wish to silence warnings in this subcase.
15474 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15475 Selector S = ME->getSelector();
15476 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15477 if (SelArg0.starts_with(Prefix: "performSelector"))
15478 Diag = diag::warn_objc_pointer_masking_performSelector;
15479 }
15480
15481 S.Diag(Loc: OpLoc, DiagID: Diag)
15482 << ObjCPointerExpr->getSourceRange();
15483 }
15484}
15485
15486// This helper function promotes a binary operator's operands (which are of a
15487// half vector type) to a vector of floats and then truncates the result to
15488// a vector of either half or short.
15489static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15490 BinaryOperatorKind Opc, QualType ResultTy,
15491 ExprValueKind VK, ExprObjectKind OK,
15492 bool IsCompAssign, SourceLocation OpLoc,
15493 FPOptionsOverride FPFeatures) {
15494 auto &Context = S.getASTContext();
15495 assert((isVector(ResultTy, Context.HalfTy) ||
15496 isVector(ResultTy, Context.ShortTy)) &&
15497 "Result must be a vector of half or short");
15498 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15499 isVector(RHS.get()->getType(), Context.HalfTy) &&
15500 "both operands expected to be a half vector");
15501
15502 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15503 QualType BinOpResTy = RHS.get()->getType();
15504
15505 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15506 // change BinOpResTy to a vector of ints.
15507 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15508 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15509
15510 if (IsCompAssign)
15511 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15512 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15513 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15514
15515 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15516 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15517 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15518 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15519}
15520
15521/// Returns true if conversion between vectors of halfs and vectors of floats
15522/// is needed.
15523static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15524 Expr *E0, Expr *E1 = nullptr) {
15525 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15526 return false;
15527
15528 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15529 QualType Ty = E->IgnoreImplicit()->getType();
15530
15531 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15532 // to vectors of floats. Although the element type of the vectors is __fp16,
15533 // the vectors shouldn't be treated as storage-only types. See the
15534 // discussion here: https://reviews.llvm.org/rG825235c140e7
15535 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15536 if (VT->getVectorKind() == VectorKind::Neon)
15537 return false;
15538 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15539 }
15540 return false;
15541 };
15542
15543 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15544}
15545
15546ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15547 BinaryOperatorKind Opc, Expr *LHSExpr,
15548 Expr *RHSExpr, bool ForFoldExpression) {
15549 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15550 // The syntax only allows initializer lists on the RHS of assignment,
15551 // so we don't need to worry about accepting invalid code for
15552 // non-assignment operators.
15553 // C++11 5.17p9:
15554 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15555 // of x = {} is x = T().
15556 InitializationKind Kind = InitializationKind::CreateDirectList(
15557 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15558 InitializedEntity Entity =
15559 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15560 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15561 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15562 if (Init.isInvalid())
15563 return Init;
15564 RHSExpr = Init.get();
15565 }
15566
15567 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15568 QualType ResultTy; // Result type of the binary operator.
15569 // The following two variables are used for compound assignment operators
15570 QualType CompLHSTy; // Type of LHS after promotions for computation
15571 QualType CompResultTy; // Type of computation result
15572 ExprValueKind VK = VK_PRValue;
15573 ExprObjectKind OK = OK_Ordinary;
15574 bool ConvertHalfVec = false;
15575
15576 if (!LHS.isUsable() || !RHS.isUsable())
15577 return ExprError();
15578
15579 if (getLangOpts().OpenCL) {
15580 QualType LHSTy = LHSExpr->getType();
15581 QualType RHSTy = RHSExpr->getType();
15582 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15583 // the ATOMIC_VAR_INIT macro.
15584 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15585 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15586 if (BO_Assign == Opc)
15587 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15588 else
15589 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15590 return ExprError();
15591 }
15592
15593 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15594 // only with a builtin functions and therefore should be disallowed here.
15595 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15596 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15597 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15598 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15599 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15600 return ExprError();
15601 }
15602 }
15603
15604 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15605 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15606
15607 switch (Opc) {
15608 case BO_Assign:
15609 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15610 if (getLangOpts().CPlusPlus &&
15611 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15612 VK = LHS.get()->getValueKind();
15613 OK = LHS.get()->getObjectKind();
15614 }
15615 if (!ResultTy.isNull()) {
15616 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15617 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15618
15619 // Avoid copying a block to the heap if the block is assigned to a local
15620 // auto variable that is declared in the same scope as the block. This
15621 // optimization is unsafe if the local variable is declared in an outer
15622 // scope. For example:
15623 //
15624 // BlockTy b;
15625 // {
15626 // b = ^{...};
15627 // }
15628 // // It is unsafe to invoke the block here if it wasn't copied to the
15629 // // heap.
15630 // b();
15631
15632 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15633 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15634 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15635 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15636 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15637
15638 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15639 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15640 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15641 }
15642 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15643 break;
15644 case BO_PtrMemD:
15645 case BO_PtrMemI:
15646 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15647 isIndirect: Opc == BO_PtrMemI);
15648 break;
15649 case BO_Mul:
15650 case BO_Div:
15651 ConvertHalfVec = true;
15652 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15653 break;
15654 case BO_Rem:
15655 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15656 break;
15657 case BO_Add:
15658 ConvertHalfVec = true;
15659 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15660 break;
15661 case BO_Sub:
15662 ConvertHalfVec = true;
15663 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15664 break;
15665 case BO_Shl:
15666 case BO_Shr:
15667 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15668 break;
15669 case BO_LE:
15670 case BO_LT:
15671 case BO_GE:
15672 case BO_GT:
15673 ConvertHalfVec = true;
15674 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15675
15676 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15677 !ForFoldExpression && BI && BI->isComparisonOp())
15678 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15679 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15680
15681 break;
15682 case BO_EQ:
15683 case BO_NE:
15684 ConvertHalfVec = true;
15685 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15686 break;
15687 case BO_Cmp:
15688 ConvertHalfVec = true;
15689 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15690 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15691 break;
15692 case BO_And:
15693 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15694 [[fallthrough]];
15695 case BO_Xor:
15696 case BO_Or:
15697 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15698 break;
15699 case BO_LAnd:
15700 case BO_LOr:
15701 ConvertHalfVec = true;
15702 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15703 break;
15704 case BO_MulAssign:
15705 case BO_DivAssign:
15706 ConvertHalfVec = true;
15707 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15708 CompLHSTy = CompResultTy;
15709 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15710 ResultTy =
15711 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15712 break;
15713 case BO_RemAssign:
15714 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15715 CompLHSTy = CompResultTy;
15716 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15717 ResultTy =
15718 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15719 break;
15720 case BO_AddAssign:
15721 ConvertHalfVec = true;
15722 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15723 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15724 ResultTy =
15725 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15726 break;
15727 case BO_SubAssign:
15728 ConvertHalfVec = true;
15729 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15730 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15731 ResultTy =
15732 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15733 break;
15734 case BO_ShlAssign:
15735 case BO_ShrAssign:
15736 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15737 CompLHSTy = CompResultTy;
15738 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15739 ResultTy =
15740 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15741 break;
15742 case BO_AndAssign:
15743 case BO_OrAssign: // fallthrough
15744 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15745 [[fallthrough]];
15746 case BO_XorAssign:
15747 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15748 CompLHSTy = CompResultTy;
15749 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15750 ResultTy =
15751 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15752 break;
15753 case BO_Comma:
15754 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15755 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15756 VK = RHS.get()->getValueKind();
15757 OK = RHS.get()->getObjectKind();
15758 }
15759 break;
15760 }
15761 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15762 return ExprError();
15763
15764 // Some of the binary operations require promoting operands of half vector to
15765 // float vectors and truncating the result back to half vector. For now, we do
15766 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15767 // arm64).
15768 assert(
15769 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15770 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15771 "both sides are half vectors or neither sides are");
15772 ConvertHalfVec =
15773 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15774
15775 // Check for array bounds violations for both sides of the BinaryOperator
15776 CheckArrayAccess(E: LHS.get());
15777 CheckArrayAccess(E: RHS.get());
15778
15779 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15780 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15781 Name: &Context.Idents.get(Name: "object_setClass"),
15782 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15783 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15784 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15785 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15786 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15787 Code: "object_setClass(")
15788 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15789 Code: ",")
15790 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15791 }
15792 else
15793 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15794 }
15795 else if (const ObjCIvarRefExpr *OIRE =
15796 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15797 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15798
15799 // Opc is not a compound assignment if CompResultTy is null.
15800 if (CompResultTy.isNull()) {
15801 if (ConvertHalfVec)
15802 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15803 OpLoc, FPFeatures: CurFPFeatureOverrides());
15804 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15805 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15806 }
15807
15808 // Handle compound assignments.
15809 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15810 OK_ObjCProperty) {
15811 VK = VK_LValue;
15812 OK = LHS.get()->getObjectKind();
15813 }
15814
15815 // The LHS is not converted to the result type for fixed-point compound
15816 // assignment as the common type is computed on demand. Reset the CompLHSTy
15817 // to the LHS type we would have gotten after unary conversions.
15818 if (CompResultTy->isFixedPointType())
15819 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15820
15821 if (ConvertHalfVec)
15822 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15823 OpLoc, FPFeatures: CurFPFeatureOverrides());
15824
15825 return CompoundAssignOperator::Create(
15826 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15827 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15828}
15829
15830/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15831/// operators are mixed in a way that suggests that the programmer forgot that
15832/// comparison operators have higher precedence. The most typical example of
15833/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15834static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15835 SourceLocation OpLoc, Expr *LHSExpr,
15836 Expr *RHSExpr) {
15837 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15838 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15839
15840 // Check that one of the sides is a comparison operator and the other isn't.
15841 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15842 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15843 if (isLeftComp == isRightComp)
15844 return;
15845
15846 // Bitwise operations are sometimes used as eager logical ops.
15847 // Don't diagnose this.
15848 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15849 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15850 if (isLeftBitwise || isRightBitwise)
15851 return;
15852
15853 SourceRange DiagRange = isLeftComp
15854 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15855 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15856 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15857 SourceRange ParensRange =
15858 isLeftComp
15859 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15860 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15861
15862 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15863 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15864 SuggestParentheses(Self, Loc: OpLoc,
15865 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15866 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15867 SuggestParentheses(Self, Loc: OpLoc,
15868 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15869 << BinaryOperator::getOpcodeStr(Op: Opc),
15870 ParenRange: ParensRange);
15871}
15872
15873/// It accepts a '&&' expr that is inside a '||' one.
15874/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15875/// in parentheses.
15876static void
15877EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15878 BinaryOperator *Bop) {
15879 assert(Bop->getOpcode() == BO_LAnd);
15880 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15881 << Bop->getSourceRange() << OpLoc;
15882 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15883 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15884 << Bop->getOpcodeStr(),
15885 ParenRange: Bop->getSourceRange());
15886}
15887
15888/// Look for '&&' in the left hand of a '||' expr.
15889static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15890 Expr *LHSExpr, Expr *RHSExpr) {
15891 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15892 if (Bop->getOpcode() == BO_LAnd) {
15893 // If it's "string_literal && a || b" don't warn since the precedence
15894 // doesn't matter.
15895 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15896 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15897 } else if (Bop->getOpcode() == BO_LOr) {
15898 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15899 // If it's "a || b && string_literal || c" we didn't warn earlier for
15900 // "a || b && string_literal", but warn now.
15901 if (RBop->getOpcode() == BO_LAnd &&
15902 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15903 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15904 }
15905 }
15906 }
15907}
15908
15909/// Look for '&&' in the right hand of a '||' expr.
15910static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15911 Expr *LHSExpr, Expr *RHSExpr) {
15912 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15913 if (Bop->getOpcode() == BO_LAnd) {
15914 // If it's "a || b && string_literal" don't warn since the precedence
15915 // doesn't matter.
15916 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15917 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15918 }
15919 }
15920}
15921
15922/// Look for bitwise op in the left or right hand of a bitwise op with
15923/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15924/// the '&' expression in parentheses.
15925static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15926 SourceLocation OpLoc, Expr *SubExpr) {
15927 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15928 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15929 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15930 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15931 << Bop->getSourceRange() << OpLoc;
15932 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15933 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15934 << Bop->getOpcodeStr(),
15935 ParenRange: Bop->getSourceRange());
15936 }
15937 }
15938}
15939
15940static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15941 Expr *SubExpr, StringRef Shift) {
15942 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15943 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15944 StringRef Op = Bop->getOpcodeStr();
15945 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15946 << Bop->getSourceRange() << OpLoc << Shift << Op;
15947 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15948 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15949 ParenRange: Bop->getSourceRange());
15950 }
15951 }
15952}
15953
15954static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15955 Expr *LHSExpr, Expr *RHSExpr) {
15956 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15957 if (!OCE)
15958 return;
15959
15960 FunctionDecl *FD = OCE->getDirectCallee();
15961 if (!FD || !FD->isOverloadedOperator())
15962 return;
15963
15964 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15965 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15966 return;
15967
15968 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
15969 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15970 << (Kind == OO_LessLess);
15971 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
15972 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15973 << (Kind == OO_LessLess ? "<<" : ">>"),
15974 ParenRange: OCE->getSourceRange());
15975 SuggestParentheses(
15976 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
15977 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
15978}
15979
15980/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15981/// precedence.
15982static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15983 SourceLocation OpLoc, Expr *LHSExpr,
15984 Expr *RHSExpr){
15985 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15986 if (BinaryOperator::isBitwiseOp(Opc))
15987 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15988
15989 // Diagnose "arg1 & arg2 | arg3"
15990 if ((Opc == BO_Or || Opc == BO_Xor) &&
15991 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15992 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15993 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
15994 }
15995
15996 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15997 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15998 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15999 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16000 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16001 }
16002
16003 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16004 || Opc == BO_Shr) {
16005 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16006 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16007 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16008 }
16009
16010 // Warn on overloaded shift operators and comparisons, such as:
16011 // cout << 5 == 4;
16012 if (BinaryOperator::isComparisonOp(Opc))
16013 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16014}
16015
16016ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16017 tok::TokenKind Kind,
16018 Expr *LHSExpr, Expr *RHSExpr) {
16019 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16020 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16021 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16022
16023 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16024 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16025
16026 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
16027 ? BuiltinCountedByRefKind::Assignment
16028 : BuiltinCountedByRefKind::BinaryExpr;
16029
16030 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
16031 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
16032
16033 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16034}
16035
16036void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16037 UnresolvedSetImpl &Functions) {
16038 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16039 if (OverOp != OO_None && OverOp != OO_Equal)
16040 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16041
16042 // In C++20 onwards, we may have a second operator to look up.
16043 if (getLangOpts().CPlusPlus20) {
16044 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16045 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16046 }
16047}
16048
16049/// Build an overloaded binary operator expression in the given scope.
16050static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16051 BinaryOperatorKind Opc,
16052 Expr *LHS, Expr *RHS) {
16053 switch (Opc) {
16054 case BO_Assign:
16055 // In the non-overloaded case, we warn about self-assignment (x = x) for
16056 // both simple assignment and certain compound assignments where algebra
16057 // tells us the operation yields a constant result. When the operator is
16058 // overloaded, we can't do the latter because we don't want to assume that
16059 // those algebraic identities still apply; for example, a path-building
16060 // library might use operator/= to append paths. But it's still reasonable
16061 // to assume that simple assignment is just moving/copying values around
16062 // and so self-assignment is likely a bug.
16063 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16064 [[fallthrough]];
16065 case BO_DivAssign:
16066 case BO_RemAssign:
16067 case BO_SubAssign:
16068 case BO_AndAssign:
16069 case BO_OrAssign:
16070 case BO_XorAssign:
16071 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16072 break;
16073 default:
16074 break;
16075 }
16076
16077 // Find all of the overloaded operators visible from this point.
16078 UnresolvedSet<16> Functions;
16079 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16080
16081 // Build the (potentially-overloaded, potentially-dependent)
16082 // binary operation.
16083 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16084}
16085
16086ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16087 BinaryOperatorKind Opc, Expr *LHSExpr,
16088 Expr *RHSExpr, bool ForFoldExpression) {
16089 if (!LHSExpr || !RHSExpr)
16090 return ExprError();
16091
16092 // We want to end up calling one of SemaPseudoObject::checkAssignment
16093 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16094 // both expressions are overloadable or either is type-dependent),
16095 // or CreateBuiltinBinOp (in any other case). We also want to get
16096 // any placeholder types out of the way.
16097
16098 // Handle pseudo-objects in the LHS.
16099 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16100 // Assignments with a pseudo-object l-value need special analysis.
16101 if (pty->getKind() == BuiltinType::PseudoObject &&
16102 BinaryOperator::isAssignmentOp(Opc))
16103 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16104
16105 // Don't resolve overloads if the other type is overloadable.
16106 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16107 // We can't actually test that if we still have a placeholder,
16108 // though. Fortunately, none of the exceptions we see in that
16109 // code below are valid when the LHS is an overload set. Note
16110 // that an overload set can be dependently-typed, but it never
16111 // instantiates to having an overloadable type.
16112 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16113 if (resolvedRHS.isInvalid()) return ExprError();
16114 RHSExpr = resolvedRHS.get();
16115
16116 if (RHSExpr->isTypeDependent() ||
16117 RHSExpr->getType()->isOverloadableType())
16118 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16119 }
16120
16121 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16122 // template, diagnose the missing 'template' keyword instead of diagnosing
16123 // an invalid use of a bound member function.
16124 //
16125 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16126 // to C++1z [over.over]/1.4, but we already checked for that case above.
16127 if (Opc == BO_LT && inTemplateInstantiation() &&
16128 (pty->getKind() == BuiltinType::BoundMember ||
16129 pty->getKind() == BuiltinType::Overload)) {
16130 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16131 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16132 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16133 return isa<FunctionTemplateDecl>(Val: ND);
16134 })) {
16135 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16136 : OE->getNameLoc(),
16137 DiagID: diag::err_template_kw_missing)
16138 << OE->getName().getAsIdentifierInfo();
16139 return ExprError();
16140 }
16141 }
16142
16143 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16144 if (LHS.isInvalid()) return ExprError();
16145 LHSExpr = LHS.get();
16146 }
16147
16148 // Handle pseudo-objects in the RHS.
16149 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16150 // An overload in the RHS can potentially be resolved by the type
16151 // being assigned to.
16152 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16153 if (getLangOpts().CPlusPlus &&
16154 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16155 LHSExpr->getType()->isOverloadableType()))
16156 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16157
16158 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16159 ForFoldExpression);
16160 }
16161
16162 // Don't resolve overloads if the other type is overloadable.
16163 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16164 LHSExpr->getType()->isOverloadableType())
16165 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16166
16167 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16168 if (!resolvedRHS.isUsable()) return ExprError();
16169 RHSExpr = resolvedRHS.get();
16170 }
16171
16172 if (getLangOpts().HLSL) {
16173 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16174 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16175 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16176 return ExprError();
16177 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16178 std::optional<ExprResult> ConvRHS =
16179 HLSL().tryPerformConstantBufferConversion(BaseExpr: RHSExpr);
16180 if (ConvRHS && Context.hasSameUnqualifiedType(
16181 T1: LHSExpr->getType(), T2: ConvRHS->get()->getType())) {
16182 assert(!ConvRHS->isInvalid());
16183 RHSExpr = ConvRHS->get();
16184 }
16185 }
16186 }
16187
16188 if (getLangOpts().CPlusPlus) {
16189 bool CanOverloadBinOp =
16190 !getLangOpts().HLSL ||
16191 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16192 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16193 bool TypeDependent =
16194 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16195 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16196 RHSExpr->getType()->isOverloadableType();
16197 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16198 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16199 }
16200
16201 if (getLangOpts().RecoveryAST &&
16202 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16203 assert(!getLangOpts().CPlusPlus);
16204 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16205 "Should only occur in error-recovery path.");
16206 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16207 // C [6.15.16] p3:
16208 // An assignment expression has the value of the left operand after the
16209 // assignment, but is not an lvalue.
16210 return CompoundAssignOperator::Create(
16211 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16212 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16213 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16214 QualType ResultType;
16215 switch (Opc) {
16216 case BO_Assign:
16217 ResultType = LHSExpr->getType().getUnqualifiedType();
16218 break;
16219 case BO_LT:
16220 case BO_GT:
16221 case BO_LE:
16222 case BO_GE:
16223 case BO_EQ:
16224 case BO_NE:
16225 case BO_LAnd:
16226 case BO_LOr:
16227 // These operators have a fixed result type regardless of operands.
16228 ResultType = Context.IntTy;
16229 break;
16230 case BO_Comma:
16231 ResultType = RHSExpr->getType();
16232 break;
16233 default:
16234 ResultType = Context.DependentTy;
16235 break;
16236 }
16237 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16238 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16239 FPFeatures: CurFPFeatureOverrides());
16240 }
16241
16242 // Build a built-in binary operation.
16243 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16244}
16245
16246static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16247 if (T.isNull() || T->isDependentType())
16248 return false;
16249
16250 if (!Ctx.isPromotableIntegerType(T))
16251 return true;
16252
16253 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16254}
16255
16256ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16257 UnaryOperatorKind Opc, Expr *InputExpr,
16258 bool IsAfterAmp) {
16259 ExprResult Input = InputExpr;
16260 ExprValueKind VK = VK_PRValue;
16261 ExprObjectKind OK = OK_Ordinary;
16262 QualType resultType;
16263 bool CanOverflow = false;
16264
16265 bool ConvertHalfVec = false;
16266 if (getLangOpts().OpenCL) {
16267 QualType Ty = InputExpr->getType();
16268 // The only legal unary operation for atomics is '&'.
16269 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16270 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16271 // only with a builtin functions and therefore should be disallowed here.
16272 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16273 || Ty->isBlockPointerType())) {
16274 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16275 << InputExpr->getType()
16276 << Input.get()->getSourceRange());
16277 }
16278 }
16279
16280 if (getLangOpts().HLSL && OpLoc.isValid()) {
16281 if (Opc == UO_AddrOf)
16282 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16283 if (Opc == UO_Deref)
16284 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16285 }
16286
16287 if (InputExpr->isTypeDependent() &&
16288 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16289 resultType = Context.DependentTy;
16290 } else {
16291 switch (Opc) {
16292 case UO_PreInc:
16293 case UO_PreDec:
16294 case UO_PostInc:
16295 case UO_PostDec:
16296 resultType =
16297 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16298 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16299 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16300 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16301 break;
16302 case UO_AddrOf:
16303 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16304 CheckAddressOfNoDeref(E: InputExpr);
16305 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16306 break;
16307 case UO_Deref: {
16308 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16309 if (Input.isInvalid())
16310 return ExprError();
16311 resultType =
16312 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16313 break;
16314 }
16315 case UO_Plus:
16316 case UO_Minus:
16317 CanOverflow = Opc == UO_Minus &&
16318 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16319 Input = UsualUnaryConversions(E: Input.get());
16320 if (Input.isInvalid())
16321 return ExprError();
16322 // Unary plus and minus require promoting an operand of half vector to a
16323 // float vector and truncating the result back to a half vector. For now,
16324 // we do this only when HalfArgsAndReturns is set (that is, when the
16325 // target is arm or arm64).
16326 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16327
16328 // If the operand is a half vector, promote it to a float vector.
16329 if (ConvertHalfVec)
16330 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16331 resultType = Input.get()->getType();
16332 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16333 break;
16334 else if (resultType->isVectorType() &&
16335 // The z vector extensions don't allow + or - with bool vectors.
16336 (!Context.getLangOpts().ZVector ||
16337 resultType->castAs<VectorType>()->getVectorKind() !=
16338 VectorKind::AltiVecBool))
16339 break;
16340 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16341 break;
16342 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16343 Opc == UO_Plus && resultType->isPointerType())
16344 break;
16345
16346 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16347 << resultType << Input.get()->getSourceRange());
16348
16349 case UO_Not: // bitwise complement
16350 Input = UsualUnaryConversions(E: Input.get());
16351 if (Input.isInvalid())
16352 return ExprError();
16353 resultType = Input.get()->getType();
16354 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16355 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16356 // C99 does not support '~' for complex conjugation.
16357 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16358 << resultType << Input.get()->getSourceRange();
16359 else if (resultType->hasIntegerRepresentation())
16360 break;
16361 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16362 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16363 // on vector float types.
16364 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16365 if (!T->isIntegerType())
16366 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16367 << resultType << Input.get()->getSourceRange());
16368 } else {
16369 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16370 << resultType << Input.get()->getSourceRange());
16371 }
16372 break;
16373
16374 case UO_LNot: // logical negation
16375 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16376 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16377 if (Input.isInvalid())
16378 return ExprError();
16379 resultType = Input.get()->getType();
16380
16381 // Though we still have to promote half FP to float...
16382 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16383 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16384 .get();
16385 resultType = Context.FloatTy;
16386 }
16387
16388 // WebAsembly tables can't be used in unary expressions.
16389 if (resultType->isPointerType() &&
16390 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16391 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16392 << resultType << Input.get()->getSourceRange());
16393 }
16394
16395 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16396 // C99 6.5.3.3p1: ok, fallthrough;
16397 if (Context.getLangOpts().CPlusPlus) {
16398 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16399 // operand contextually converted to bool.
16400 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16401 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16402 } else if (Context.getLangOpts().OpenCL &&
16403 Context.getLangOpts().OpenCLVersion < 120) {
16404 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16405 // operate on scalar float types.
16406 if (!resultType->isIntegerType() && !resultType->isPointerType())
16407 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16408 << resultType << Input.get()->getSourceRange());
16409 }
16410 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16411 !resultType->hasBooleanRepresentation()) {
16412 // HLSL unary logical 'not' behaves like C++, which states that the
16413 // operand is converted to bool and the result is bool, however HLSL
16414 // extends this property to vectors.
16415 const VectorType *VTy = resultType->castAs<VectorType>();
16416 resultType =
16417 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16418
16419 Input = ImpCastExprToType(
16420 E: Input.get(), Type: resultType,
16421 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16422 .get();
16423 break;
16424 } else if (resultType->isExtVectorType()) {
16425 if (Context.getLangOpts().OpenCL &&
16426 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16427 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16428 // operate on vector float types.
16429 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16430 if (!T->isIntegerType())
16431 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16432 << resultType << Input.get()->getSourceRange());
16433 }
16434 // Vector logical not returns the signed variant of the operand type.
16435 resultType = GetSignedVectorType(V: resultType);
16436 break;
16437 } else if (Context.getLangOpts().CPlusPlus &&
16438 resultType->isVectorType()) {
16439 const VectorType *VTy = resultType->castAs<VectorType>();
16440 if (VTy->getVectorKind() != VectorKind::Generic)
16441 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16442 << resultType << Input.get()->getSourceRange());
16443
16444 // Vector logical not returns the signed variant of the operand type.
16445 resultType = GetSignedVectorType(V: resultType);
16446 break;
16447 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16448 resultType = Context.getLogicalOperationType();
16449 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16450 break;
16451 } else {
16452 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16453 << resultType << Input.get()->getSourceRange());
16454 }
16455
16456 // LNot always has type int. C99 6.5.3.3p5.
16457 // In C++, it's bool. C++ 5.3.1p8
16458 resultType = Context.getLogicalOperationType();
16459 break;
16460 case UO_Real:
16461 case UO_Imag:
16462 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16463 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16464 // ordinary complex l-values to ordinary l-values and all other values to
16465 // r-values.
16466 if (Input.isInvalid())
16467 return ExprError();
16468 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16469 if (Input.get()->isGLValue() &&
16470 Input.get()->getObjectKind() == OK_Ordinary)
16471 VK = Input.get()->getValueKind();
16472 } else if (!getLangOpts().CPlusPlus) {
16473 // In C, a volatile scalar is read by __imag. In C++, it is not.
16474 Input = DefaultLvalueConversion(E: Input.get());
16475 }
16476 break;
16477 case UO_Extension:
16478 resultType = Input.get()->getType();
16479 VK = Input.get()->getValueKind();
16480 OK = Input.get()->getObjectKind();
16481 break;
16482 case UO_Coawait:
16483 // It's unnecessary to represent the pass-through operator co_await in the
16484 // AST; just return the input expression instead.
16485 assert(!Input.get()->getType()->isDependentType() &&
16486 "the co_await expression must be non-dependant before "
16487 "building operator co_await");
16488 return Input;
16489 }
16490 }
16491 if (resultType.isNull() || Input.isInvalid())
16492 return ExprError();
16493
16494 // Check for array bounds violations in the operand of the UnaryOperator,
16495 // except for the '*' and '&' operators that have to be handled specially
16496 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16497 // that are explicitly defined as valid by the standard).
16498 if (Opc != UO_AddrOf && Opc != UO_Deref)
16499 CheckArrayAccess(E: Input.get());
16500
16501 auto *UO =
16502 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16503 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16504
16505 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16506 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16507 !isUnevaluatedContext())
16508 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16509
16510 // Convert the result back to a half vector.
16511 if (ConvertHalfVec)
16512 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16513 return UO;
16514}
16515
16516bool Sema::isQualifiedMemberAccess(Expr *E) {
16517 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16518 if (!DRE->getQualifier())
16519 return false;
16520
16521 ValueDecl *VD = DRE->getDecl();
16522 if (!VD->isCXXClassMember())
16523 return false;
16524
16525 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16526 return true;
16527 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16528 return Method->isImplicitObjectMemberFunction();
16529
16530 return false;
16531 }
16532
16533 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16534 if (!ULE->getQualifier())
16535 return false;
16536
16537 for (NamedDecl *D : ULE->decls()) {
16538 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16539 if (Method->isImplicitObjectMemberFunction())
16540 return true;
16541 } else {
16542 // Overload set does not contain methods.
16543 break;
16544 }
16545 }
16546
16547 return false;
16548 }
16549
16550 return false;
16551}
16552
16553ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16554 UnaryOperatorKind Opc, Expr *Input,
16555 bool IsAfterAmp) {
16556 // First things first: handle placeholders so that the
16557 // overloaded-operator check considers the right type.
16558 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16559 // Increment and decrement of pseudo-object references.
16560 if (pty->getKind() == BuiltinType::PseudoObject &&
16561 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16562 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16563
16564 // extension is always a builtin operator.
16565 if (Opc == UO_Extension)
16566 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16567
16568 // & gets special logic for several kinds of placeholder.
16569 // The builtin code knows what to do.
16570 if (Opc == UO_AddrOf &&
16571 (pty->getKind() == BuiltinType::Overload ||
16572 pty->getKind() == BuiltinType::UnknownAny ||
16573 pty->getKind() == BuiltinType::BoundMember))
16574 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16575
16576 // Anything else needs to be handled now.
16577 ExprResult Result = CheckPlaceholderExpr(E: Input);
16578 if (Result.isInvalid()) return ExprError();
16579 Input = Result.get();
16580 }
16581
16582 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16583 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16584 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16585 // Find all of the overloaded operators visible from this point.
16586 UnresolvedSet<16> Functions;
16587 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16588 if (S && OverOp != OO_None)
16589 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16590
16591 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16592 }
16593
16594 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16595}
16596
16597ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16598 Expr *Input, bool IsAfterAmp) {
16599 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16600 IsAfterAmp);
16601}
16602
16603ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16604 LabelDecl *TheDecl) {
16605 TheDecl->markUsed(C&: Context);
16606 // Create the AST node. The address of a label always has type 'void*'.
16607 auto *Res = new (Context) AddrLabelExpr(
16608 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16609
16610 if (getCurFunction())
16611 getCurFunction()->AddrLabels.push_back(Elt: Res);
16612
16613 return Res;
16614}
16615
16616void Sema::ActOnStartStmtExpr() {
16617 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16618 // Make sure we diagnose jumping into a statement expression.
16619 setFunctionHasBranchProtectedScope();
16620}
16621
16622void Sema::ActOnStmtExprError() {
16623 // Note that function is also called by TreeTransform when leaving a
16624 // StmtExpr scope without rebuilding anything.
16625
16626 DiscardCleanupsInEvaluationContext();
16627 PopExpressionEvaluationContext();
16628}
16629
16630ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16631 SourceLocation RPLoc) {
16632 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16633}
16634
16635ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16636 SourceLocation RPLoc, unsigned TemplateDepth) {
16637 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16638 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16639
16640 if (hasAnyUnrecoverableErrorsInThisFunction())
16641 DiscardCleanupsInEvaluationContext();
16642 assert(!Cleanup.exprNeedsCleanups() &&
16643 "cleanups within StmtExpr not correctly bound!");
16644 PopExpressionEvaluationContext();
16645
16646 // FIXME: there are a variety of strange constraints to enforce here, for
16647 // example, it is not possible to goto into a stmt expression apparently.
16648 // More semantic analysis is needed.
16649
16650 // If there are sub-stmts in the compound stmt, take the type of the last one
16651 // as the type of the stmtexpr.
16652 QualType Ty = Context.VoidTy;
16653 bool StmtExprMayBindToTemp = false;
16654 if (!Compound->body_empty()) {
16655 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16656 if (const Expr *Value = LastStmt->getExprStmt()) {
16657 StmtExprMayBindToTemp = true;
16658 Ty = Value->getType();
16659 }
16660 }
16661 }
16662
16663 // FIXME: Check that expression type is complete/non-abstract; statement
16664 // expressions are not lvalues.
16665 Expr *ResStmtExpr =
16666 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16667 if (StmtExprMayBindToTemp)
16668 return MaybeBindToTemporary(E: ResStmtExpr);
16669 return ResStmtExpr;
16670}
16671
16672ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16673 if (ER.isInvalid())
16674 return ExprError();
16675
16676 // Do function/array conversion on the last expression, but not
16677 // lvalue-to-rvalue. However, initialize an unqualified type.
16678 ER = DefaultFunctionArrayConversion(E: ER.get());
16679 if (ER.isInvalid())
16680 return ExprError();
16681 Expr *E = ER.get();
16682
16683 if (E->isTypeDependent())
16684 return E;
16685
16686 // In ARC, if the final expression ends in a consume, splice
16687 // the consume out and bind it later. In the alternate case
16688 // (when dealing with a retainable type), the result
16689 // initialization will create a produce. In both cases the
16690 // result will be +1, and we'll need to balance that out with
16691 // a bind.
16692 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16693 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16694 return Cast->getSubExpr();
16695
16696 // FIXME: Provide a better location for the initialization.
16697 return PerformCopyInitialization(
16698 Entity: InitializedEntity::InitializeStmtExprResult(
16699 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16700 EqualLoc: SourceLocation(), Init: E);
16701}
16702
16703ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16704 TypeSourceInfo *TInfo,
16705 const Designation &Desig,
16706 SourceLocation RParenLoc) {
16707 QualType ArgTy = TInfo->getType();
16708 bool Dependent = ArgTy->isDependentType();
16709 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16710
16711 // We must have at least one component that refers to the type, and the first
16712 // one is known to be a field designator. Verify that the ArgTy represents
16713 // a struct/union/class.
16714 if (!Dependent && !ArgTy->isRecordType())
16715 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16716 << ArgTy << TypeRange);
16717
16718 // Type must be complete per C99 7.17p3 because a declaring a variable
16719 // with an incomplete type would be ill-formed.
16720 if (!Dependent
16721 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16722 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16723 return ExprError();
16724
16725 bool DidWarnAboutNonPOD = false;
16726 QualType CurrentType = ArgTy;
16727 SmallVector<OffsetOfNode, 4> Comps;
16728 SmallVector<Expr *, 4> Exprs;
16729 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16730 const Designator &D = Desig.getDesignator(Idx: I);
16731 assert(!D.isArrayRangeDesignator());
16732 if (D.isArrayDesignator()) {
16733 // Offset of an array sub-field. TODO: Should we allow vector elements?
16734 if (!CurrentType->isDependentType()) {
16735 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16736 if(!AT)
16737 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
16738 << CurrentType);
16739 CurrentType = AT->getElementType();
16740 } else
16741 CurrentType = Context.DependentTy;
16742
16743 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
16744 if (IdxRval.isInvalid())
16745 return ExprError();
16746 Expr *Idx = IdxRval.get();
16747
16748 // The expression must be an integral expression.
16749 // FIXME: An integral constant expression?
16750 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16751 !Idx->getType()->isIntegerType())
16752 return ExprError(
16753 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16754 << Idx->getSourceRange());
16755
16756 // Record this array index.
16757 Comps.push_back(
16758 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16759 Exprs.push_back(Elt: Idx);
16760 continue;
16761 }
16762
16763 assert(D.isFieldDesignator());
16764 const IdentifierInfo *Name = D.getFieldDecl();
16765
16766 // Offset of a field.
16767 if (CurrentType->isDependentType()) {
16768 // We have the offset of a field, but we can't look into the dependent
16769 // type. Just record the identifier of the field.
16770 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16771 CurrentType = Context.DependentTy;
16772 continue;
16773 }
16774
16775 // We need to have a complete type to look into.
16776 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
16777 DiagID: diag::err_offsetof_incomplete_type))
16778 return ExprError();
16779
16780 // Look for the designated field.
16781 auto *RD = CurrentType->getAsRecordDecl();
16782 if (!RD)
16783 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
16784 << CurrentType);
16785
16786 // C++ [lib.support.types]p5:
16787 // The macro offsetof accepts a restricted set of type arguments in this
16788 // International Standard. type shall be a POD structure or a POD union
16789 // (clause 9).
16790 // C++11 [support.types]p4:
16791 // If type is not a standard-layout class (Clause 9), the results are
16792 // undefined.
16793 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16794 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16795 unsigned DiagID =
16796 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16797 : diag::ext_offsetof_non_pod_type;
16798
16799 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16800 Diag(Loc: BuiltinLoc, DiagID)
16801 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
16802 << CurrentType;
16803 DidWarnAboutNonPOD = true;
16804 }
16805 }
16806
16807 // Look for the field.
16808 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
16809 LookupQualifiedName(R, LookupCtx: RD);
16810 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16811 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16812 if (!MemberDecl) {
16813 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16814 MemberDecl = IndirectMemberDecl->getAnonField();
16815 }
16816
16817 if (!MemberDecl) {
16818 // Lookup could be ambiguous when looking up a placeholder variable
16819 // __builtin_offsetof(S, _).
16820 // In that case we would already have emitted a diagnostic
16821 if (!R.isAmbiguous())
16822 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16823 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
16824 return ExprError();
16825 }
16826
16827 // C99 7.17p3:
16828 // (If the specified member is a bit-field, the behavior is undefined.)
16829 //
16830 // We diagnose this as an error.
16831 if (MemberDecl->isBitField()) {
16832 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
16833 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16834 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16835 return ExprError();
16836 }
16837
16838 RecordDecl *Parent = MemberDecl->getParent();
16839 if (IndirectMemberDecl)
16840 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16841
16842 // If the member was found in a base class, introduce OffsetOfNodes for
16843 // the base class indirections.
16844 CXXBasePaths Paths;
16845 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
16846 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16847 if (Paths.getDetectedVirtual()) {
16848 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
16849 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16850 return ExprError();
16851 }
16852
16853 CXXBasePath &Path = Paths.front();
16854 for (const CXXBasePathElement &B : Path)
16855 Comps.push_back(Elt: OffsetOfNode(B.Base));
16856 }
16857
16858 if (IndirectMemberDecl) {
16859 for (auto *FI : IndirectMemberDecl->chain()) {
16860 assert(isa<FieldDecl>(FI));
16861 Comps.push_back(
16862 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
16863 }
16864 } else
16865 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
16866
16867 CurrentType = MemberDecl->getType().getNonReferenceType();
16868 }
16869
16870 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16871 comps: Comps, exprs: Exprs, RParenLoc);
16872}
16873
16874ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
16875 SourceLocation TypeLoc,
16876 ParsedType ParsedArgTy,
16877 const Designation &Desig,
16878 SourceLocation RParenLoc) {
16879
16880 TypeSourceInfo *ArgTInfo;
16881 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16882 if (ArgTy.isNull())
16883 return ExprError();
16884
16885 if (!ArgTInfo)
16886 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16887
16888 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
16889}
16890
16891ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16892 Expr *CondExpr,
16893 Expr *LHSExpr, Expr *RHSExpr,
16894 SourceLocation RPLoc) {
16895 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16896
16897 ExprValueKind VK = VK_PRValue;
16898 ExprObjectKind OK = OK_Ordinary;
16899 QualType resType;
16900 bool CondIsTrue = false;
16901 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16902 resType = Context.DependentTy;
16903 } else {
16904 // The conditional expression is required to be a constant expression.
16905 llvm::APSInt condEval(32);
16906 ExprResult CondICE = VerifyIntegerConstantExpression(
16907 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16908 if (CondICE.isInvalid())
16909 return ExprError();
16910 CondExpr = CondICE.get();
16911 CondIsTrue = condEval.getZExtValue();
16912
16913 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16914 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16915
16916 resType = ActiveExpr->getType();
16917 VK = ActiveExpr->getValueKind();
16918 OK = ActiveExpr->getObjectKind();
16919 }
16920
16921 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16922 resType, VK, OK, RPLoc, CondIsTrue);
16923}
16924
16925//===----------------------------------------------------------------------===//
16926// Clang Extensions.
16927//===----------------------------------------------------------------------===//
16928
16929void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16930 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16931
16932 if (LangOpts.CPlusPlus) {
16933 MangleNumberingContext *MCtx;
16934 Decl *ManglingContextDecl;
16935 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16936 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16937 if (MCtx) {
16938 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16939 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16940 }
16941 }
16942
16943 PushBlockScope(BlockScope: CurScope, Block);
16944 CurContext->addDecl(D: Block);
16945 if (CurScope)
16946 PushDeclContext(S: CurScope, DC: Block);
16947 else
16948 CurContext = Block;
16949
16950 getCurBlock()->HasImplicitReturnType = true;
16951
16952 // Enter a new evaluation context to insulate the block from any
16953 // cleanups from the enclosing full-expression.
16954 PushExpressionEvaluationContext(
16955 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16956}
16957
16958void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16959 Scope *CurScope) {
16960 assert(ParamInfo.getIdentifier() == nullptr &&
16961 "block-id should have no identifier!");
16962 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16963 BlockScopeInfo *CurBlock = getCurBlock();
16964
16965 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16966 QualType T = Sig->getType();
16967 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
16968
16969 // GetTypeForDeclarator always produces a function type for a block
16970 // literal signature. Furthermore, it is always a FunctionProtoType
16971 // unless the function was written with a typedef.
16972 assert(T->isFunctionType() &&
16973 "GetTypeForDeclarator made a non-function block signature");
16974
16975 // Look for an explicit signature in that function type.
16976 FunctionProtoTypeLoc ExplicitSignature;
16977
16978 if ((ExplicitSignature = Sig->getTypeLoc()
16979 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16980
16981 // Check whether that explicit signature was synthesized by
16982 // GetTypeForDeclarator. If so, don't save that as part of the
16983 // written signature.
16984 if (ExplicitSignature.getLocalRangeBegin() ==
16985 ExplicitSignature.getLocalRangeEnd()) {
16986 // This would be much cheaper if we stored TypeLocs instead of
16987 // TypeSourceInfos.
16988 TypeLoc Result = ExplicitSignature.getReturnLoc();
16989 unsigned Size = Result.getFullDataSize();
16990 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
16991 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
16992
16993 ExplicitSignature = FunctionProtoTypeLoc();
16994 }
16995 }
16996
16997 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16998 CurBlock->FunctionType = T;
16999
17000 const auto *Fn = T->castAs<FunctionType>();
17001 QualType RetTy = Fn->getReturnType();
17002 bool isVariadic =
17003 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17004
17005 CurBlock->TheDecl->setIsVariadic(isVariadic);
17006
17007 // Context.DependentTy is used as a placeholder for a missing block
17008 // return type. TODO: what should we do with declarators like:
17009 // ^ * { ... }
17010 // If the answer is "apply template argument deduction"....
17011 if (RetTy != Context.DependentTy) {
17012 CurBlock->ReturnType = RetTy;
17013 CurBlock->TheDecl->setBlockMissingReturnType(false);
17014 CurBlock->HasImplicitReturnType = false;
17015 }
17016
17017 // Push block parameters from the declarator if we had them.
17018 SmallVector<ParmVarDecl*, 8> Params;
17019 if (ExplicitSignature) {
17020 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17021 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
17022 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17023 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17024 // Diagnose this as an extension in C17 and earlier.
17025 if (!getLangOpts().C23)
17026 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
17027 }
17028 Params.push_back(Elt: Param);
17029 }
17030
17031 // Fake up parameter variables if we have a typedef, like
17032 // ^ fntype { ... }
17033 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17034 for (const auto &I : Fn->param_types()) {
17035 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17036 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
17037 Params.push_back(Elt: Param);
17038 }
17039 }
17040
17041 // Set the parameters on the block decl.
17042 if (!Params.empty()) {
17043 CurBlock->TheDecl->setParams(Params);
17044 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17045 /*CheckParameterNames=*/false);
17046 }
17047
17048 // Finally we can process decl attributes.
17049 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17050
17051 // Put the parameter variables in scope.
17052 for (auto *AI : CurBlock->TheDecl->parameters()) {
17053 AI->setOwningFunction(CurBlock->TheDecl);
17054
17055 // If this has an identifier, add it to the scope stack.
17056 if (AI->getIdentifier()) {
17057 CheckShadow(S: CurBlock->TheScope, D: AI);
17058
17059 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17060 }
17061
17062 if (AI->isInvalidDecl())
17063 CurBlock->TheDecl->setInvalidDecl();
17064 }
17065}
17066
17067void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17068 // Leave the expression-evaluation context.
17069 DiscardCleanupsInEvaluationContext();
17070 PopExpressionEvaluationContext();
17071
17072 // Pop off CurBlock, handle nested blocks.
17073 PopDeclContext();
17074 PopFunctionScopeInfo();
17075}
17076
17077ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17078 Stmt *Body, Scope *CurScope) {
17079 // If blocks are disabled, emit an error.
17080 if (!LangOpts.Blocks)
17081 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17082
17083 // Leave the expression-evaluation context.
17084 if (hasAnyUnrecoverableErrorsInThisFunction())
17085 DiscardCleanupsInEvaluationContext();
17086 assert(!Cleanup.exprNeedsCleanups() &&
17087 "cleanups within block not correctly bound!");
17088 PopExpressionEvaluationContext();
17089
17090 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17091 BlockDecl *BD = BSI->TheDecl;
17092
17093 maybeAddDeclWithEffects(D: BD);
17094
17095 if (BSI->HasImplicitReturnType)
17096 deduceClosureReturnType(CSI&: *BSI);
17097
17098 QualType RetTy = Context.VoidTy;
17099 if (!BSI->ReturnType.isNull())
17100 RetTy = BSI->ReturnType;
17101
17102 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17103 QualType BlockTy;
17104
17105 // If the user wrote a function type in some form, try to use that.
17106 if (!BSI->FunctionType.isNull()) {
17107 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17108
17109 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17110 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17111
17112 // Turn protoless block types into nullary block types.
17113 if (isa<FunctionNoProtoType>(Val: FTy)) {
17114 FunctionProtoType::ExtProtoInfo EPI;
17115 EPI.ExtInfo = Ext;
17116 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17117
17118 // Otherwise, if we don't need to change anything about the function type,
17119 // preserve its sugar structure.
17120 } else if (FTy->getReturnType() == RetTy &&
17121 (!NoReturn || FTy->getNoReturnAttr())) {
17122 BlockTy = BSI->FunctionType;
17123
17124 // Otherwise, make the minimal modifications to the function type.
17125 } else {
17126 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17127 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17128 EPI.TypeQuals = Qualifiers();
17129 EPI.ExtInfo = Ext;
17130 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17131 }
17132
17133 // If we don't have a function type, just build one from nothing.
17134 } else {
17135 FunctionProtoType::ExtProtoInfo EPI;
17136 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17137 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17138 }
17139
17140 DiagnoseUnusedParameters(Parameters: BD->parameters());
17141 BlockTy = Context.getBlockPointerType(T: BlockTy);
17142
17143 // If needed, diagnose invalid gotos and switches in the block.
17144 if (getCurFunction()->NeedsScopeChecking() &&
17145 !PP.isCodeCompletionEnabled())
17146 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17147
17148 BD->setBody(cast<CompoundStmt>(Val: Body));
17149
17150 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17151 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17152
17153 // Try to apply the named return value optimization. We have to check again
17154 // if we can do this, though, because blocks keep return statements around
17155 // to deduce an implicit return type.
17156 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17157 !BD->isDependentContext())
17158 computeNRVO(Body, Scope: BSI);
17159
17160 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17161 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17162 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17163 UseContext: NonTrivialCUnionContext::FunctionReturn,
17164 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17165
17166 PopDeclContext();
17167
17168 // Set the captured variables on the block.
17169 SmallVector<BlockDecl::Capture, 4> Captures;
17170 for (Capture &Cap : BSI->Captures) {
17171 if (Cap.isInvalid() || Cap.isThisCapture())
17172 continue;
17173 // Cap.getVariable() is always a VarDecl because
17174 // blocks cannot capture structured bindings or other ValueDecl kinds.
17175 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17176 Expr *CopyExpr = nullptr;
17177 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17178 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17179 // The capture logic needs the destructor, so make sure we mark it.
17180 // Usually this is unnecessary because most local variables have
17181 // their destructors marked at declaration time, but parameters are
17182 // an exception because it's technically only the call site that
17183 // actually requires the destructor.
17184 if (isa<ParmVarDecl>(Val: Var))
17185 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17186
17187 // Enter a separate potentially-evaluated context while building block
17188 // initializers to isolate their cleanups from those of the block
17189 // itself.
17190 // FIXME: Is this appropriate even when the block itself occurs in an
17191 // unevaluated operand?
17192 EnterExpressionEvaluationContext EvalContext(
17193 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17194
17195 SourceLocation Loc = Cap.getLocation();
17196
17197 ExprResult Result = BuildDeclarationNameExpr(
17198 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17199
17200 // According to the blocks spec, the capture of a variable from
17201 // the stack requires a const copy constructor. This is not true
17202 // of the copy/move done to move a __block variable to the heap.
17203 if (!Result.isInvalid() &&
17204 !Result.get()->getType().isConstQualified()) {
17205 Result = ImpCastExprToType(E: Result.get(),
17206 Type: Result.get()->getType().withConst(),
17207 CK: CK_NoOp, VK: VK_LValue);
17208 }
17209
17210 if (!Result.isInvalid()) {
17211 Result = PerformCopyInitialization(
17212 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17213 Type: Cap.getCaptureType()),
17214 EqualLoc: Loc, Init: Result.get());
17215 }
17216
17217 // Build a full-expression copy expression if initialization
17218 // succeeded and used a non-trivial constructor. Recover from
17219 // errors by pretending that the copy isn't necessary.
17220 if (!Result.isInvalid() &&
17221 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17222 ->isTrivial()) {
17223 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17224 CopyExpr = Result.get();
17225 }
17226 }
17227 }
17228
17229 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17230 CopyExpr);
17231 Captures.push_back(Elt: NewCap);
17232 }
17233 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17234
17235 // Pop the block scope now but keep it alive to the end of this function.
17236 AnalysisBasedWarnings::Policy WP =
17237 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17238 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17239
17240 BlockExpr *Result = new (Context)
17241 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17242
17243 // If the block isn't obviously global, i.e. it captures anything at
17244 // all, then we need to do a few things in the surrounding context:
17245 if (Result->getBlockDecl()->hasCaptures()) {
17246 // First, this expression has a new cleanup object.
17247 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17248 Cleanup.setExprNeedsCleanups(true);
17249
17250 // It also gets a branch-protected scope if any of the captured
17251 // variables needs destruction.
17252 for (const auto &CI : Result->getBlockDecl()->captures()) {
17253 const VarDecl *var = CI.getVariable();
17254 if (var->getType().isDestructedType() != QualType::DK_none) {
17255 setFunctionHasBranchProtectedScope();
17256 break;
17257 }
17258 }
17259 }
17260
17261 if (getCurFunction())
17262 getCurFunction()->addBlock(BD);
17263
17264 // This can happen if the block's return type is deduced, but
17265 // the return expression is invalid.
17266 if (BD->isInvalidDecl())
17267 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17268 SubExprs: {Result}, T: Result->getType());
17269 return Result;
17270}
17271
17272ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17273 SourceLocation RPLoc) {
17274 TypeSourceInfo *TInfo;
17275 GetTypeFromParser(Ty, TInfo: &TInfo);
17276 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17277}
17278
17279ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17280 Expr *E, TypeSourceInfo *TInfo,
17281 SourceLocation RPLoc) {
17282 Expr *OrigExpr = E;
17283 VAArgExpr::VarArgKind VAKind = VAArgExpr::VA_Std;
17284
17285 // CUDA device global function does not support varargs.
17286 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17287 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17288 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17289 if (T == CUDAFunctionTarget::Global)
17290 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17291 }
17292 }
17293
17294 // NVPTX does not support va_arg expression.
17295 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17296 Context.getTargetInfo().getTriple().isNVPTX())
17297 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17298
17299 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17300 // as Microsoft ABI on an actual Microsoft platform, where
17301 // __builtin_ms_va_list and __builtin_va_list are the same.)
17302 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17303 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17304 QualType MSVaListType = Context.getBuiltinMSVaListType();
17305 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17306 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17307 return ExprError();
17308 VAKind = VAArgExpr::VA_MS;
17309 }
17310 }
17311
17312 // Get the va_list type
17313 QualType VaListType = Context.getBuiltinVaListType();
17314
17315 // It might be a __builtin_zos_va_list!
17316 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17317 // E->getType() can be:
17318 // - va_list: equal to array (char*)[2] (inside function)
17319 // - char **: decayed array (va_list passed as parameter)
17320 // We need to check for both cases.
17321 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17322 assert(ZOSVaListType->isArrayType() &&
17323 "__builtin_zos_va_list must be an array type");
17324 QualType DecayedType = Context.getArrayDecayedType(T: ZOSVaListType);
17325 if (Context.hasSameType(T1: ZOSVaListType, T2: E->getType()) ||
17326 Context.hasSameType(T1: DecayedType, T2: E->getType())) {
17327 VAKind = VAArgExpr::VA_ZOS;
17328 VaListType = ZOSVaListType;
17329 }
17330 }
17331
17332 if (VAKind != VAArgExpr::VA_MS) {
17333 if (VaListType->isArrayType()) {
17334 // Deal with implicit array decay; for example, on x86-64,
17335 // va_list is an array, but it's supposed to decay to
17336 // a pointer for va_arg.
17337 VaListType = Context.getArrayDecayedType(T: VaListType);
17338 // Make sure the input expression also decays appropriately.
17339 ExprResult Result = UsualUnaryConversions(E);
17340 if (Result.isInvalid())
17341 return ExprError();
17342 E = Result.get();
17343 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17344 // If va_list is a record type and we are compiling in C++ mode,
17345 // check the argument using reference binding.
17346 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17347 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17348 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17349 if (Init.isInvalid())
17350 return ExprError();
17351 E = Init.getAs<Expr>();
17352 } else {
17353 // Otherwise, the va_list argument must be an l-value because
17354 // it is modified by va_arg.
17355 if (!E->isTypeDependent() &&
17356 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17357 return ExprError();
17358 }
17359 }
17360
17361 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17362 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17363 return ExprError(
17364 Diag(Loc: E->getBeginLoc(),
17365 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17366 << OrigExpr->getType() << E->getSourceRange());
17367
17368 if (!TInfo->getType()->isDependentType()) {
17369 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17370 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17371 Args: TInfo->getTypeLoc()))
17372 return ExprError();
17373
17374 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17375 T: TInfo->getType(),
17376 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17377 Args: TInfo->getTypeLoc()))
17378 return ExprError();
17379
17380 if (!TInfo->getType().isPODType(Context)) {
17381 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17382 DiagID: TInfo->getType()->isObjCLifetimeType()
17383 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17384 : diag::warn_second_parameter_to_va_arg_not_pod)
17385 << TInfo->getType()
17386 << TInfo->getTypeLoc().getSourceRange();
17387 }
17388
17389 if (TInfo->getType()->isArrayType()) {
17390 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17391 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17392 << TInfo->getType()
17393 << TInfo->getTypeLoc().getSourceRange());
17394 }
17395
17396 // Check for va_arg where arguments of the given type will be promoted
17397 // (i.e. this va_arg is guaranteed to have undefined behavior).
17398 QualType PromoteType;
17399 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17400 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17401 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17402 // and C23 7.16.1.1p2 says, in part:
17403 // If type is not compatible with the type of the actual next argument
17404 // (as promoted according to the default argument promotions), the
17405 // behavior is undefined, except for the following cases:
17406 // - both types are pointers to qualified or unqualified versions of
17407 // compatible types;
17408 // - one type is compatible with a signed integer type, the other
17409 // type is compatible with the corresponding unsigned integer type,
17410 // and the value is representable in both types;
17411 // - one type is pointer to qualified or unqualified void and the
17412 // other is a pointer to a qualified or unqualified character type;
17413 // - or, the type of the next argument is nullptr_t and type is a
17414 // pointer type that has the same representation and alignment
17415 // requirements as a pointer to a character type.
17416 // Given that type compatibility is the primary requirement (ignoring
17417 // qualifications), you would think we could call typesAreCompatible()
17418 // directly to test this. However, in C++, that checks for *same type*,
17419 // which causes false positives when passing an enumeration type to
17420 // va_arg. Instead, get the underlying type of the enumeration and pass
17421 // that.
17422 QualType UnderlyingType = TInfo->getType();
17423 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17424 UnderlyingType = ED->getIntegerType();
17425 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17426 /*CompareUnqualified*/ true))
17427 PromoteType = QualType();
17428
17429 // If the types are still not compatible, we need to test whether the
17430 // promoted type and the underlying type are the same except for
17431 // signedness. Ask the AST for the correctly corresponding type and see
17432 // if that's compatible.
17433 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17434 PromoteType->isUnsignedIntegerType() !=
17435 UnderlyingType->isUnsignedIntegerType()) {
17436 UnderlyingType =
17437 UnderlyingType->isUnsignedIntegerType()
17438 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17439 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17440 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17441 /*CompareUnqualified*/ true))
17442 PromoteType = QualType();
17443 }
17444 }
17445 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17446 PromoteType = Context.DoubleTy;
17447 if (!PromoteType.isNull())
17448 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17449 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17450 << TInfo->getType()
17451 << PromoteType
17452 << TInfo->getTypeLoc().getSourceRange());
17453 }
17454
17455 QualType T = TInfo->getType().getNonLValueExprType(Context);
17456 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17457}
17458
17459ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17460 // The type of __null will be int or long, depending on the size of
17461 // pointers on the target.
17462 QualType Ty;
17463 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17464 if (pw == Context.getTargetInfo().getIntWidth())
17465 Ty = Context.IntTy;
17466 else if (pw == Context.getTargetInfo().getLongWidth())
17467 Ty = Context.LongTy;
17468 else if (pw == Context.getTargetInfo().getLongLongWidth())
17469 Ty = Context.LongLongTy;
17470 else {
17471 llvm_unreachable("I don't know size of pointer!");
17472 }
17473
17474 return new (Context) GNUNullExpr(Ty, TokenLoc);
17475}
17476
17477static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17478 CXXRecordDecl *ImplDecl = nullptr;
17479
17480 // Fetch the std::source_location::__impl decl.
17481 if (NamespaceDecl *Std = S.getStdNamespace()) {
17482 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17483 Loc, Sema::LookupOrdinaryName);
17484 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17485 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17486 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17487 Loc, Sema::LookupOrdinaryName);
17488 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17489 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17490 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17491 }
17492 }
17493 }
17494 }
17495
17496 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17497 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17498 return nullptr;
17499 }
17500
17501 // Verify that __impl is a trivial struct type, with no base classes, and with
17502 // only the four expected fields.
17503 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17504 ImplDecl->getNumBases() != 0) {
17505 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17506 return nullptr;
17507 }
17508
17509 unsigned Count = 0;
17510 for (FieldDecl *F : ImplDecl->fields()) {
17511 StringRef Name = F->getName();
17512
17513 if (Name == "_M_file_name") {
17514 if (F->getType() !=
17515 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17516 break;
17517 Count++;
17518 } else if (Name == "_M_function_name") {
17519 if (F->getType() !=
17520 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17521 break;
17522 Count++;
17523 } else if (Name == "_M_line") {
17524 if (!F->getType()->isIntegerType())
17525 break;
17526 Count++;
17527 } else if (Name == "_M_column") {
17528 if (!F->getType()->isIntegerType())
17529 break;
17530 Count++;
17531 } else {
17532 Count = 100; // invalid
17533 break;
17534 }
17535 }
17536 if (Count != 4) {
17537 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17538 return nullptr;
17539 }
17540
17541 return ImplDecl;
17542}
17543
17544ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17545 SourceLocation BuiltinLoc,
17546 SourceLocation RPLoc) {
17547 QualType ResultTy;
17548 switch (Kind) {
17549 case SourceLocIdentKind::File:
17550 case SourceLocIdentKind::FileName:
17551 case SourceLocIdentKind::Function:
17552 case SourceLocIdentKind::FuncSig: {
17553 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17554 ResultTy =
17555 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17556 break;
17557 }
17558 case SourceLocIdentKind::Line:
17559 case SourceLocIdentKind::Column:
17560 ResultTy = Context.UnsignedIntTy;
17561 break;
17562 case SourceLocIdentKind::SourceLocStruct:
17563 if (!StdSourceLocationImplDecl) {
17564 StdSourceLocationImplDecl =
17565 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17566 if (!StdSourceLocationImplDecl)
17567 return ExprError();
17568 }
17569 ResultTy = Context.getPointerType(
17570 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17571 break;
17572 }
17573
17574 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17575}
17576
17577ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17578 SourceLocation BuiltinLoc,
17579 SourceLocation RPLoc,
17580 DeclContext *ParentContext) {
17581 return new (Context)
17582 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17583}
17584
17585ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17586 StringLiteral *BinaryData, StringRef FileName) {
17587 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17588 Data->BinaryData = BinaryData;
17589 Data->FileName = FileName;
17590 return new (Context)
17591 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17592 Data->getDataElementCount());
17593}
17594
17595static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17596 const Expr *SrcExpr) {
17597 if (!DstType->isFunctionPointerType() ||
17598 !SrcExpr->getType()->isFunctionType())
17599 return false;
17600
17601 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17602 if (!DRE)
17603 return false;
17604
17605 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17606 if (!FD)
17607 return false;
17608
17609 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17610 /*Complain=*/true,
17611 Loc: SrcExpr->getBeginLoc());
17612}
17613
17614bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17615 SourceLocation Loc,
17616 QualType DstType, QualType SrcType,
17617 Expr *SrcExpr, AssignmentAction Action,
17618 bool *Complained) {
17619 if (Complained)
17620 *Complained = false;
17621
17622 // Decode the result (notice that AST's are still created for extensions).
17623 bool CheckInferredResultType = false;
17624 bool isInvalid = false;
17625 unsigned DiagKind = 0;
17626 ConversionFixItGenerator ConvHints;
17627 bool MayHaveConvFixit = false;
17628 bool MayHaveFunctionDiff = false;
17629 const ObjCInterfaceDecl *IFace = nullptr;
17630 const ObjCProtocolDecl *PDecl = nullptr;
17631
17632 switch (ConvTy) {
17633 case AssignConvertType::Compatible:
17634 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17635 return false;
17636 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17637 // Still a valid conversion, but we may want to diagnose for C++
17638 // compatibility reasons.
17639 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17640 break;
17641 case AssignConvertType::PointerToInt:
17642 if (getLangOpts().CPlusPlus) {
17643 DiagKind = diag::err_typecheck_convert_pointer_int;
17644 isInvalid = true;
17645 } else {
17646 DiagKind = diag::ext_typecheck_convert_pointer_int;
17647 }
17648 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17649 MayHaveConvFixit = true;
17650 break;
17651 case AssignConvertType::IntToPointer:
17652 if (getLangOpts().CPlusPlus) {
17653 DiagKind = diag::err_typecheck_convert_int_pointer;
17654 isInvalid = true;
17655 } else {
17656 DiagKind = diag::ext_typecheck_convert_int_pointer;
17657 }
17658 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17659 MayHaveConvFixit = true;
17660 break;
17661 case AssignConvertType::IncompatibleFunctionPointerStrict:
17662 DiagKind =
17663 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17664 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17665 MayHaveConvFixit = true;
17666 break;
17667 case AssignConvertType::IncompatibleFunctionPointer:
17668 if (getLangOpts().CPlusPlus) {
17669 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17670 isInvalid = true;
17671 } else {
17672 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17673 }
17674 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17675 MayHaveConvFixit = true;
17676 break;
17677 case AssignConvertType::IncompatiblePointer:
17678 if (Action == AssignmentAction::Passing_CFAudited) {
17679 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17680 } else if (getLangOpts().CPlusPlus) {
17681 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17682 isInvalid = true;
17683 } else {
17684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17685 }
17686 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17687 SrcType->isObjCObjectPointerType();
17688 if (CheckInferredResultType) {
17689 SrcType = SrcType.getUnqualifiedType();
17690 DstType = DstType.getUnqualifiedType();
17691 } else {
17692 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17693 }
17694 MayHaveConvFixit = true;
17695 break;
17696 case AssignConvertType::IncompatiblePointerSign:
17697 if (getLangOpts().CPlusPlus) {
17698 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17699 isInvalid = true;
17700 } else {
17701 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17702 }
17703 break;
17704 case AssignConvertType::FunctionVoidPointer:
17705 if (getLangOpts().CPlusPlus) {
17706 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17707 isInvalid = true;
17708 } else {
17709 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17710 }
17711 break;
17712 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17713 // Perform decay if necessary.
17714 if (SrcType->canDecayToPointerType())
17715 SrcType = Context.getDecayedType(T: SrcType);
17716
17717 isInvalid = true;
17718
17719 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17720 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17721 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17722 DiagKind = diag::err_typecheck_incompatible_address_space;
17723 break;
17724 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17725 DiagKind = diag::err_typecheck_incompatible_ownership;
17726 break;
17727 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17728 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17729 break;
17730 }
17731
17732 llvm_unreachable("unknown error case for discarding qualifiers!");
17733 // fallthrough
17734 }
17735 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17736 if (SrcType->isArrayType())
17737 SrcType = Context.getArrayDecayedType(T: SrcType);
17738
17739 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17740 break;
17741 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17742 // If the qualifiers lost were because we were applying the
17743 // (deprecated) C++ conversion from a string literal to a char*
17744 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17745 // Ideally, this check would be performed in
17746 // checkPointerTypesForAssignment. However, that would require a
17747 // bit of refactoring (so that the second argument is an
17748 // expression, rather than a type), which should be done as part
17749 // of a larger effort to fix checkPointerTypesForAssignment for
17750 // C++ semantics.
17751 if (getLangOpts().CPlusPlus &&
17752 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17753 return false;
17754 if (getLangOpts().CPlusPlus) {
17755 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17756 isInvalid = true;
17757 } else {
17758 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17759 }
17760
17761 break;
17762 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17763 if (getLangOpts().CPlusPlus) {
17764 isInvalid = true;
17765 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17766 } else {
17767 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17768 }
17769 break;
17770 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17771 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17772 isInvalid = true;
17773 break;
17774 case AssignConvertType::IntToBlockPointer:
17775 DiagKind = diag::err_int_to_block_pointer;
17776 isInvalid = true;
17777 break;
17778 case AssignConvertType::IncompatibleBlockPointer:
17779 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17780 isInvalid = true;
17781 break;
17782 case AssignConvertType::IncompatibleObjCQualifiedId: {
17783 if (SrcType->isObjCQualifiedIdType()) {
17784 const ObjCObjectPointerType *srcOPT =
17785 SrcType->castAs<ObjCObjectPointerType>();
17786 for (auto *srcProto : srcOPT->quals()) {
17787 PDecl = srcProto;
17788 break;
17789 }
17790 if (const ObjCInterfaceType *IFaceT =
17791 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17792 IFace = IFaceT->getDecl();
17793 }
17794 else if (DstType->isObjCQualifiedIdType()) {
17795 const ObjCObjectPointerType *dstOPT =
17796 DstType->castAs<ObjCObjectPointerType>();
17797 for (auto *dstProto : dstOPT->quals()) {
17798 PDecl = dstProto;
17799 break;
17800 }
17801 if (const ObjCInterfaceType *IFaceT =
17802 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17803 IFace = IFaceT->getDecl();
17804 }
17805 if (getLangOpts().CPlusPlus) {
17806 DiagKind = diag::err_incompatible_qualified_id;
17807 isInvalid = true;
17808 } else {
17809 DiagKind = diag::warn_incompatible_qualified_id;
17810 }
17811 break;
17812 }
17813 case AssignConvertType::IncompatibleVectors:
17814 if (getLangOpts().CPlusPlus) {
17815 DiagKind = diag::err_incompatible_vectors;
17816 isInvalid = true;
17817 } else {
17818 DiagKind = diag::warn_incompatible_vectors;
17819 }
17820 break;
17821 case AssignConvertType::IncompatibleObjCWeakRef:
17822 DiagKind = diag::err_arc_weak_unavailable_assign;
17823 isInvalid = true;
17824 break;
17825 case AssignConvertType::CompatibleOBTDiscards:
17826 return false;
17827 case AssignConvertType::IncompatibleOBTKinds: {
17828 assert(!SrcType->isFunctionType() &&
17829 "Unexpected function type found in IncompatibleOBTKinds assignment");
17830 if (SrcType->canDecayToPointerType())
17831 SrcType = Context.getDecayedType(T: SrcType);
17832
17833 auto getOBTKindName = [](QualType Ty) -> StringRef {
17834 if (Ty->isPointerType())
17835 Ty = Ty->getPointeeType();
17836 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17837 return OBT->getBehaviorKind() ==
17838 OverflowBehaviorType::OverflowBehaviorKind::Trap
17839 ? "__ob_trap"
17840 : "__ob_wrap";
17841 }
17842 llvm_unreachable("OBT kind unhandled");
17843 };
17844
17845 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
17846 << DstType << SrcType << getOBTKindName(DstType)
17847 << getOBTKindName(SrcType);
17848 isInvalid = true;
17849 return true;
17850 }
17851 case AssignConvertType::Incompatible:
17852 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17853 if (Complained)
17854 *Complained = true;
17855 return true;
17856 }
17857
17858 DiagKind = diag::err_typecheck_convert_incompatible;
17859 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17860 MayHaveConvFixit = true;
17861 isInvalid = true;
17862 MayHaveFunctionDiff = true;
17863 break;
17864 }
17865
17866 QualType FirstType, SecondType;
17867 switch (Action) {
17868 case AssignmentAction::Assigning:
17869 case AssignmentAction::Initializing:
17870 // The destination type comes first.
17871 FirstType = DstType;
17872 SecondType = SrcType;
17873 break;
17874
17875 case AssignmentAction::Returning:
17876 case AssignmentAction::Passing:
17877 case AssignmentAction::Passing_CFAudited:
17878 case AssignmentAction::Converting:
17879 case AssignmentAction::Sending:
17880 case AssignmentAction::Casting:
17881 // The source type comes first.
17882 FirstType = SrcType;
17883 SecondType = DstType;
17884 break;
17885 }
17886
17887 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17888 AssignmentAction ActionForDiag = Action;
17889 if (Action == AssignmentAction::Passing_CFAudited)
17890 ActionForDiag = AssignmentAction::Passing;
17891
17892 FDiag << FirstType << SecondType << ActionForDiag
17893 << SrcExpr->getSourceRange();
17894
17895 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17896 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17897 auto isPlainChar = [](const clang::Type *Type) {
17898 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17899 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17900 };
17901 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17902 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17903 }
17904
17905 // If we can fix the conversion, suggest the FixIts.
17906 if (!ConvHints.isNull()) {
17907 for (FixItHint &H : ConvHints.Hints)
17908 FDiag << H;
17909 }
17910
17911 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17912
17913 if (MayHaveFunctionDiff)
17914 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17915
17916 Diag(Loc, PD: FDiag);
17917 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17918 DiagKind == diag::err_incompatible_qualified_id) &&
17919 PDecl && IFace && !IFace->hasDefinition())
17920 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17921 << IFace << PDecl;
17922
17923 if (SecondType == Context.OverloadTy)
17924 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17925 DestType: FirstType, /*TakingAddress=*/true);
17926
17927 if (CheckInferredResultType)
17928 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17929
17930 if (Action == AssignmentAction::Returning &&
17931 ConvTy == AssignConvertType::IncompatiblePointer)
17932 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17933
17934 if (Complained)
17935 *Complained = true;
17936 return isInvalid;
17937}
17938
17939ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17940 llvm::APSInt *Result,
17941 AllowFoldKind CanFold) {
17942 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17943 public:
17944 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17945 QualType T) override {
17946 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17947 << T << S.LangOpts.CPlusPlus;
17948 }
17949 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17950 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17951 }
17952 } Diagnoser;
17953
17954 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17955}
17956
17957ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17958 llvm::APSInt *Result,
17959 unsigned DiagID,
17960 AllowFoldKind CanFold) {
17961 class IDDiagnoser : public VerifyICEDiagnoser {
17962 unsigned DiagID;
17963
17964 public:
17965 IDDiagnoser(unsigned DiagID)
17966 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17967
17968 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17969 return S.Diag(Loc, DiagID);
17970 }
17971 } Diagnoser(DiagID);
17972
17973 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17974}
17975
17976Sema::SemaDiagnosticBuilder
17977Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17978 QualType T) {
17979 return diagnoseNotICE(S, Loc);
17980}
17981
17982Sema::SemaDiagnosticBuilder
17983Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17984 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17985}
17986
17987ExprResult
17988Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17989 VerifyICEDiagnoser &Diagnoser,
17990 AllowFoldKind CanFold) {
17991 SourceLocation DiagLoc = E->getBeginLoc();
17992
17993 if (getLangOpts().CPlusPlus11) {
17994 // C++11 [expr.const]p5:
17995 // If an expression of literal class type is used in a context where an
17996 // integral constant expression is required, then that class type shall
17997 // have a single non-explicit conversion function to an integral or
17998 // unscoped enumeration type
17999 ExprResult Converted;
18000 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18001 VerifyICEDiagnoser &BaseDiagnoser;
18002 public:
18003 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18004 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18005 BaseDiagnoser.Suppress, true),
18006 BaseDiagnoser(BaseDiagnoser) {}
18007
18008 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18009 QualType T) override {
18010 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18011 }
18012
18013 SemaDiagnosticBuilder diagnoseIncomplete(
18014 Sema &S, SourceLocation Loc, QualType T) override {
18015 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
18016 }
18017
18018 SemaDiagnosticBuilder diagnoseExplicitConv(
18019 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18020 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
18021 }
18022
18023 SemaDiagnosticBuilder noteExplicitConv(
18024 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18025 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18026 << ConvTy->isEnumeralType() << ConvTy;
18027 }
18028
18029 SemaDiagnosticBuilder diagnoseAmbiguous(
18030 Sema &S, SourceLocation Loc, QualType T) override {
18031 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
18032 }
18033
18034 SemaDiagnosticBuilder noteAmbiguous(
18035 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18036 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18037 << ConvTy->isEnumeralType() << ConvTy;
18038 }
18039
18040 SemaDiagnosticBuilder diagnoseConversion(
18041 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18042 llvm_unreachable("conversion functions are permitted");
18043 }
18044 } ConvertDiagnoser(Diagnoser);
18045
18046 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18047 Converter&: ConvertDiagnoser);
18048 if (Converted.isInvalid())
18049 return Converted;
18050 E = Converted.get();
18051 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18052 // don't try to evaluate it later. We also don't want to return the
18053 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18054 // this function will attempt to use 'Value'.
18055 if (isa<RecoveryExpr>(Val: E))
18056 return ExprError();
18057 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18058 return ExprError();
18059 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18060 // An ICE must be of integral or unscoped enumeration type.
18061 if (!Diagnoser.Suppress)
18062 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18063 << E->getSourceRange();
18064 return ExprError();
18065 }
18066
18067 ExprResult RValueExpr = DefaultLvalueConversion(E);
18068 if (RValueExpr.isInvalid())
18069 return ExprError();
18070
18071 E = RValueExpr.get();
18072
18073 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18074 // in the non-ICE case.
18075 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18076 SmallVector<PartialDiagnosticAt, 8> Notes;
18077 if (Result)
18078 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18079 if (!isa<ConstantExpr>(Val: E))
18080 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18081 : ConstantExpr::Create(Context, E);
18082
18083 if (Notes.empty())
18084 return E;
18085
18086 // If our only note is the usual "invalid subexpression" note, just point
18087 // the caret at its location rather than producing an essentially
18088 // redundant note.
18089 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18090 diag::note_invalid_subexpr_in_const_expr) {
18091 DiagLoc = Notes[0].first;
18092 Notes.clear();
18093 }
18094
18095 if (getLangOpts().CPlusPlus) {
18096 if (!Diagnoser.Suppress) {
18097 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18098 for (const PartialDiagnosticAt &Note : Notes)
18099 Diag(Loc: Note.first, PD: Note.second);
18100 }
18101 return ExprError();
18102 }
18103
18104 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18105 for (const PartialDiagnosticAt &Note : Notes)
18106 Diag(Loc: Note.first, PD: Note.second);
18107
18108 return E;
18109 }
18110
18111 Expr::EvalResult EvalResult;
18112 SmallVector<PartialDiagnosticAt, 8> Notes;
18113 EvalResult.Diag = &Notes;
18114
18115 // Try to evaluate the expression, and produce diagnostics explaining why it's
18116 // not a constant expression as a side-effect.
18117 bool Folded =
18118 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18119 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18120 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18121
18122 if (!isa<ConstantExpr>(Val: E))
18123 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18124
18125 // In C++11, we can rely on diagnostics being produced for any expression
18126 // which is not a constant expression. If no diagnostics were produced, then
18127 // this is a constant expression.
18128 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18129 if (Result)
18130 *Result = EvalResult.Val.getInt();
18131 return E;
18132 }
18133
18134 // If our only note is the usual "invalid subexpression" note, just point
18135 // the caret at its location rather than producing an essentially
18136 // redundant note.
18137 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18138 diag::note_invalid_subexpr_in_const_expr) {
18139 DiagLoc = Notes[0].first;
18140 Notes.clear();
18141 }
18142
18143 if (!Folded || CanFold == AllowFoldKind::No) {
18144 if (!Diagnoser.Suppress) {
18145 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18146 for (const PartialDiagnosticAt &Note : Notes)
18147 Diag(Loc: Note.first, PD: Note.second);
18148 }
18149
18150 return ExprError();
18151 }
18152
18153 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18154 for (const PartialDiagnosticAt &Note : Notes)
18155 Diag(Loc: Note.first, PD: Note.second);
18156
18157 if (Result)
18158 *Result = EvalResult.Val.getInt();
18159 return E;
18160}
18161
18162namespace {
18163 // Handle the case where we conclude a expression which we speculatively
18164 // considered to be unevaluated is actually evaluated.
18165 class TransformToPE : public TreeTransform<TransformToPE> {
18166 typedef TreeTransform<TransformToPE> BaseTransform;
18167
18168 public:
18169 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18170
18171 // Make sure we redo semantic analysis
18172 bool AlwaysRebuild() { return true; }
18173 bool ReplacingOriginal() { return true; }
18174
18175 // We need to special-case DeclRefExprs referring to FieldDecls which
18176 // are not part of a member pointer formation; normal TreeTransforming
18177 // doesn't catch this case because of the way we represent them in the AST.
18178 // FIXME: This is a bit ugly; is it really the best way to handle this
18179 // case?
18180 //
18181 // Error on DeclRefExprs referring to FieldDecls.
18182 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18183 if (isa<FieldDecl>(Val: E->getDecl()) &&
18184 !SemaRef.isUnevaluatedContext())
18185 return SemaRef.Diag(Loc: E->getLocation(),
18186 DiagID: diag::err_invalid_non_static_member_use)
18187 << E->getDecl() << E->getSourceRange();
18188
18189 return BaseTransform::TransformDeclRefExpr(E);
18190 }
18191
18192 // Exception: filter out member pointer formation
18193 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18194 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18195 return E;
18196
18197 return BaseTransform::TransformUnaryOperator(E);
18198 }
18199
18200 // The body of a lambda-expression is in a separate expression evaluation
18201 // context so never needs to be transformed.
18202 // FIXME: Ideally we wouldn't transform the closure type either, and would
18203 // just recreate the capture expressions and lambda expression.
18204 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18205 return SkipLambdaBody(E, S: Body);
18206 }
18207 };
18208}
18209
18210ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18211 assert(isUnevaluatedContext() &&
18212 "Should only transform unevaluated expressions");
18213 ExprEvalContexts.back().Context =
18214 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18215 if (isUnevaluatedContext())
18216 return E;
18217 return TransformToPE(*this).TransformExpr(E);
18218}
18219
18220TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18221 assert(isUnevaluatedContext() &&
18222 "Should only transform unevaluated expressions");
18223 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18224 if (isUnevaluatedContext())
18225 return TInfo;
18226 return TransformToPE(*this).TransformType(TSI: TInfo);
18227}
18228
18229void
18230Sema::PushExpressionEvaluationContext(
18231 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18232 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18233 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18234 Args&: LambdaContextDecl, Args&: ExprContext);
18235
18236 // Discarded statements and immediate contexts nested in other
18237 // discarded statements or immediate context are themselves
18238 // a discarded statement or an immediate context, respectively.
18239 ExprEvalContexts.back().InDiscardedStatement =
18240 parentEvaluationContext().isDiscardedStatementContext();
18241
18242 // C++23 [expr.const]/p15
18243 // An expression or conversion is in an immediate function context if [...]
18244 // it is a subexpression of a manifestly constant-evaluated expression or
18245 // conversion.
18246 const auto &Prev = parentEvaluationContext();
18247 ExprEvalContexts.back().InImmediateFunctionContext =
18248 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18249
18250 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18251 Prev.InImmediateEscalatingFunctionContext;
18252
18253 Cleanup.reset();
18254 if (!MaybeODRUseExprs.empty())
18255 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18256}
18257
18258void
18259Sema::PushExpressionEvaluationContext(
18260 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18261 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18262 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18263 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18264}
18265
18266void Sema::PushExpressionEvaluationContextForFunction(
18267 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18268 // [expr.const]/p14.1
18269 // An expression or conversion is in an immediate function context if it is
18270 // potentially evaluated and either: its innermost enclosing non-block scope
18271 // is a function parameter scope of an immediate function.
18272 PushExpressionEvaluationContext(
18273 NewContext: FD && FD->isConsteval()
18274 ? ExpressionEvaluationContext::ImmediateFunctionContext
18275 : NewContext);
18276 const Sema::ExpressionEvaluationContextRecord &Parent =
18277 parentEvaluationContext();
18278 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18279
18280 Current.InDiscardedStatement = false;
18281
18282 if (FD) {
18283
18284 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18285 // context is nested in an immediate function context, so smaller contexts
18286 // that appear inside immediate functions (like variable initializers) are
18287 // considered to be inside an immediate function context even though by
18288 // themselves they are not immediate function contexts. But when a new
18289 // function is entered, we need to reset this tracking, since the entered
18290 // function might be not an immediate function.
18291
18292 Current.InImmediateEscalatingFunctionContext =
18293 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18294
18295 if (isLambdaMethod(DC: FD))
18296 Current.InImmediateFunctionContext =
18297 FD->isConsteval() ||
18298 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18299 Parent.isImmediateFunctionContext()));
18300 else
18301 Current.InImmediateFunctionContext = FD->isConsteval();
18302 }
18303}
18304
18305ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18306 TypeSourceInfo *TSI) {
18307 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18308}
18309
18310ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18311 TypeSourceInfo *TSI) {
18312 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18313}
18314
18315namespace {
18316
18317const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18318 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18319 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18320 if (E->getOpcode() == UO_Deref)
18321 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18322 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18323 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18324 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18325 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18326 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18327 QualType Inner;
18328 QualType Ty = E->getType();
18329 if (const auto *Ptr = Ty->getAs<PointerType>())
18330 Inner = Ptr->getPointeeType();
18331 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18332 Inner = Arr->getElementType();
18333 else
18334 return nullptr;
18335
18336 if (Inner->hasAttr(AK: attr::NoDeref))
18337 return E;
18338 }
18339 return nullptr;
18340}
18341
18342} // namespace
18343
18344void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18345 for (const Expr *E : Rec.PossibleDerefs) {
18346 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18347 if (DeclRef) {
18348 const ValueDecl *Decl = DeclRef->getDecl();
18349 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18350 << Decl->getName() << E->getSourceRange();
18351 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18352 } else {
18353 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18354 << E->getSourceRange();
18355 }
18356 }
18357 Rec.PossibleDerefs.clear();
18358}
18359
18360void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18361 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18362 return;
18363
18364 // Note: ignoring parens here is not justified by the standard rules, but
18365 // ignoring parentheses seems like a more reasonable approach, and this only
18366 // drives a deprecation warning so doesn't affect conformance.
18367 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18368 if (BO->getOpcode() == BO_Assign) {
18369 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18370 llvm::erase(C&: LHSs, V: BO->getLHS());
18371 }
18372 }
18373}
18374
18375void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18376 assert(getLangOpts().CPlusPlus20 &&
18377 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18378 "Cannot mark an immediate escalating expression outside of an "
18379 "immediate escalating context");
18380 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18381 Call && Call->getCallee()) {
18382 if (auto *DeclRef =
18383 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18384 DeclRef->setIsImmediateEscalating(true);
18385 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18386 Ctr->setIsImmediateEscalating(true);
18387 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18388 DeclRef->setIsImmediateEscalating(true);
18389 } else {
18390 assert(false && "expected an immediately escalating expression");
18391 }
18392 if (FunctionScopeInfo *FI = getCurFunction())
18393 FI->FoundImmediateEscalatingExpression = true;
18394}
18395
18396ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18397 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18398 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18399 isCheckingDefaultArgumentOrInitializer() ||
18400 RebuildingImmediateInvocation || isImmediateFunctionContext())
18401 return E;
18402
18403 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18404 /// It's OK if this fails; we'll also remove this in
18405 /// HandleImmediateInvocations, but catching it here allows us to avoid
18406 /// walking the AST looking for it in simple cases.
18407 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18408 if (auto *DeclRef =
18409 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18410 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18411
18412 // C++23 [expr.const]/p16
18413 // An expression or conversion is immediate-escalating if it is not initially
18414 // in an immediate function context and it is [...] an immediate invocation
18415 // that is not a constant expression and is not a subexpression of an
18416 // immediate invocation.
18417 APValue Cached;
18418 auto CheckConstantExpressionAndKeepResult = [&]() {
18419 Expr::EvalResult Eval;
18420 bool Res = E.get()->EvaluateAsConstantExpr(
18421 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18422 if (Res && !Eval.DiagEmitted) {
18423 Cached = std::move(Eval.Val);
18424 return true;
18425 }
18426 return false;
18427 };
18428
18429 if (!E.get()->isValueDependent() &&
18430 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18431 !CheckConstantExpressionAndKeepResult()) {
18432 MarkExpressionAsImmediateEscalating(E: E.get());
18433 return E;
18434 }
18435
18436 if (Cleanup.exprNeedsCleanups()) {
18437 // Since an immediate invocation is a full expression itself - it requires
18438 // an additional ExprWithCleanups node, but it can participate to a bigger
18439 // full expression which actually requires cleanups to be run after so
18440 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18441 // may discard cleanups for outer expression too early.
18442
18443 // Note that ExprWithCleanups created here must always have empty cleanup
18444 // objects:
18445 // - compound literals do not create cleanup objects in C++ and immediate
18446 // invocations are C++-only.
18447 // - blocks are not allowed inside constant expressions and compiler will
18448 // issue an error if they appear there.
18449 //
18450 // Hence, in correct code any cleanup objects created inside current
18451 // evaluation context must be outside the immediate invocation.
18452 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18453 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18454 }
18455
18456 ConstantExpr *Res = ConstantExpr::Create(
18457 Context: getASTContext(), E: E.get(),
18458 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18459 Context: getASTContext()),
18460 /*IsImmediateInvocation*/ true);
18461 if (Cached.hasValue())
18462 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18463 /// Value-dependent constant expressions should not be immediately
18464 /// evaluated until they are instantiated.
18465 if (!Res->isValueDependent())
18466 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18467 return Res;
18468}
18469
18470static void EvaluateAndDiagnoseImmediateInvocation(
18471 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18472 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18473 Expr::EvalResult Eval;
18474 Eval.Diag = &Notes;
18475 ConstantExpr *CE = Candidate.getPointer();
18476 bool Result = CE->EvaluateAsConstantExpr(
18477 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18478 if (!Result || !Notes.empty()) {
18479 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18480 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18481 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18482 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18483 FunctionDecl *FD = nullptr;
18484 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18485 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18486 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18487 FD = Call->getConstructor();
18488 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18489 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18490
18491 assert(FD && FD->isImmediateFunction() &&
18492 "could not find an immediate function in this expression");
18493 if (FD->isInvalidDecl())
18494 return;
18495 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18496 << FD << FD->isConsteval();
18497 if (auto Context =
18498 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18499 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18500 << Context->Decl;
18501 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18502 }
18503 if (!FD->isConsteval())
18504 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18505 for (auto &Note : Notes)
18506 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18507 return;
18508 }
18509 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18510}
18511
18512static void RemoveNestedImmediateInvocation(
18513 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18514 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18515 struct ComplexRemove : TreeTransform<ComplexRemove> {
18516 using Base = TreeTransform<ComplexRemove>;
18517 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18518 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18519 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18520 CurrentII;
18521 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18522 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18523 SmallVector<Sema::ImmediateInvocationCandidate,
18524 4>::reverse_iterator Current)
18525 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18526 void RemoveImmediateInvocation(ConstantExpr* E) {
18527 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18528 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18529 return Elem.getPointer() == E;
18530 });
18531 // It is possible that some subexpression of the current immediate
18532 // invocation was handled from another expression evaluation context. Do
18533 // not handle the current immediate invocation if some of its
18534 // subexpressions failed before.
18535 if (It == IISet.rend()) {
18536 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18537 CurrentII->setInt(1);
18538 } else {
18539 It->setInt(1); // Mark as deleted
18540 }
18541 }
18542 ExprResult TransformConstantExpr(ConstantExpr *E) {
18543 if (!E->isImmediateInvocation())
18544 return Base::TransformConstantExpr(E);
18545 RemoveImmediateInvocation(E);
18546 return Base::TransformExpr(E: E->getSubExpr());
18547 }
18548 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18549 /// we need to remove its DeclRefExpr from the DRSet.
18550 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18551 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18552 return Base::TransformCXXOperatorCallExpr(E);
18553 }
18554 /// Base::TransformUserDefinedLiteral doesn't preserve the
18555 /// UserDefinedLiteral node.
18556 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18557 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18558 /// here.
18559 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18560 if (!Init)
18561 return Init;
18562
18563 // We cannot use IgnoreImpCasts because we need to preserve
18564 // full expressions.
18565 while (true) {
18566 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18567 Init = ICE->getSubExpr();
18568 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18569 Init = ICE->getSubExpr();
18570 else
18571 break;
18572 }
18573 /// ConstantExprs are the first layer of implicit node to be removed so if
18574 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18575 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18576 CE && CE->isImmediateInvocation())
18577 RemoveImmediateInvocation(E: CE);
18578 return Base::TransformInitializer(Init, NotCopyInit);
18579 }
18580 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18581 DRSet.erase(Ptr: E);
18582 return E;
18583 }
18584 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18585 // Do not rebuild lambdas to avoid creating a new type.
18586 // Lambdas have already been processed inside their eval contexts.
18587 return E;
18588 }
18589
18590 // We do not have enough information to transform opaque expressions and
18591 // assume they do not contain immediate subexpressions.
18592 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18593
18594 bool AlwaysRebuild() { return false; }
18595 bool ReplacingOriginal() { return true; }
18596 bool AllowSkippingCXXConstructExpr() {
18597 bool Res = AllowSkippingFirstCXXConstructExpr;
18598 AllowSkippingFirstCXXConstructExpr = true;
18599 return Res;
18600 }
18601 bool AllowSkippingFirstCXXConstructExpr = true;
18602 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18603 Rec.ImmediateInvocationCandidates, It);
18604
18605 /// CXXConstructExpr with a single argument are getting skipped by
18606 /// TreeTransform in some situtation because they could be implicit. This
18607 /// can only occur for the top-level CXXConstructExpr because it is used
18608 /// nowhere in the expression being transformed therefore will not be rebuilt.
18609 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18610 /// skipping the first CXXConstructExpr.
18611 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18612 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18613
18614 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18615 // The result may not be usable in case of previous compilation errors.
18616 // In this case evaluation of the expression may result in crash so just
18617 // don't do anything further with the result.
18618 if (Res.isUsable()) {
18619 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18620 It->getPointer()->setSubExpr(Res.get());
18621 }
18622}
18623
18624static void
18625HandleImmediateInvocations(Sema &SemaRef,
18626 Sema::ExpressionEvaluationContextRecord &Rec) {
18627 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18628 Rec.ReferenceToConsteval.size() == 0) ||
18629 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18630 return;
18631
18632 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18633 // [...]
18634 // - the initializer of a variable that is usable in constant expressions or
18635 // has constant initialization.
18636 if (SemaRef.getLangOpts().CPlusPlus23 &&
18637 Rec.ExprContext ==
18638 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18639 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18640 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18641 VD->hasConstantInitialization())) {
18642 // An expression or conversion is in an 'immediate function context' if it
18643 // is potentially evaluated and either:
18644 // [...]
18645 // - it is a subexpression of a manifestly constant-evaluated expression
18646 // or conversion.
18647 return;
18648 }
18649 }
18650
18651 /// When we have more than 1 ImmediateInvocationCandidates or previously
18652 /// failed immediate invocations, we need to check for nested
18653 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18654 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18655 /// invocation.
18656 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18657 !SemaRef.FailedImmediateInvocations.empty()) {
18658
18659 /// Prevent sema calls during the tree transform from adding pointers that
18660 /// are already in the sets.
18661 llvm::SaveAndRestore DisableIITracking(
18662 SemaRef.RebuildingImmediateInvocation, true);
18663
18664 /// Prevent diagnostic during tree transfrom as they are duplicates
18665 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18666
18667 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18668 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18669 if (!It->getInt())
18670 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18671 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18672 Rec.ReferenceToConsteval.size()) {
18673 struct SimpleRemove : DynamicRecursiveASTVisitor {
18674 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18675 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18676 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18677 DRSet.erase(Ptr: E);
18678 return DRSet.size();
18679 }
18680 } Visitor(Rec.ReferenceToConsteval);
18681 Visitor.TraverseStmt(
18682 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18683 }
18684 for (auto CE : Rec.ImmediateInvocationCandidates)
18685 if (!CE.getInt())
18686 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18687 for (auto *DR : Rec.ReferenceToConsteval) {
18688 // If the expression is immediate escalating, it is not an error;
18689 // The outer context itself becomes immediate and further errors,
18690 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18691 if (DR->isImmediateEscalating())
18692 continue;
18693 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18694 const NamedDecl *ND = FD;
18695 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18696 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18697 ND = MD->getParent();
18698
18699 // C++23 [expr.const]/p16
18700 // An expression or conversion is immediate-escalating if it is not
18701 // initially in an immediate function context and it is [...] a
18702 // potentially-evaluated id-expression that denotes an immediate function
18703 // that is not a subexpression of an immediate invocation.
18704 bool ImmediateEscalating = false;
18705 bool IsPotentiallyEvaluated =
18706 Rec.Context ==
18707 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18708 Rec.Context ==
18709 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18710 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18711 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18712
18713 if (!Rec.InImmediateEscalatingFunctionContext ||
18714 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18715 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18716 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18717 if (!FD->getBuiltinID())
18718 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18719 if (auto Context =
18720 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18721 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18722 << Context->Decl;
18723 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18724 }
18725 if (FD->isImmediateEscalating() && !FD->isConsteval())
18726 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18727
18728 } else {
18729 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18730 }
18731 }
18732}
18733
18734void Sema::PopExpressionEvaluationContext() {
18735 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18736 if (!Rec.Lambdas.empty()) {
18737 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18738 if (!getLangOpts().CPlusPlus20 &&
18739 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18740 Rec.isUnevaluated() ||
18741 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18742 unsigned D;
18743 if (Rec.isUnevaluated()) {
18744 // C++11 [expr.prim.lambda]p2:
18745 // A lambda-expression shall not appear in an unevaluated operand
18746 // (Clause 5).
18747 D = diag::err_lambda_unevaluated_operand;
18748 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18749 // C++1y [expr.const]p2:
18750 // A conditional-expression e is a core constant expression unless the
18751 // evaluation of e, following the rules of the abstract machine, would
18752 // evaluate [...] a lambda-expression.
18753 D = diag::err_lambda_in_constant_expression;
18754 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18755 // C++17 [expr.prim.lamda]p2:
18756 // A lambda-expression shall not appear [...] in a template-argument.
18757 D = diag::err_lambda_in_invalid_context;
18758 } else
18759 llvm_unreachable("Couldn't infer lambda error message.");
18760
18761 for (const auto *L : Rec.Lambdas)
18762 Diag(Loc: L->getBeginLoc(), DiagID: D);
18763 }
18764 }
18765
18766 // Append the collected materialized temporaries into previous context before
18767 // exit if the previous also is a lifetime extending context.
18768 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18769 parentEvaluationContext().InLifetimeExtendingContext &&
18770 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18771 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18772 RHS: Rec.ForRangeLifetimeExtendTemps);
18773 }
18774
18775 WarnOnPendingNoDerefs(Rec);
18776 HandleImmediateInvocations(SemaRef&: *this, Rec);
18777
18778 // Warn on any volatile-qualified simple-assignments that are not discarded-
18779 // value expressions nor unevaluated operands (those cases get removed from
18780 // this list by CheckUnusedVolatileAssignment).
18781 for (auto *BO : Rec.VolatileAssignmentLHSs)
18782 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18783 << BO->getType();
18784
18785 // When are coming out of an unevaluated context, clear out any
18786 // temporaries that we may have created as part of the evaluation of
18787 // the expression in that context: they aren't relevant because they
18788 // will never be constructed.
18789 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18790 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18791 CE: ExprCleanupObjects.end());
18792 Cleanup = Rec.ParentCleanup;
18793 CleanupVarDeclMarking();
18794 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18795 // Otherwise, merge the contexts together.
18796 } else {
18797 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18798 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18799 }
18800
18801 DiagnoseMisalignedMembers();
18802
18803 // Pop the current expression evaluation context off the stack.
18804 ExprEvalContexts.pop_back();
18805}
18806
18807void Sema::DiscardCleanupsInEvaluationContext() {
18808 ExprCleanupObjects.erase(
18809 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18810 CE: ExprCleanupObjects.end());
18811 Cleanup.reset();
18812 MaybeODRUseExprs.clear();
18813}
18814
18815ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18816 ExprResult Result = CheckPlaceholderExpr(E);
18817 if (Result.isInvalid())
18818 return ExprError();
18819 E = Result.get();
18820 if (!E->getType()->isVariablyModifiedType())
18821 return E;
18822 return TransformToPotentiallyEvaluated(E);
18823}
18824
18825/// Are we in a context that is potentially constant evaluated per C++20
18826/// [expr.const]p12?
18827static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18828 /// C++2a [expr.const]p12:
18829 // An expression or conversion is potentially constant evaluated if it is
18830 switch (SemaRef.ExprEvalContexts.back().Context) {
18831 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18832 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18833
18834 // -- a manifestly constant-evaluated expression,
18835 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18836 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18837 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18838 // -- a potentially-evaluated expression,
18839 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18840 // -- an immediate subexpression of a braced-init-list,
18841
18842 // -- [FIXME] an expression of the form & cast-expression that occurs
18843 // within a templated entity
18844 // -- a subexpression of one of the above that is not a subexpression of
18845 // a nested unevaluated operand.
18846 return true;
18847
18848 case Sema::ExpressionEvaluationContext::Unevaluated:
18849 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18850 // Expressions in this context are never evaluated.
18851 return false;
18852 }
18853 llvm_unreachable("Invalid context");
18854}
18855
18856/// Return true if this function has a calling convention that requires mangling
18857/// in the size of the parameter pack.
18858static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18859 // These manglings are only applicable for targets whcih use Microsoft
18860 // mangling scheme for C.
18861 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18862 return false;
18863
18864 // If this is C++ and this isn't an extern "C" function, parameters do not
18865 // need to be complete. In this case, C++ mangling will apply, which doesn't
18866 // use the size of the parameters.
18867 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18868 return false;
18869
18870 // Stdcall, fastcall, and vectorcall need this special treatment.
18871 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18872 switch (CC) {
18873 case CC_X86StdCall:
18874 case CC_X86FastCall:
18875 case CC_X86VectorCall:
18876 return true;
18877 default:
18878 break;
18879 }
18880 return false;
18881}
18882
18883/// Require that all of the parameter types of function be complete. Normally,
18884/// parameter types are only required to be complete when a function is called
18885/// or defined, but to mangle functions with certain calling conventions, the
18886/// mangler needs to know the size of the parameter list. In this situation,
18887/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18888/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18889/// result in a linker error. Clang doesn't implement this behavior, and instead
18890/// attempts to error at compile time.
18891static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18892 SourceLocation Loc) {
18893 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18894 FunctionDecl *FD;
18895 ParmVarDecl *Param;
18896
18897 public:
18898 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18899 : FD(FD), Param(Param) {}
18900
18901 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18902 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18903 StringRef CCName;
18904 switch (CC) {
18905 case CC_X86StdCall:
18906 CCName = "stdcall";
18907 break;
18908 case CC_X86FastCall:
18909 CCName = "fastcall";
18910 break;
18911 case CC_X86VectorCall:
18912 CCName = "vectorcall";
18913 break;
18914 default:
18915 llvm_unreachable("CC does not need mangling");
18916 }
18917
18918 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18919 << Param->getDeclName() << FD->getDeclName() << CCName;
18920 }
18921 };
18922
18923 for (ParmVarDecl *Param : FD->parameters()) {
18924 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18925 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18926 }
18927}
18928
18929namespace {
18930enum class OdrUseContext {
18931 /// Declarations in this context are not odr-used.
18932 None,
18933 /// Declarations in this context are formally odr-used, but this is a
18934 /// dependent context.
18935 Dependent,
18936 /// Declarations in this context are odr-used but not actually used (yet).
18937 FormallyOdrUsed,
18938 /// Declarations in this context are used.
18939 Used
18940};
18941}
18942
18943/// Are we within a context in which references to resolved functions or to
18944/// variables result in odr-use?
18945static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18946 const Sema::ExpressionEvaluationContextRecord &Context =
18947 SemaRef.currentEvaluationContext();
18948
18949 if (Context.isUnevaluated())
18950 return OdrUseContext::None;
18951
18952 if (SemaRef.CurContext->isDependentContext())
18953 return OdrUseContext::Dependent;
18954
18955 if (Context.isDiscardedStatementContext())
18956 return OdrUseContext::FormallyOdrUsed;
18957
18958 else if (Context.Context ==
18959 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18960 return OdrUseContext::FormallyOdrUsed;
18961
18962 return OdrUseContext::Used;
18963}
18964
18965static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18966 if (!Func->isConstexpr())
18967 return false;
18968
18969 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18970 return true;
18971
18972 // Lambda conversion operators are never user provided.
18973 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
18974 return isLambdaConversionOperator(C: Conv);
18975
18976 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18977 return CCD && CCD->getInheritedConstructor();
18978}
18979
18980void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18981 bool MightBeOdrUse) {
18982 assert(Func && "No function?");
18983
18984 Func->setReferenced();
18985
18986 // Recursive functions aren't really used until they're used from some other
18987 // context.
18988 bool IsRecursiveCall = CurContext == Func;
18989
18990 // C++11 [basic.def.odr]p3:
18991 // A function whose name appears as a potentially-evaluated expression is
18992 // odr-used if it is the unique lookup result or the selected member of a
18993 // set of overloaded functions [...].
18994 //
18995 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18996 // can just check that here.
18997 OdrUseContext OdrUse =
18998 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18999 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19000 OdrUse = OdrUseContext::FormallyOdrUsed;
19001
19002 // Trivial default constructors and destructors are never actually used.
19003 // FIXME: What about other special members?
19004 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19005 OdrUse == OdrUseContext::Used) {
19006 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
19007 if (Constructor->isDefaultConstructor())
19008 OdrUse = OdrUseContext::FormallyOdrUsed;
19009 if (isa<CXXDestructorDecl>(Val: Func))
19010 OdrUse = OdrUseContext::FormallyOdrUsed;
19011 }
19012
19013 // C++20 [expr.const]p12:
19014 // A function [...] is needed for constant evaluation if it is [...] a
19015 // constexpr function that is named by an expression that is potentially
19016 // constant evaluated
19017 bool NeededForConstantEvaluation =
19018 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
19019 isImplicitlyDefinableConstexprFunction(Func);
19020
19021 // Determine whether we require a function definition to exist, per
19022 // C++11 [temp.inst]p3:
19023 // Unless a function template specialization has been explicitly
19024 // instantiated or explicitly specialized, the function template
19025 // specialization is implicitly instantiated when the specialization is
19026 // referenced in a context that requires a function definition to exist.
19027 // C++20 [temp.inst]p7:
19028 // The existence of a definition of a [...] function is considered to
19029 // affect the semantics of the program if the [...] function is needed for
19030 // constant evaluation by an expression
19031 // C++20 [basic.def.odr]p10:
19032 // Every program shall contain exactly one definition of every non-inline
19033 // function or variable that is odr-used in that program outside of a
19034 // discarded statement
19035 // C++20 [special]p1:
19036 // The implementation will implicitly define [defaulted special members]
19037 // if they are odr-used or needed for constant evaluation.
19038 //
19039 // Note that we skip the implicit instantiation of templates that are only
19040 // used in unused default arguments or by recursive calls to themselves.
19041 // This is formally non-conforming, but seems reasonable in practice.
19042 bool NeedDefinition =
19043 !IsRecursiveCall &&
19044 (OdrUse == OdrUseContext::Used ||
19045 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19046
19047 // C++14 [temp.expl.spec]p6:
19048 // If a template [...] is explicitly specialized then that specialization
19049 // shall be declared before the first use of that specialization that would
19050 // cause an implicit instantiation to take place, in every translation unit
19051 // in which such a use occurs
19052 if (NeedDefinition &&
19053 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19054 Func->getMemberSpecializationInfo()))
19055 checkSpecializationReachability(Loc, Spec: Func);
19056
19057 if (getLangOpts().CUDA)
19058 CUDA().CheckCall(Loc, Callee: Func);
19059
19060 // If we need a definition, try to create one.
19061 if (NeedDefinition && !Func->getBody()) {
19062 runWithSufficientStackSpace(Loc, Fn: [&] {
19063 if (CXXConstructorDecl *Constructor =
19064 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19065 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19066 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19067 if (Constructor->isDefaultConstructor()) {
19068 if (Constructor->isTrivial() &&
19069 !Constructor->hasAttr<DLLExportAttr>())
19070 return;
19071 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19072 } else if (Constructor->isCopyConstructor()) {
19073 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19074 } else if (Constructor->isMoveConstructor()) {
19075 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19076 }
19077 } else if (Constructor->getInheritedConstructor()) {
19078 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19079 }
19080 } else if (CXXDestructorDecl *Destructor =
19081 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19082 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19083 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19084 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19085 return;
19086 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19087 }
19088 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19089 MarkVTableUsed(Loc, Class: Destructor->getParent());
19090 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19091 if (MethodDecl->isOverloadedOperator() &&
19092 MethodDecl->getOverloadedOperator() == OO_Equal) {
19093 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19094 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19095 if (MethodDecl->isCopyAssignmentOperator())
19096 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19097 else if (MethodDecl->isMoveAssignmentOperator())
19098 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19099 }
19100 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19101 MethodDecl->getParent()->isLambda()) {
19102 CXXConversionDecl *Conversion =
19103 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19104 if (Conversion->isLambdaToBlockPointerConversion())
19105 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19106 else
19107 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19108 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19109 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19110 }
19111
19112 if (Func->isDefaulted() && !Func->isDeleted()) {
19113 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
19114 if (DCK != DefaultedComparisonKind::None)
19115 DefineDefaultedComparison(Loc, FD: Func, DCK);
19116 }
19117
19118 // Implicit instantiation of function templates and member functions of
19119 // class templates.
19120 if (Func->isImplicitlyInstantiable()) {
19121 TemplateSpecializationKind TSK =
19122 Func->getTemplateSpecializationKindForInstantiation();
19123 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19124 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19125 if (FirstInstantiation) {
19126 PointOfInstantiation = Loc;
19127 if (auto *MSI = Func->getMemberSpecializationInfo())
19128 MSI->setPointOfInstantiation(Loc);
19129 // FIXME: Notify listener.
19130 else
19131 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19132 } else if (TSK != TSK_ImplicitInstantiation) {
19133 // Use the point of use as the point of instantiation, instead of the
19134 // point of explicit instantiation (which we track as the actual point
19135 // of instantiation). This gives better backtraces in diagnostics.
19136 PointOfInstantiation = Loc;
19137 }
19138
19139 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19140 Func->isConstexpr()) {
19141 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19142 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19143 CodeSynthesisContexts.size())
19144 PendingLocalImplicitInstantiations.push_back(
19145 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19146 else if (Func->isConstexpr())
19147 // Do not defer instantiations of constexpr functions, to avoid the
19148 // expression evaluator needing to call back into Sema if it sees a
19149 // call to such a function.
19150 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19151 else {
19152 Func->setInstantiationIsPending(true);
19153 PendingInstantiations.push_back(
19154 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19155 if (llvm::isTimeTraceVerbose()) {
19156 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19157 std::string Name;
19158 llvm::raw_string_ostream OS(Name);
19159 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19160 /*Qualified=*/true);
19161 return Name;
19162 });
19163 }
19164 // Notify the consumer that a function was implicitly instantiated.
19165 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19166 }
19167 }
19168 } else {
19169 // Walk redefinitions, as some of them may be instantiable.
19170 for (auto *i : Func->redecls()) {
19171 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19172 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19173 }
19174 }
19175 });
19176 }
19177
19178 // If a constructor was defined in the context of a default parameter
19179 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19180 // context), its initializers may not be referenced yet.
19181 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19182 EnterExpressionEvaluationContext EvalContext(
19183 *this,
19184 Constructor->isImmediateFunction()
19185 ? ExpressionEvaluationContext::ImmediateFunctionContext
19186 : ExpressionEvaluationContext::PotentiallyEvaluated,
19187 Constructor);
19188 for (CXXCtorInitializer *Init : Constructor->inits()) {
19189 if (Init->isInClassMemberInitializer())
19190 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19191 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19192 });
19193 }
19194 }
19195
19196 // C++14 [except.spec]p17:
19197 // An exception-specification is considered to be needed when:
19198 // - the function is odr-used or, if it appears in an unevaluated operand,
19199 // would be odr-used if the expression were potentially-evaluated;
19200 //
19201 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19202 // function is a pure virtual function we're calling, and in that case the
19203 // function was selected by overload resolution and we need to resolve its
19204 // exception specification for a different reason.
19205 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19206 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19207 ResolveExceptionSpec(Loc, FPT);
19208
19209 // A callee could be called by a host function then by a device function.
19210 // If we only try recording once, we will miss recording the use on device
19211 // side. Therefore keep trying until it is recorded.
19212 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19213 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19214 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19215
19216 // If this is the first "real" use, act on that.
19217 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19218 // Keep track of used but undefined functions.
19219 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19220 if (mightHaveNonExternalLinkage(FD: Func))
19221 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19222 else if (Func->getMostRecentDecl()->isInlined() &&
19223 !LangOpts.GNUInline &&
19224 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19225 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19226 else if (isExternalWithNoLinkageType(VD: Func))
19227 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19228 }
19229
19230 // Some x86 Windows calling conventions mangle the size of the parameter
19231 // pack into the name. Computing the size of the parameters requires the
19232 // parameter types to be complete. Check that now.
19233 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19234 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19235
19236 // In the MS C++ ABI, the compiler emits destructor variants where they are
19237 // used. If the destructor is used here but defined elsewhere, mark the
19238 // virtual base destructors referenced. If those virtual base destructors
19239 // are inline, this will ensure they are defined when emitting the complete
19240 // destructor variant. This checking may be redundant if the destructor is
19241 // provided later in this TU.
19242 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19243 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19244 CXXRecordDecl *Parent = Dtor->getParent();
19245 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19246 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19247 }
19248 }
19249
19250 Func->markUsed(C&: Context);
19251 }
19252}
19253
19254/// Directly mark a variable odr-used. Given a choice, prefer to use
19255/// MarkVariableReferenced since it does additional checks and then
19256/// calls MarkVarDeclODRUsed.
19257/// If the variable must be captured:
19258/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19259/// - else capture it in the DeclContext that maps to the
19260/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19261static void
19262MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19263 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19264 // Keep track of used but undefined variables.
19265 // FIXME: We shouldn't suppress this warning for static data members.
19266 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19267 assert(Var && "expected a capturable variable");
19268
19269 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19270 (!Var->isExternallyVisible() || Var->isInline() ||
19271 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19272 !(Var->isStaticDataMember() && Var->hasInit())) {
19273 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19274 if (old.isInvalid())
19275 old = Loc;
19276 }
19277 QualType CaptureType, DeclRefType;
19278 if (SemaRef.LangOpts.OpenMP)
19279 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19280 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19281 /*EllipsisLoc*/ SourceLocation(),
19282 /*BuildAndDiagnose*/ true, CaptureType,
19283 DeclRefType, FunctionScopeIndexToStopAt);
19284
19285 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19286 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19287 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19288 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19289 if (VarTarget == SemaCUDA::CVT_Host &&
19290 (UserTarget == CUDAFunctionTarget::Device ||
19291 UserTarget == CUDAFunctionTarget::HostDevice ||
19292 UserTarget == CUDAFunctionTarget::Global)) {
19293 // Diagnose ODR-use of host global variables in device functions.
19294 // Reference of device global variables in host functions is allowed
19295 // through shadow variables therefore it is not diagnosed.
19296 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19297 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19298 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19299 SemaRef.targetDiag(Loc: Var->getLocation(),
19300 DiagID: Var->getType().isConstQualified()
19301 ? diag::note_cuda_const_var_unpromoted
19302 : diag::note_cuda_host_var);
19303 }
19304 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19305 // Also capture __device__ const variables, which are classified
19306 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19307 // an explicit CUDADeviceAttr to distinguish them from plain
19308 // const variables (no __device__), which also get CVT_Both but
19309 // only have an implicit CUDADeviceAttr.
19310 (VarTarget == SemaCUDA::CVT_Both &&
19311 Var->hasAttr<CUDADeviceAttr>() &&
19312 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19313 !Var->hasAttr<CUDASharedAttr>() &&
19314 (UserTarget == CUDAFunctionTarget::Host ||
19315 UserTarget == CUDAFunctionTarget::HostDevice)) {
19316 // Record a CUDA/HIP device side variable if it is ODR-used
19317 // by host code. This is done conservatively, when the variable is
19318 // referenced in any of the following contexts:
19319 // - a non-function context
19320 // - a host function
19321 // - a host device function
19322 // This makes the ODR-use of the device side variable by host code to
19323 // be visible in the device compilation for the compiler to be able to
19324 // emit template variables instantiated by host code only and to
19325 // externalize the static device side variable ODR-used by host code.
19326 if (!Var->hasExternalStorage())
19327 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19328 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19329 (!FD || (!FD->getDescribedFunctionTemplate() &&
19330 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19331 GVA_StrongExternal)))
19332 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19333 }
19334 }
19335
19336 V->markUsed(C&: SemaRef.Context);
19337}
19338
19339void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19340 SourceLocation Loc,
19341 unsigned CapturingScopeIndex) {
19342 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19343}
19344
19345static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19346 SourceLocation loc,
19347 ValueDecl *var) {
19348 DeclContext *VarDC = var->getDeclContext();
19349
19350 // If the parameter still belongs to the translation unit, then
19351 // we're actually just using one parameter in the declaration of
19352 // the next.
19353 if (isa<ParmVarDecl>(Val: var) &&
19354 isa<TranslationUnitDecl>(Val: VarDC))
19355 return;
19356
19357 // For C code, don't diagnose about capture if we're not actually in code
19358 // right now; it's impossible to write a non-constant expression outside of
19359 // function context, so we'll get other (more useful) diagnostics later.
19360 //
19361 // For C++, things get a bit more nasty... it would be nice to suppress this
19362 // diagnostic for certain cases like using a local variable in an array bound
19363 // for a member of a local class, but the correct predicate is not obvious.
19364 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19365 return;
19366
19367 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19368 unsigned ContextKind = 3; // unknown
19369 if (isa<CXXMethodDecl>(Val: VarDC) &&
19370 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19371 ContextKind = 2;
19372 } else if (isa<FunctionDecl>(Val: VarDC)) {
19373 ContextKind = 0;
19374 } else if (isa<BlockDecl>(Val: VarDC)) {
19375 ContextKind = 1;
19376 }
19377
19378 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19379 << var << ValueKind << ContextKind << VarDC;
19380 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19381 << var;
19382
19383 // FIXME: Add additional diagnostic info about class etc. which prevents
19384 // capture.
19385}
19386
19387static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19388 ValueDecl *Var,
19389 bool &SubCapturesAreNested,
19390 QualType &CaptureType,
19391 QualType &DeclRefType) {
19392 // Check whether we've already captured it.
19393 if (CSI->CaptureMap.count(Val: Var)) {
19394 // If we found a capture, any subcaptures are nested.
19395 SubCapturesAreNested = true;
19396
19397 // Retrieve the capture type for this variable.
19398 CaptureType = CSI->getCapture(Var).getCaptureType();
19399
19400 // Compute the type of an expression that refers to this variable.
19401 DeclRefType = CaptureType.getNonReferenceType();
19402
19403 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19404 // are mutable in the sense that user can change their value - they are
19405 // private instances of the captured declarations.
19406 const Capture &Cap = CSI->getCapture(Var);
19407 // C++ [expr.prim.lambda]p10:
19408 // The type of such a data member is [...] an lvalue reference to the
19409 // referenced function type if the entity is a reference to a function.
19410 // [...]
19411 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19412 !(isa<LambdaScopeInfo>(Val: CSI) &&
19413 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19414 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19415 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19416 DeclRefType.addConst();
19417 return true;
19418 }
19419 return false;
19420}
19421
19422// Only block literals, captured statements, and lambda expressions can
19423// capture; other scopes don't work.
19424static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19425 ValueDecl *Var,
19426 SourceLocation Loc,
19427 const bool Diagnose,
19428 Sema &S) {
19429 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19430 return getLambdaAwareParentOfDeclContext(DC);
19431
19432 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19433 if (Underlying) {
19434 if (Underlying->hasLocalStorage() && Diagnose)
19435 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19436 }
19437 return nullptr;
19438}
19439
19440// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19441// certain types of variables (unnamed, variably modified types etc.)
19442// so check for eligibility.
19443static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19444 SourceLocation Loc, const bool Diagnose,
19445 Sema &S) {
19446
19447 assert((isa<VarDecl, BindingDecl>(Var)) &&
19448 "Only variables and structured bindings can be captured");
19449
19450 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19451 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19452
19453 // Lambdas are not allowed to capture unnamed variables
19454 // (e.g. anonymous unions).
19455 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19456 // assuming that's the intent.
19457 if (IsLambda && !Var->getDeclName()) {
19458 if (Diagnose) {
19459 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19460 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19461 }
19462 return false;
19463 }
19464
19465 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19466 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19467 if (Diagnose) {
19468 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19469 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19470 }
19471 return false;
19472 }
19473 // Prohibit structs with flexible array members too.
19474 // We cannot capture what is in the tail end of the struct.
19475 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19476 VTD && VTD->hasFlexibleArrayMember()) {
19477 if (Diagnose) {
19478 if (IsBlock)
19479 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19480 else
19481 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19482 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19483 }
19484 return false;
19485 }
19486 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19487 // Lambdas and captured statements are not allowed to capture __block
19488 // variables; they don't support the expected semantics.
19489 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19490 if (Diagnose) {
19491 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19492 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19493 }
19494 return false;
19495 }
19496 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19497 if (S.getLangOpts().OpenCL && IsBlock &&
19498 Var->getType()->isBlockPointerType()) {
19499 if (Diagnose)
19500 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19501 return false;
19502 }
19503
19504 if (isa<BindingDecl>(Val: Var)) {
19505 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19506 if (Diagnose)
19507 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19508 return false;
19509 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19510 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19511 ? diag::warn_cxx17_compat_capture_binding
19512 : diag::ext_capture_binding)
19513 << Var;
19514 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19515 }
19516 }
19517
19518 return true;
19519}
19520
19521// Returns true if the capture by block was successful.
19522static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19523 SourceLocation Loc, const bool BuildAndDiagnose,
19524 QualType &CaptureType, QualType &DeclRefType,
19525 const bool Nested, Sema &S, bool Invalid) {
19526 bool ByRef = false;
19527
19528 // Blocks are not allowed to capture arrays, excepting OpenCL.
19529 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19530 // (decayed to pointers).
19531 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19532 if (BuildAndDiagnose) {
19533 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19534 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19535 Invalid = true;
19536 } else {
19537 return false;
19538 }
19539 }
19540
19541 // Forbid the block-capture of autoreleasing variables.
19542 if (!Invalid &&
19543 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19544 if (BuildAndDiagnose) {
19545 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19546 << /*block*/ 0;
19547 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19548 Invalid = true;
19549 } else {
19550 return false;
19551 }
19552 }
19553
19554 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19555 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19556 QualType PointeeTy = PT->getPointeeType();
19557
19558 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19559 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19560 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19561 if (BuildAndDiagnose) {
19562 SourceLocation VarLoc = Var->getLocation();
19563 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19564 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19565 }
19566 }
19567 }
19568
19569 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19570 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19571 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19572 // Block capture by reference does not change the capture or
19573 // declaration reference types.
19574 ByRef = true;
19575 } else {
19576 // Block capture by copy introduces 'const'.
19577 CaptureType = CaptureType.getNonReferenceType().withConst();
19578 DeclRefType = CaptureType;
19579 }
19580
19581 // Actually capture the variable.
19582 if (BuildAndDiagnose)
19583 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19584 CaptureType, Invalid);
19585
19586 return !Invalid;
19587}
19588
19589/// Capture the given variable in the captured region.
19590static bool captureInCapturedRegion(
19591 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19592 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19593 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19594 Sema &S, bool Invalid) {
19595 // By default, capture variables by reference.
19596 bool ByRef = true;
19597 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19598 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19599 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19600 // Using an LValue reference type is consistent with Lambdas (see below).
19601 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19602 bool HasConst = DeclRefType.isConstQualified();
19603 DeclRefType = DeclRefType.getUnqualifiedType();
19604 // Don't lose diagnostics about assignments to const.
19605 if (HasConst)
19606 DeclRefType.addConst();
19607 }
19608 // Do not capture firstprivates in tasks.
19609 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19610 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19611 return true;
19612 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19613 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19614 }
19615
19616 if (ByRef)
19617 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19618 else
19619 CaptureType = DeclRefType;
19620
19621 // Actually capture the variable.
19622 if (BuildAndDiagnose)
19623 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19624 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19625
19626 return !Invalid;
19627}
19628
19629/// Capture the given variable in the lambda.
19630static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19631 SourceLocation Loc, const bool BuildAndDiagnose,
19632 QualType &CaptureType, QualType &DeclRefType,
19633 const bool RefersToCapturedVariable,
19634 const TryCaptureKind Kind,
19635 SourceLocation EllipsisLoc, const bool IsTopScope,
19636 Sema &S, bool Invalid) {
19637 // Determine whether we are capturing by reference or by value.
19638 bool ByRef = false;
19639 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19640 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19641 } else {
19642 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19643 }
19644
19645 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19646 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19647 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19648 Invalid = true;
19649 }
19650
19651 // Compute the type of the field that will capture this variable.
19652 if (ByRef) {
19653 // C++11 [expr.prim.lambda]p15:
19654 // An entity is captured by reference if it is implicitly or
19655 // explicitly captured but not captured by copy. It is
19656 // unspecified whether additional unnamed non-static data
19657 // members are declared in the closure type for entities
19658 // captured by reference.
19659 //
19660 // FIXME: It is not clear whether we want to build an lvalue reference
19661 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19662 // to do the former, while EDG does the latter. Core issue 1249 will
19663 // clarify, but for now we follow GCC because it's a more permissive and
19664 // easily defensible position.
19665 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19666 } else {
19667 // C++11 [expr.prim.lambda]p14:
19668 // For each entity captured by copy, an unnamed non-static
19669 // data member is declared in the closure type. The
19670 // declaration order of these members is unspecified. The type
19671 // of such a data member is the type of the corresponding
19672 // captured entity if the entity is not a reference to an
19673 // object, or the referenced type otherwise. [Note: If the
19674 // captured entity is a reference to a function, the
19675 // corresponding data member is also a reference to a
19676 // function. - end note ]
19677 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19678 if (!RefType->getPointeeType()->isFunctionType())
19679 CaptureType = RefType->getPointeeType();
19680 }
19681
19682 // Forbid the lambda copy-capture of autoreleasing variables.
19683 if (!Invalid &&
19684 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19685 if (BuildAndDiagnose) {
19686 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19687 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19688 << Var->getDeclName();
19689 Invalid = true;
19690 } else {
19691 return false;
19692 }
19693 }
19694
19695 // Make sure that by-copy captures are of a complete and non-abstract type.
19696 if (!Invalid && BuildAndDiagnose) {
19697 if (!CaptureType->isDependentType() &&
19698 S.RequireCompleteSizedType(
19699 Loc, T: CaptureType,
19700 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19701 Args: Var->getDeclName()))
19702 Invalid = true;
19703 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19704 DiagID: diag::err_capture_of_abstract_type))
19705 Invalid = true;
19706 }
19707 }
19708
19709 // Compute the type of a reference to this captured variable.
19710 if (ByRef)
19711 DeclRefType = CaptureType.getNonReferenceType();
19712 else {
19713 // C++ [expr.prim.lambda]p5:
19714 // The closure type for a lambda-expression has a public inline
19715 // function call operator [...]. This function call operator is
19716 // declared const (9.3.1) if and only if the lambda-expression's
19717 // parameter-declaration-clause is not followed by mutable.
19718 DeclRefType = CaptureType.getNonReferenceType();
19719 bool Const = LSI->lambdaCaptureShouldBeConst();
19720 // C++ [expr.prim.lambda]p10:
19721 // The type of such a data member is [...] an lvalue reference to the
19722 // referenced function type if the entity is a reference to a function.
19723 // [...]
19724 if (Const && !CaptureType->isReferenceType() &&
19725 !DeclRefType->isFunctionType())
19726 DeclRefType.addConst();
19727 }
19728
19729 // Add the capture.
19730 if (BuildAndDiagnose)
19731 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19732 Loc, EllipsisLoc, CaptureType, Invalid);
19733
19734 return !Invalid;
19735}
19736
19737static bool canCaptureVariableByCopy(ValueDecl *Var,
19738 const ASTContext &Context) {
19739 // Offer a Copy fix even if the type is dependent.
19740 if (Var->getType()->isDependentType())
19741 return true;
19742 QualType T = Var->getType().getNonReferenceType();
19743 if (T.isTriviallyCopyableType(Context))
19744 return true;
19745 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19746
19747 if (!(RD = RD->getDefinition()))
19748 return false;
19749 if (RD->hasSimpleCopyConstructor())
19750 return true;
19751 if (RD->hasUserDeclaredCopyConstructor())
19752 for (CXXConstructorDecl *Ctor : RD->ctors())
19753 if (Ctor->isCopyConstructor())
19754 return !Ctor->isDeleted();
19755 }
19756 return false;
19757}
19758
19759/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19760/// default capture. Fixes may be omitted if they aren't allowed by the
19761/// standard, for example we can't emit a default copy capture fix-it if we
19762/// already explicitly copy capture capture another variable.
19763static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19764 ValueDecl *Var) {
19765 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19766 // Don't offer Capture by copy of default capture by copy fixes if Var is
19767 // known not to be copy constructible.
19768 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19769
19770 SmallString<32> FixBuffer;
19771 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19772 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19773 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19774 if (ShouldOfferCopyFix) {
19775 // Offer fixes to insert an explicit capture for the variable.
19776 // [] -> [VarName]
19777 // [OtherCapture] -> [OtherCapture, VarName]
19778 FixBuffer.assign(Refs: {Separator, Var->getName()});
19779 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19780 << Var << /*value*/ 0
19781 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19782 }
19783 // As above but capture by reference.
19784 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19785 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19786 << Var << /*reference*/ 1
19787 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19788 }
19789
19790 // Only try to offer default capture if there are no captures excluding this
19791 // and init captures.
19792 // [this]: OK.
19793 // [X = Y]: OK.
19794 // [&A, &B]: Don't offer.
19795 // [A, B]: Don't offer.
19796 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19797 return !C.isThisCapture() && !C.isInitCapture();
19798 }))
19799 return;
19800
19801 // The default capture specifiers, '=' or '&', must appear first in the
19802 // capture body.
19803 SourceLocation DefaultInsertLoc =
19804 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19805
19806 if (ShouldOfferCopyFix) {
19807 bool CanDefaultCopyCapture = true;
19808 // [=, *this] OK since c++17
19809 // [=, this] OK since c++20
19810 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19811 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19812 ? LSI->getCXXThisCapture().isCopyCapture()
19813 : false;
19814 // We can't use default capture by copy if any captures already specified
19815 // capture by copy.
19816 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19817 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19818 })) {
19819 FixBuffer.assign(Refs: {"=", Separator});
19820 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19821 << /*value*/ 0
19822 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19823 }
19824 }
19825
19826 // We can't use default capture by reference if any captures already specified
19827 // capture by reference.
19828 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19829 return !C.isInitCapture() && C.isReferenceCapture() &&
19830 !C.isThisCapture();
19831 })) {
19832 FixBuffer.assign(Refs: {"&", Separator});
19833 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19834 << /*reference*/ 1
19835 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19836 }
19837}
19838
19839bool Sema::tryCaptureVariable(
19840 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19841 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19842 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19843 // An init-capture is notionally from the context surrounding its
19844 // declaration, but its parent DC is the lambda class.
19845 DeclContext *VarDC =
19846 Var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19847 DeclContext *DC = CurContext;
19848
19849 // Skip past RequiresExprBodys because they don't constitute function scopes.
19850 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
19851 DC = DC->getParent();
19852
19853 // tryCaptureVariable is called every time a DeclRef is formed,
19854 // it can therefore have non-negigible impact on performances.
19855 // For local variables and when there is no capturing scope,
19856 // we can bailout early.
19857 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19858 return true;
19859
19860 // Exception: Function parameters are not tied to the function's DeclContext
19861 // until we enter the function definition. Capturing them anyway would result
19862 // in an out-of-bounds error while traversing DC and its parents.
19863 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19864 return true;
19865
19866 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19867 if (VD) {
19868 if (VD->isInitCapture())
19869 VarDC = VarDC->getParent();
19870 } else {
19871 VD = Var->getPotentiallyDecomposedVarDecl();
19872 }
19873 assert(VD && "Cannot capture a null variable");
19874
19875 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19876 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19877 // We need to sync up the Declaration Context with the
19878 // FunctionScopeIndexToStopAt
19879 if (FunctionScopeIndexToStopAt) {
19880 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19881 unsigned FSIndex = FunctionScopes.size() - 1;
19882 // When we're parsing the lambda parameter list, the current DeclContext is
19883 // NOT the lambda but its parent. So move away the current LSI before
19884 // aligning DC and FunctionScopeIndexToStopAt.
19885 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19886 FSIndex && LSI && !LSI->AfterParameterList)
19887 --FSIndex;
19888 assert(MaxFunctionScopesIndex <= FSIndex &&
19889 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19890 "FunctionScopes.");
19891 while (FSIndex != MaxFunctionScopesIndex) {
19892 DC = getLambdaAwareParentOfDeclContext(DC);
19893 --FSIndex;
19894 }
19895 }
19896
19897 // Capture global variables if it is required to use private copy of this
19898 // variable.
19899 bool IsGlobal = !VD->hasLocalStorage();
19900 if (IsGlobal && !(LangOpts.OpenMP &&
19901 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19902 StopAt: MaxFunctionScopesIndex)))
19903 return true;
19904
19905 if (isa<VarDecl>(Val: Var))
19906 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19907
19908 // Walk up the stack to determine whether we can capture the variable,
19909 // performing the "simple" checks that don't depend on type. We stop when
19910 // we've either hit the declared scope of the variable or find an existing
19911 // capture of that variable. We start from the innermost capturing-entity
19912 // (the DC) and ensure that all intervening capturing-entities
19913 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19914 // declcontext can either capture the variable or have already captured
19915 // the variable.
19916 CaptureType = Var->getType();
19917 DeclRefType = CaptureType.getNonReferenceType();
19918 bool Nested = false;
19919 bool Explicit = (Kind != TryCaptureKind::Implicit);
19920 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19921 do {
19922
19923 LambdaScopeInfo *LSI = nullptr;
19924 if (!FunctionScopes.empty())
19925 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19926 Val: FunctionScopes[FunctionScopesIndex]);
19927
19928 bool IsInScopeDeclarationContext =
19929 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19930
19931 if (LSI && !LSI->AfterParameterList) {
19932 // This allows capturing parameters from a default value which does not
19933 // seems correct
19934 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19935 return true;
19936 }
19937 // If the variable is declared in the current context, there is no need to
19938 // capture it.
19939 if (IsInScopeDeclarationContext &&
19940 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19941 return true;
19942
19943 // Only block literals, captured statements, and lambda expressions can
19944 // capture; other scopes don't work.
19945 DeclContext *ParentDC =
19946 !IsInScopeDeclarationContext
19947 ? DC->getParent()
19948 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19949 Diagnose: BuildAndDiagnose, S&: *this);
19950 // We need to check for the parent *first* because, if we *have*
19951 // private-captured a global variable, we need to recursively capture it in
19952 // intermediate blocks, lambdas, etc.
19953 if (!ParentDC) {
19954 if (IsGlobal) {
19955 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19956 break;
19957 }
19958 return true;
19959 }
19960
19961 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19962 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19963
19964 // Check whether we've already captured it.
19965 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19966 DeclRefType)) {
19967 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19968 break;
19969 }
19970
19971 // When evaluating some attributes (like enable_if) we might refer to a
19972 // function parameter appertaining to the same declaration as that
19973 // attribute.
19974 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19975 Parm && Parm->getDeclContext() == DC)
19976 return true;
19977
19978 // If we are instantiating a generic lambda call operator body,
19979 // we do not want to capture new variables. What was captured
19980 // during either a lambdas transformation or initial parsing
19981 // should be used.
19982 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19983 if (BuildAndDiagnose) {
19984 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19985 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19986 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19987 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19988 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19989 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19990 } else
19991 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19992 }
19993 return true;
19994 }
19995
19996 // Try to capture variable-length arrays types.
19997 if (Var->getType()->isVariablyModifiedType()) {
19998 // We're going to walk down into the type and look for VLA
19999 // expressions.
20000 QualType QTy = Var->getType();
20001 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20002 QTy = PVD->getOriginalType();
20003 captureVariablyModifiedType(Context, T: QTy, CSI);
20004 }
20005
20006 if (getLangOpts().OpenMP) {
20007 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20008 // OpenMP private variables should not be captured in outer scope, so
20009 // just break here. Similarly, global variables that are captured in a
20010 // target region should not be captured outside the scope of the region.
20011 if (RSI->CapRegionKind == CR_OpenMP) {
20012 // FIXME: We should support capturing structured bindings in OpenMP.
20013 if (isa<BindingDecl>(Val: Var)) {
20014 if (BuildAndDiagnose) {
20015 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
20016 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
20017 }
20018 return true;
20019 }
20020 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20021 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
20022 // If the variable is private (i.e. not captured) and has variably
20023 // modified type, we still need to capture the type for correct
20024 // codegen in all regions, associated with the construct. Currently,
20025 // it is captured in the innermost captured region only.
20026 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20027 Var->getType()->isVariablyModifiedType()) {
20028 QualType QTy = Var->getType();
20029 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20030 QTy = PVD->getOriginalType();
20031 for (int I = 1,
20032 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
20033 I < E; ++I) {
20034 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20035 Val: FunctionScopes[FunctionScopesIndex - I]);
20036 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20037 "Wrong number of captured regions associated with the "
20038 "OpenMP construct.");
20039 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
20040 }
20041 }
20042 bool IsTargetCap =
20043 IsOpenMPPrivateDecl != OMPC_private &&
20044 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
20045 CaptureLevel: RSI->OpenMPCaptureLevel);
20046 // Do not capture global if it is not privatized in outer regions.
20047 bool IsGlobalCap =
20048 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20049 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
20050
20051 // When we detect target captures we are looking from inside the
20052 // target region, therefore we need to propagate the capture from the
20053 // enclosing region. Therefore, the capture is not initially nested.
20054 if (IsTargetCap)
20055 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20056 Level: RSI->OpenMPLevel);
20057
20058 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20059 (IsGlobal && !IsGlobalCap)) {
20060 Nested = !IsTargetCap;
20061 bool HasConst = DeclRefType.isConstQualified();
20062 DeclRefType = DeclRefType.getUnqualifiedType();
20063 // Don't lose diagnostics about assignments to const.
20064 if (HasConst)
20065 DeclRefType.addConst();
20066 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20067 break;
20068 }
20069 }
20070 }
20071 }
20072 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20073 // No capture-default, and this is not an explicit capture
20074 // so cannot capture this variable.
20075 if (BuildAndDiagnose) {
20076 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20077 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20078 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20079 if (LSI->Lambda) {
20080 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20081 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20082 }
20083 // FIXME: If we error out because an outer lambda can not implicitly
20084 // capture a variable that an inner lambda explicitly captures, we
20085 // should have the inner lambda do the explicit capture - because
20086 // it makes for cleaner diagnostics later. This would purely be done
20087 // so that the diagnostic does not misleadingly claim that a variable
20088 // can not be captured by a lambda implicitly even though it is captured
20089 // explicitly. Suggestion:
20090 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20091 // at the function head
20092 // - cache the StartingDeclContext - this must be a lambda
20093 // - captureInLambda in the innermost lambda the variable.
20094 }
20095 return true;
20096 }
20097 Explicit = false;
20098 FunctionScopesIndex--;
20099 if (IsInScopeDeclarationContext)
20100 DC = ParentDC;
20101 } while (!VarDC->Equals(DC));
20102
20103 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20104 // computing the type of the capture at each step, checking type-specific
20105 // requirements, and adding captures if requested.
20106 // If the variable had already been captured previously, we start capturing
20107 // at the lambda nested within that one.
20108 bool Invalid = false;
20109 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20110 ++I) {
20111 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20112
20113 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20114 // certain types of variables (unnamed, variably modified types etc.)
20115 // so check for eligibility.
20116 if (!Invalid)
20117 Invalid =
20118 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20119
20120 // After encountering an error, if we're actually supposed to capture, keep
20121 // capturing in nested contexts to suppress any follow-on diagnostics.
20122 if (Invalid && !BuildAndDiagnose)
20123 return true;
20124
20125 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20126 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20127 DeclRefType, Nested, S&: *this, Invalid);
20128 Nested = true;
20129 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20130 Invalid = !captureInCapturedRegion(
20131 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20132 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20133 Nested = true;
20134 } else {
20135 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20136 Invalid =
20137 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20138 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20139 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20140 Nested = true;
20141 }
20142
20143 if (Invalid && !BuildAndDiagnose)
20144 return true;
20145 }
20146 return Invalid;
20147}
20148
20149bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20150 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20151 QualType CaptureType;
20152 QualType DeclRefType;
20153 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20154 /*BuildAndDiagnose=*/true, CaptureType,
20155 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20156}
20157
20158bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20159 QualType CaptureType;
20160 QualType DeclRefType;
20161 return !tryCaptureVariable(
20162 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20163 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20164}
20165
20166QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20167 assert(Var && "Null value cannot be captured");
20168
20169 QualType CaptureType;
20170 QualType DeclRefType;
20171
20172 // Determine whether we can capture this variable.
20173 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20174 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20175 FunctionScopeIndexToStopAt: nullptr))
20176 return QualType();
20177
20178 return DeclRefType;
20179}
20180
20181namespace {
20182// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20183// The produced TemplateArgumentListInfo* points to data stored within this
20184// object, so should only be used in contexts where the pointer will not be
20185// used after the CopiedTemplateArgs object is destroyed.
20186class CopiedTemplateArgs {
20187 bool HasArgs;
20188 TemplateArgumentListInfo TemplateArgStorage;
20189public:
20190 template<typename RefExpr>
20191 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20192 if (HasArgs)
20193 E->copyTemplateArgumentsInto(TemplateArgStorage);
20194 }
20195 operator TemplateArgumentListInfo*()
20196#ifdef __has_cpp_attribute
20197#if __has_cpp_attribute(clang::lifetimebound)
20198 [[clang::lifetimebound]]
20199#endif
20200#endif
20201 {
20202 return HasArgs ? &TemplateArgStorage : nullptr;
20203 }
20204};
20205}
20206
20207/// Walk the set of potential results of an expression and mark them all as
20208/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20209///
20210/// \return A new expression if we found any potential results, ExprEmpty() if
20211/// not, and ExprError() if we diagnosed an error.
20212static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20213 NonOdrUseReason NOUR) {
20214 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20215 // an object that satisfies the requirements for appearing in a
20216 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20217 // is immediately applied." This function handles the lvalue-to-rvalue
20218 // conversion part.
20219 //
20220 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20221 // transform it into the relevant kind of non-odr-use node and rebuild the
20222 // tree of nodes leading to it.
20223 //
20224 // This is a mini-TreeTransform that only transforms a restricted subset of
20225 // nodes (and only certain operands of them).
20226
20227 // Rebuild a subexpression.
20228 auto Rebuild = [&](Expr *Sub) {
20229 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20230 };
20231
20232 // Check whether a potential result satisfies the requirements of NOUR.
20233 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20234 // Any entity other than a VarDecl is always odr-used whenever it's named
20235 // in a potentially-evaluated expression.
20236 auto *VD = dyn_cast<VarDecl>(Val: D);
20237 if (!VD)
20238 return true;
20239
20240 // C++2a [basic.def.odr]p4:
20241 // A variable x whose name appears as a potentially-evalauted expression
20242 // e is odr-used by e unless
20243 // -- x is a reference that is usable in constant expressions, or
20244 // -- x is a variable of non-reference type that is usable in constant
20245 // expressions and has no mutable subobjects, and e is an element of
20246 // the set of potential results of an expression of
20247 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20248 // conversion is applied, or
20249 // -- x is a variable of non-reference type, and e is an element of the
20250 // set of potential results of a discarded-value expression to which
20251 // the lvalue-to-rvalue conversion is not applied
20252 //
20253 // We check the first bullet and the "potentially-evaluated" condition in
20254 // BuildDeclRefExpr. We check the type requirements in the second bullet
20255 // in CheckLValueToRValueConversionOperand below.
20256 switch (NOUR) {
20257 case NOUR_None:
20258 case NOUR_Unevaluated:
20259 llvm_unreachable("unexpected non-odr-use-reason");
20260
20261 case NOUR_Constant:
20262 // Constant references were handled when they were built.
20263 if (VD->getType()->isReferenceType())
20264 return true;
20265 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20266 if (RD->hasDefinition() && RD->hasMutableFields())
20267 return true;
20268 if (!VD->isUsableInConstantExpressions(C: S.Context))
20269 return true;
20270 break;
20271
20272 case NOUR_Discarded:
20273 if (VD->getType()->isReferenceType())
20274 return true;
20275 break;
20276 }
20277 return false;
20278 };
20279
20280 // Check whether this expression may be odr-used in CUDA/HIP.
20281 auto MaybeCUDAODRUsed = [&]() -> bool {
20282 if (!S.LangOpts.CUDA)
20283 return false;
20284 LambdaScopeInfo *LSI = S.getCurLambda();
20285 if (!LSI)
20286 return false;
20287 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20288 if (!DRE)
20289 return false;
20290 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20291 if (!VD)
20292 return false;
20293 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20294 };
20295
20296 // Mark that this expression does not constitute an odr-use.
20297 auto MarkNotOdrUsed = [&] {
20298 if (!MaybeCUDAODRUsed()) {
20299 S.MaybeODRUseExprs.remove(X: E);
20300 if (LambdaScopeInfo *LSI = S.getCurLambda())
20301 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20302 }
20303 };
20304
20305 // C++2a [basic.def.odr]p2:
20306 // The set of potential results of an expression e is defined as follows:
20307 switch (E->getStmtClass()) {
20308 // -- If e is an id-expression, ...
20309 case Expr::DeclRefExprClass: {
20310 auto *DRE = cast<DeclRefExpr>(Val: E);
20311 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20312 break;
20313
20314 // Rebuild as a non-odr-use DeclRefExpr.
20315 MarkNotOdrUsed();
20316 return DeclRefExpr::Create(
20317 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20318 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20319 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20320 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20321 }
20322
20323 case Expr::FunctionParmPackExprClass: {
20324 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20325 // If any of the declarations in the pack is odr-used, then the expression
20326 // as a whole constitutes an odr-use.
20327 for (ValueDecl *D : *FPPE)
20328 if (IsPotentialResultOdrUsed(D))
20329 return ExprEmpty();
20330
20331 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20332 // nothing cares about whether we marked this as an odr-use, but it might
20333 // be useful for non-compiler tools.
20334 MarkNotOdrUsed();
20335 break;
20336 }
20337
20338 // -- If e is a subscripting operation with an array operand...
20339 case Expr::ArraySubscriptExprClass: {
20340 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20341 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20342 if (!OldBase->getType()->isArrayType())
20343 break;
20344 ExprResult Base = Rebuild(OldBase);
20345 if (!Base.isUsable())
20346 return Base;
20347 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20348 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20349 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20350 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20351 rbLoc: ASE->getRBracketLoc());
20352 }
20353
20354 case Expr::MemberExprClass: {
20355 auto *ME = cast<MemberExpr>(Val: E);
20356 // -- If e is a class member access expression [...] naming a non-static
20357 // data member...
20358 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20359 ExprResult Base = Rebuild(ME->getBase());
20360 if (!Base.isUsable())
20361 return Base;
20362 return MemberExpr::Create(
20363 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20364 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20365 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20366 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20367 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20368 }
20369
20370 if (ME->getMemberDecl()->isCXXInstanceMember())
20371 break;
20372
20373 // -- If e is a class member access expression naming a static data member,
20374 // ...
20375 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20376 break;
20377
20378 // Rebuild as a non-odr-use MemberExpr.
20379 MarkNotOdrUsed();
20380 return MemberExpr::Create(
20381 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20382 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20383 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20384 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20385 }
20386
20387 case Expr::BinaryOperatorClass: {
20388 auto *BO = cast<BinaryOperator>(Val: E);
20389 Expr *LHS = BO->getLHS();
20390 Expr *RHS = BO->getRHS();
20391 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20392 if (BO->getOpcode() == BO_PtrMemD) {
20393 ExprResult Sub = Rebuild(LHS);
20394 if (!Sub.isUsable())
20395 return Sub;
20396 BO->setLHS(Sub.get());
20397 // -- If e is a comma expression, ...
20398 } else if (BO->getOpcode() == BO_Comma) {
20399 ExprResult Sub = Rebuild(RHS);
20400 if (!Sub.isUsable())
20401 return Sub;
20402 BO->setRHS(Sub.get());
20403 } else {
20404 break;
20405 }
20406 return ExprResult(BO);
20407 }
20408
20409 // -- If e has the form (e1)...
20410 case Expr::ParenExprClass: {
20411 auto *PE = cast<ParenExpr>(Val: E);
20412 ExprResult Sub = Rebuild(PE->getSubExpr());
20413 if (!Sub.isUsable())
20414 return Sub;
20415 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20416 }
20417
20418 // -- If e is a glvalue conditional expression, ...
20419 // We don't apply this to a binary conditional operator. FIXME: Should we?
20420 case Expr::ConditionalOperatorClass: {
20421 auto *CO = cast<ConditionalOperator>(Val: E);
20422 ExprResult LHS = Rebuild(CO->getLHS());
20423 if (LHS.isInvalid())
20424 return ExprError();
20425 ExprResult RHS = Rebuild(CO->getRHS());
20426 if (RHS.isInvalid())
20427 return ExprError();
20428 if (!LHS.isUsable() && !RHS.isUsable())
20429 return ExprEmpty();
20430 if (!LHS.isUsable())
20431 LHS = CO->getLHS();
20432 if (!RHS.isUsable())
20433 RHS = CO->getRHS();
20434 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20435 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20436 }
20437
20438 // [Clang extension]
20439 // -- If e has the form __extension__ e1...
20440 case Expr::UnaryOperatorClass: {
20441 auto *UO = cast<UnaryOperator>(Val: E);
20442 if (UO->getOpcode() != UO_Extension)
20443 break;
20444 ExprResult Sub = Rebuild(UO->getSubExpr());
20445 if (!Sub.isUsable())
20446 return Sub;
20447 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20448 Input: Sub.get());
20449 }
20450
20451 // [Clang extension]
20452 // -- If e has the form _Generic(...), the set of potential results is the
20453 // union of the sets of potential results of the associated expressions.
20454 case Expr::GenericSelectionExprClass: {
20455 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20456
20457 SmallVector<Expr *, 4> AssocExprs;
20458 bool AnyChanged = false;
20459 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20460 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20461 if (AssocExpr.isInvalid())
20462 return ExprError();
20463 if (AssocExpr.isUsable()) {
20464 AssocExprs.push_back(Elt: AssocExpr.get());
20465 AnyChanged = true;
20466 } else {
20467 AssocExprs.push_back(Elt: OrigAssocExpr);
20468 }
20469 }
20470
20471 void *ExOrTy = nullptr;
20472 bool IsExpr = GSE->isExprPredicate();
20473 if (IsExpr)
20474 ExOrTy = GSE->getControllingExpr();
20475 else
20476 ExOrTy = GSE->getControllingType();
20477 return AnyChanged ? S.CreateGenericSelectionExpr(
20478 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20479 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20480 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20481 : ExprEmpty();
20482 }
20483
20484 // [Clang extension]
20485 // -- If e has the form __builtin_choose_expr(...), the set of potential
20486 // results is the union of the sets of potential results of the
20487 // second and third subexpressions.
20488 case Expr::ChooseExprClass: {
20489 auto *CE = cast<ChooseExpr>(Val: E);
20490
20491 ExprResult LHS = Rebuild(CE->getLHS());
20492 if (LHS.isInvalid())
20493 return ExprError();
20494
20495 ExprResult RHS = Rebuild(CE->getLHS());
20496 if (RHS.isInvalid())
20497 return ExprError();
20498
20499 if (!LHS.get() && !RHS.get())
20500 return ExprEmpty();
20501 if (!LHS.isUsable())
20502 LHS = CE->getLHS();
20503 if (!RHS.isUsable())
20504 RHS = CE->getRHS();
20505
20506 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20507 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20508 }
20509
20510 // Step through non-syntactic nodes.
20511 case Expr::ConstantExprClass: {
20512 auto *CE = cast<ConstantExpr>(Val: E);
20513 ExprResult Sub = Rebuild(CE->getSubExpr());
20514 if (!Sub.isUsable())
20515 return Sub;
20516 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20517 }
20518
20519 // We could mostly rely on the recursive rebuilding to rebuild implicit
20520 // casts, but not at the top level, so rebuild them here.
20521 case Expr::ImplicitCastExprClass: {
20522 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20523 // Only step through the narrow set of cast kinds we expect to encounter.
20524 // Anything else suggests we've left the region in which potential results
20525 // can be found.
20526 switch (ICE->getCastKind()) {
20527 case CK_NoOp:
20528 case CK_DerivedToBase:
20529 case CK_UncheckedDerivedToBase: {
20530 ExprResult Sub = Rebuild(ICE->getSubExpr());
20531 if (!Sub.isUsable())
20532 return Sub;
20533 CXXCastPath Path(ICE->path());
20534 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20535 VK: ICE->getValueKind(), BasePath: &Path);
20536 }
20537
20538 default:
20539 break;
20540 }
20541 break;
20542 }
20543
20544 default:
20545 break;
20546 }
20547
20548 // Can't traverse through this node. Nothing to do.
20549 return ExprEmpty();
20550}
20551
20552ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20553 // Check whether the operand is or contains an object of non-trivial C union
20554 // type.
20555 if (E->getType().isVolatileQualified() &&
20556 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20557 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20558 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20559 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20560 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20561
20562 // C++2a [basic.def.odr]p4:
20563 // [...] an expression of non-volatile-qualified non-class type to which
20564 // the lvalue-to-rvalue conversion is applied [...]
20565 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20566 return E;
20567
20568 ExprResult Result =
20569 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20570 if (Result.isInvalid())
20571 return ExprError();
20572 return Result.get() ? Result : E;
20573}
20574
20575ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20576 if (!Res.isUsable())
20577 return Res;
20578
20579 // If a constant-expression is a reference to a variable where we delay
20580 // deciding whether it is an odr-use, just assume we will apply the
20581 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20582 // (a non-type template argument), we have special handling anyway.
20583 return CheckLValueToRValueConversionOperand(E: Res.get());
20584}
20585
20586void Sema::CleanupVarDeclMarking() {
20587 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20588 // call.
20589 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20590 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20591
20592 for (Expr *E : LocalMaybeODRUseExprs) {
20593 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20594 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20595 Loc: DRE->getLocation(), SemaRef&: *this);
20596 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20597 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20598 SemaRef&: *this);
20599 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20600 for (ValueDecl *VD : *FP)
20601 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20602 } else {
20603 llvm_unreachable("Unexpected expression");
20604 }
20605 }
20606
20607 assert(MaybeODRUseExprs.empty() &&
20608 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20609}
20610
20611static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20612 ValueDecl *Var, Expr *E) {
20613 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20614 if (!VD)
20615 return;
20616
20617 const bool RefersToEnclosingScope =
20618 (SemaRef.CurContext != VD->getDeclContext() &&
20619 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20620 if (RefersToEnclosingScope) {
20621 LambdaScopeInfo *const LSI =
20622 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20623 if (LSI && (!LSI->CallOperator ||
20624 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20625 // If a variable could potentially be odr-used, defer marking it so
20626 // until we finish analyzing the full expression for any
20627 // lvalue-to-rvalue
20628 // or discarded value conversions that would obviate odr-use.
20629 // Add it to the list of potential captures that will be analyzed
20630 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20631 // unless the variable is a reference that was initialized by a constant
20632 // expression (this will never need to be captured or odr-used).
20633 //
20634 // FIXME: We can simplify this a lot after implementing P0588R1.
20635 assert(E && "Capture variable should be used in an expression.");
20636 if (!Var->getType()->isReferenceType() ||
20637 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20638 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20639 }
20640 }
20641}
20642
20643static void DoMarkVarDeclReferenced(
20644 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20645 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20646 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20647 isa<FunctionParmPackExpr>(E)) &&
20648 "Invalid Expr argument to DoMarkVarDeclReferenced");
20649 Var->setReferenced();
20650
20651 if (Var->isInvalidDecl())
20652 return;
20653
20654 auto *MSI = Var->getMemberSpecializationInfo();
20655 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20656 : Var->getTemplateSpecializationKind();
20657
20658 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20659 bool UsableInConstantExpr =
20660 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20661
20662 // Only track variables with internal linkage or local scope.
20663 // Use canonical decl so in-class declarations and out-of-class definitions
20664 // of static data members in anonymous namespaces are tracked as a single
20665 // entry.
20666 const VarDecl *CanonVar = Var->getCanonicalDecl();
20667 if ((CanonVar->isLocalVarDeclOrParm() ||
20668 CanonVar->isInternalLinkageFileVar()) &&
20669 !CanonVar->hasExternalStorage()) {
20670 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20671 }
20672
20673 // C++20 [expr.const]p12:
20674 // A variable [...] is needed for constant evaluation if it is [...] a
20675 // variable whose name appears as a potentially constant evaluated
20676 // expression that is either a contexpr variable or is of non-volatile
20677 // const-qualified integral type or of reference type
20678 bool NeededForConstantEvaluation =
20679 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20680
20681 bool NeedDefinition =
20682 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20683 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20684 Var->getType()->isUndeducedType());
20685
20686 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20687 "Can't instantiate a partial template specialization.");
20688
20689 // If this might be a member specialization of a static data member, check
20690 // the specialization is visible. We already did the checks for variable
20691 // template specializations when we created them.
20692 if (NeedDefinition && TSK != TSK_Undeclared &&
20693 !isa<VarTemplateSpecializationDecl>(Val: Var))
20694 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20695
20696 // Perform implicit instantiation of static data members, static data member
20697 // templates of class templates, and variable template specializations. Delay
20698 // instantiations of variable templates, except for those that could be used
20699 // in a constant expression.
20700 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20701 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20702 // instantiation declaration if a variable is usable in a constant
20703 // expression (among other cases).
20704 bool TryInstantiating =
20705 TSK == TSK_ImplicitInstantiation ||
20706 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20707
20708 if (TryInstantiating) {
20709 SourceLocation PointOfInstantiation =
20710 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20711 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20712 if (FirstInstantiation) {
20713 PointOfInstantiation = Loc;
20714 if (MSI)
20715 MSI->setPointOfInstantiation(PointOfInstantiation);
20716 // FIXME: Notify listener.
20717 else
20718 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20719 }
20720
20721 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20722 // Do not defer instantiations of variables that could be used in a
20723 // constant expression.
20724 // The type deduction also needs a complete initializer.
20725 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20726 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20727 });
20728
20729 // The size of an incomplete array type can be updated by
20730 // instantiating the initializer. The DeclRefExpr's type should be
20731 // updated accordingly too, or users of it would be confused!
20732 if (E)
20733 SemaRef.getCompletedType(E);
20734
20735 // Re-set the member to trigger a recomputation of the dependence bits
20736 // for the expression.
20737 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20738 DRE->setDecl(DRE->getDecl());
20739 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20740 ME->setMemberDecl(ME->getMemberDecl());
20741 } else if (FirstInstantiation) {
20742 SemaRef.PendingInstantiations
20743 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20744 } else {
20745 bool Inserted = false;
20746 for (auto &I : SemaRef.SavedPendingInstantiations) {
20747 auto Iter = llvm::find_if(
20748 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20749 return P.first == Var;
20750 });
20751 if (Iter != I.end()) {
20752 SemaRef.PendingInstantiations.push_back(x: *Iter);
20753 I.erase(position: Iter);
20754 Inserted = true;
20755 break;
20756 }
20757 }
20758
20759 // FIXME: For a specialization of a variable template, we don't
20760 // distinguish between "declaration and type implicitly instantiated"
20761 // and "implicit instantiation of definition requested", so we have
20762 // no direct way to avoid enqueueing the pending instantiation
20763 // multiple times.
20764 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20765 SemaRef.PendingInstantiations
20766 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20767 }
20768 }
20769 }
20770
20771 // C++2a [basic.def.odr]p4:
20772 // A variable x whose name appears as a potentially-evaluated expression e
20773 // is odr-used by e unless
20774 // -- x is a reference that is usable in constant expressions
20775 // -- x is a variable of non-reference type that is usable in constant
20776 // expressions and has no mutable subobjects [FIXME], and e is an
20777 // element of the set of potential results of an expression of
20778 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20779 // conversion is applied
20780 // -- x is a variable of non-reference type, and e is an element of the set
20781 // of potential results of a discarded-value expression to which the
20782 // lvalue-to-rvalue conversion is not applied [FIXME]
20783 //
20784 // We check the first part of the second bullet here, and
20785 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20786 // FIXME: To get the third bullet right, we need to delay this even for
20787 // variables that are not usable in constant expressions.
20788
20789 // If we already know this isn't an odr-use, there's nothing more to do.
20790 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20791 if (DRE->isNonOdrUse())
20792 return;
20793 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20794 if (ME->isNonOdrUse())
20795 return;
20796
20797 switch (OdrUse) {
20798 case OdrUseContext::None:
20799 // In some cases, a variable may not have been marked unevaluated, if it
20800 // appears in a defaukt initializer.
20801 assert((!E || isa<FunctionParmPackExpr>(E) ||
20802 SemaRef.isUnevaluatedContext()) &&
20803 "missing non-odr-use marking for unevaluated decl ref");
20804 break;
20805
20806 case OdrUseContext::FormallyOdrUsed:
20807 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20808 // behavior.
20809 break;
20810
20811 case OdrUseContext::Used:
20812 // If we might later find that this expression isn't actually an odr-use,
20813 // delay the marking.
20814 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20815 SemaRef.MaybeODRUseExprs.insert(X: E);
20816 else
20817 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20818 break;
20819
20820 case OdrUseContext::Dependent:
20821 // If this is a dependent context, we don't need to mark variables as
20822 // odr-used, but we may still need to track them for lambda capture.
20823 // FIXME: Do we also need to do this inside dependent typeid expressions
20824 // (which are modeled as unevaluated at this point)?
20825 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20826 break;
20827 }
20828}
20829
20830static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20831 BindingDecl *BD, Expr *E) {
20832 BD->setReferenced();
20833
20834 if (BD->isInvalidDecl())
20835 return;
20836
20837 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20838 if (OdrUse == OdrUseContext::Used) {
20839 QualType CaptureType, DeclRefType;
20840 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20841 /*EllipsisLoc*/ SourceLocation(),
20842 /*BuildAndDiagnose*/ true, CaptureType,
20843 DeclRefType,
20844 /*FunctionScopeIndexToStopAt*/ nullptr);
20845 } else if (OdrUse == OdrUseContext::Dependent) {
20846 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20847 }
20848}
20849
20850void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20851 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20852}
20853
20854// C++ [temp.dep.expr]p3:
20855// An id-expression is type-dependent if it contains:
20856// - an identifier associated by name lookup with an entity captured by copy
20857// in a lambda-expression that has an explicit object parameter whose type
20858// is dependent ([dcl.fct]),
20859static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20860 Sema &SemaRef, ValueDecl *D, Expr *E) {
20861 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20862 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20863 return;
20864
20865 // If any enclosing lambda with a dependent explicit object parameter either
20866 // explicitly captures the variable by value, or has a capture default of '='
20867 // and does not capture the variable by reference, then the type of the DRE
20868 // is dependent on the type of that lambda's explicit object parameter.
20869 auto IsDependent = [&]() {
20870 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20871 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20872 if (!LSI)
20873 continue;
20874
20875 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20876 LSI->AfterParameterList)
20877 return false;
20878
20879 const auto *MD = LSI->CallOperator;
20880 if (MD->getType().isNull())
20881 continue;
20882
20883 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20884 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20885 !Ty->getParamType(i: 0)->isDependentType())
20886 continue;
20887
20888 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20889 if (C->isCopyCapture())
20890 return true;
20891 continue;
20892 }
20893
20894 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20895 return true;
20896 }
20897 return false;
20898 }();
20899
20900 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20901 Set: IsDependent, Context: SemaRef.getASTContext());
20902}
20903
20904static void
20905MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20906 bool MightBeOdrUse,
20907 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20908 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20909 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20910
20911 if (SemaRef.getLangOpts().OpenACC)
20912 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20913
20914 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20915 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20916 if (SemaRef.getLangOpts().CPlusPlus)
20917 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20918 D: Var, E);
20919 return;
20920 }
20921
20922 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20923 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20924 if (SemaRef.getLangOpts().CPlusPlus)
20925 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20926 D: Decl, E);
20927 return;
20928 }
20929 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20930
20931 // If this is a call to a method via a cast, also mark the method in the
20932 // derived class used in case codegen can devirtualize the call.
20933 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20934 if (!ME)
20935 return;
20936 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20937 if (!MD)
20938 return;
20939 // Only attempt to devirtualize if this is truly a virtual call.
20940 bool IsVirtualCall = MD->isVirtual() &&
20941 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20942 if (!IsVirtualCall)
20943 return;
20944
20945 // If it's possible to devirtualize the call, mark the called function
20946 // referenced.
20947 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20948 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20949 if (DM)
20950 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20951}
20952
20953void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20954 // [basic.def.odr] (CWG 1614)
20955 // A function is named by an expression or conversion [...]
20956 // unless it is a pure virtual function and either the expression is not an
20957 // id-expression naming the function with an explicitly qualified name or
20958 // the expression forms a pointer to member
20959 bool OdrUse = true;
20960 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20961 if (Method->isVirtual() &&
20962 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20963 OdrUse = false;
20964
20965 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20966 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20967 !isImmediateFunctionContext() &&
20968 !isCheckingDefaultArgumentOrInitializer() &&
20969 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20970 !FD->isDependentContext())
20971 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20972 }
20973 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
20974 RefsMinusAssignments);
20975}
20976
20977void Sema::MarkMemberReferenced(MemberExpr *E) {
20978 // C++11 [basic.def.odr]p2:
20979 // A non-overloaded function whose name appears as a potentially-evaluated
20980 // expression or a member of a set of candidate functions, if selected by
20981 // overload resolution when referred to from a potentially-evaluated
20982 // expression, is odr-used, unless it is a pure virtual function and its
20983 // name is not explicitly qualified.
20984 bool MightBeOdrUse = true;
20985 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20986 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20987 if (Method->isPureVirtual())
20988 MightBeOdrUse = false;
20989 }
20990 SourceLocation Loc =
20991 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20992 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
20993 RefsMinusAssignments);
20994}
20995
20996void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20997 for (ValueDecl *VD : *E)
20998 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
20999 RefsMinusAssignments);
21000}
21001
21002/// Perform marking for a reference to an arbitrary declaration. It
21003/// marks the declaration referenced, and performs odr-use checking for
21004/// functions and variables. This method should not be used when building a
21005/// normal expression which refers to a variable.
21006void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
21007 bool MightBeOdrUse) {
21008 if (MightBeOdrUse) {
21009 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
21010 MarkVariableReferenced(Loc, Var: VD);
21011 return;
21012 }
21013 }
21014 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
21015 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
21016 return;
21017 }
21018 D->setReferenced();
21019}
21020
21021namespace {
21022 // Mark all of the declarations used by a type as referenced.
21023 // FIXME: Not fully implemented yet! We need to have a better understanding
21024 // of when we're entering a context we should not recurse into.
21025 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21026 // TreeTransforms rebuilding the type in a new context. Rather than
21027 // duplicating the TreeTransform logic, we should consider reusing it here.
21028 // Currently that causes problems when rebuilding LambdaExprs.
21029class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21030 Sema &S;
21031 SourceLocation Loc;
21032
21033public:
21034 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21035
21036 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21037};
21038}
21039
21040bool MarkReferencedDecls::TraverseTemplateArgument(
21041 const TemplateArgument &Arg) {
21042 {
21043 // A non-type template argument is a constant-evaluated context.
21044 EnterExpressionEvaluationContext Evaluated(
21045 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
21046 if (Arg.getKind() == TemplateArgument::Declaration) {
21047 if (Decl *D = Arg.getAsDecl())
21048 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
21049 } else if (Arg.getKind() == TemplateArgument::Expression) {
21050 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
21051 }
21052 }
21053
21054 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
21055}
21056
21057void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
21058 MarkReferencedDecls Marker(*this, Loc);
21059 Marker.TraverseType(T);
21060}
21061
21062namespace {
21063/// Helper class that marks all of the declarations referenced by
21064/// potentially-evaluated subexpressions as "referenced".
21065class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21066public:
21067 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21068 bool SkipLocalVariables;
21069 ArrayRef<const Expr *> StopAt;
21070
21071 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21072 ArrayRef<const Expr *> StopAt)
21073 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21074
21075 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21076 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21077 }
21078
21079 void Visit(Expr *E) {
21080 if (llvm::is_contained(Range&: StopAt, Element: E))
21081 return;
21082 Inherited::Visit(S: E);
21083 }
21084
21085 void VisitConstantExpr(ConstantExpr *E) {
21086 // Don't mark declarations within a ConstantExpression, as this expression
21087 // will be evaluated and folded to a value.
21088 }
21089
21090 void VisitDeclRefExpr(DeclRefExpr *E) {
21091 // If we were asked not to visit local variables, don't.
21092 if (SkipLocalVariables) {
21093 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21094 if (VD->hasLocalStorage())
21095 return;
21096 }
21097
21098 // FIXME: This can trigger the instantiation of the initializer of a
21099 // variable, which can cause the expression to become value-dependent
21100 // or error-dependent. Do we need to propagate the new dependence bits?
21101 S.MarkDeclRefReferenced(E);
21102 }
21103
21104 void VisitMemberExpr(MemberExpr *E) {
21105 S.MarkMemberReferenced(E);
21106 Visit(E: E->getBase());
21107 }
21108};
21109} // namespace
21110
21111void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21112 bool SkipLocalVariables,
21113 ArrayRef<const Expr*> StopAt) {
21114 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21115}
21116
21117/// Emit a diagnostic when statements are reachable.
21118bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21119 const PartialDiagnostic &PD) {
21120 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21121 // The initializer of a constexpr variable or of the first declaration of a
21122 // static data member is not syntactically a constant evaluated constant,
21123 // but nonetheless is always required to be a constant expression, so we
21124 // can skip diagnosing.
21125 if (Decl &&
21126 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21127 Decl->isFirstDecl() && !Decl->isInline())))
21128 return false;
21129
21130 if (Stmts.empty()) {
21131 Diag(Loc, PD);
21132 return true;
21133 }
21134
21135 if (getCurFunction()) {
21136 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21137 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21138 return true;
21139 }
21140
21141 // For non-constexpr file-scope variables with reachability context (non-empty
21142 // Stmts), build a CFG for the initializer and check whether the context in
21143 // question is reachable.
21144 if (Decl && Decl->isFileVarDecl()) {
21145 AnalysisWarnings.registerVarDeclWarning(
21146 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21147 return true;
21148 }
21149
21150 Diag(Loc, PD);
21151 return true;
21152}
21153
21154/// Emit a diagnostic that describes an effect on the run-time behavior
21155/// of the program being compiled.
21156///
21157/// This routine emits the given diagnostic when the code currently being
21158/// type-checked is "potentially evaluated", meaning that there is a
21159/// possibility that the code will actually be executable. Code in sizeof()
21160/// expressions, code used only during overload resolution, etc., are not
21161/// potentially evaluated. This routine will suppress such diagnostics or,
21162/// in the absolutely nutty case of potentially potentially evaluated
21163/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21164/// later.
21165///
21166/// This routine should be used for all diagnostics that describe the run-time
21167/// behavior of a program, such as passing a non-POD value through an ellipsis.
21168/// Failure to do so will likely result in spurious diagnostics or failures
21169/// during overload resolution or within sizeof/alignof/typeof/typeid.
21170bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21171 const PartialDiagnostic &PD) {
21172
21173 if (ExprEvalContexts.back().isDiscardedStatementContext())
21174 return false;
21175
21176 switch (ExprEvalContexts.back().Context) {
21177 case ExpressionEvaluationContext::Unevaluated:
21178 case ExpressionEvaluationContext::UnevaluatedList:
21179 case ExpressionEvaluationContext::UnevaluatedAbstract:
21180 case ExpressionEvaluationContext::DiscardedStatement:
21181 // The argument will never be evaluated, so don't complain.
21182 break;
21183
21184 case ExpressionEvaluationContext::ConstantEvaluated:
21185 case ExpressionEvaluationContext::ImmediateFunctionContext:
21186 // Relevant diagnostics should be produced by constant evaluation.
21187 break;
21188
21189 case ExpressionEvaluationContext::PotentiallyEvaluated:
21190 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21191 return DiagIfReachable(Loc, Stmts, PD);
21192 }
21193
21194 return false;
21195}
21196
21197bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21198 const PartialDiagnostic &PD) {
21199 return DiagRuntimeBehavior(
21200 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21201 PD);
21202}
21203
21204bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21205 CallExpr *CE, FunctionDecl *FD) {
21206 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21207 return false;
21208
21209 // If we're inside a decltype's expression, don't check for a valid return
21210 // type or construct temporaries until we know whether this is the last call.
21211 if (ExprEvalContexts.back().ExprContext ==
21212 ExpressionEvaluationContextRecord::EK_Decltype) {
21213 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21214 return false;
21215 }
21216
21217 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21218 FunctionDecl *FD;
21219 CallExpr *CE;
21220
21221 public:
21222 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21223 : FD(FD), CE(CE) { }
21224
21225 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21226 if (!FD) {
21227 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21228 << T << CE->getSourceRange();
21229 return;
21230 }
21231
21232 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21233 << CE->getSourceRange() << FD << T;
21234 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21235 << FD->getDeclName();
21236 }
21237 } Diagnoser(FD, CE);
21238
21239 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21240 return true;
21241
21242 return false;
21243}
21244
21245// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21246// will prevent this condition from triggering, which is what we want.
21247void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21248 SourceLocation Loc;
21249
21250 unsigned diagnostic = diag::warn_condition_is_assignment;
21251 bool IsOrAssign = false;
21252
21253 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21254 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21255 return;
21256
21257 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21258
21259 // Greylist some idioms by putting them into a warning subcategory.
21260 if (ObjCMessageExpr *ME
21261 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21262 Selector Sel = ME->getSelector();
21263
21264 // self = [<foo> init...]
21265 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21266 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21267
21268 // <foo> = [<bar> nextObject]
21269 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21270 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21271 }
21272
21273 Loc = Op->getOperatorLoc();
21274 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21275 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21276 return;
21277
21278 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21279 Loc = Op->getOperatorLoc();
21280 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21281 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21282 else {
21283 // Not an assignment.
21284 return;
21285 }
21286
21287 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21288
21289 SourceLocation Open = E->getBeginLoc();
21290 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21291 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21292 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21293 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21294
21295 if (IsOrAssign)
21296 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21297 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21298 else
21299 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21300 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21301}
21302
21303void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21304 // Don't warn if the parens came from a macro.
21305 SourceLocation parenLoc = ParenE->getBeginLoc();
21306 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21307 return;
21308 // Don't warn for dependent expressions.
21309 if (ParenE->isTypeDependent())
21310 return;
21311
21312 Expr *E = ParenE->IgnoreParens();
21313 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21314 return;
21315
21316 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21317 if (opE->getOpcode() == BO_EQ &&
21318 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21319 == Expr::MLV_Valid) {
21320 SourceLocation Loc = opE->getOperatorLoc();
21321
21322 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21323 SourceRange ParenERange = ParenE->getSourceRange();
21324 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21325 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21326 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21327 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21328 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21329 }
21330}
21331
21332ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21333 bool IsConstexpr) {
21334 DiagnoseAssignmentAsCondition(E);
21335 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21336 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21337
21338 ExprResult result = CheckPlaceholderExpr(E);
21339 if (result.isInvalid()) return ExprError();
21340 E = result.get();
21341
21342 if (!E->isTypeDependent()) {
21343 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21344 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21345
21346 if (getLangOpts().CPlusPlus)
21347 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21348
21349 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21350 if (ERes.isInvalid())
21351 return ExprError();
21352 E = ERes.get();
21353
21354 QualType T = E->getType();
21355 if (!T->isScalarType()) { // C99 6.8.4.1p1
21356 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21357 << T << E->getSourceRange();
21358 return ExprError();
21359 }
21360 CheckBoolLikeConversion(E, CC: Loc);
21361 }
21362
21363 return E;
21364}
21365
21366Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21367 Expr *SubExpr, ConditionKind CK,
21368 bool MissingOK) {
21369 // MissingOK indicates whether having no condition expression is valid
21370 // (for loop) or invalid (e.g. while loop).
21371 if (!SubExpr)
21372 return MissingOK ? ConditionResult() : ConditionError();
21373
21374 ExprResult Cond;
21375 switch (CK) {
21376 case ConditionKind::Boolean:
21377 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21378 break;
21379
21380 case ConditionKind::ConstexprIf:
21381 // Note: this might produce a FullExpr
21382 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21383 break;
21384
21385 case ConditionKind::Switch:
21386 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21387 break;
21388 }
21389 if (Cond.isInvalid()) {
21390 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21391 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21392 if (!Cond.get())
21393 return ConditionError();
21394 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21395 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21396
21397 if (!Cond.isUsable())
21398 return ConditionError();
21399
21400 return ConditionResult(*this, nullptr, Cond,
21401 CK == ConditionKind::ConstexprIf);
21402}
21403
21404namespace {
21405 /// A visitor for rebuilding a call to an __unknown_any expression
21406 /// to have an appropriate type.
21407 struct RebuildUnknownAnyFunction
21408 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21409
21410 Sema &S;
21411
21412 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21413
21414 ExprResult VisitStmt(Stmt *S) {
21415 llvm_unreachable("unexpected statement!");
21416 }
21417
21418 ExprResult VisitExpr(Expr *E) {
21419 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21420 << E->getSourceRange();
21421 return ExprError();
21422 }
21423
21424 /// Rebuild an expression which simply semantically wraps another
21425 /// expression which it shares the type and value kind of.
21426 template <class T> ExprResult rebuildSugarExpr(T *E) {
21427 ExprResult SubResult = Visit(S: E->getSubExpr());
21428 if (SubResult.isInvalid()) return ExprError();
21429
21430 Expr *SubExpr = SubResult.get();
21431 E->setSubExpr(SubExpr);
21432 E->setType(SubExpr->getType());
21433 E->setValueKind(SubExpr->getValueKind());
21434 assert(E->getObjectKind() == OK_Ordinary);
21435 return E;
21436 }
21437
21438 ExprResult VisitParenExpr(ParenExpr *E) {
21439 return rebuildSugarExpr(E);
21440 }
21441
21442 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21443 return rebuildSugarExpr(E);
21444 }
21445
21446 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21447 ExprResult SubResult = Visit(S: E->getSubExpr());
21448 if (SubResult.isInvalid()) return ExprError();
21449
21450 Expr *SubExpr = SubResult.get();
21451 E->setSubExpr(SubExpr);
21452 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21453 assert(E->isPRValue());
21454 assert(E->getObjectKind() == OK_Ordinary);
21455 return E;
21456 }
21457
21458 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21459 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21460
21461 E->setType(VD->getType());
21462
21463 assert(E->isPRValue());
21464 if (S.getLangOpts().CPlusPlus &&
21465 !(isa<CXXMethodDecl>(Val: VD) &&
21466 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21467 E->setValueKind(VK_LValue);
21468
21469 return E;
21470 }
21471
21472 ExprResult VisitMemberExpr(MemberExpr *E) {
21473 return resolveDecl(E, VD: E->getMemberDecl());
21474 }
21475
21476 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21477 return resolveDecl(E, VD: E->getDecl());
21478 }
21479 };
21480}
21481
21482/// Given a function expression of unknown-any type, try to rebuild it
21483/// to have a function type.
21484static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21485 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21486 if (Result.isInvalid()) return ExprError();
21487 return S.DefaultFunctionArrayConversion(E: Result.get());
21488}
21489
21490namespace {
21491 /// A visitor for rebuilding an expression of type __unknown_anytype
21492 /// into one which resolves the type directly on the referring
21493 /// expression. Strict preservation of the original source
21494 /// structure is not a goal.
21495 struct RebuildUnknownAnyExpr
21496 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21497
21498 Sema &S;
21499
21500 /// The current destination type.
21501 QualType DestType;
21502
21503 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21504 : S(S), DestType(CastType) {}
21505
21506 ExprResult VisitStmt(Stmt *S) {
21507 llvm_unreachable("unexpected statement!");
21508 }
21509
21510 ExprResult VisitExpr(Expr *E) {
21511 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21512 << E->getSourceRange();
21513 return ExprError();
21514 }
21515
21516 ExprResult VisitCallExpr(CallExpr *E);
21517 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21518
21519 /// Rebuild an expression which simply semantically wraps another
21520 /// expression which it shares the type and value kind of.
21521 template <class T> ExprResult rebuildSugarExpr(T *E) {
21522 ExprResult SubResult = Visit(S: E->getSubExpr());
21523 if (SubResult.isInvalid()) return ExprError();
21524 Expr *SubExpr = SubResult.get();
21525 E->setSubExpr(SubExpr);
21526 E->setType(SubExpr->getType());
21527 E->setValueKind(SubExpr->getValueKind());
21528 assert(E->getObjectKind() == OK_Ordinary);
21529 return E;
21530 }
21531
21532 ExprResult VisitParenExpr(ParenExpr *E) {
21533 return rebuildSugarExpr(E);
21534 }
21535
21536 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21537 return rebuildSugarExpr(E);
21538 }
21539
21540 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21541 const PointerType *Ptr = DestType->getAs<PointerType>();
21542 if (!Ptr) {
21543 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21544 << E->getSourceRange();
21545 return ExprError();
21546 }
21547
21548 if (isa<CallExpr>(Val: E->getSubExpr())) {
21549 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21550 << E->getSourceRange();
21551 return ExprError();
21552 }
21553
21554 assert(E->isPRValue());
21555 assert(E->getObjectKind() == OK_Ordinary);
21556 E->setType(DestType);
21557
21558 // Build the sub-expression as if it were an object of the pointee type.
21559 DestType = Ptr->getPointeeType();
21560 ExprResult SubResult = Visit(S: E->getSubExpr());
21561 if (SubResult.isInvalid()) return ExprError();
21562 E->setSubExpr(SubResult.get());
21563 return E;
21564 }
21565
21566 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21567
21568 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21569
21570 ExprResult VisitMemberExpr(MemberExpr *E) {
21571 return resolveDecl(E, VD: E->getMemberDecl());
21572 }
21573
21574 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21575 return resolveDecl(E, VD: E->getDecl());
21576 }
21577 };
21578}
21579
21580/// Rebuilds a call expression which yielded __unknown_anytype.
21581ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21582 Expr *CalleeExpr = E->getCallee();
21583
21584 enum FnKind {
21585 FK_MemberFunction,
21586 FK_FunctionPointer,
21587 FK_BlockPointer
21588 };
21589
21590 FnKind Kind;
21591 QualType CalleeType = CalleeExpr->getType();
21592 if (CalleeType == S.Context.BoundMemberTy) {
21593 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21594 Kind = FK_MemberFunction;
21595 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21596 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21597 CalleeType = Ptr->getPointeeType();
21598 Kind = FK_FunctionPointer;
21599 } else {
21600 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21601 Kind = FK_BlockPointer;
21602 }
21603 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21604
21605 // Verify that this is a legal result type of a function.
21606 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21607 DestType->isFunctionType()) {
21608 unsigned diagID = diag::err_func_returning_array_function;
21609 if (Kind == FK_BlockPointer)
21610 diagID = diag::err_block_returning_array_function;
21611
21612 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21613 << DestType->isFunctionType() << DestType;
21614 return ExprError();
21615 }
21616
21617 // Otherwise, go ahead and set DestType as the call's result.
21618 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21619 E->setValueKind(Expr::getValueKindForType(T: DestType));
21620 assert(E->getObjectKind() == OK_Ordinary);
21621
21622 // Rebuild the function type, replacing the result type with DestType.
21623 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21624 if (Proto) {
21625 // __unknown_anytype(...) is a special case used by the debugger when
21626 // it has no idea what a function's signature is.
21627 //
21628 // We want to build this call essentially under the K&R
21629 // unprototyped rules, but making a FunctionNoProtoType in C++
21630 // would foul up all sorts of assumptions. However, we cannot
21631 // simply pass all arguments as variadic arguments, nor can we
21632 // portably just call the function under a non-variadic type; see
21633 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21634 // However, it turns out that in practice it is generally safe to
21635 // call a function declared as "A foo(B,C,D);" under the prototype
21636 // "A foo(B,C,D,...);". The only known exception is with the
21637 // Windows ABI, where any variadic function is implicitly cdecl
21638 // regardless of its normal CC. Therefore we change the parameter
21639 // types to match the types of the arguments.
21640 //
21641 // This is a hack, but it is far superior to moving the
21642 // corresponding target-specific code from IR-gen to Sema/AST.
21643
21644 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21645 SmallVector<QualType, 8> ArgTypes;
21646 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21647 ArgTypes.reserve(N: E->getNumArgs());
21648 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21649 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21650 }
21651 ParamTypes = ArgTypes;
21652 }
21653 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21654 EPI: Proto->getExtProtoInfo());
21655 } else {
21656 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21657 Info: FnType->getExtInfo());
21658 }
21659
21660 // Rebuild the appropriate pointer-to-function type.
21661 switch (Kind) {
21662 case FK_MemberFunction:
21663 // Nothing to do.
21664 break;
21665
21666 case FK_FunctionPointer:
21667 DestType = S.Context.getPointerType(T: DestType);
21668 break;
21669
21670 case FK_BlockPointer:
21671 DestType = S.Context.getBlockPointerType(T: DestType);
21672 break;
21673 }
21674
21675 // Finally, we can recurse.
21676 ExprResult CalleeResult = Visit(S: CalleeExpr);
21677 if (!CalleeResult.isUsable()) return ExprError();
21678 E->setCallee(CalleeResult.get());
21679
21680 // Bind a temporary if necessary.
21681 return S.MaybeBindToTemporary(E);
21682}
21683
21684ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21685 // Verify that this is a legal result type of a call.
21686 if (DestType->isArrayType() || DestType->isFunctionType()) {
21687 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21688 << DestType->isFunctionType() << DestType;
21689 return ExprError();
21690 }
21691
21692 // Rewrite the method result type if available.
21693 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21694 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21695 Method->setReturnType(DestType);
21696 }
21697
21698 // Change the type of the message.
21699 E->setType(DestType.getNonReferenceType());
21700 E->setValueKind(Expr::getValueKindForType(T: DestType));
21701
21702 return S.MaybeBindToTemporary(E);
21703}
21704
21705ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21706 // The only case we should ever see here is a function-to-pointer decay.
21707 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21708 assert(E->isPRValue());
21709 assert(E->getObjectKind() == OK_Ordinary);
21710
21711 E->setType(DestType);
21712
21713 // Rebuild the sub-expression as the pointee (function) type.
21714 DestType = DestType->castAs<PointerType>()->getPointeeType();
21715
21716 ExprResult Result = Visit(S: E->getSubExpr());
21717 if (!Result.isUsable()) return ExprError();
21718
21719 E->setSubExpr(Result.get());
21720 return E;
21721 } else if (E->getCastKind() == CK_LValueToRValue) {
21722 assert(E->isPRValue());
21723 assert(E->getObjectKind() == OK_Ordinary);
21724
21725 assert(isa<BlockPointerType>(E->getType()));
21726
21727 E->setType(DestType);
21728
21729 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21730 DestType = S.Context.getLValueReferenceType(T: DestType);
21731
21732 ExprResult Result = Visit(S: E->getSubExpr());
21733 if (!Result.isUsable()) return ExprError();
21734
21735 E->setSubExpr(Result.get());
21736 return E;
21737 } else {
21738 llvm_unreachable("Unhandled cast type!");
21739 }
21740}
21741
21742ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21743 ExprValueKind ValueKind = VK_LValue;
21744 QualType Type = DestType;
21745
21746 // We know how to make this work for certain kinds of decls:
21747
21748 // - functions
21749 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21750 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21751 DestType = Ptr->getPointeeType();
21752 ExprResult Result = resolveDecl(E, VD);
21753 if (Result.isInvalid()) return ExprError();
21754 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21755 VK: VK_PRValue);
21756 }
21757
21758 if (!Type->isFunctionType()) {
21759 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21760 << VD << E->getSourceRange();
21761 return ExprError();
21762 }
21763 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21764 // We must match the FunctionDecl's type to the hack introduced in
21765 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21766 // type. See the lengthy commentary in that routine.
21767 QualType FDT = FD->getType();
21768 const FunctionType *FnType = FDT->castAs<FunctionType>();
21769 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21770 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21771 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21772 SourceLocation Loc = FD->getLocation();
21773 FunctionDecl *NewFD = FunctionDecl::Create(
21774 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21775 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21776 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21777 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21778 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21779
21780 if (FD->getQualifier())
21781 NewFD->setQualifierInfo(FD->getQualifierLoc());
21782
21783 SmallVector<ParmVarDecl*, 16> Params;
21784 for (const auto &AI : FT->param_types()) {
21785 ParmVarDecl *Param =
21786 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21787 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21788 Params.push_back(Elt: Param);
21789 }
21790 NewFD->setParams(Params);
21791 DRE->setDecl(NewFD);
21792 VD = DRE->getDecl();
21793 }
21794 }
21795
21796 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21797 if (MD->isInstance()) {
21798 ValueKind = VK_PRValue;
21799 Type = S.Context.BoundMemberTy;
21800 }
21801
21802 // Function references aren't l-values in C.
21803 if (!S.getLangOpts().CPlusPlus)
21804 ValueKind = VK_PRValue;
21805
21806 // - variables
21807 } else if (isa<VarDecl>(Val: VD)) {
21808 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21809 Type = RefTy->getPointeeType();
21810 } else if (Type->isFunctionType()) {
21811 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21812 << VD << E->getSourceRange();
21813 return ExprError();
21814 }
21815
21816 // - nothing else
21817 } else {
21818 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21819 << VD << E->getSourceRange();
21820 return ExprError();
21821 }
21822
21823 // Modifying the declaration like this is friendly to IR-gen but
21824 // also really dangerous.
21825 VD->setType(DestType);
21826 E->setType(Type);
21827 E->setValueKind(ValueKind);
21828 return E;
21829}
21830
21831ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21832 Expr *CastExpr, CastKind &CastKind,
21833 ExprValueKind &VK, CXXCastPath &Path) {
21834 // The type we're casting to must be either void or complete.
21835 if (!CastType->isVoidType() &&
21836 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21837 DiagID: diag::err_typecheck_cast_to_incomplete))
21838 return ExprError();
21839
21840 // Rewrite the casted expression from scratch.
21841 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21842 if (!result.isUsable()) return ExprError();
21843
21844 CastExpr = result.get();
21845 VK = CastExpr->getValueKind();
21846 CastKind = CK_NoOp;
21847
21848 return CastExpr;
21849}
21850
21851ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21852 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21853}
21854
21855ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21856 Expr *arg, QualType &paramType) {
21857 // If the syntactic form of the argument is not an explicit cast of
21858 // any sort, just do default argument promotion.
21859 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21860 if (!castArg) {
21861 ExprResult result = DefaultArgumentPromotion(E: arg);
21862 if (result.isInvalid()) return ExprError();
21863 paramType = result.get()->getType();
21864 return result;
21865 }
21866
21867 // Otherwise, use the type that was written in the explicit cast.
21868 assert(!arg->hasPlaceholderType());
21869 paramType = castArg->getTypeAsWritten();
21870
21871 // Copy-initialize a parameter of that type.
21872 InitializedEntity entity =
21873 InitializedEntity::InitializeParameter(Context, Type: paramType,
21874 /*consumed*/ Consumed: false);
21875 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21876}
21877
21878static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21879 Expr *orig = E;
21880 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21881 while (true) {
21882 E = E->IgnoreParenImpCasts();
21883 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21884 E = call->getCallee();
21885 diagID = diag::err_uncasted_call_of_unknown_any;
21886 } else {
21887 break;
21888 }
21889 }
21890
21891 SourceLocation loc;
21892 NamedDecl *d;
21893 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21894 loc = ref->getLocation();
21895 d = ref->getDecl();
21896 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21897 loc = mem->getMemberLoc();
21898 d = mem->getMemberDecl();
21899 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21900 diagID = diag::err_uncasted_call_of_unknown_any;
21901 loc = msg->getSelectorStartLoc();
21902 d = msg->getMethodDecl();
21903 if (!d) {
21904 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21905 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21906 << orig->getSourceRange();
21907 return ExprError();
21908 }
21909 } else {
21910 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21911 << E->getSourceRange();
21912 return ExprError();
21913 }
21914
21915 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21916
21917 // Never recoverable.
21918 return ExprError();
21919}
21920
21921ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21922 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21923 if (!placeholderType) return E;
21924
21925 switch (placeholderType->getKind()) {
21926 case BuiltinType::UnresolvedTemplate: {
21927 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
21928 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21929 // There's only one FoundDecl for UnresolvedTemplate type. See
21930 // BuildTemplateIdExpr.
21931 NamedDecl *Temp = *ULE->decls_begin();
21932 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21933
21934 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21935 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21936 // as it models only the unqualified-id case, where this case can clearly be
21937 // qualified. Thus we can't just qualify an assumed template.
21938 TemplateName TN;
21939 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21940 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21941 Template: TemplateName(TD));
21942 else
21943 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21944
21945 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21946 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21947 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
21948 << IsTypeAliasTemplateDecl;
21949
21950 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21951 bool HasAnyDependentTA = false;
21952 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21953 HasAnyDependentTA |= Arg.getArgument().isDependent();
21954 TAL.addArgument(Loc: Arg);
21955 }
21956
21957 QualType TST;
21958 {
21959 SFINAETrap Trap(*this);
21960 TST = CheckTemplateIdType(
21961 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
21962 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21963 }
21964 if (TST.isNull())
21965 TST = Context.getTemplateSpecializationType(
21966 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
21967 /*CanonicalArgs=*/{},
21968 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21969 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
21970 T: TST);
21971 }
21972
21973 // Overloaded expressions.
21974 case BuiltinType::Overload: {
21975 // Try to resolve a single function template specialization.
21976 // This is obligatory.
21977 ExprResult Result = E;
21978 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21979 return Result;
21980
21981 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21982 // leaves Result unchanged on failure.
21983 Result = E;
21984 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21985 return Result;
21986
21987 // If that failed, try to recover with a call.
21988 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
21989 /*complain*/ ForceComplain: true);
21990 return Result;
21991 }
21992
21993 // Bound member functions.
21994 case BuiltinType::BoundMember: {
21995 ExprResult result = E;
21996 const Expr *BME = E->IgnoreParens();
21997 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
21998 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21999 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
22000 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22001 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
22002 if (ME->getMemberNameInfo().getName().getNameKind() ==
22003 DeclarationName::CXXDestructorName)
22004 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22005 }
22006 tryToRecoverWithCall(E&: result, PD,
22007 /*complain*/ ForceComplain: true);
22008 return result;
22009 }
22010
22011 // ARC unbridged casts.
22012 case BuiltinType::ARCUnbridgedCast: {
22013 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
22014 ObjC().diagnoseARCUnbridgedCast(e: realCast);
22015 return realCast;
22016 }
22017
22018 // Expressions of unknown type.
22019 case BuiltinType::UnknownAny:
22020 return diagnoseUnknownAnyExpr(S&: *this, E);
22021
22022 // Pseudo-objects.
22023 case BuiltinType::PseudoObject:
22024 return PseudoObject().checkRValue(E);
22025
22026 case BuiltinType::BuiltinFn: {
22027 // Accept __noop without parens by implicitly converting it to a call expr.
22028 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
22029 if (DRE) {
22030 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
22031 unsigned BuiltinID = FD->getBuiltinID();
22032 if (BuiltinID == Builtin::BI__noop) {
22033 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
22034 CK: CK_BuiltinFnToFnPtr)
22035 .get();
22036 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
22037 VK: VK_PRValue, RParenLoc: SourceLocation(),
22038 FPFeatures: FPOptionsOverride());
22039 }
22040
22041 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
22042 // Any use of these other than a direct call is ill-formed as of C++20,
22043 // because they are not addressable functions. In earlier language
22044 // modes, warn and force an instantiation of the real body.
22045 Diag(Loc: E->getBeginLoc(),
22046 DiagID: getLangOpts().CPlusPlus20
22047 ? diag::err_use_of_unaddressable_function
22048 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22049 if (FD->isImplicitlyInstantiable()) {
22050 // Require a definition here because a normal attempt at
22051 // instantiation for a builtin will be ignored, and we won't try
22052 // again later. We assume that the definition of the template
22053 // precedes this use.
22054 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
22055 /*Recursive=*/false,
22056 /*DefinitionRequired=*/true,
22057 /*AtEndOfTU=*/false);
22058 }
22059 // Produce a properly-typed reference to the function.
22060 CXXScopeSpec SS;
22061 SS.Adopt(Other: DRE->getQualifierLoc());
22062 TemplateArgumentListInfo TemplateArgs;
22063 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22064 return BuildDeclRefExpr(
22065 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22066 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22067 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22068 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22069 }
22070 }
22071
22072 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22073 return ExprError();
22074 }
22075
22076 case BuiltinType::IncompleteMatrixIdx: {
22077 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22078 // At this point, we know there was no second [] to complete the operator.
22079 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22080 if (getLangOpts().HLSL) {
22081 return CreateBuiltinMatrixSingleSubscriptExpr(
22082 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22083 }
22084 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22085 return ExprError();
22086 }
22087
22088 // Expressions of unknown type.
22089 case BuiltinType::ArraySection:
22090 // If we've already diagnosed something on the array section type, we
22091 // shouldn't need to do any further diagnostic here.
22092 if (!E->containsErrors())
22093 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22094 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22095 return ExprError();
22096
22097 // Expressions of unknown type.
22098 case BuiltinType::OMPArrayShaping:
22099 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22100
22101 case BuiltinType::OMPIterator:
22102 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22103
22104 // Everything else should be impossible.
22105#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22106 case BuiltinType::Id:
22107#include "clang/Basic/OpenCLImageTypes.def"
22108#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22109 case BuiltinType::Id:
22110#include "clang/Basic/OpenCLExtensionTypes.def"
22111#define SVE_TYPE(Name, Id, SingletonId) \
22112 case BuiltinType::Id:
22113#include "clang/Basic/AArch64ACLETypes.def"
22114#define PPC_VECTOR_TYPE(Name, Id, Size) \
22115 case BuiltinType::Id:
22116#include "clang/Basic/PPCTypes.def"
22117#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22118#include "clang/Basic/RISCVVTypes.def"
22119#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22120#include "clang/Basic/WebAssemblyReferenceTypes.def"
22121#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22122#include "clang/Basic/AMDGPUTypes.def"
22123#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22124#include "clang/Basic/HLSLIntangibleTypes.def"
22125#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22126#define PLACEHOLDER_TYPE(Id, SingletonId)
22127#include "clang/AST/BuiltinTypes.def"
22128 break;
22129 }
22130
22131 llvm_unreachable("invalid placeholder type!");
22132}
22133
22134bool Sema::CheckCaseExpression(Expr *E) {
22135 if (E->isTypeDependent())
22136 return true;
22137 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22138 return E->getType()->isIntegralOrEnumerationType();
22139 return false;
22140}
22141
22142ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22143 ArrayRef<Expr *> SubExprs, QualType T) {
22144 if (!Context.getLangOpts().RecoveryAST)
22145 return ExprError();
22146
22147 if (isSFINAEContext())
22148 return ExprError();
22149
22150 if (T.isNull() || T->isUndeducedType() ||
22151 !Context.getLangOpts().RecoveryASTType)
22152 // We don't know the concrete type, fallback to dependent type.
22153 T = Context.DependentTy;
22154
22155 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22156}
22157