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/Attrs.inc"
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/SemaARM.h"
57#include "clang/Sema/SemaCUDA.h"
58#include "clang/Sema/SemaFixItUtils.h"
59#include "clang/Sema/SemaHLSL.h"
60#include "clang/Sema/SemaObjC.h"
61#include "clang/Sema/SemaOpenMP.h"
62#include "clang/Sema/SemaPseudoObject.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/STLExtras.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/Support/ConvertUTF.h"
67#include "llvm/Support/SaveAndRestore.h"
68#include "llvm/Support/TimeProfiler.h"
69#include "llvm/Support/TypeSize.h"
70#include <limits>
71#include <optional>
72
73using namespace clang;
74using namespace sema;
75
76bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
77 // See if this is an auto-typed variable whose initializer we are parsing.
78 if (ParsingInitForAutoVars.count(Ptr: D))
79 return false;
80
81 // See if this is a deleted function.
82 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
83 if (FD->isDeleted())
84 return false;
85
86 // If the function has a deduced return type, and we can't deduce it,
87 // then we can't use it either.
88 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
89 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
90 return false;
91
92 // See if this is an aligned allocation/deallocation function that is
93 // unavailable.
94 if (TreatUnavailableAsInvalid &&
95 isUnavailableAlignedAllocationFunction(FD: *FD))
96 return false;
97 }
98
99 // See if this function is unavailable.
100 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
101 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
102 return false;
103
104 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
105 return false;
106
107 return true;
108}
109
110static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
111 // Warn if this is used but marked unused.
112 if (const auto *A = D->getAttr<UnusedAttr>()) {
113 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
114 // should diagnose them.
115 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
116 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
117 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
118 if (DC && !DC->hasAttr<UnusedAttr>())
119 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
120 }
121 }
122}
123
124void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
125 assert(Decl && Decl->isDeleted());
126
127 if (Decl->isDefaulted()) {
128 // If the method was explicitly defaulted, point at that declaration.
129 if (!Decl->isImplicit())
130 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
131
132 // Try to diagnose why this special member function was implicitly
133 // deleted. This might fail, if that reason no longer applies.
134 DiagnoseDeletedDefaultedFunction(FD: Decl);
135 return;
136 }
137
138 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
139 if (Ctor && Ctor->isInheritingConstructor())
140 return NoteDeletedInheritingConstructor(CD: Ctor);
141
142 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
143 << Decl << 1;
144}
145
146/// Determine whether a FunctionDecl was ever declared with an
147/// explicit storage class.
148static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
149 for (auto *I : D->redecls()) {
150 if (I->getStorageClass() != SC_None)
151 return true;
152 }
153 return false;
154}
155
156/// Check whether we're in an extern inline function and referring to a
157/// variable or function with internal linkage (C11 6.7.4p3).
158///
159/// This is only a warning because we used to silently accept this code, but
160/// in many cases it will not behave correctly. This is not enabled in C++ mode
161/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
162/// and so while there may still be user mistakes, most of the time we can't
163/// prove that there are errors.
164static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
165 const NamedDecl *D,
166 SourceLocation Loc) {
167 // This is disabled under C++; there are too many ways for this to fire in
168 // contexts where the warning is a false positive, or where it is technically
169 // correct but benign.
170 //
171 // WG14 N3622 which removed the constraint entirely in C2y. It is left
172 // enabled in earlier language modes because this is a constraint in those
173 // language modes. But in C2y mode, we still want to issue the "incompatible
174 // with previous standards" diagnostic, too.
175 if (S.getLangOpts().CPlusPlus)
176 return;
177
178 // Check if this is an inlined function or method.
179 FunctionDecl *Current = S.getCurFunctionDecl();
180 if (!Current)
181 return;
182 if (!Current->isInlined())
183 return;
184 if (!Current->isExternallyVisible())
185 return;
186
187 // Check if the decl has internal linkage.
188 if (D->getFormalLinkage() != Linkage::Internal)
189 return;
190
191 // Downgrade from ExtWarn to Extension if
192 // (1) the supposedly external inline function is in the main file,
193 // and probably won't be included anywhere else.
194 // (2) the thing we're referencing is a pure function.
195 // (3) the thing we're referencing is another inline function.
196 // This last can give us false negatives, but it's better than warning on
197 // wrappers for simple C library functions.
198 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
199 unsigned DiagID;
200 if (S.getLangOpts().C2y)
201 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
202 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
203 S.getSourceManager().isInMainFile(Loc))
204 DiagID = diag::ext_internal_in_extern_inline_quiet;
205 else
206 DiagID = diag::ext_internal_in_extern_inline;
207
208 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
209 S.MaybeSuggestAddingStaticToDecl(D: Current);
210 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
211 << D;
212}
213
214void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
215 const FunctionDecl *First = Cur->getFirstDecl();
216
217 // Suggest "static" on the function, if possible.
218 if (!hasAnyExplicitStorageClass(D: First)) {
219 SourceLocation DeclBegin = First->getSourceRange().getBegin();
220 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
221 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
222 }
223}
224
225bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
226 const ObjCInterfaceDecl *UnknownObjCClass,
227 bool ObjCPropertyAccess,
228 bool AvoidPartialAvailabilityChecks,
229 ObjCInterfaceDecl *ClassReceiver,
230 bool SkipTrailingRequiresClause) {
231 SourceLocation Loc = Locs.front();
232 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
233 // If there were any diagnostics suppressed by template argument deduction,
234 // emit them now.
235 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
236 if (Pos != SuppressedDiagnostics.end()) {
237 for (const auto &[DiagLoc, PD] : Pos->second) {
238 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
239 PD.Emit(DB: Builder);
240 }
241 // Clear out the list of suppressed diagnostics, so that we don't emit
242 // them again for this specialization. However, we don't obsolete this
243 // entry from the table, because we want to avoid ever emitting these
244 // diagnostics again.
245 Pos->second.clear();
246 }
247
248 // C++ [basic.start.main]p3:
249 // The function 'main' shall not be used within a program.
250 if (cast<FunctionDecl>(Val: D)->isMain())
251 Diag(Loc, DiagID: diag::ext_main_used);
252
253 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
254 }
255
256 // See if this is an auto-typed variable whose initializer we are parsing.
257 if (ParsingInitForAutoVars.count(Ptr: D)) {
258 if (isa<BindingDecl>(Val: D)) {
259 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
260 << D->getDeclName();
261 } else {
262 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
263 << diag::ParsingInitFor::Var << D->getDeclName()
264 << cast<VarDecl>(Val: D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, DiagID: diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
282 NoteDeletedFunction(Decl: FD);
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
317 return true;
318
319 }
320
321 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
322 Concept && CheckConceptUseInDefinition(Concept, Loc))
323 return true;
324
325 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
326 // Lambdas are only default-constructible or assignable in C++2a onwards.
327 if (MD->getParent()->isLambda() &&
328 ((isa<CXXConstructorDecl>(Val: MD) &&
329 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
330 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
331 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
332 << !isa<CXXConstructorDecl>(Val: MD);
333 }
334 }
335
336 auto getReferencedObjCProp = [](const NamedDecl *D) ->
337 const ObjCPropertyDecl * {
338 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
339 return MD->findPropertyDecl();
340 return nullptr;
341 };
342 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
343 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
344 return true;
345 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
346 return true;
347 }
348
349 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
350 // Only the variables omp_in and omp_out are allowed in the combiner.
351 // Only the variables omp_priv and omp_orig are allowed in the
352 // initializer-clause.
353 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
354 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
355 isa<VarDecl>(Val: D)) {
356 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
357 << getCurFunction()->HasOMPDeclareReductionCombiner;
358 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
359 return true;
360 }
361
362 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
363 // List-items in map clauses on this construct may only refer to the declared
364 // variable var and entities that could be referenced by a procedure defined
365 // at the same location.
366 // [OpenMP 5.2] Also allow iterator declared variables.
367 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
368 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
369 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
370 << OpenMP().getOpenMPDeclareMapperVarName();
371 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
372 return true;
373 }
374
375 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
376 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
377 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
378 return true;
379 }
380
381 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
382 AvoidPartialAvailabilityChecks, ClassReceiver);
383
384 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
385
386 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
387
388 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
389 if (getLangOpts().getFPEvalMethod() !=
390 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
391 PP.getLastFPEvalPragmaLocation().isValid() &&
392 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
393 Diag(Loc: D->getLocation(),
394 DiagID: diag::err_type_available_only_in_default_eval_method)
395 << D->getName();
396 }
397
398 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
399 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
400
401 if (LangOpts.SYCLIsDevice ||
402 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
403 if (!Context.getTargetInfo().isTLSSupported())
404 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
405 if (VD->getTLSKind() != VarDecl::TLS_None)
406 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
407 }
408
409 return false;
410}
411
412void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(E: SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined(Id: "NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
503 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
507SourceRange Sema::getExprRange(Expr *E) const {
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
516ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
519 ExprResult result = CheckPlaceholderExpr(E);
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
530 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
531 return ExprError();
532
533 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
534 CK: CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
548 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
549 CK: CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
558static void CheckForNullPointerDereference(Sema &S, Expr *E) {
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
572 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
575 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
578 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
591 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
592 if (!Member || !Member->isStr(Str: "isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
607 S.LookupSingleName(S: S.TUScope,
608 Name: &S.Context.Idents.get(Name: "object_setClass"),
609 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
612 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
613 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
614 Code: "object_setClass(")
615 << FixItHint::CreateReplacement(
616 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
617 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
618 }
619 else
620 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
623 S.LookupSingleName(S: S.TUScope,
624 Name: &S.Context.Idents.get(Name: "object_getClass"),
625 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
626 if (ObjectGetClass)
627 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
628 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
629 Code: "object_getClass(")
630 << FixItHint::CreateReplacement(
631 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
632 else
633 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
634 }
635 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
636 }
637 }
638}
639
640ExprResult Sema::DefaultLvalueConversion(Expr *E) {
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
643 ExprResult result = CheckPlaceholderExpr(E);
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
658 if (T->canDecayToPointerType())
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
666 !T->isMemberPointerType()))
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
687 CheckForNullPointerDereference(S&: *this, E);
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
690 Name: &Context.Idents.get(Name: "object_getClass"),
691 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
692 if (ObjectGetClass)
693 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
695 << FixItHint::CreateReplacement(
696 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
697 else
698 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
718 Context.getTargetInfo().getCXXABI().isMicrosoft())
719 (void)isCompleteType(Loc: E->getExprLoc(), T);
720
721 ExprResult Res = CheckLValueToRValueConversionOperand(E);
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
728 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
729 Cleanup.setExprNeedsCleanups(true);
730
731 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
732 Cleanup.setExprNeedsCleanups(true);
733
734 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
735 return ExprError();
736
737 // C++ [conv.lval]p3:
738 // If T is cv std::nullptr_t, the result is a null pointer constant.
739 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
740 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
741 FPO: CurFPFeatureOverrides());
742
743 // C11 6.3.2.1p2:
744 // ... if the lvalue has atomic type, the value has the non-atomic version
745 // of the type of the lvalue ...
746 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
747 T = Atomic->getValueType().getUnqualifiedType();
748 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
749 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
750 }
751
752 return Res;
753}
754
755ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
756 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
757 if (Res.isInvalid())
758 return ExprError();
759 Res = DefaultLvalueConversion(E: Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res;
763}
764
765ExprResult Sema::CallExprUnaryConversions(Expr *E) {
766 QualType Ty = E->getType();
767 ExprResult Res = E;
768 // Only do implicit cast for a function type, but not for a pointer
769 // to function type.
770 if (Ty->isFunctionType()) {
771 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
772 CK: CK_FunctionToPointerDecay);
773 if (Res.isInvalid())
774 return ExprError();
775 }
776 Res = DefaultLvalueConversion(E: Res.get());
777 if (Res.isInvalid())
778 return ExprError();
779 return Res.get();
780}
781
782/// UsualUnaryFPConversions - Promotes floating-point types according to the
783/// current language semantics.
784ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
785 QualType Ty = E->getType();
786 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
787
788 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
789 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
790 (getLangOpts().getFPEvalMethod() !=
791 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
792 PP.getLastFPEvalPragmaLocation().isValid())) {
793 switch (EvalMethod) {
794 default:
795 llvm_unreachable("Unrecognized float evaluation method");
796 break;
797 case LangOptions::FEM_UnsetOnCommandLine:
798 llvm_unreachable("Float evaluation method should be set by now");
799 break;
800 case LangOptions::FEM_Double:
801 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
802 // Widen the expression to double.
803 return Ty->isComplexType()
804 ? ImpCastExprToType(E,
805 Type: Context.getComplexType(T: Context.DoubleTy),
806 CK: CK_FloatingComplexCast)
807 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
808 break;
809 case LangOptions::FEM_Extended:
810 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
811 // Widen the expression to long double.
812 return Ty->isComplexType()
813 ? ImpCastExprToType(
814 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
815 CK: CK_FloatingComplexCast)
816 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
817 CK: CK_FloatingCast);
818 break;
819 }
820 }
821
822 // Half FP have to be promoted to float unless it is natively supported
823 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
824 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
825
826 return E;
827}
828
829/// UsualUnaryConversions - Performs various conversions that are common to most
830/// operators (C99 6.3). The conversions of array and function types are
831/// sometimes suppressed. For example, the array->pointer conversion doesn't
832/// apply if the array is an argument to the sizeof or address (&) operators.
833/// In these instances, this routine should *not* be called.
834ExprResult Sema::UsualUnaryConversions(Expr *E) {
835 // First, convert to an r-value.
836 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
837 if (Res.isInvalid())
838 return ExprError();
839
840 // Promote floating-point types.
841 Res = UsualUnaryFPConversions(E: Res.get());
842 if (Res.isInvalid())
843 return ExprError();
844 E = Res.get();
845
846 QualType Ty = E->getType();
847 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
848
849 // Try to perform integral promotions if the object has a theoretically
850 // promotable type.
851 if (Ty->isIntegralOrUnscopedEnumerationType()) {
852 // C99 6.3.1.1p2:
853 //
854 // The following may be used in an expression wherever an int or
855 // unsigned int may be used:
856 // - an object or expression with an integer type whose integer
857 // conversion rank is less than or equal to the rank of int
858 // and unsigned int.
859 // - A bit-field of type _Bool, int, signed int, or unsigned int.
860 //
861 // If an int can represent all values of the original type, the
862 // value is converted to an int; otherwise, it is converted to an
863 // unsigned int. These are called the integer promotions. All
864 // other types are unchanged by the integer promotions.
865
866 QualType PTy = Context.isPromotableBitField(E);
867 if (!PTy.isNull()) {
868 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
869 return E;
870 }
871 if (Context.isPromotableIntegerType(T: Ty)) {
872 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
873 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
874 return E;
875 }
876 }
877 return E;
878}
879
880/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
881/// do not have a prototype. Arguments that have type float or __fp16
882/// are promoted to double. All other argument types are converted by
883/// UsualUnaryConversions().
884ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
885 QualType Ty = E->getType();
886 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
887
888 ExprResult Res = UsualUnaryConversions(E);
889 if (Res.isInvalid())
890 return ExprError();
891 E = Res.get();
892
893 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
894 // promote to double.
895 // Note that default argument promotion applies only to float (and
896 // half/fp16); it does not apply to _Float16.
897 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
898 if (BTy && (BTy->getKind() == BuiltinType::Half ||
899 BTy->getKind() == BuiltinType::Float)) {
900 if (getLangOpts().OpenCL &&
901 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
902 if (BTy->getKind() == BuiltinType::Half) {
903 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
904 }
905 } else {
906 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
907 }
908 }
909 if (BTy &&
910 getLangOpts().getExtendIntArgs() ==
911 LangOptions::ExtendArgsKind::ExtendTo64 &&
912 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
913 Context.getTypeSizeInChars(T: BTy) <
914 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
915 E = (Ty->isUnsignedIntegerType())
916 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
917 .get()
918 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
919 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
920 "Unexpected typesize for LongLongTy");
921 }
922
923 // C++ performs lvalue-to-rvalue conversion as a default argument
924 // promotion, even on class types, but note:
925 // C++11 [conv.lval]p2:
926 // When an lvalue-to-rvalue conversion occurs in an unevaluated
927 // operand or a subexpression thereof the value contained in the
928 // referenced object is not accessed. Otherwise, if the glvalue
929 // has a class type, the conversion copy-initializes a temporary
930 // of type T from the glvalue and the result of the conversion
931 // is a prvalue for the temporary.
932 // FIXME: add some way to gate this entire thing for correctness in
933 // potentially potentially evaluated contexts.
934 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
935 ExprResult Temp = PerformCopyInitialization(
936 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
937 EqualLoc: E->getExprLoc(), Init: E);
938 if (Temp.isInvalid())
939 return ExprError();
940 E = Temp.get();
941 }
942
943 // C++ [expr.call]p7, per CWG722:
944 // An argument that has (possibly cv-qualified) type std::nullptr_t is
945 // converted to void* ([conv.ptr]).
946 // (This does not apply to C23 nullptr)
947 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
948 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
949
950 return E;
951}
952
953VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
954 if (Ty->isIncompleteType()) {
955 // C++11 [expr.call]p7:
956 // After these conversions, if the argument does not have arithmetic,
957 // enumeration, pointer, pointer to member, or class type, the program
958 // is ill-formed.
959 //
960 // Since we've already performed null pointer conversion, array-to-pointer
961 // decay and function-to-pointer decay, the only such type in C++ is cv
962 // void. This also handles initializer lists as variadic arguments.
963 if (Ty->isVoidType())
964 return VarArgKind::Invalid;
965
966 if (Ty->isObjCObjectType())
967 return VarArgKind::Invalid;
968 return VarArgKind::Valid;
969 }
970
971 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
972 return VarArgKind::Invalid;
973
974 if (Context.getTargetInfo().getTriple().isWasm() &&
975 Ty.isWebAssemblyReferenceType()) {
976 return VarArgKind::Invalid;
977 }
978
979 if (Ty.isCXX98PODType(Context))
980 return VarArgKind::Valid;
981
982 // C++11 [expr.call]p7:
983 // Passing a potentially-evaluated argument of class type (Clause 9)
984 // having a non-trivial copy constructor, a non-trivial move constructor,
985 // or a non-trivial destructor, with no corresponding parameter,
986 // is conditionally-supported with implementation-defined semantics.
987 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
988 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
989 if (!Record->hasNonTrivialCopyConstructor() &&
990 !Record->hasNonTrivialMoveConstructor() &&
991 !Record->hasNonTrivialDestructor())
992 return VarArgKind::ValidInCXX11;
993
994 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
995 return VarArgKind::Valid;
996
997 if (Ty->isObjCObjectType())
998 return VarArgKind::Invalid;
999
1000 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1001 return VarArgKind::Valid;
1002
1003 if (getLangOpts().MSVCCompat)
1004 return VarArgKind::MSVCUndefined;
1005
1006 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1007 return VarArgKind::Valid;
1008
1009 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1010 // permitted to reject them. We should consider doing so.
1011 return VarArgKind::Undefined;
1012}
1013
1014void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1015 // Don't allow one to pass an Objective-C interface to a vararg.
1016 const QualType &Ty = E->getType();
1017 VarArgKind VAK = isValidVarArgType(Ty);
1018
1019 // Complain about passing non-POD types through varargs.
1020 switch (VAK) {
1021 case VarArgKind::ValidInCXX11:
1022 DiagRuntimeBehavior(
1023 Loc: E->getBeginLoc(), Statement: nullptr,
1024 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1025 [[fallthrough]];
1026 case VarArgKind::Valid:
1027 if (Ty->isRecordType()) {
1028 // This is unlikely to be what the user intended. If the class has a
1029 // 'c_str' member function, the user probably meant to call that.
1030 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1031 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1032 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1033 }
1034 break;
1035
1036 case VarArgKind::Undefined:
1037 case VarArgKind::MSVCUndefined:
1038 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1039 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1040 << getLangOpts().CPlusPlus11 << Ty << CT);
1041 break;
1042
1043 case VarArgKind::Invalid:
1044 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1045 Diag(Loc: E->getBeginLoc(),
1046 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1047 << Ty << CT;
1048 else if (Ty->isObjCObjectType())
1049 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1050 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1051 << Ty << CT);
1052 else
1053 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1054 << isa<InitListExpr>(Val: E) << Ty << CT;
1055 break;
1056 }
1057}
1058
1059ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1060 FunctionDecl *FDecl) {
1061 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1062 // Strip the unbridged-cast placeholder expression off, if applicable.
1063 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1064 (CT == VariadicCallType::Method ||
1065 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1066 E = ObjC().stripARCUnbridgedCast(e: E);
1067
1068 // Otherwise, do normal placeholder checking.
1069 } else {
1070 ExprResult ExprRes = CheckPlaceholderExpr(E);
1071 if (ExprRes.isInvalid())
1072 return ExprError();
1073 E = ExprRes.get();
1074 }
1075 }
1076
1077 ExprResult ExprRes = DefaultArgumentPromotion(E);
1078 if (ExprRes.isInvalid())
1079 return ExprError();
1080
1081 // Copy blocks to the heap.
1082 if (ExprRes.get()->getType()->isBlockPointerType())
1083 maybeExtendBlockObject(E&: ExprRes);
1084
1085 E = ExprRes.get();
1086
1087 // Diagnostics regarding non-POD argument types are
1088 // emitted along with format string checking in Sema::CheckFunctionCall().
1089 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1090 // Turn this into a trap.
1091 CXXScopeSpec SS;
1092 SourceLocation TemplateKWLoc;
1093 UnqualifiedId Name;
1094 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1095 IdLoc: E->getBeginLoc());
1096 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1097 /*HasTrailingLParen=*/true,
1098 /*IsAddressOfOperand=*/false);
1099 if (TrapFn.isInvalid())
1100 return ExprError();
1101
1102 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1103 RParenLoc: E->getEndLoc());
1104 if (Call.isInvalid())
1105 return ExprError();
1106
1107 ExprResult Comma =
1108 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1109 if (Comma.isInvalid())
1110 return ExprError();
1111 return Comma.get();
1112 }
1113
1114 if (!getLangOpts().CPlusPlus &&
1115 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1116 DiagID: diag::err_call_incomplete_argument))
1117 return ExprError();
1118
1119 return E;
1120}
1121
1122/// Convert complex integers to complex floats and real integers to
1123/// real floats as required for complex arithmetic. Helper function of
1124/// UsualArithmeticConversions()
1125///
1126/// \return false if the integer expression is an integer type and is
1127/// successfully converted to the (complex) float type.
1128static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1129 ExprResult &ComplexExpr,
1130 QualType IntTy,
1131 QualType ComplexTy,
1132 bool SkipCast) {
1133 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1134 if (SkipCast) return false;
1135 if (IntTy->isIntegerType()) {
1136 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1137 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1138 } else {
1139 assert(IntTy->isComplexIntegerType());
1140 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1141 CK: CK_IntegralComplexToFloatingComplex);
1142 }
1143 return false;
1144}
1145
1146// This handles complex/complex, complex/float, or float/complex.
1147// When both operands are complex, the shorter operand is converted to the
1148// type of the longer, and that is the type of the result. This corresponds
1149// to what is done when combining two real floating-point operands.
1150// The fun begins when size promotion occur across type domains.
1151// From H&S 6.3.4: When one operand is complex and the other is a real
1152// floating-point type, the less precise type is converted, within it's
1153// real or complex domain, to the precision of the other type. For example,
1154// when combining a "long double" with a "double _Complex", the
1155// "double _Complex" is promoted to "long double _Complex".
1156static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1157 QualType ShorterType,
1158 QualType LongerType,
1159 bool PromotePrecision) {
1160 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1161 QualType Result =
1162 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1163
1164 if (PromotePrecision) {
1165 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1166 Shorter =
1167 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1168 } else {
1169 if (LongerIsComplex)
1170 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1171 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1172 }
1173 }
1174 return Result;
1175}
1176
1177/// Handle arithmetic conversion with complex types. Helper function of
1178/// UsualArithmeticConversions()
1179static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1180 ExprResult &RHS, QualType LHSType,
1181 QualType RHSType, bool IsCompAssign) {
1182 // Handle (complex) integer types.
1183 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1184 /*SkipCast=*/false))
1185 return LHSType;
1186 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1187 /*SkipCast=*/IsCompAssign))
1188 return RHSType;
1189
1190 // Compute the rank of the two types, regardless of whether they are complex.
1191 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1192 if (Order < 0)
1193 // Promote the precision of the LHS if not an assignment.
1194 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1195 /*PromotePrecision=*/!IsCompAssign);
1196 // Promote the precision of the RHS unless it is already the same as the LHS.
1197 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1198 /*PromotePrecision=*/Order > 0);
1199}
1200
1201/// Handle arithmetic conversion from integer to float. Helper function
1202/// of UsualArithmeticConversions()
1203static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1204 ExprResult &IntExpr,
1205 QualType FloatTy, QualType IntTy,
1206 bool ConvertFloat, bool ConvertInt) {
1207 if (IntTy->isIntegerType()) {
1208 if (ConvertInt)
1209 // Convert intExpr to the lhs floating point type.
1210 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1211 CK: CK_IntegralToFloating);
1212 return FloatTy;
1213 }
1214
1215 // Convert both sides to the appropriate complex float.
1216 assert(IntTy->isComplexIntegerType());
1217 QualType result = S.Context.getComplexType(T: FloatTy);
1218
1219 // _Complex int -> _Complex float
1220 if (ConvertInt)
1221 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1222 CK: CK_IntegralComplexToFloatingComplex);
1223
1224 // float -> _Complex float
1225 if (ConvertFloat)
1226 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1227 CK: CK_FloatingRealToComplex);
1228
1229 return result;
1230}
1231
1232/// Handle arithmethic conversion with floating point types. Helper
1233/// function of UsualArithmeticConversions()
1234static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1235 ExprResult &RHS, QualType LHSType,
1236 QualType RHSType, bool IsCompAssign) {
1237 bool LHSFloat = LHSType->isRealFloatingType();
1238 bool RHSFloat = RHSType->isRealFloatingType();
1239
1240 // N1169 4.1.4: If one of the operands has a floating type and the other
1241 // operand has a fixed-point type, the fixed-point operand
1242 // is converted to the floating type [...]
1243 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1244 if (LHSFloat)
1245 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1246 else if (!IsCompAssign)
1247 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1248 return LHSFloat ? LHSType : RHSType;
1249 }
1250
1251 // If we have two real floating types, convert the smaller operand
1252 // to the bigger result.
1253 if (LHSFloat && RHSFloat) {
1254 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1255 if (order > 0) {
1256 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1257 return LHSType;
1258 }
1259
1260 assert(order < 0 && "illegal float comparison");
1261 if (!IsCompAssign)
1262 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1263 return RHSType;
1264 }
1265
1266 if (LHSFloat) {
1267 // Half FP has to be promoted to float unless it is natively supported
1268 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1269 LHSType = S.Context.FloatTy;
1270
1271 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1272 /*ConvertFloat=*/!IsCompAssign,
1273 /*ConvertInt=*/ true);
1274 }
1275 assert(RHSFloat);
1276 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1277 /*ConvertFloat=*/ true,
1278 /*ConvertInt=*/!IsCompAssign);
1279}
1280
1281/// Diagnose attempts to convert between __float128, __ibm128 and
1282/// long double if there is no support for such conversion.
1283/// Helper function of UsualArithmeticConversions().
1284static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1285 QualType RHSType) {
1286 // No issue if either is not a floating point type.
1287 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1288 return false;
1289
1290 // No issue if both have the same 128-bit float semantics.
1291 auto *LHSComplex = LHSType->getAs<ComplexType>();
1292 auto *RHSComplex = RHSType->getAs<ComplexType>();
1293
1294 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1295 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1296
1297 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1298 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1299
1300 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1301 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1302 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1303 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1304 return false;
1305
1306 return true;
1307}
1308
1309typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1310
1311namespace {
1312/// These helper callbacks are placed in an anonymous namespace to
1313/// permit their use as function template parameters.
1314ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1315 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1316}
1317
1318ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1319 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1320 CK: CK_IntegralComplexCast);
1321}
1322}
1323
1324/// Handle integer arithmetic conversions. Helper function of
1325/// UsualArithmeticConversions()
1326template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1327static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1328 ExprResult &RHS, QualType LHSType,
1329 QualType RHSType, bool IsCompAssign) {
1330 // The rules for this case are in C99 6.3.1.8
1331 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1332 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1333 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1334 if (LHSSigned == RHSSigned) {
1335 // Same signedness; use the higher-ranked type
1336 if (order >= 0) {
1337 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1338 return LHSType;
1339 } else if (!IsCompAssign)
1340 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1341 return RHSType;
1342 } else if (order != (LHSSigned ? 1 : -1)) {
1343 // The unsigned type has greater than or equal rank to the
1344 // signed type, so use the unsigned type
1345 if (RHSSigned) {
1346 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1347 return LHSType;
1348 } else if (!IsCompAssign)
1349 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1350 return RHSType;
1351 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1352 // The two types are different widths; if we are here, that
1353 // means the signed type is larger than the unsigned type, so
1354 // use the signed type.
1355 if (LHSSigned) {
1356 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1357 return LHSType;
1358 } else if (!IsCompAssign)
1359 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1360 return RHSType;
1361 } else {
1362 // The signed type is higher-ranked than the unsigned type,
1363 // but isn't actually any bigger (like unsigned int and long
1364 // on most 32-bit systems). Use the unsigned type corresponding
1365 // to the signed type.
1366 QualType result =
1367 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1368 RHS = (*doRHSCast)(S, RHS.get(), result);
1369 if (!IsCompAssign)
1370 LHS = (*doLHSCast)(S, LHS.get(), result);
1371 return result;
1372 }
1373}
1374
1375/// Handle conversions with GCC complex int extension. Helper function
1376/// of UsualArithmeticConversions()
1377static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1378 ExprResult &RHS, QualType LHSType,
1379 QualType RHSType,
1380 bool IsCompAssign) {
1381 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1382 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1383
1384 if (LHSComplexInt && RHSComplexInt) {
1385 QualType LHSEltType = LHSComplexInt->getElementType();
1386 QualType RHSEltType = RHSComplexInt->getElementType();
1387 QualType ScalarType =
1388 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1389 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1390
1391 return S.Context.getComplexType(T: ScalarType);
1392 }
1393
1394 if (LHSComplexInt) {
1395 QualType LHSEltType = LHSComplexInt->getElementType();
1396 QualType ScalarType =
1397 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1398 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1399 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1400 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1401 CK: CK_IntegralRealToComplex);
1402
1403 return ComplexType;
1404 }
1405
1406 assert(RHSComplexInt);
1407
1408 QualType RHSEltType = RHSComplexInt->getElementType();
1409 QualType ScalarType =
1410 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1411 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1412 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1413
1414 if (!IsCompAssign)
1415 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1416 CK: CK_IntegralRealToComplex);
1417 return ComplexType;
1418}
1419
1420/// Return the rank of a given fixed point or integer type. The value itself
1421/// doesn't matter, but the values must be increasing with proper increasing
1422/// rank as described in N1169 4.1.1.
1423static unsigned GetFixedPointRank(QualType Ty) {
1424 const auto *BTy = Ty->getAs<BuiltinType>();
1425 assert(BTy && "Expected a builtin type.");
1426
1427 switch (BTy->getKind()) {
1428 case BuiltinType::ShortFract:
1429 case BuiltinType::UShortFract:
1430 case BuiltinType::SatShortFract:
1431 case BuiltinType::SatUShortFract:
1432 return 1;
1433 case BuiltinType::Fract:
1434 case BuiltinType::UFract:
1435 case BuiltinType::SatFract:
1436 case BuiltinType::SatUFract:
1437 return 2;
1438 case BuiltinType::LongFract:
1439 case BuiltinType::ULongFract:
1440 case BuiltinType::SatLongFract:
1441 case BuiltinType::SatULongFract:
1442 return 3;
1443 case BuiltinType::ShortAccum:
1444 case BuiltinType::UShortAccum:
1445 case BuiltinType::SatShortAccum:
1446 case BuiltinType::SatUShortAccum:
1447 return 4;
1448 case BuiltinType::Accum:
1449 case BuiltinType::UAccum:
1450 case BuiltinType::SatAccum:
1451 case BuiltinType::SatUAccum:
1452 return 5;
1453 case BuiltinType::LongAccum:
1454 case BuiltinType::ULongAccum:
1455 case BuiltinType::SatLongAccum:
1456 case BuiltinType::SatULongAccum:
1457 return 6;
1458 default:
1459 if (BTy->isInteger())
1460 return 0;
1461 llvm_unreachable("Unexpected fixed point or integer type");
1462 }
1463}
1464
1465/// handleFixedPointConversion - Fixed point operations between fixed
1466/// point types and integers or other fixed point types do not fall under
1467/// usual arithmetic conversion since these conversions could result in loss
1468/// of precsision (N1169 4.1.4). These operations should be calculated with
1469/// the full precision of their result type (N1169 4.1.6.2.1).
1470static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1471 QualType RHSTy) {
1472 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1473 "Expected at least one of the operands to be a fixed point type");
1474 assert((LHSTy->isFixedPointOrIntegerType() ||
1475 RHSTy->isFixedPointOrIntegerType()) &&
1476 "Special fixed point arithmetic operation conversions are only "
1477 "applied to ints or other fixed point types");
1478
1479 // If one operand has signed fixed-point type and the other operand has
1480 // unsigned fixed-point type, then the unsigned fixed-point operand is
1481 // converted to its corresponding signed fixed-point type and the resulting
1482 // type is the type of the converted operand.
1483 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1484 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1485 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1486 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1487
1488 // The result type is the type with the highest rank, whereby a fixed-point
1489 // conversion rank is always greater than an integer conversion rank; if the
1490 // type of either of the operands is a saturating fixedpoint type, the result
1491 // type shall be the saturating fixed-point type corresponding to the type
1492 // with the highest rank; the resulting value is converted (taking into
1493 // account rounding and overflow) to the precision of the resulting type.
1494 // Same ranks between signed and unsigned types are resolved earlier, so both
1495 // types are either signed or both unsigned at this point.
1496 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1497 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1498
1499 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1500
1501 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1502 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1503
1504 return ResultTy;
1505}
1506
1507/// Check that the usual arithmetic conversions can be performed on this pair of
1508/// expressions that might be of enumeration type.
1509void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1510 SourceLocation Loc,
1511 ArithConvKind ACK) {
1512 // C++2a [expr.arith.conv]p1:
1513 // If one operand is of enumeration type and the other operand is of a
1514 // different enumeration type or a floating-point type, this behavior is
1515 // deprecated ([depr.arith.conv.enum]).
1516 //
1517 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1518 // Eventually we will presumably reject these cases (in C++23 onwards?).
1519 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1520 R = RHS->getEnumCoercedType(Ctx: Context);
1521 bool LEnum = L->isUnscopedEnumerationType(),
1522 REnum = R->isUnscopedEnumerationType();
1523 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1524 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1525 (REnum && L->isFloatingType())) {
1526 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1527 : getLangOpts().CPlusPlus20
1528 ? diag::warn_arith_conv_enum_float_cxx20
1529 : diag::warn_arith_conv_enum_float)
1530 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1531 << L << R;
1532 } else if (!IsCompAssign && LEnum && REnum &&
1533 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1534 unsigned DiagID;
1535 // In C++ 26, usual arithmetic conversions between 2 different enum types
1536 // are ill-formed.
1537 if (getLangOpts().CPlusPlus26)
1538 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1539 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1540 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1541 // If either enumeration type is unnamed, it's less likely that the
1542 // user cares about this, but this situation is still deprecated in
1543 // C++2a. Use a different warning group.
1544 DiagID = getLangOpts().CPlusPlus20
1545 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1546 : diag::warn_arith_conv_mixed_anon_enum_types;
1547 } else if (ACK == ArithConvKind::Conditional) {
1548 // Conditional expressions are separated out because they have
1549 // historically had a different warning flag.
1550 DiagID = getLangOpts().CPlusPlus20
1551 ? diag::warn_conditional_mixed_enum_types_cxx20
1552 : diag::warn_conditional_mixed_enum_types;
1553 } else if (ACK == ArithConvKind::Comparison) {
1554 // Comparison expressions are separated out because they have
1555 // historically had a different warning flag.
1556 DiagID = getLangOpts().CPlusPlus20
1557 ? diag::warn_comparison_mixed_enum_types_cxx20
1558 : diag::warn_comparison_mixed_enum_types;
1559 } else {
1560 DiagID = getLangOpts().CPlusPlus20
1561 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1562 : diag::warn_arith_conv_mixed_enum_types;
1563 }
1564 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1565 << (int)ACK << L << R;
1566 }
1567}
1568
1569static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1570 Expr *RHS, SourceLocation Loc,
1571 ArithConvKind ACK) {
1572 QualType LHSType = LHS->getType().getUnqualifiedType();
1573 QualType RHSType = RHS->getType().getUnqualifiedType();
1574
1575 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1576 !RHSType->isUnicodeCharacterType())
1577 return;
1578
1579 if (ACK == ArithConvKind::Comparison) {
1580 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1581 return;
1582
1583 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1584 if (T->isChar8Type())
1585 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1586 if (T->isChar16Type())
1587 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1588 assert(T->isChar32Type());
1589 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1590 };
1591
1592 Expr::EvalResult LHSRes, RHSRes;
1593 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1594 AllowSideEffects: Expr::SE_AllowSideEffects,
1595 InConstantContext: SemaRef.isConstantEvaluatedContext());
1596 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1597 AllowSideEffects: Expr::SE_AllowSideEffects,
1598 InConstantContext: SemaRef.isConstantEvaluatedContext());
1599
1600 // Don't warn if the one known value is a representable
1601 // in the type of both expressions.
1602 if (LHSSuccess != RHSuccess) {
1603 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1604 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1605 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1606 return;
1607 }
1608
1609 if (!LHSSuccess || !RHSuccess) {
1610 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1611 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1612 << RHSType;
1613 return;
1614 }
1615
1616 llvm::APSInt LHSValue(32);
1617 LHSValue = LHSRes.Val.getInt();
1618 llvm::APSInt RHSValue(32);
1619 RHSValue = RHSRes.Val.getInt();
1620
1621 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1622 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1623 if (LHSSafe && RHSSafe)
1624 return;
1625
1626 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1627 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1628 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1629 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1630 return;
1631 }
1632
1633 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1634 return;
1635
1636 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1637 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1638 << RHSType;
1639}
1640
1641/// UsualArithmeticConversions - Performs various conversions that are common to
1642/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1643/// routine returns the first non-arithmetic type found. The client is
1644/// responsible for emitting appropriate error diagnostics.
1645QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1646 SourceLocation Loc,
1647 ArithConvKind ACK) {
1648
1649 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1650
1651 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1652
1653 if (ACK != ArithConvKind::CompAssign) {
1654 LHS = UsualUnaryConversions(E: LHS.get());
1655 if (LHS.isInvalid())
1656 return QualType();
1657 }
1658
1659 RHS = UsualUnaryConversions(E: RHS.get());
1660 if (RHS.isInvalid())
1661 return QualType();
1662
1663 // For conversion purposes, we ignore any qualifiers.
1664 // For example, "const float" and "float" are equivalent.
1665 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1666 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1667
1668 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1669 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1670 LHSType = AtomicLHS->getValueType();
1671
1672 // If both types are identical, no conversion is needed.
1673 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1674 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1675
1676 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1677 // The caller can deal with this (e.g. pointer + int).
1678 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1679 return QualType();
1680
1681 // Apply unary and bitfield promotions to the LHS's type.
1682 QualType LHSUnpromotedType = LHSType;
1683 if (Context.isPromotableIntegerType(T: LHSType))
1684 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1685 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1686 if (!LHSBitfieldPromoteTy.isNull())
1687 LHSType = LHSBitfieldPromoteTy;
1688 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1689 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1690
1691 // If both types are identical, no conversion is needed.
1692 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1693 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1694
1695 // At this point, we have two different arithmetic types.
1696
1697 // Diagnose attempts to convert between __ibm128, __float128 and long double
1698 // where such conversions currently can't be handled.
1699 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1700 return QualType();
1701
1702 // Handle complex types first (C99 6.3.1.8p1).
1703 if (LHSType->isComplexType() || RHSType->isComplexType())
1704 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1705 IsCompAssign: ACK == ArithConvKind::CompAssign);
1706
1707 // Now handle "real" floating types (i.e. float, double, long double).
1708 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1709 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1710 IsCompAssign: ACK == ArithConvKind::CompAssign);
1711
1712 // Handle GCC complex int extension.
1713 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1714 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1715 IsCompAssign: ACK == ArithConvKind::CompAssign);
1716
1717 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1718 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1719
1720 // Finally, we have two differing integer types.
1721 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1722 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1723}
1724
1725//===----------------------------------------------------------------------===//
1726// Semantic Analysis for various Expression Types
1727//===----------------------------------------------------------------------===//
1728
1729
1730ExprResult Sema::ActOnGenericSelectionExpr(
1731 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1732 bool PredicateIsExpr, void *ControllingExprOrType,
1733 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1734 unsigned NumAssocs = ArgTypes.size();
1735 assert(NumAssocs == ArgExprs.size());
1736
1737 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1738 for (unsigned i = 0; i < NumAssocs; ++i) {
1739 if (ArgTypes[i])
1740 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1741 else
1742 Types[i] = nullptr;
1743 }
1744
1745 // If we have a controlling type, we need to convert it from a parsed type
1746 // into a semantic type and then pass that along.
1747 if (!PredicateIsExpr) {
1748 TypeSourceInfo *ControllingType;
1749 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1750 TInfo: &ControllingType);
1751 assert(ControllingType && "couldn't get the type out of the parser");
1752 ControllingExprOrType = ControllingType;
1753 }
1754
1755 ExprResult ER = CreateGenericSelectionExpr(
1756 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1757 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1758 delete [] Types;
1759 return ER;
1760}
1761
1762ExprResult Sema::CreateGenericSelectionExpr(
1763 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1764 bool PredicateIsExpr, void *ControllingExprOrType,
1765 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1766 unsigned NumAssocs = Types.size();
1767 assert(NumAssocs == Exprs.size());
1768 assert(ControllingExprOrType &&
1769 "Must have either a controlling expression or a controlling type");
1770
1771 Expr *ControllingExpr = nullptr;
1772 TypeSourceInfo *ControllingType = nullptr;
1773 if (PredicateIsExpr) {
1774 // Decay and strip qualifiers for the controlling expression type, and
1775 // handle placeholder type replacement. See committee discussion from WG14
1776 // DR423.
1777 EnterExpressionEvaluationContext Unevaluated(
1778 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1779 ExprResult R = DefaultFunctionArrayLvalueConversion(
1780 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1781 if (R.isInvalid())
1782 return ExprError();
1783 ControllingExpr = R.get();
1784 } else {
1785 // The extension form uses the type directly rather than converting it.
1786 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1787 if (!ControllingType)
1788 return ExprError();
1789 }
1790
1791 bool TypeErrorFound = false,
1792 IsResultDependent = ControllingExpr
1793 ? ControllingExpr->isTypeDependent()
1794 : ControllingType->getType()->isDependentType(),
1795 ContainsUnexpandedParameterPack =
1796 ControllingExpr
1797 ? ControllingExpr->containsUnexpandedParameterPack()
1798 : ControllingType->getType()->containsUnexpandedParameterPack();
1799
1800 // The controlling expression is an unevaluated operand, so side effects are
1801 // likely unintended.
1802 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1803 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1804 Diag(Loc: ControllingExpr->getExprLoc(),
1805 DiagID: diag::warn_side_effects_unevaluated_context);
1806
1807 for (unsigned i = 0; i < NumAssocs; ++i) {
1808 if (Exprs[i]->containsUnexpandedParameterPack())
1809 ContainsUnexpandedParameterPack = true;
1810
1811 if (Types[i]) {
1812 if (Types[i]->getType()->containsUnexpandedParameterPack())
1813 ContainsUnexpandedParameterPack = true;
1814
1815 if (Types[i]->getType()->isDependentType()) {
1816 IsResultDependent = true;
1817 } else {
1818 // We relax the restriction on use of incomplete types and non-object
1819 // types with the type-based extension of _Generic. Allowing incomplete
1820 // objects means those can be used as "tags" for a type-safe way to map
1821 // to a value. Similarly, matching on function types rather than
1822 // function pointer types can be useful. However, the restriction on VM
1823 // types makes sense to retain as there are open questions about how
1824 // the selection can be made at compile time.
1825 //
1826 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1827 // complete object type other than a variably modified type."
1828 // C2y removed the requirement that an expression form must
1829 // use a complete type, though it's still as-if the type has undergone
1830 // lvalue conversion. We support this as an extension in C23 and
1831 // earlier because GCC does so.
1832 unsigned D = 0;
1833 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1834 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1835 : diag::ext_assoc_type_incomplete;
1836 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1837 D = diag::err_assoc_type_nonobject;
1838 else if (Types[i]->getType()->isVariablyModifiedType())
1839 D = diag::err_assoc_type_variably_modified;
1840 else if (ControllingExpr) {
1841 // Because the controlling expression undergoes lvalue conversion,
1842 // array conversion, and function conversion, an association which is
1843 // of array type, function type, or is qualified can never be
1844 // reached. We will warn about this so users are less surprised by
1845 // the unreachable association. However, we don't have to handle
1846 // function types; that's not an object type, so it's handled above.
1847 //
1848 // The logic is somewhat different for C++ because C++ has different
1849 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1850 // If T is a non-class type, the type of the prvalue is the cv-
1851 // unqualified version of T. Otherwise, the type of the prvalue is T.
1852 // The result of these rules is that all qualified types in an
1853 // association in C are unreachable, and in C++, only qualified non-
1854 // class types are unreachable.
1855 //
1856 // NB: this does not apply when the first operand is a type rather
1857 // than an expression, because the type form does not undergo
1858 // conversion.
1859 unsigned Reason = 0;
1860 QualType QT = Types[i]->getType();
1861 if (QT->isArrayType())
1862 Reason = 1;
1863 else if (QT.hasQualifiers() &&
1864 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1865 Reason = 2;
1866
1867 if (Reason)
1868 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1869 DiagID: diag::warn_unreachable_association)
1870 << QT << (Reason - 1);
1871 }
1872
1873 if (D != 0) {
1874 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1875 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1876 if (getDiagnostics().getDiagnosticLevel(
1877 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1878 DiagnosticsEngine::Error)
1879 TypeErrorFound = true;
1880 }
1881
1882 // C11 6.5.1.1p2 "No two generic associations in the same generic
1883 // selection shall specify compatible types."
1884 for (unsigned j = i+1; j < NumAssocs; ++j)
1885 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1886 Context.typesAreCompatible(T1: Types[i]->getType(),
1887 T2: Types[j]->getType())) {
1888 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1889 DiagID: diag::err_assoc_compatible_types)
1890 << Types[j]->getTypeLoc().getSourceRange()
1891 << Types[j]->getType()
1892 << Types[i]->getType();
1893 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1894 DiagID: diag::note_compat_assoc)
1895 << Types[i]->getTypeLoc().getSourceRange()
1896 << Types[i]->getType();
1897 TypeErrorFound = true;
1898 }
1899 }
1900 }
1901 }
1902 if (TypeErrorFound)
1903 return ExprError();
1904
1905 // If we determined that the generic selection is result-dependent, don't
1906 // try to compute the result expression.
1907 if (IsResultDependent) {
1908 if (ControllingExpr)
1909 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
1910 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1911 ContainsUnexpandedParameterPack);
1912 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
1913 AssocExprs: Exprs, DefaultLoc, RParenLoc,
1914 ContainsUnexpandedParameterPack);
1915 }
1916
1917 SmallVector<unsigned, 1> CompatIndices;
1918 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
1919 // Look at the canonical type of the controlling expression in case it was a
1920 // deduced type like __auto_type. However, when issuing diagnostics, use the
1921 // type the user wrote in source rather than the canonical one.
1922 for (unsigned i = 0; i < NumAssocs; ++i) {
1923 if (!Types[i])
1924 DefaultIndex = i;
1925 else if (ControllingExpr &&
1926 Context.typesAreCompatible(
1927 T1: ControllingExpr->getType().getCanonicalType(),
1928 T2: Types[i]->getType()))
1929 CompatIndices.push_back(Elt: i);
1930 else if (ControllingType &&
1931 Context.typesAreCompatible(
1932 T1: ControllingType->getType().getCanonicalType(),
1933 T2: Types[i]->getType()))
1934 CompatIndices.push_back(Elt: i);
1935 }
1936
1937 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1938 TypeSourceInfo *ControllingType) {
1939 // We strip parens here because the controlling expression is typically
1940 // parenthesized in macro definitions.
1941 if (ControllingExpr)
1942 ControllingExpr = ControllingExpr->IgnoreParens();
1943
1944 SourceRange SR = ControllingExpr
1945 ? ControllingExpr->getSourceRange()
1946 : ControllingType->getTypeLoc().getSourceRange();
1947 QualType QT = ControllingExpr ? ControllingExpr->getType()
1948 : ControllingType->getType();
1949
1950 return std::make_pair(x&: SR, y&: QT);
1951 };
1952
1953 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1954 // type compatible with at most one of the types named in its generic
1955 // association list."
1956 if (CompatIndices.size() > 1) {
1957 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1958 SourceRange SR = P.first;
1959 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
1960 << SR << P.second << (unsigned)CompatIndices.size();
1961 for (unsigned I : CompatIndices) {
1962 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
1963 DiagID: diag::note_compat_assoc)
1964 << Types[I]->getTypeLoc().getSourceRange()
1965 << Types[I]->getType();
1966 }
1967 return ExprError();
1968 }
1969
1970 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1971 // its controlling expression shall have type compatible with exactly one of
1972 // the types named in its generic association list."
1973 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
1974 CompatIndices.size() == 0) {
1975 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1976 SourceRange SR = P.first;
1977 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
1978 return ExprError();
1979 }
1980
1981 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1982 // type name that is compatible with the type of the controlling expression,
1983 // then the result expression of the generic selection is the expression
1984 // in that generic association. Otherwise, the result expression of the
1985 // generic selection is the expression in the default generic association."
1986 unsigned ResultIndex =
1987 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1988
1989 if (ControllingExpr) {
1990 return GenericSelectionExpr::Create(
1991 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1992 ContainsUnexpandedParameterPack, ResultIndex);
1993 }
1994 return GenericSelectionExpr::Create(
1995 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1996 ContainsUnexpandedParameterPack, ResultIndex);
1997}
1998
1999static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2000 switch (Kind) {
2001 default:
2002 llvm_unreachable("unexpected TokenKind");
2003 case tok::kw___func__:
2004 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2005 case tok::kw___FUNCTION__:
2006 return PredefinedIdentKind::Function;
2007 case tok::kw___FUNCDNAME__:
2008 return PredefinedIdentKind::FuncDName; // [MS]
2009 case tok::kw___FUNCSIG__:
2010 return PredefinedIdentKind::FuncSig; // [MS]
2011 case tok::kw_L__FUNCTION__:
2012 return PredefinedIdentKind::LFunction; // [MS]
2013 case tok::kw_L__FUNCSIG__:
2014 return PredefinedIdentKind::LFuncSig; // [MS]
2015 case tok::kw___PRETTY_FUNCTION__:
2016 return PredefinedIdentKind::PrettyFunction; // [GNU]
2017 }
2018}
2019
2020/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2021/// to determine the value of a PredefinedExpr. This can be either a
2022/// block, lambda, captured statement, function, otherwise a nullptr.
2023static Decl *getPredefinedExprDecl(DeclContext *DC) {
2024 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
2025 DC = DC->getParent();
2026 return cast_or_null<Decl>(Val: DC);
2027}
2028
2029/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2030/// location of the token and the offset of the ud-suffix within it.
2031static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2032 unsigned Offset) {
2033 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2034 LangOpts: S.getLangOpts());
2035}
2036
2037/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2038/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2039static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2040 IdentifierInfo *UDSuffix,
2041 SourceLocation UDSuffixLoc,
2042 ArrayRef<Expr*> Args,
2043 SourceLocation LitEndLoc) {
2044 assert(Args.size() <= 2 && "too many arguments for literal operator");
2045
2046 QualType ArgTy[2];
2047 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2048 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2049 if (ArgTy[ArgIdx]->isArrayType())
2050 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2051 }
2052
2053 DeclarationName OpName =
2054 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2055 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2056 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2057
2058 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2059 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2060 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2061 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2062 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2063 return ExprError();
2064
2065 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2066}
2067
2068ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2069 // StringToks needs backing storage as it doesn't hold array elements itself
2070 std::vector<Token> ExpandedToks;
2071 if (getLangOpts().MicrosoftExt)
2072 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2073
2074 StringLiteralParser Literal(StringToks, PP,
2075 StringLiteralEvalMethod::Unevaluated);
2076 if (Literal.hadError)
2077 return ExprError();
2078
2079 SmallVector<SourceLocation, 4> StringTokLocs;
2080 for (const Token &Tok : StringToks)
2081 StringTokLocs.push_back(Elt: Tok.getLocation());
2082
2083 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2084 Kind: StringLiteralKind::Unevaluated,
2085 Pascal: false, Ty: {}, Locs: StringTokLocs);
2086
2087 if (!Literal.getUDSuffix().empty()) {
2088 SourceLocation UDSuffixLoc =
2089 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2090 Offset: Literal.getUDSuffixOffset());
2091 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2092 }
2093
2094 return Lit;
2095}
2096
2097std::vector<Token>
2098Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2099 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2100 // local macros that expand to string literals that may be concatenated.
2101 // These macros are expanded here (in Sema), because StringLiteralParser
2102 // (in Lex) doesn't know the enclosing function (because it hasn't been
2103 // parsed yet).
2104 assert(getLangOpts().MicrosoftExt);
2105
2106 // Note: Although function local macros are defined only inside functions,
2107 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2108 // expansion of macros into empty string literals without additional checks.
2109 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2110 if (!CurrentDecl)
2111 CurrentDecl = Context.getTranslationUnitDecl();
2112
2113 std::vector<Token> ExpandedToks;
2114 ExpandedToks.reserve(n: Toks.size());
2115 for (const Token &Tok : Toks) {
2116 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2117 assert(tok::isStringLiteral(Tok.getKind()));
2118 ExpandedToks.emplace_back(args: Tok);
2119 continue;
2120 }
2121 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2122 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2123 // Stringify predefined expression
2124 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2125 << Tok.getKind();
2126 SmallString<64> Str;
2127 llvm::raw_svector_ostream OS(Str);
2128 Token &Exp = ExpandedToks.emplace_back();
2129 Exp.startToken();
2130 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2131 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2132 OS << 'L';
2133 Exp.setKind(tok::wide_string_literal);
2134 } else {
2135 Exp.setKind(tok::string_literal);
2136 }
2137 OS << '"'
2138 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2139 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2140 << '"';
2141 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2142 }
2143 return ExpandedToks;
2144}
2145
2146ExprResult
2147Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2148 assert(!StringToks.empty() && "Must have at least one string!");
2149
2150 // StringToks needs backing storage as it doesn't hold array elements itself
2151 std::vector<Token> ExpandedToks;
2152 if (getLangOpts().MicrosoftExt)
2153 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2154
2155 StringLiteralParser Literal(StringToks, PP);
2156 if (Literal.hadError)
2157 return ExprError();
2158
2159 SmallVector<SourceLocation, 4> StringTokLocs;
2160 for (const Token &Tok : StringToks)
2161 StringTokLocs.push_back(Elt: Tok.getLocation());
2162
2163 QualType CharTy = Context.CharTy;
2164 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2165 if (Literal.isWide()) {
2166 CharTy = Context.getWideCharType();
2167 Kind = StringLiteralKind::Wide;
2168 } else if (Literal.isUTF8()) {
2169 if (getLangOpts().Char8)
2170 CharTy = Context.Char8Ty;
2171 else if (getLangOpts().C23)
2172 CharTy = Context.UnsignedCharTy;
2173 Kind = StringLiteralKind::UTF8;
2174 } else if (Literal.isUTF16()) {
2175 CharTy = Context.Char16Ty;
2176 Kind = StringLiteralKind::UTF16;
2177 } else if (Literal.isUTF32()) {
2178 CharTy = Context.Char32Ty;
2179 Kind = StringLiteralKind::UTF32;
2180 } else if (Literal.isPascal()) {
2181 CharTy = Context.UnsignedCharTy;
2182 }
2183
2184 // Warn on u8 string literals before C++20 and C23, whose type
2185 // was an array of char before but becomes an array of char8_t.
2186 // In C++20, it cannot be used where a pointer to char is expected.
2187 // In C23, it might have an unexpected value if char was signed.
2188 if (Kind == StringLiteralKind::UTF8 &&
2189 (getLangOpts().CPlusPlus
2190 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2191 : !getLangOpts().C23)) {
2192 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2193 ? diag::warn_cxx20_compat_utf8_string
2194 : diag::warn_c23_compat_utf8_string);
2195
2196 // Create removals for all 'u8' prefixes in the string literal(s). This
2197 // ensures C++20/C23 compatibility (but may change the program behavior when
2198 // built by non-Clang compilers for which the execution character set is
2199 // not always UTF-8).
2200 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2201 SourceLocation RemovalDiagLoc;
2202 for (const Token &Tok : StringToks) {
2203 if (Tok.getKind() == tok::utf8_string_literal) {
2204 if (RemovalDiagLoc.isInvalid())
2205 RemovalDiagLoc = Tok.getLocation();
2206 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2207 B: Tok.getLocation(),
2208 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2209 SM: getSourceManager(), LangOpts: getLangOpts())));
2210 }
2211 }
2212 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2213 }
2214
2215 QualType StrTy =
2216 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2217
2218 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2219 StringLiteral *Lit = StringLiteral::Create(
2220 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2221 if (Literal.getUDSuffix().empty())
2222 return Lit;
2223
2224 // We're building a user-defined literal.
2225 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2226 SourceLocation UDSuffixLoc =
2227 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2228 Offset: Literal.getUDSuffixOffset());
2229
2230 // Make sure we're allowed user-defined literals here.
2231 if (!UDLScope)
2232 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2233
2234 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2235 // operator "" X (str, len)
2236 QualType SizeType = Context.getSizeType();
2237
2238 DeclarationName OpName =
2239 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2240 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2241 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2242
2243 QualType ArgTy[] = {
2244 Context.getArrayDecayedType(T: StrTy), SizeType
2245 };
2246
2247 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2248 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2249 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2250 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2251 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2252
2253 case LOLR_Cooked: {
2254 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2255 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2256 l: StringTokLocs[0]);
2257 Expr *Args[] = { Lit, LenArg };
2258
2259 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2260 }
2261
2262 case LOLR_Template: {
2263 TemplateArgumentListInfo ExplicitArgs;
2264 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2265 TemplateArgumentLocInfo ArgInfo(Lit);
2266 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2267 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2268 ExplicitTemplateArgs: &ExplicitArgs);
2269 }
2270
2271 case LOLR_StringTemplatePack: {
2272 TemplateArgumentListInfo ExplicitArgs;
2273
2274 unsigned CharBits = Context.getIntWidth(T: CharTy);
2275 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2276 llvm::APSInt Value(CharBits, CharIsUnsigned);
2277
2278 TemplateArgument TypeArg(CharTy);
2279 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2280 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2281
2282 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2283 Value = Lit->getCodeUnit(i: I);
2284 TemplateArgument Arg(Context, Value, CharTy);
2285 TemplateArgumentLocInfo ArgInfo;
2286 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2287 }
2288 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2289 ExplicitTemplateArgs: &ExplicitArgs);
2290 }
2291 case LOLR_Raw:
2292 case LOLR_ErrorNoDiagnostic:
2293 llvm_unreachable("unexpected literal operator lookup result");
2294 case LOLR_Error:
2295 return ExprError();
2296 }
2297 llvm_unreachable("unexpected literal operator lookup result");
2298}
2299
2300DeclRefExpr *
2301Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2302 SourceLocation Loc,
2303 const CXXScopeSpec *SS) {
2304 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2305 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2306}
2307
2308DeclRefExpr *
2309Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2310 const DeclarationNameInfo &NameInfo,
2311 const CXXScopeSpec *SS, NamedDecl *FoundD,
2312 SourceLocation TemplateKWLoc,
2313 const TemplateArgumentListInfo *TemplateArgs) {
2314 NestedNameSpecifierLoc NNS =
2315 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2316 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2317 TemplateArgs);
2318}
2319
2320// CUDA/HIP: Check whether a captured reference variable is referencing a
2321// host variable in a device or host device lambda.
2322static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2323 VarDecl *VD) {
2324 if (!S.getLangOpts().CUDA || !VD->hasInit())
2325 return false;
2326 assert(VD->getType()->isReferenceType());
2327
2328 // Check whether the reference variable is referencing a host variable.
2329 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2330 if (!DRE)
2331 return false;
2332 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2333 if (!Referee || !Referee->hasGlobalStorage() ||
2334 Referee->hasAttr<CUDADeviceAttr>())
2335 return false;
2336
2337 // Check whether the current function is a device or host device lambda.
2338 // Check whether the reference variable is a capture by getDeclContext()
2339 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2340 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2341 if (MD && MD->getParent()->isLambda() &&
2342 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2343 VD->getDeclContext() != MD)
2344 return true;
2345
2346 return false;
2347}
2348
2349NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2350 // A declaration named in an unevaluated operand never constitutes an odr-use.
2351 if (isUnevaluatedContext())
2352 return NOUR_Unevaluated;
2353
2354 // C++2a [basic.def.odr]p4:
2355 // A variable x whose name appears as a potentially-evaluated expression e
2356 // is odr-used by e unless [...] x is a reference that is usable in
2357 // constant expressions.
2358 // CUDA/HIP:
2359 // If a reference variable referencing a host variable is captured in a
2360 // device or host device lambda, the value of the referee must be copied
2361 // to the capture and the reference variable must be treated as odr-use
2362 // since the value of the referee is not known at compile time and must
2363 // be loaded from the captured.
2364 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2365 if (VD->getType()->isReferenceType() &&
2366 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2367 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2368 VD->isUsableInConstantExpressions(C: Context))
2369 return NOUR_Constant;
2370 }
2371
2372 // All remaining non-variable cases constitute an odr-use. For variables, we
2373 // need to wait and see how the expression is used.
2374 return NOUR_None;
2375}
2376
2377DeclRefExpr *
2378Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2379 const DeclarationNameInfo &NameInfo,
2380 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2381 SourceLocation TemplateKWLoc,
2382 const TemplateArgumentListInfo *TemplateArgs) {
2383 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2384 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2385
2386 DeclRefExpr *E = DeclRefExpr::Create(
2387 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2388 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2389 MarkDeclRefReferenced(E);
2390
2391 // C++ [except.spec]p17:
2392 // An exception-specification is considered to be needed when:
2393 // - in an expression, the function is the unique lookup result or
2394 // the selected member of a set of overloaded functions.
2395 //
2396 // We delay doing this until after we've built the function reference and
2397 // marked it as used so that:
2398 // a) if the function is defaulted, we get errors from defining it before /
2399 // instead of errors from computing its exception specification, and
2400 // b) if the function is a defaulted comparison, we can use the body we
2401 // build when defining it as input to the exception specification
2402 // computation rather than computing a new body.
2403 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2404 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2405 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2406 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2407 }
2408 }
2409
2410 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2411 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2412 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2413 getCurFunction()->recordUseOfWeak(E);
2414
2415 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2416 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2417 FD = IFD->getAnonField();
2418 if (FD) {
2419 UnusedPrivateFields.remove(X: FD);
2420 // Just in case we're building an illegal pointer-to-member.
2421 if (FD->isBitField())
2422 E->setObjectKind(OK_BitField);
2423 }
2424
2425 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2426 // designates a bit-field.
2427 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2428 if (const auto *BE = BD->getBinding())
2429 E->setObjectKind(BE->getObjectKind());
2430
2431 return E;
2432}
2433
2434void
2435Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2436 TemplateArgumentListInfo &Buffer,
2437 DeclarationNameInfo &NameInfo,
2438 const TemplateArgumentListInfo *&TemplateArgs) {
2439 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2440 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2441 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2442
2443 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2444 Id.TemplateId->NumArgs);
2445 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2446
2447 TemplateName TName = Id.TemplateId->Template.get();
2448 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2449 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2450 TemplateArgs = &Buffer;
2451 } else {
2452 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2453 TemplateArgs = nullptr;
2454 }
2455}
2456
2457bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2458 // During a default argument instantiation the CurContext points
2459 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2460 // function parameter list, hence add an explicit check.
2461 bool isDefaultArgument =
2462 !CodeSynthesisContexts.empty() &&
2463 CodeSynthesisContexts.back().Kind ==
2464 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2465 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2466 bool isInstance = CurMethod && CurMethod->isInstance() &&
2467 R.getNamingClass() == CurMethod->getParent() &&
2468 !isDefaultArgument;
2469
2470 // There are two ways we can find a class-scope declaration during template
2471 // instantiation that we did not find in the template definition: if it is a
2472 // member of a dependent base class, or if it is declared after the point of
2473 // use in the same class. Distinguish these by comparing the class in which
2474 // the member was found to the naming class of the lookup.
2475 unsigned DiagID = diag::err_found_in_dependent_base;
2476 unsigned NoteID = diag::note_member_declared_at;
2477 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2478 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2479 : diag::err_found_later_in_class;
2480 } else if (getLangOpts().MSVCCompat) {
2481 DiagID = diag::ext_found_in_dependent_base;
2482 NoteID = diag::note_dependent_member_use;
2483 }
2484
2485 if (isInstance) {
2486 // Give a code modification hint to insert 'this->'.
2487 Diag(Loc: R.getNameLoc(), DiagID)
2488 << R.getLookupName()
2489 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2490 CheckCXXThisCapture(Loc: R.getNameLoc());
2491 } else {
2492 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2493 // they're not shadowed).
2494 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2495 }
2496
2497 for (const NamedDecl *D : R)
2498 Diag(Loc: D->getLocation(), DiagID: NoteID);
2499
2500 // Return true if we are inside a default argument instantiation
2501 // and the found name refers to an instance member function, otherwise
2502 // the caller will try to create an implicit member call and this is wrong
2503 // for default arguments.
2504 //
2505 // FIXME: Is this special case necessary? We could allow the caller to
2506 // diagnose this.
2507 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2508 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2509 return true;
2510 }
2511
2512 // Tell the callee to try to recover.
2513 return false;
2514}
2515
2516bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2517 CorrectionCandidateCallback &CCC,
2518 TemplateArgumentListInfo *ExplicitTemplateArgs,
2519 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2520 DeclarationName Name = R.getLookupName();
2521 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2522
2523 unsigned diagnostic = diag::err_undeclared_var_use;
2524 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2525 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2526 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2527 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2528 diagnostic = diag::err_undeclared_use;
2529 diagnostic_suggest = diag::err_undeclared_use_suggest;
2530 }
2531
2532 // If the original lookup was an unqualified lookup, fake an
2533 // unqualified lookup. This is useful when (for example) the
2534 // original lookup would not have found something because it was a
2535 // dependent name.
2536 DeclContext *DC =
2537 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2538 while (DC) {
2539 if (isa<CXXRecordDecl>(Val: DC)) {
2540 if (ExplicitTemplateArgs) {
2541 if (LookupTemplateName(
2542 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2543 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2544 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2545 return true;
2546 } else {
2547 LookupQualifiedName(R, LookupCtx: DC);
2548 }
2549
2550 if (!R.empty()) {
2551 // Don't give errors about ambiguities in this lookup.
2552 R.suppressDiagnostics();
2553
2554 // If there's a best viable function among the results, only mention
2555 // that one in the notes.
2556 OverloadCandidateSet Candidates(R.getNameLoc(),
2557 OverloadCandidateSet::CSK_Normal);
2558 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2559 OverloadCandidateSet::iterator Best;
2560 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2561 OR_Success) {
2562 R.clear();
2563 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2564 R.resolveKind();
2565 }
2566
2567 return DiagnoseDependentMemberLookup(R);
2568 }
2569
2570 R.clear();
2571 }
2572
2573 DC = DC->getLookupParent();
2574 }
2575
2576 // We didn't find anything, so try to correct for a typo.
2577 TypoCorrection Corrected;
2578 if (S && (Corrected =
2579 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2580 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2581 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2582 bool DroppedSpecifier =
2583 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2584 R.setLookupName(Corrected.getCorrection());
2585
2586 bool AcceptableWithRecovery = false;
2587 bool AcceptableWithoutRecovery = false;
2588 NamedDecl *ND = Corrected.getFoundDecl();
2589 if (ND) {
2590 if (Corrected.isOverloaded()) {
2591 OverloadCandidateSet OCS(R.getNameLoc(),
2592 OverloadCandidateSet::CSK_Normal);
2593 OverloadCandidateSet::iterator Best;
2594 for (NamedDecl *CD : Corrected) {
2595 if (FunctionTemplateDecl *FTD =
2596 dyn_cast<FunctionTemplateDecl>(Val: CD))
2597 AddTemplateOverloadCandidate(
2598 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2599 Args, CandidateSet&: OCS);
2600 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2601 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2602 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2603 Args, CandidateSet&: OCS);
2604 }
2605 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2606 case OR_Success:
2607 ND = Best->FoundDecl;
2608 Corrected.setCorrectionDecl(ND);
2609 break;
2610 default:
2611 // FIXME: Arbitrarily pick the first declaration for the note.
2612 Corrected.setCorrectionDecl(ND);
2613 break;
2614 }
2615 }
2616 R.addDecl(D: ND);
2617 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2618 CXXRecordDecl *Record =
2619 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2620 if (!Record)
2621 Record = cast<CXXRecordDecl>(
2622 Val: ND->getDeclContext()->getRedeclContext());
2623 R.setNamingClass(Record);
2624 }
2625
2626 auto *UnderlyingND = ND->getUnderlyingDecl();
2627 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2628 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2629 // FIXME: If we ended up with a typo for a type name or
2630 // Objective-C class name, we're in trouble because the parser
2631 // is in the wrong place to recover. Suggest the typo
2632 // correction, but don't make it a fix-it since we're not going
2633 // to recover well anyway.
2634 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2635 getAsTypeTemplateDecl(D: UnderlyingND) ||
2636 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2637 } else {
2638 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2639 // because we aren't able to recover.
2640 AcceptableWithoutRecovery = true;
2641 }
2642
2643 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2644 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2645 ? diag::note_implicit_param_decl
2646 : diag::note_previous_decl;
2647 if (SS.isEmpty())
2648 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2649 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2650 else
2651 diagnoseTypo(Correction: Corrected,
2652 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2653 << Name << computeDeclContext(SS, EnteringContext: false)
2654 << DroppedSpecifier << NameRange,
2655 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2656
2657 // Tell the callee whether to try to recover.
2658 return !AcceptableWithRecovery;
2659 }
2660 }
2661 R.clear();
2662
2663 // Emit a special diagnostic for failed member lookups.
2664 // FIXME: computing the declaration context might fail here (?)
2665 if (!SS.isEmpty()) {
2666 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2667 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2668 return true;
2669 }
2670
2671 // Give up, we can't recover.
2672 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2673 return true;
2674}
2675
2676/// In Microsoft mode, if we are inside a template class whose parent class has
2677/// dependent base classes, and we can't resolve an unqualified identifier, then
2678/// assume the identifier is a member of a dependent base class. We can only
2679/// recover successfully in static methods, instance methods, and other contexts
2680/// where 'this' is available. This doesn't precisely match MSVC's
2681/// instantiation model, but it's close enough.
2682static Expr *
2683recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2684 DeclarationNameInfo &NameInfo,
2685 SourceLocation TemplateKWLoc,
2686 const TemplateArgumentListInfo *TemplateArgs) {
2687 // Only try to recover from lookup into dependent bases in static methods or
2688 // contexts where 'this' is available.
2689 QualType ThisType = S.getCurrentThisType();
2690 const CXXRecordDecl *RD = nullptr;
2691 if (!ThisType.isNull())
2692 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2693 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2694 RD = MD->getParent();
2695 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2696 return nullptr;
2697
2698 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2699 // is available, suggest inserting 'this->' as a fixit.
2700 SourceLocation Loc = NameInfo.getLoc();
2701 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2702 DB << NameInfo.getName() << RD;
2703
2704 if (!ThisType.isNull()) {
2705 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2706 return CXXDependentScopeMemberExpr::Create(
2707 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2708 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2709 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2710 }
2711
2712 // Synthesize a fake NNS that points to the derived class. This will
2713 // perform name lookup during template instantiation.
2714 CXXScopeSpec SS;
2715 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2716 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2717 return DependentScopeDeclRefExpr::Create(
2718 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2719 TemplateArgs);
2720}
2721
2722ExprResult
2723Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2724 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2725 bool HasTrailingLParen, bool IsAddressOfOperand,
2726 CorrectionCandidateCallback *CCC,
2727 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2728 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2729 "cannot be direct & operand and have a trailing lparen");
2730 if (SS.isInvalid())
2731 return ExprError();
2732
2733 TemplateArgumentListInfo TemplateArgsBuffer;
2734
2735 // Decompose the UnqualifiedId into the following data.
2736 DeclarationNameInfo NameInfo;
2737 const TemplateArgumentListInfo *TemplateArgs;
2738 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2739
2740 DeclarationName Name = NameInfo.getName();
2741 IdentifierInfo *II = Name.getAsIdentifierInfo();
2742 SourceLocation NameLoc = NameInfo.getLoc();
2743
2744 if (II && II->isEditorPlaceholder()) {
2745 // FIXME: When typed placeholders are supported we can create a typed
2746 // placeholder expression node.
2747 return ExprError();
2748 }
2749
2750 // This specially handles arguments of attributes appertains to a type of C
2751 // struct field such that the name lookup within a struct finds the member
2752 // name, which is not the case for other contexts in C.
2753 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2754 // See if this is reference to a field of struct.
2755 LookupResult R(*this, NameInfo, LookupMemberName);
2756 // LookupName handles a name lookup from within anonymous struct.
2757 if (LookupName(R, S)) {
2758 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2759 QualType type = VD->getType().getNonReferenceType();
2760 // This will eventually be translated into MemberExpr upon
2761 // the use of instantiated struct fields.
2762 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2763 }
2764 }
2765 }
2766
2767 // Perform the required lookup.
2768 LookupResult R(*this, NameInfo,
2769 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2770 ? LookupObjCImplicitSelfParam
2771 : LookupOrdinaryName);
2772 if (TemplateKWLoc.isValid() || TemplateArgs) {
2773 // Lookup the template name again to correctly establish the context in
2774 // which it was found. This is really unfortunate as we already did the
2775 // lookup to determine that it was a template name in the first place. If
2776 // this becomes a performance hit, we can work harder to preserve those
2777 // results until we get here but it's likely not worth it.
2778 AssumedTemplateKind AssumedTemplate;
2779 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2780 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2781 ATK: &AssumedTemplate))
2782 return ExprError();
2783
2784 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2790 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2791
2792 // If the result might be in a dependent base class, this is a dependent
2793 // id-expression.
2794 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2795 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2796 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2797
2798 // If this reference is in an Objective-C method, then we need to do
2799 // some special Objective-C lookup, too.
2800 if (IvarLookupFollowUp) {
2801 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2802 if (E.isInvalid())
2803 return ExprError();
2804
2805 if (Expr *Ex = E.getAs<Expr>())
2806 return Ex;
2807 }
2808 }
2809
2810 if (R.isAmbiguous())
2811 return ExprError();
2812
2813 // This could be an implicitly declared function reference if the language
2814 // mode allows it as a feature.
2815 if (R.empty() && HasTrailingLParen && II &&
2816 getLangOpts().implicitFunctionsAllowed()) {
2817 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2818 if (D) R.addDecl(D);
2819 }
2820
2821 // Determine whether this name might be a candidate for
2822 // argument-dependent lookup.
2823 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2824
2825 if (R.empty() && !ADL) {
2826 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2827 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2828 TemplateKWLoc, TemplateArgs))
2829 return E;
2830 }
2831
2832 // Don't diagnose an empty lookup for inline assembly.
2833 if (IsInlineAsmIdentifier)
2834 return ExprError();
2835
2836 // If this name wasn't predeclared and if this is not a function
2837 // call, diagnose the problem.
2838 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2839 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2840 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2841 "Typo correction callback misconfigured");
2842 if (CCC) {
2843 // Make sure the callback knows what the typo being diagnosed is.
2844 CCC->setTypoName(II);
2845 if (SS.isValid())
2846 CCC->setTypoNNS(SS.getScopeRep());
2847 }
2848 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2849 // a template name, but we happen to have always already looked up the name
2850 // before we get here if it must be a template name.
2851 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2852 Args: {}, LookupCtx: nullptr))
2853 return ExprError();
2854
2855 assert(!R.empty() &&
2856 "DiagnoseEmptyLookup returned false but added no results");
2857
2858 // If we found an Objective-C instance variable, let
2859 // LookupInObjCMethod build the appropriate expression to
2860 // reference the ivar.
2861 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2862 R.clear();
2863 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2864 // In a hopelessly buggy code, Objective-C instance variable
2865 // lookup fails and no expression will be built to reference it.
2866 if (!E.isInvalid() && !E.get())
2867 return ExprError();
2868 return E;
2869 }
2870 }
2871
2872 // This is guaranteed from this point on.
2873 assert(!R.empty() || ADL);
2874
2875 // Check whether this might be a C++ implicit instance member access.
2876 // C++ [class.mfct.non-static]p3:
2877 // When an id-expression that is not part of a class member access
2878 // syntax and not used to form a pointer to member is used in the
2879 // body of a non-static member function of class X, if name lookup
2880 // resolves the name in the id-expression to a non-static non-type
2881 // member of some class C, the id-expression is transformed into a
2882 // class member access expression using (*this) as the
2883 // postfix-expression to the left of the . operator.
2884 //
2885 // But we don't actually need to do this for '&' operands if R
2886 // resolved to a function or overloaded function set, because the
2887 // expression is ill-formed if it actually works out to be a
2888 // non-static member function:
2889 //
2890 // C++ [expr.ref]p4:
2891 // Otherwise, if E1.E2 refers to a non-static member function. . .
2892 // [t]he expression can be used only as the left-hand operand of a
2893 // member function call.
2894 //
2895 // There are other safeguards against such uses, but it's important
2896 // to get this right here so that we don't end up making a
2897 // spuriously dependent expression if we're inside a dependent
2898 // instance method.
2899 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2900 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2901 S);
2902
2903 if (TemplateArgs || TemplateKWLoc.isValid()) {
2904
2905 // In C++1y, if this is a variable template id, then check it
2906 // in BuildTemplateIdExpr().
2907 // The single lookup result must be a variable template declaration.
2908 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2909 (Id.TemplateId->Kind == TNK_Var_template ||
2910 Id.TemplateId->Kind == TNK_Concept_template)) {
2911 assert(R.getAsSingle<TemplateDecl>() &&
2912 "There should only be one declaration found.");
2913 }
2914
2915 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
2916 }
2917
2918 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
2919}
2920
2921ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2922 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2923 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2924 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2925 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
2926
2927 if (R.isAmbiguous())
2928 return ExprError();
2929
2930 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2931 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2932 NameInfo, /*TemplateArgs=*/nullptr);
2933
2934 if (R.empty()) {
2935 // Don't diagnose problems with invalid record decl, the secondary no_member
2936 // diagnostic during template instantiation is likely bogus, e.g. if a class
2937 // is invalid because it's derived from an invalid base class, then missing
2938 // members were likely supposed to be inherited.
2939 DeclContext *DC = computeDeclContext(SS);
2940 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
2941 if (CD->isInvalidDecl())
2942 return ExprError();
2943 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
2944 << NameInfo.getName() << DC << SS.getRange();
2945 return ExprError();
2946 }
2947
2948 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2949 QualType ET;
2950 TypeLocBuilder TLB;
2951 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
2952 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
2953 Qualifier: SS.getScopeRep(), TD: TagD,
2954 /*OwnsTag=*/false);
2955 auto TL = TLB.push<TagTypeLoc>(T: ET);
2956 TL.setElaboratedKeywordLoc(SourceLocation());
2957 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2958 TL.setNameLoc(NameInfo.getLoc());
2959 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
2960 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
2961 Qualifier: SS.getScopeRep(), Decl: TypedefD);
2962 TLB.push<TypedefTypeLoc>(T: ET).set(
2963 /*ElaboratedKeywordLoc=*/SourceLocation(),
2964 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
2965 } else {
2966 // FIXME: What else can appear here?
2967 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
2968 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
2969 assert(SS.isEmpty());
2970 }
2971
2972 // Diagnose a missing typename if this resolved unambiguously to a type in
2973 // a dependent context. If we can recover with a type, downgrade this to
2974 // a warning in Microsoft compatibility mode.
2975 unsigned DiagID = diag::err_typename_missing;
2976 if (RecoveryTSI && getLangOpts().MSVCCompat)
2977 DiagID = diag::ext_typename_missing;
2978 SourceLocation Loc = SS.getBeginLoc();
2979 auto D = Diag(Loc, DiagID);
2980 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
2981
2982 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2983 // context.
2984 if (!RecoveryTSI)
2985 return ExprError();
2986
2987 // Only issue the fixit if we're prepared to recover.
2988 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
2989
2990 // Recover by pretending this was an elaborated type.
2991 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
2992
2993 return ExprEmpty();
2994 }
2995
2996 // If necessary, build an implicit class member access.
2997 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2998 return BuildPossibleImplicitMemberExpr(SS,
2999 /*TemplateKWLoc=*/SourceLocation(),
3000 R, /*TemplateArgs=*/nullptr,
3001 /*S=*/nullptr);
3002
3003 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3004}
3005
3006ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3007 NestedNameSpecifier Qualifier,
3008 NamedDecl *FoundDecl,
3009 NamedDecl *Member) {
3010 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3011 if (!RD)
3012 return From;
3013
3014 QualType DestRecordType;
3015 QualType DestType;
3016 QualType FromRecordType;
3017 QualType FromType = From->getType();
3018 bool PointerConversions = false;
3019 if (isa<FieldDecl>(Val: Member)) {
3020 DestRecordType = Context.getCanonicalTagType(TD: RD);
3021 auto FromPtrType = FromType->getAs<PointerType>();
3022 DestRecordType = Context.getAddrSpaceQualType(
3023 T: DestRecordType, AddressSpace: FromPtrType
3024 ? FromType->getPointeeType().getAddressSpace()
3025 : FromType.getAddressSpace());
3026
3027 if (FromPtrType) {
3028 DestType = Context.getPointerType(T: DestRecordType);
3029 FromRecordType = FromPtrType->getPointeeType();
3030 PointerConversions = true;
3031 } else {
3032 DestType = DestRecordType;
3033 FromRecordType = FromType;
3034 }
3035 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3036 if (!Method->isImplicitObjectMemberFunction())
3037 return From;
3038
3039 DestType = Method->getThisType().getNonReferenceType();
3040 DestRecordType = Method->getFunctionObjectParameterType();
3041
3042 if (FromType->getAs<PointerType>()) {
3043 FromRecordType = FromType->getPointeeType();
3044 PointerConversions = true;
3045 } else {
3046 FromRecordType = FromType;
3047 DestType = DestRecordType;
3048 }
3049
3050 LangAS FromAS = FromRecordType.getAddressSpace();
3051 LangAS DestAS = DestRecordType.getAddressSpace();
3052 if (FromAS != DestAS) {
3053 QualType FromRecordTypeWithoutAS =
3054 Context.removeAddrSpaceQualType(T: FromRecordType);
3055 QualType FromTypeWithDestAS =
3056 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3057 if (PointerConversions)
3058 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3059 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3060 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3061 .get();
3062 }
3063 } else {
3064 // No conversion necessary.
3065 return From;
3066 }
3067
3068 if (DestType->isDependentType() || FromType->isDependentType())
3069 return From;
3070
3071 // If the unqualified types are the same, no conversion is necessary.
3072 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3073 return From;
3074
3075 SourceRange FromRange = From->getSourceRange();
3076 SourceLocation FromLoc = FromRange.getBegin();
3077
3078 ExprValueKind VK = From->getValueKind();
3079
3080 // C++ [class.member.lookup]p8:
3081 // [...] Ambiguities can often be resolved by qualifying a name with its
3082 // class name.
3083 //
3084 // If the member was a qualified name and the qualified referred to a
3085 // specific base subobject type, we'll cast to that intermediate type
3086 // first and then to the object in which the member is declared. That allows
3087 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3088 //
3089 // class Base { public: int x; };
3090 // class Derived1 : public Base { };
3091 // class Derived2 : public Base { };
3092 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3093 //
3094 // void VeryDerived::f() {
3095 // x = 17; // error: ambiguous base subobjects
3096 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3097 // }
3098 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3099 QualType QType = QualType(Qualifier.getAsType(), 0);
3100 assert(QType->isRecordType() && "lookup done with non-record type");
3101
3102 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3103
3104 // In C++98, the qualifier type doesn't actually have to be a base
3105 // type of the object type, in which case we just ignore it.
3106 // Otherwise build the appropriate casts.
3107 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3108 CXXCastPath BasePath;
3109 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3110 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3111 return ExprError();
3112
3113 if (PointerConversions)
3114 QType = Context.getPointerType(T: QType);
3115 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3116 VK, BasePath: &BasePath).get();
3117
3118 FromType = QType;
3119 FromRecordType = QRecordType;
3120
3121 // If the qualifier type was the same as the destination type,
3122 // we're done.
3123 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3124 return From;
3125 }
3126 }
3127
3128 CXXCastPath BasePath;
3129 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3130 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3131 /*IgnoreAccess=*/true))
3132 return ExprError();
3133
3134 // Propagate qualifiers to base subobjects as per:
3135 // C++ [basic.type.qualifier]p1.2:
3136 // A volatile object is [...] a subobject of a volatile object.
3137 Qualifiers FromTypeQuals = FromType.getQualifiers();
3138 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3139 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3140
3141 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3142 BasePath: &BasePath);
3143}
3144
3145bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3146 const LookupResult &R,
3147 bool HasTrailingLParen) {
3148 // Only when used directly as the postfix-expression of a call.
3149 if (!HasTrailingLParen)
3150 return false;
3151
3152 // Never if a scope specifier was provided.
3153 if (SS.isNotEmpty())
3154 return false;
3155
3156 // Only in C++ or ObjC++.
3157 if (!getLangOpts().CPlusPlus)
3158 return false;
3159
3160 // Turn off ADL when we find certain kinds of declarations during
3161 // normal lookup:
3162 for (const NamedDecl *D : R) {
3163 // C++0x [basic.lookup.argdep]p3:
3164 // -- a declaration of a class member
3165 // Since using decls preserve this property, we check this on the
3166 // original decl.
3167 if (D->isCXXClassMember())
3168 return false;
3169
3170 // C++0x [basic.lookup.argdep]p3:
3171 // -- a block-scope function declaration that is not a
3172 // using-declaration
3173 // NOTE: we also trigger this for function templates (in fact, we
3174 // don't check the decl type at all, since all other decl types
3175 // turn off ADL anyway).
3176 if (isa<UsingShadowDecl>(Val: D))
3177 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3178 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3179 return false;
3180
3181 // C++0x [basic.lookup.argdep]p3:
3182 // -- a declaration that is neither a function or a function
3183 // template
3184 // And also for builtin functions.
3185 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3186 // But also builtin functions.
3187 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3188 return false;
3189 } else if (!isa<FunctionTemplateDecl>(Val: D))
3190 return false;
3191 }
3192
3193 return true;
3194}
3195
3196
3197/// Diagnoses obvious problems with the use of the given declaration
3198/// as an expression. This is only actually called for lookups that
3199/// were not overloaded, and it doesn't promise that the declaration
3200/// will in fact be used.
3201static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3202 bool AcceptInvalid) {
3203 if (D->isInvalidDecl() && !AcceptInvalid)
3204 return true;
3205
3206 if (isa<TypedefNameDecl>(Val: D)) {
3207 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3208 return true;
3209 }
3210
3211 if (isa<ObjCInterfaceDecl>(Val: D)) {
3212 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3213 return true;
3214 }
3215
3216 if (isa<NamespaceDecl>(Val: D)) {
3217 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3218 return true;
3219 }
3220
3221 return false;
3222}
3223
3224// Certain multiversion types should be treated as overloaded even when there is
3225// only one result.
3226static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3227 assert(R.isSingleResult() && "Expected only a single result");
3228 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3229 return FD &&
3230 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3231}
3232
3233ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3234 LookupResult &R, bool NeedsADL,
3235 bool AcceptInvalidDecl) {
3236 // If this is a single, fully-resolved result and we don't need ADL,
3237 // just build an ordinary singleton decl ref.
3238 if (!NeedsADL && R.isSingleResult() &&
3239 !R.getAsSingle<FunctionTemplateDecl>() &&
3240 !ShouldLookupResultBeMultiVersionOverload(R))
3241 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3242 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3243 AcceptInvalidDecl);
3244
3245 // We only need to check the declaration if there's exactly one
3246 // result, because in the overloaded case the results can only be
3247 // functions and function templates.
3248 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3249 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3250 AcceptInvalid: AcceptInvalidDecl))
3251 return ExprError();
3252
3253 // Otherwise, just build an unresolved lookup expression. Suppress
3254 // any lookup-related diagnostics; we'll hash these out later, when
3255 // we've picked a target.
3256 R.suppressDiagnostics();
3257
3258 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3259 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3260 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3261 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3262
3263 return ULE;
3264}
3265
3266ExprResult Sema::BuildDeclarationNameExpr(
3267 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3268 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3269 bool AcceptInvalidDecl) {
3270 assert(D && "Cannot refer to a NULL declaration");
3271 assert(!isa<FunctionTemplateDecl>(D) &&
3272 "Cannot refer unambiguously to a function template");
3273
3274 SourceLocation Loc = NameInfo.getLoc();
3275 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3276 // Recovery from invalid cases (e.g. D is an invalid Decl).
3277 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3278 // diagnostics, as invalid decls use int as a fallback type.
3279 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3280 }
3281
3282 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3283 // Specifically diagnose references to class templates that are missing
3284 // a template argument list.
3285 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3286 return ExprError();
3287 }
3288
3289 // Make sure that we're referring to a value.
3290 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3291 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3292 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3293 return ExprError();
3294 }
3295
3296 // Check whether this declaration can be used. Note that we suppress
3297 // this check when we're going to perform argument-dependent lookup
3298 // on this function name, because this might not be the function
3299 // that overload resolution actually selects.
3300 if (DiagnoseUseOfDecl(D, Locs: Loc))
3301 return ExprError();
3302
3303 auto *VD = cast<ValueDecl>(Val: D);
3304
3305 // Only create DeclRefExpr's for valid Decl's.
3306 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3307 return ExprError();
3308
3309 // Handle members of anonymous structs and unions. If we got here,
3310 // and the reference is to a class member indirect field, then this
3311 // must be the subject of a pointer-to-member expression.
3312 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3313 IndirectField && !IndirectField->isCXXClassMember())
3314 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3315 indirectField: IndirectField);
3316
3317 QualType type = VD->getType();
3318 if (type.isNull())
3319 return ExprError();
3320 ExprValueKind valueKind = VK_PRValue;
3321
3322 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3323 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3324 // is expanded by some outer '...' in the context of the use.
3325 type = type.getNonPackExpansionType();
3326
3327 switch (D->getKind()) {
3328 // Ignore all the non-ValueDecl kinds.
3329#define ABSTRACT_DECL(kind)
3330#define VALUE(type, base)
3331#define DECL(type, base) case Decl::type:
3332#include "clang/AST/DeclNodes.inc"
3333 llvm_unreachable("invalid value decl kind");
3334
3335 // These shouldn't make it here.
3336 case Decl::ObjCAtDefsField:
3337 llvm_unreachable("forming non-member reference to ivar?");
3338
3339 // Enum constants are always r-values and never references.
3340 // Unresolved using declarations are dependent.
3341 case Decl::EnumConstant:
3342 case Decl::UnresolvedUsingValue:
3343 case Decl::OMPDeclareReduction:
3344 case Decl::OMPDeclareMapper:
3345 valueKind = VK_PRValue;
3346 break;
3347
3348 // Fields and indirect fields that got here must be for
3349 // pointer-to-member expressions; we just call them l-values for
3350 // internal consistency, because this subexpression doesn't really
3351 // exist in the high-level semantics.
3352 case Decl::Field:
3353 case Decl::IndirectField:
3354 case Decl::ObjCIvar:
3355 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3356 "building reference to field in C?");
3357
3358 // These can't have reference type in well-formed programs, but
3359 // for internal consistency we do this anyway.
3360 type = type.getNonReferenceType();
3361 valueKind = VK_LValue;
3362 break;
3363
3364 // Non-type template parameters are either l-values or r-values
3365 // depending on the type.
3366 case Decl::NonTypeTemplateParm: {
3367 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3368 type = reftype->getPointeeType();
3369 valueKind = VK_LValue; // even if the parameter is an r-value reference
3370 break;
3371 }
3372
3373 // [expr.prim.id.unqual]p2:
3374 // If the entity is a template parameter object for a template
3375 // parameter of type T, the type of the expression is const T.
3376 // [...] The expression is an lvalue if the entity is a [...] template
3377 // parameter object.
3378 if (type->isRecordType()) {
3379 type = type.getUnqualifiedType().withConst();
3380 valueKind = VK_LValue;
3381 break;
3382 }
3383
3384 // For non-references, we need to strip qualifiers just in case
3385 // the template parameter was declared as 'const int' or whatever.
3386 valueKind = VK_PRValue;
3387 type = type.getUnqualifiedType();
3388 break;
3389 }
3390
3391 case Decl::Var:
3392 case Decl::VarTemplateSpecialization:
3393 case Decl::VarTemplatePartialSpecialization:
3394 case Decl::Decomposition:
3395 case Decl::Binding:
3396 case Decl::OMPCapturedExpr:
3397 // In C, "extern void blah;" is valid and is an r-value.
3398 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3399 type->isVoidType()) {
3400 valueKind = VK_PRValue;
3401 break;
3402 }
3403 [[fallthrough]];
3404
3405 case Decl::ImplicitParam:
3406 case Decl::ParmVar: {
3407 // These are always l-values.
3408 valueKind = VK_LValue;
3409 type = type.getNonReferenceType();
3410
3411 // FIXME: Does the addition of const really only apply in
3412 // potentially-evaluated contexts? Since the variable isn't actually
3413 // captured in an unevaluated context, it seems that the answer is no.
3414 if (!isUnevaluatedContext()) {
3415 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3416 if (!CapturedType.isNull())
3417 type = CapturedType;
3418 }
3419 break;
3420 }
3421
3422 case Decl::Function: {
3423 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3424 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3425 type = Context.BuiltinFnTy;
3426 valueKind = VK_PRValue;
3427 break;
3428 }
3429 }
3430
3431 const FunctionType *fty = type->castAs<FunctionType>();
3432
3433 // If we're referring to a function with an __unknown_anytype
3434 // result type, make the entire expression __unknown_anytype.
3435 if (fty->getReturnType() == Context.UnknownAnyTy) {
3436 type = Context.UnknownAnyTy;
3437 valueKind = VK_PRValue;
3438 break;
3439 }
3440
3441 // Functions are l-values in C++.
3442 if (getLangOpts().CPlusPlus) {
3443 valueKind = VK_LValue;
3444 break;
3445 }
3446
3447 // C99 DR 316 says that, if a function type comes from a
3448 // function definition (without a prototype), that type is only
3449 // used for checking compatibility. Therefore, when referencing
3450 // the function, we pretend that we don't have the full function
3451 // type.
3452 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3453 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3454 Info: fty->getExtInfo());
3455
3456 // Functions are r-values in C.
3457 valueKind = VK_PRValue;
3458 break;
3459 }
3460
3461 case Decl::CXXDeductionGuide:
3462 llvm_unreachable("building reference to deduction guide");
3463
3464 case Decl::MSProperty:
3465 case Decl::MSGuid:
3466 case Decl::TemplateParamObject:
3467 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3468 // capture in OpenMP, or duplicated between host and device?
3469 valueKind = VK_LValue;
3470 break;
3471
3472 case Decl::UnnamedGlobalConstant:
3473 valueKind = VK_LValue;
3474 break;
3475
3476 case Decl::CXXMethod:
3477 // If we're referring to a method with an __unknown_anytype
3478 // result type, make the entire expression __unknown_anytype.
3479 // This should only be possible with a type written directly.
3480 if (const FunctionProtoType *proto =
3481 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3482 if (proto->getReturnType() == Context.UnknownAnyTy) {
3483 type = Context.UnknownAnyTy;
3484 valueKind = VK_PRValue;
3485 break;
3486 }
3487
3488 // C++ methods are l-values if static, r-values if non-static.
3489 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3490 valueKind = VK_LValue;
3491 break;
3492 }
3493 [[fallthrough]];
3494
3495 case Decl::CXXConversion:
3496 case Decl::CXXDestructor:
3497 case Decl::CXXConstructor:
3498 valueKind = VK_PRValue;
3499 break;
3500 }
3501
3502 auto *E =
3503 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3504 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3505 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3506 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3507 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3508 // diagnostics).
3509 if (VD->isInvalidDecl() && E)
3510 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3511 return E;
3512}
3513
3514static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3515 SmallString<32> &Target) {
3516 Target.resize(N: CharByteWidth * (Source.size() + 1));
3517 char *ResultPtr = &Target[0];
3518 const llvm::UTF8 *ErrorPtr;
3519 bool success =
3520 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3521 (void)success;
3522 assert(success);
3523 Target.resize(N: ResultPtr - &Target[0]);
3524}
3525
3526ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3527 PredefinedIdentKind IK) {
3528 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3529 if (!currentDecl) {
3530 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3531 currentDecl = Context.getTranslationUnitDecl();
3532 }
3533
3534 QualType ResTy;
3535 StringLiteral *SL = nullptr;
3536 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3537 ResTy = Context.DependentTy;
3538 else {
3539 // Pre-defined identifiers are of type char[x], where x is the length of
3540 // the string.
3541 bool ForceElaboratedPrinting =
3542 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3543 auto Str =
3544 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3545 unsigned Length = Str.length();
3546
3547 llvm::APInt LengthI(32, Length + 1);
3548 if (IK == PredefinedIdentKind::LFunction ||
3549 IK == PredefinedIdentKind::LFuncSig) {
3550 ResTy =
3551 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3552 SmallString<32> RawChars;
3553 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3554 Source: Str, Target&: RawChars);
3555 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3556 ASM: ArraySizeModifier::Normal,
3557 /*IndexTypeQuals*/ 0);
3558 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3559 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3560 } else {
3561 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3562 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3563 ASM: ArraySizeModifier::Normal,
3564 /*IndexTypeQuals*/ 0);
3565 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3566 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3567 }
3568 }
3569
3570 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3571 SL);
3572}
3573
3574ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3575 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3576}
3577
3578ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3579 SmallString<16> CharBuffer;
3580 bool Invalid = false;
3581 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3582 if (Invalid)
3583 return ExprError();
3584
3585 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3586 PP, Tok.getKind());
3587 if (Literal.hadError())
3588 return ExprError();
3589
3590 QualType Ty;
3591 if (Literal.isWide())
3592 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3593 else if (Literal.isUTF8() && getLangOpts().C23)
3594 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3595 else if (Literal.isUTF8() && getLangOpts().Char8)
3596 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3597 else if (Literal.isUTF16())
3598 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3599 else if (Literal.isUTF32())
3600 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3601 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3602 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3603 else
3604 Ty = Context.CharTy; // 'x' -> char in C++;
3605 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3606
3607 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3608 if (Literal.isWide())
3609 Kind = CharacterLiteralKind::Wide;
3610 else if (Literal.isUTF16())
3611 Kind = CharacterLiteralKind::UTF16;
3612 else if (Literal.isUTF32())
3613 Kind = CharacterLiteralKind::UTF32;
3614 else if (Literal.isUTF8())
3615 Kind = CharacterLiteralKind::UTF8;
3616
3617 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3618 Tok.getLocation());
3619
3620 if (Literal.getUDSuffix().empty())
3621 return Lit;
3622
3623 // We're building a user-defined literal.
3624 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3625 SourceLocation UDSuffixLoc =
3626 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3627
3628 // Make sure we're allowed user-defined literals here.
3629 if (!UDLScope)
3630 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3631
3632 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3633 // operator "" X (ch)
3634 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3635 Args: Lit, LitEndLoc: Tok.getLocation());
3636}
3637
3638ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3639 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3640 return IntegerLiteral::Create(C: Context,
3641 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3642 type: Context.IntTy, l: Loc);
3643}
3644
3645static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3646 QualType Ty, SourceLocation Loc) {
3647 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3648
3649 using llvm::APFloat;
3650 APFloat Val(Format);
3651
3652 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3653 if (RM == llvm::RoundingMode::Dynamic)
3654 RM = llvm::RoundingMode::NearestTiesToEven;
3655 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3656
3657 // Overflow is always an error, but underflow is only an error if
3658 // we underflowed to zero (APFloat reports denormals as underflow).
3659 if ((result & APFloat::opOverflow) ||
3660 ((result & APFloat::opUnderflow) && Val.isZero())) {
3661 unsigned diagnostic;
3662 SmallString<20> buffer;
3663 if (result & APFloat::opOverflow) {
3664 diagnostic = diag::warn_float_overflow;
3665 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3666 } else {
3667 diagnostic = diag::warn_float_underflow;
3668 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3669 }
3670
3671 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3672 }
3673
3674 bool isExact = (result == APFloat::opOK);
3675 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3676}
3677
3678bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3679 assert(E && "Invalid expression");
3680
3681 if (E->isValueDependent())
3682 return false;
3683
3684 QualType QT = E->getType();
3685 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3686 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3687 return true;
3688 }
3689
3690 llvm::APSInt ValueAPS;
3691 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3692
3693 if (R.isInvalid())
3694 return true;
3695
3696 // GCC allows the value of unroll count to be 0.
3697 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3698 // "The values of 0 and 1 block any unrolling of the loop."
3699 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3700 // '#pragma unroll' cases.
3701 bool ValueIsPositive =
3702 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3703 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3704 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3705 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3706 return true;
3707 }
3708
3709 return false;
3710}
3711
3712ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3713 // Fast path for a single digit (which is quite common). A single digit
3714 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3715 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3716 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3717 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3718 }
3719
3720 SmallString<128> SpellingBuffer;
3721 // NumericLiteralParser wants to overread by one character. Add padding to
3722 // the buffer in case the token is copied to the buffer. If getSpelling()
3723 // returns a StringRef to the memory buffer, it should have a null char at
3724 // the EOF, so it is also safe.
3725 SpellingBuffer.resize(N: Tok.getLength() + 1);
3726
3727 // Get the spelling of the token, which eliminates trigraphs, etc.
3728 bool Invalid = false;
3729 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3730 if (Invalid)
3731 return ExprError();
3732
3733 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3734 PP.getSourceManager(), PP.getLangOpts(),
3735 PP.getTargetInfo(), PP.getDiagnostics());
3736 if (Literal.hadError)
3737 return ExprError();
3738
3739 if (Literal.hasUDSuffix()) {
3740 // We're building a user-defined literal.
3741 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3742 SourceLocation UDSuffixLoc =
3743 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3744
3745 // Make sure we're allowed user-defined literals here.
3746 if (!UDLScope)
3747 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3748
3749 QualType CookedTy;
3750 if (Literal.isFloatingLiteral()) {
3751 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3752 // long double, the literal is treated as a call of the form
3753 // operator "" X (f L)
3754 CookedTy = Context.LongDoubleTy;
3755 } else {
3756 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3757 // unsigned long long, the literal is treated as a call of the form
3758 // operator "" X (n ULL)
3759 CookedTy = Context.UnsignedLongLongTy;
3760 }
3761
3762 DeclarationName OpName =
3763 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3764 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3765 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3766
3767 SourceLocation TokLoc = Tok.getLocation();
3768
3769 // Perform literal operator lookup to determine if we're building a raw
3770 // literal or a cooked one.
3771 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3772 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3773 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3774 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3775 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3776 case LOLR_ErrorNoDiagnostic:
3777 // Lookup failure for imaginary constants isn't fatal, there's still the
3778 // GNU extension producing _Complex types.
3779 break;
3780 case LOLR_Error:
3781 return ExprError();
3782 case LOLR_Cooked: {
3783 Expr *Lit;
3784 if (Literal.isFloatingLiteral()) {
3785 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3786 } else {
3787 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3788 if (Literal.GetIntegerValue(Val&: ResultVal))
3789 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3790 << /* Unsigned */ 1;
3791 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3792 l: Tok.getLocation());
3793 }
3794 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3795 }
3796
3797 case LOLR_Raw: {
3798 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3799 // literal is treated as a call of the form
3800 // operator "" X ("n")
3801 unsigned Length = Literal.getUDSuffixOffset();
3802 QualType StrTy = Context.getConstantArrayType(
3803 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3804 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3805 Expr *Lit =
3806 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3807 Kind: StringLiteralKind::Ordinary,
3808 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3809 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3810 }
3811
3812 case LOLR_Template: {
3813 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3814 // template), L is treated as a call fo the form
3815 // operator "" X <'c1', 'c2', ... 'ck'>()
3816 // where n is the source character sequence c1 c2 ... ck.
3817 TemplateArgumentListInfo ExplicitArgs;
3818 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3819 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3820 llvm::APSInt Value(CharBits, CharIsUnsigned);
3821 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3822 Value = TokSpelling[I];
3823 TemplateArgument Arg(Context, Value, Context.CharTy);
3824 TemplateArgumentLocInfo ArgInfo;
3825 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3826 }
3827 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3828 }
3829 case LOLR_StringTemplatePack:
3830 llvm_unreachable("unexpected literal operator lookup result");
3831 }
3832 }
3833
3834 Expr *Res;
3835
3836 if (Literal.isFixedPointLiteral()) {
3837 QualType Ty;
3838
3839 if (Literal.isAccum) {
3840 if (Literal.isHalf) {
3841 Ty = Context.ShortAccumTy;
3842 } else if (Literal.isLong) {
3843 Ty = Context.LongAccumTy;
3844 } else {
3845 Ty = Context.AccumTy;
3846 }
3847 } else if (Literal.isFract) {
3848 if (Literal.isHalf) {
3849 Ty = Context.ShortFractTy;
3850 } else if (Literal.isLong) {
3851 Ty = Context.LongFractTy;
3852 } else {
3853 Ty = Context.FractTy;
3854 }
3855 }
3856
3857 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
3858
3859 bool isSigned = !Literal.isUnsigned;
3860 unsigned scale = Context.getFixedPointScale(Ty);
3861 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
3862
3863 llvm::APInt Val(bit_width, 0, isSigned);
3864 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
3865 bool ValIsZero = Val.isZero() && !Overflowed;
3866
3867 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3868 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3869 // Clause 6.4.4 - The value of a constant shall be in the range of
3870 // representable values for its type, with exception for constants of a
3871 // fract type with a value of exactly 1; such a constant shall denote
3872 // the maximal value for the type.
3873 --Val;
3874 else if (Val.ugt(RHS: MaxVal) || Overflowed)
3875 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
3876
3877 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
3878 l: Tok.getLocation(), Scale: scale);
3879 } else if (Literal.isFloatingLiteral()) {
3880 QualType Ty;
3881 if (Literal.isHalf){
3882 if (getLangOpts().HLSL ||
3883 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
3884 Ty = Context.HalfTy;
3885 else {
3886 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
3887 return ExprError();
3888 }
3889 } else if (Literal.isFloat)
3890 Ty = Context.FloatTy;
3891 else if (Literal.isLong)
3892 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3893 else if (Literal.isFloat16)
3894 Ty = Context.Float16Ty;
3895 else if (Literal.isFloat128)
3896 Ty = Context.Float128Ty;
3897 else if (getLangOpts().HLSL)
3898 Ty = Context.FloatTy;
3899 else
3900 Ty = Context.DoubleTy;
3901
3902 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
3903
3904 if (Ty == Context.DoubleTy) {
3905 if (getLangOpts().SinglePrecisionConstants) {
3906 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3907 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
3908 }
3909 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3910 Ext: "cl_khr_fp64", LO: getLangOpts())) {
3911 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3912 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
3913 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3914 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
3915 }
3916 }
3917 } else if (!Literal.isIntegerLiteral()) {
3918 return ExprError();
3919 } else {
3920 QualType Ty;
3921
3922 // 'z/uz' literals are a C++23 feature.
3923 if (Literal.isSizeT)
3924 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
3925 ? getLangOpts().CPlusPlus23
3926 ? diag::warn_cxx20_compat_size_t_suffix
3927 : diag::ext_cxx23_size_t_suffix
3928 : diag::err_cxx23_size_t_suffix);
3929
3930 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3931 // but we do not currently support the suffix in C++ mode because it's not
3932 // entirely clear whether WG21 will prefer this suffix to return a library
3933 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3934 // literals are a C++ extension.
3935 if (Literal.isBitInt)
3936 PP.Diag(Loc: Tok.getLocation(),
3937 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3938 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3939 : diag::ext_c23_bitint_suffix);
3940
3941 // Get the value in the widest-possible width. What is "widest" depends on
3942 // whether the literal is a bit-precise integer or not. For a bit-precise
3943 // integer type, try to scan the source to determine how many bits are
3944 // needed to represent the value. This may seem a bit expensive, but trying
3945 // to get the integer value from an overly-wide APInt is *extremely*
3946 // expensive, so the naive approach of assuming
3947 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3948 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
3949 if (Literal.isBitInt)
3950 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
3951 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
3952 if (Literal.MicrosoftInteger) {
3953 if (Literal.MicrosoftInteger == 128 &&
3954 !Context.getTargetInfo().hasInt128Type())
3955 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3956 << Literal.isUnsigned;
3957 BitsNeeded = Literal.MicrosoftInteger;
3958 }
3959
3960 llvm::APInt ResultVal(BitsNeeded, 0);
3961
3962 if (Literal.GetIntegerValue(Val&: ResultVal)) {
3963 // If this value didn't fit into uintmax_t, error and force to ull.
3964 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3965 << /* Unsigned */ 1;
3966 Ty = Context.UnsignedLongLongTy;
3967 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3968 "long long is not intmax_t?");
3969 } else {
3970 // If this value fits into a ULL, try to figure out what else it fits into
3971 // according to the rules of C99 6.4.4.1p5.
3972
3973 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3974 // be an unsigned int.
3975 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3976
3977 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3978 // suffix for portability of code with C++, but both `l` and `ll` are
3979 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3980 // same.
3981 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3982 Literal.isLong = true;
3983 Literal.isLongLong = false;
3984 }
3985
3986 // Check from smallest to largest, picking the smallest type we can.
3987 unsigned Width = 0;
3988
3989 // Microsoft specific integer suffixes are explicitly sized.
3990 if (Literal.MicrosoftInteger) {
3991 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3992 Width = 8;
3993 Ty = Context.CharTy;
3994 } else {
3995 Width = Literal.MicrosoftInteger;
3996 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
3997 /*Signed=*/!Literal.isUnsigned);
3998 }
3999 }
4000
4001 // Bit-precise integer literals are automagically-sized based on the
4002 // width required by the literal.
4003 if (Literal.isBitInt) {
4004 // The signed version has one more bit for the sign value. There are no
4005 // zero-width bit-precise integers, even if the literal value is 0.
4006 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4007 (Literal.isUnsigned ? 0u : 1u);
4008
4009 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4010 // and reset the type to the largest supported width.
4011 unsigned int MaxBitIntWidth =
4012 Context.getTargetInfo().getMaxBitIntWidth();
4013 if (Width > MaxBitIntWidth) {
4014 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4015 << Literal.isUnsigned;
4016 Width = MaxBitIntWidth;
4017 }
4018
4019 // Reset the result value to the smaller APInt and select the correct
4020 // type to be used. Note, we zext even for signed values because the
4021 // literal itself is always an unsigned value (a preceeding - is a
4022 // unary operator, not part of the literal).
4023 ResultVal = ResultVal.zextOrTrunc(width: Width);
4024 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4025 }
4026
4027 // Check C++23 size_t literals.
4028 if (Literal.isSizeT) {
4029 assert(!Literal.MicrosoftInteger &&
4030 "size_t literals can't be Microsoft literals");
4031 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4032 T: Context.getTargetInfo().getSizeType());
4033
4034 // Does it fit in size_t?
4035 if (ResultVal.isIntN(N: SizeTSize)) {
4036 // Does it fit in ssize_t?
4037 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4038 Ty = Context.getSignedSizeType();
4039 else if (AllowUnsigned)
4040 Ty = Context.getSizeType();
4041 Width = SizeTSize;
4042 }
4043 }
4044
4045 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4046 !Literal.isSizeT) {
4047 // Are int/unsigned possibilities?
4048 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4049
4050 // Does it fit in a unsigned int?
4051 if (ResultVal.isIntN(N: IntSize)) {
4052 // Does it fit in a signed int?
4053 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4054 Ty = Context.IntTy;
4055 else if (AllowUnsigned)
4056 Ty = Context.UnsignedIntTy;
4057 Width = IntSize;
4058 }
4059 }
4060
4061 // Are long/unsigned long possibilities?
4062 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4063 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4064
4065 // Does it fit in a unsigned long?
4066 if (ResultVal.isIntN(N: LongSize)) {
4067 // Does it fit in a signed long?
4068 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4069 Ty = Context.LongTy;
4070 else if (AllowUnsigned)
4071 Ty = Context.UnsignedLongTy;
4072 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4073 // is compatible.
4074 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4075 const unsigned LongLongSize =
4076 Context.getTargetInfo().getLongLongWidth();
4077 Diag(Loc: Tok.getLocation(),
4078 DiagID: getLangOpts().CPlusPlus
4079 ? Literal.isLong
4080 ? diag::warn_old_implicitly_unsigned_long_cxx
4081 : /*C++98 UB*/ diag::
4082 ext_old_implicitly_unsigned_long_cxx
4083 : diag::warn_old_implicitly_unsigned_long)
4084 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4085 : /*will be ill-formed*/ 1);
4086 Ty = Context.UnsignedLongTy;
4087 }
4088 Width = LongSize;
4089 }
4090 }
4091
4092 // Check long long if needed.
4093 if (Ty.isNull() && !Literal.isSizeT) {
4094 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4095
4096 // Does it fit in a unsigned long long?
4097 if (ResultVal.isIntN(N: LongLongSize)) {
4098 // Does it fit in a signed long long?
4099 // To be compatible with MSVC, hex integer literals ending with the
4100 // LL or i64 suffix are always signed in Microsoft mode.
4101 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4102 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4103 Ty = Context.LongLongTy;
4104 else if (AllowUnsigned)
4105 Ty = Context.UnsignedLongLongTy;
4106 Width = LongLongSize;
4107
4108 // 'long long' is a C99 or C++11 feature, whether the literal
4109 // explicitly specified 'long long' or we needed the extra width.
4110 if (getLangOpts().CPlusPlus)
4111 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4112 ? diag::warn_cxx98_compat_longlong
4113 : diag::ext_cxx11_longlong);
4114 else if (!getLangOpts().C99)
4115 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4116 }
4117 }
4118
4119 // If we still couldn't decide a type, we either have 'size_t' literal
4120 // that is out of range, or a decimal literal that does not fit in a
4121 // signed long long and has no U suffix.
4122 if (Ty.isNull()) {
4123 if (Literal.isSizeT)
4124 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4125 << Literal.isUnsigned;
4126 else
4127 Diag(Loc: Tok.getLocation(),
4128 DiagID: diag::ext_integer_literal_too_large_for_signed);
4129 Ty = Context.UnsignedLongLongTy;
4130 Width = Context.getTargetInfo().getLongLongWidth();
4131 }
4132
4133 if (ResultVal.getBitWidth() != Width)
4134 ResultVal = ResultVal.trunc(width: Width);
4135 }
4136 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4137 }
4138
4139 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4140 if (Literal.isImaginary) {
4141 Res = new (Context) ImaginaryLiteral(Res,
4142 Context.getComplexType(T: Res->getType()));
4143
4144 // In C++, this is a GNU extension. In C, it's a C2y extension.
4145 unsigned DiagId;
4146 if (getLangOpts().CPlusPlus)
4147 DiagId = diag::ext_gnu_imaginary_constant;
4148 else if (getLangOpts().C2y)
4149 DiagId = diag::warn_c23_compat_imaginary_constant;
4150 else
4151 DiagId = diag::ext_c2y_imaginary_constant;
4152 Diag(Loc: Tok.getLocation(), DiagID: DiagId);
4153 }
4154 return Res;
4155}
4156
4157ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4158 assert(E && "ActOnParenExpr() missing expr");
4159 QualType ExprTy = E->getType();
4160 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4161 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4162 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4163 return new (Context) ParenExpr(L, R, E);
4164}
4165
4166static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4167 SourceLocation Loc,
4168 SourceRange ArgRange) {
4169 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4170 // scalar or vector data type argument..."
4171 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4172 // type (C99 6.2.5p18) or void.
4173 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4174 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4175 << T << ArgRange;
4176 return true;
4177 }
4178
4179 assert((T->isVoidType() || !T->isIncompleteType()) &&
4180 "Scalar types should always be complete");
4181 return false;
4182}
4183
4184static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4185 SourceLocation Loc,
4186 SourceRange ArgRange) {
4187 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4188 if (!T->isVectorType() && !T->isSizelessVectorType())
4189 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4190 << ""
4191 << "__builtin_vectorelements" << T << ArgRange;
4192
4193 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4194 if (T->isSVESizelessBuiltinType()) {
4195 llvm::StringMap<bool> CallerFeatureMap;
4196 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4197 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4198 }
4199 }
4200
4201 return false;
4202}
4203
4204static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4205 SourceLocation Loc,
4206 SourceRange ArgRange) {
4207 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4208 return true;
4209
4210 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4211 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4212 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4213 return true;
4214 }
4215
4216 return false;
4217}
4218
4219static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4220 SourceLocation Loc,
4221 SourceRange ArgRange,
4222 UnaryExprOrTypeTrait TraitKind) {
4223 // Invalid types must be hard errors for SFINAE in C++.
4224 if (S.LangOpts.CPlusPlus)
4225 return true;
4226
4227 // C99 6.5.3.4p1:
4228 if (T->isFunctionType() &&
4229 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4230 TraitKind == UETT_PreferredAlignOf)) {
4231 // sizeof(function)/alignof(function) is allowed as an extension.
4232 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4233 << getTraitSpelling(T: TraitKind) << ArgRange;
4234 return false;
4235 }
4236
4237 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4238 // this is an error (OpenCL v1.1 s6.3.k)
4239 if (T->isVoidType()) {
4240 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4241 : diag::ext_sizeof_alignof_void_type;
4242 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4243 return false;
4244 }
4245
4246 return true;
4247}
4248
4249static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4250 SourceLocation Loc,
4251 SourceRange ArgRange,
4252 UnaryExprOrTypeTrait TraitKind) {
4253 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4254 // runtime doesn't allow it.
4255 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4256 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4257 << T << (TraitKind == UETT_SizeOf)
4258 << ArgRange;
4259 return true;
4260 }
4261
4262 return false;
4263}
4264
4265/// Check whether E is a pointer from a decayed array type (the decayed
4266/// pointer type is equal to T) and emit a warning if it is.
4267static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4268 const Expr *E) {
4269 // Don't warn if the operation changed the type.
4270 if (T != E->getType())
4271 return;
4272
4273 // Now look for array decays.
4274 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4275 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4276 return;
4277
4278 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4279 << ICE->getType()
4280 << ICE->getSubExpr()->getType();
4281}
4282
4283bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4284 UnaryExprOrTypeTrait ExprKind) {
4285 QualType ExprTy = E->getType();
4286 assert(!ExprTy->isReferenceType());
4287
4288 bool IsUnevaluatedOperand =
4289 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4290 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4291 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4292 if (IsUnevaluatedOperand) {
4293 ExprResult Result = CheckUnevaluatedOperand(E);
4294 if (Result.isInvalid())
4295 return true;
4296 E = Result.get();
4297 }
4298
4299 // The operand for sizeof and alignof is in an unevaluated expression context,
4300 // so side effects could result in unintended consequences.
4301 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4302 // used to build SFINAE gadgets.
4303 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4304 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4305 !E->isInstantiationDependent() &&
4306 !E->getType()->isVariableArrayType() &&
4307 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4308 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4309
4310 if (ExprKind == UETT_VecStep)
4311 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4312 ArgRange: E->getSourceRange());
4313
4314 if (ExprKind == UETT_VectorElements)
4315 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4316 ArgRange: E->getSourceRange());
4317
4318 // Explicitly list some types as extensions.
4319 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4320 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4321 return false;
4322
4323 // WebAssembly tables are always illegal operands to unary expressions and
4324 // type traits.
4325 if (Context.getTargetInfo().getTriple().isWasm() &&
4326 E->getType()->isWebAssemblyTableType()) {
4327 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4328 << getTraitSpelling(T: ExprKind);
4329 return true;
4330 }
4331
4332 // 'alignof' applied to an expression only requires the base element type of
4333 // the expression to be complete. 'sizeof' requires the expression's type to
4334 // be complete (and will attempt to complete it if it's an array of unknown
4335 // bound).
4336 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4337 if (RequireCompleteSizedType(
4338 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4339 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4340 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4341 return true;
4342 } else {
4343 if (RequireCompleteSizedExprType(
4344 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4345 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4346 return true;
4347 }
4348
4349 // Completing the expression's type may have changed it.
4350 ExprTy = E->getType();
4351 assert(!ExprTy->isReferenceType());
4352
4353 if (ExprTy->isFunctionType()) {
4354 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4355 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4356 return true;
4357 }
4358
4359 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4360 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4361 return true;
4362
4363 if (ExprKind == UETT_CountOf) {
4364 // The type has to be an array type. We already checked for incomplete
4365 // types above.
4366 QualType ExprType = E->IgnoreParens()->getType();
4367 if (!ExprType->isArrayType()) {
4368 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4369 return true;
4370 }
4371 // FIXME: warn on _Countof on an array parameter. Not warning on it
4372 // currently because there are papers in WG14 about array types which do
4373 // not decay that could impact this behavior, so we want to see if anything
4374 // changes here before coming up with a warning group for _Countof-related
4375 // diagnostics.
4376 }
4377
4378 if (ExprKind == UETT_SizeOf) {
4379 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4380 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4381 QualType OType = PVD->getOriginalType();
4382 QualType Type = PVD->getType();
4383 if (Type->isPointerType() && OType->isArrayType()) {
4384 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4385 << Type << OType;
4386 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4387 }
4388 }
4389 }
4390
4391 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4392 // decays into a pointer and returns an unintended result. This is most
4393 // likely a typo for "sizeof(array) op x".
4394 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4395 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4396 E: BO->getLHS());
4397 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4398 E: BO->getRHS());
4399 }
4400 }
4401
4402 return false;
4403}
4404
4405static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4406 // Cannot know anything else if the expression is dependent.
4407 if (E->isTypeDependent())
4408 return false;
4409
4410 if (E->getObjectKind() == OK_BitField) {
4411 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4412 << 1 << E->getSourceRange();
4413 return true;
4414 }
4415
4416 ValueDecl *D = nullptr;
4417 Expr *Inner = E->IgnoreParens();
4418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4419 D = DRE->getDecl();
4420 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4421 D = ME->getMemberDecl();
4422 }
4423
4424 // If it's a field, require the containing struct to have a
4425 // complete definition so that we can compute the layout.
4426 //
4427 // This can happen in C++11 onwards, either by naming the member
4428 // in a way that is not transformed into a member access expression
4429 // (in an unevaluated operand, for instance), or by naming the member
4430 // in a trailing-return-type.
4431 //
4432 // For the record, since __alignof__ on expressions is a GCC
4433 // extension, GCC seems to permit this but always gives the
4434 // nonsensical answer 0.
4435 //
4436 // We don't really need the layout here --- we could instead just
4437 // directly check for all the appropriate alignment-lowing
4438 // attributes --- but that would require duplicating a lot of
4439 // logic that just isn't worth duplicating for such a marginal
4440 // use-case.
4441 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4442 // Fast path this check, since we at least know the record has a
4443 // definition if we can find a member of it.
4444 if (!FD->getParent()->isCompleteDefinition()) {
4445 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4446 << E->getSourceRange();
4447 return true;
4448 }
4449
4450 // Otherwise, if it's a field, and the field doesn't have
4451 // reference type, then it must have a complete type (or be a
4452 // flexible array member, which we explicitly want to
4453 // white-list anyway), which makes the following checks trivial.
4454 if (!FD->getType()->isReferenceType())
4455 return false;
4456 }
4457
4458 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4459}
4460
4461bool Sema::CheckVecStepExpr(Expr *E) {
4462 E = E->IgnoreParens();
4463
4464 // Cannot know anything else if the expression is dependent.
4465 if (E->isTypeDependent())
4466 return false;
4467
4468 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4469}
4470
4471static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4472 CapturingScopeInfo *CSI) {
4473 assert(T->isVariablyModifiedType());
4474 assert(CSI != nullptr);
4475
4476 // We're going to walk down into the type and look for VLA expressions.
4477 do {
4478 const Type *Ty = T.getTypePtr();
4479 switch (Ty->getTypeClass()) {
4480#define TYPE(Class, Base)
4481#define ABSTRACT_TYPE(Class, Base)
4482#define NON_CANONICAL_TYPE(Class, Base)
4483#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4484#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4485#include "clang/AST/TypeNodes.inc"
4486 T = QualType();
4487 break;
4488 // These types are never variably-modified.
4489 case Type::Builtin:
4490 case Type::Complex:
4491 case Type::Vector:
4492 case Type::ExtVector:
4493 case Type::ConstantMatrix:
4494 case Type::Record:
4495 case Type::Enum:
4496 case Type::TemplateSpecialization:
4497 case Type::ObjCObject:
4498 case Type::ObjCInterface:
4499 case Type::ObjCObjectPointer:
4500 case Type::ObjCTypeParam:
4501 case Type::Pipe:
4502 case Type::BitInt:
4503 case Type::HLSLInlineSpirv:
4504 llvm_unreachable("type class is never variably-modified!");
4505 case Type::Adjusted:
4506 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4507 break;
4508 case Type::Decayed:
4509 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4510 break;
4511 case Type::ArrayParameter:
4512 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4513 break;
4514 case Type::Pointer:
4515 T = cast<PointerType>(Val: Ty)->getPointeeType();
4516 break;
4517 case Type::BlockPointer:
4518 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4519 break;
4520 case Type::LValueReference:
4521 case Type::RValueReference:
4522 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4523 break;
4524 case Type::MemberPointer:
4525 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4526 break;
4527 case Type::ConstantArray:
4528 case Type::IncompleteArray:
4529 // Losing element qualification here is fine.
4530 T = cast<ArrayType>(Val: Ty)->getElementType();
4531 break;
4532 case Type::VariableArray: {
4533 // Losing element qualification here is fine.
4534 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4535
4536 // Unknown size indication requires no size computation.
4537 // Otherwise, evaluate and record it.
4538 auto Size = VAT->getSizeExpr();
4539 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4540 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4541 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4542
4543 T = VAT->getElementType();
4544 break;
4545 }
4546 case Type::FunctionProto:
4547 case Type::FunctionNoProto:
4548 T = cast<FunctionType>(Val: Ty)->getReturnType();
4549 break;
4550 case Type::Paren:
4551 case Type::TypeOf:
4552 case Type::UnaryTransform:
4553 case Type::Attributed:
4554 case Type::BTFTagAttributed:
4555 case Type::HLSLAttributedResource:
4556 case Type::SubstTemplateTypeParm:
4557 case Type::MacroQualified:
4558 case Type::CountAttributed:
4559 // Keep walking after single level desugaring.
4560 T = T.getSingleStepDesugaredType(Context);
4561 break;
4562 case Type::Typedef:
4563 T = cast<TypedefType>(Val: Ty)->desugar();
4564 break;
4565 case Type::Decltype:
4566 T = cast<DecltypeType>(Val: Ty)->desugar();
4567 break;
4568 case Type::PackIndexing:
4569 T = cast<PackIndexingType>(Val: Ty)->desugar();
4570 break;
4571 case Type::Using:
4572 T = cast<UsingType>(Val: Ty)->desugar();
4573 break;
4574 case Type::Auto:
4575 case Type::DeducedTemplateSpecialization:
4576 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4577 break;
4578 case Type::TypeOfExpr:
4579 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4580 break;
4581 case Type::Atomic:
4582 T = cast<AtomicType>(Val: Ty)->getValueType();
4583 break;
4584 case Type::PredefinedSugar:
4585 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4586 break;
4587 }
4588 } while (!T.isNull() && T->isVariablyModifiedType());
4589}
4590
4591bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4592 SourceLocation OpLoc,
4593 SourceRange ExprRange,
4594 UnaryExprOrTypeTrait ExprKind,
4595 StringRef KWName) {
4596 if (ExprType->isDependentType())
4597 return false;
4598
4599 // C++ [expr.sizeof]p2:
4600 // When applied to a reference or a reference type, the result
4601 // is the size of the referenced type.
4602 // C++11 [expr.alignof]p3:
4603 // When alignof is applied to a reference type, the result
4604 // shall be the alignment of the referenced type.
4605 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4606 ExprType = Ref->getPointeeType();
4607
4608 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4609 // When alignof or _Alignof is applied to an array type, the result
4610 // is the alignment of the element type.
4611 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4612 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4613 // If the trait is 'alignof' in C before C2y, the ability to apply the
4614 // trait to an incomplete array is an extension.
4615 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4616 ExprType->isIncompleteArrayType())
4617 Diag(Loc: OpLoc, DiagID: getLangOpts().C2y
4618 ? diag::warn_c2y_compat_alignof_incomplete_array
4619 : diag::ext_c2y_alignof_incomplete_array);
4620 ExprType = Context.getBaseElementType(QT: ExprType);
4621 }
4622
4623 if (ExprKind == UETT_VecStep)
4624 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4625
4626 if (ExprKind == UETT_VectorElements)
4627 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4628 ArgRange: ExprRange);
4629
4630 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4631 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4632 ArgRange: ExprRange);
4633
4634 // Explicitly list some types as extensions.
4635 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4636 TraitKind: ExprKind))
4637 return false;
4638
4639 if (RequireCompleteSizedType(
4640 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4641 Args: KWName, Args: ExprRange))
4642 return true;
4643
4644 if (ExprType->isFunctionType()) {
4645 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4646 return true;
4647 }
4648
4649 if (ExprKind == UETT_CountOf) {
4650 // The type has to be an array type. We already checked for incomplete
4651 // types above.
4652 if (!ExprType->isArrayType()) {
4653 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4654 return true;
4655 }
4656 }
4657
4658 // WebAssembly tables are always illegal operands to unary expressions and
4659 // type traits.
4660 if (Context.getTargetInfo().getTriple().isWasm() &&
4661 ExprType->isWebAssemblyTableType()) {
4662 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4663 << getTraitSpelling(T: ExprKind);
4664 return true;
4665 }
4666
4667 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4668 TraitKind: ExprKind))
4669 return true;
4670
4671 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4672 if (auto *TT = ExprType->getAs<TypedefType>()) {
4673 for (auto I = FunctionScopes.rbegin(),
4674 E = std::prev(x: FunctionScopes.rend());
4675 I != E; ++I) {
4676 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4677 if (CSI == nullptr)
4678 break;
4679 DeclContext *DC = nullptr;
4680 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4681 DC = LSI->CallOperator;
4682 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4683 DC = CRSI->TheCapturedDecl;
4684 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4685 DC = BSI->TheDecl;
4686 if (DC) {
4687 if (DC->containsDecl(D: TT->getDecl()))
4688 break;
4689 captureVariablyModifiedType(Context, T: ExprType, CSI);
4690 }
4691 }
4692 }
4693 }
4694
4695 return false;
4696}
4697
4698ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4699 SourceLocation OpLoc,
4700 UnaryExprOrTypeTrait ExprKind,
4701 SourceRange R) {
4702 if (!TInfo)
4703 return ExprError();
4704
4705 QualType T = TInfo->getType();
4706
4707 if (!T->isDependentType() &&
4708 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4709 KWName: getTraitSpelling(T: ExprKind)))
4710 return ExprError();
4711
4712 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4713 // properly deal with VLAs in nested calls of sizeof and typeof.
4714 if (currentEvaluationContext().isUnevaluated() &&
4715 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4716 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4717 TInfo->getType()->isVariablyModifiedType())
4718 TInfo = TransformToPotentiallyEvaluated(TInfo);
4719
4720 // It's possible that the transformation above failed.
4721 if (!TInfo)
4722 return ExprError();
4723
4724 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4725 return new (Context) UnaryExprOrTypeTraitExpr(
4726 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4727}
4728
4729ExprResult
4730Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4731 UnaryExprOrTypeTrait ExprKind) {
4732 ExprResult PE = CheckPlaceholderExpr(E);
4733 if (PE.isInvalid())
4734 return ExprError();
4735
4736 E = PE.get();
4737
4738 // Verify that the operand is valid.
4739 bool isInvalid = false;
4740 if (E->isTypeDependent()) {
4741 // Delay type-checking for type-dependent expressions.
4742 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4743 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4744 } else if (ExprKind == UETT_VecStep) {
4745 isInvalid = CheckVecStepExpr(E);
4746 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4747 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4748 isInvalid = true;
4749 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4750 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4751 isInvalid = true;
4752 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4753 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4754 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4755 }
4756
4757 if (isInvalid)
4758 return ExprError();
4759
4760 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4761 E->getType()->isVariableArrayType()) {
4762 PE = TransformToPotentiallyEvaluated(E);
4763 if (PE.isInvalid()) return ExprError();
4764 E = PE.get();
4765 }
4766
4767 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4768 return new (Context) UnaryExprOrTypeTraitExpr(
4769 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4770}
4771
4772ExprResult
4773Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4774 UnaryExprOrTypeTrait ExprKind, bool IsType,
4775 void *TyOrEx, SourceRange ArgRange) {
4776 // If error parsing type, ignore.
4777 if (!TyOrEx) return ExprError();
4778
4779 if (IsType) {
4780 TypeSourceInfo *TInfo;
4781 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4782 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4783 }
4784
4785 Expr *ArgEx = (Expr *)TyOrEx;
4786 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4787 return Result;
4788}
4789
4790bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4791 SourceLocation OpLoc, SourceRange R) {
4792 if (!TInfo)
4793 return true;
4794 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4795 ExprKind: UETT_AlignOf, KWName);
4796}
4797
4798bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4799 SourceLocation OpLoc, SourceRange R) {
4800 TypeSourceInfo *TInfo;
4801 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4802 TInfo: &TInfo);
4803 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4804}
4805
4806static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4807 bool IsReal) {
4808 if (V.get()->isTypeDependent())
4809 return S.Context.DependentTy;
4810
4811 // _Real and _Imag are only l-values for normal l-values.
4812 if (V.get()->getObjectKind() != OK_Ordinary) {
4813 V = S.DefaultLvalueConversion(E: V.get());
4814 if (V.isInvalid())
4815 return QualType();
4816 }
4817
4818 // These operators return the element type of a complex type.
4819 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4820 return CT->getElementType();
4821
4822 // Otherwise they pass through real integer and floating point types here.
4823 if (V.get()->getType()->isArithmeticType())
4824 return V.get()->getType();
4825
4826 // Test for placeholders.
4827 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4828 if (PR.isInvalid()) return QualType();
4829 if (PR.get() != V.get()) {
4830 V = PR;
4831 return CheckRealImagOperand(S, V, Loc, IsReal);
4832 }
4833
4834 // Reject anything else.
4835 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4836 << (IsReal ? "__real" : "__imag");
4837 return QualType();
4838}
4839
4840
4841
4842ExprResult
4843Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4844 tok::TokenKind Kind, Expr *Input) {
4845 UnaryOperatorKind Opc;
4846 switch (Kind) {
4847 default: llvm_unreachable("Unknown unary op!");
4848 case tok::plusplus: Opc = UO_PostInc; break;
4849 case tok::minusminus: Opc = UO_PostDec; break;
4850 }
4851
4852 // Since this might is a postfix expression, get rid of ParenListExprs.
4853 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4854 if (Result.isInvalid()) return ExprError();
4855 Input = Result.get();
4856
4857 return BuildUnaryOp(S, OpLoc, Opc, Input);
4858}
4859
4860/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4861///
4862/// \return true on error
4863static bool checkArithmeticOnObjCPointer(Sema &S,
4864 SourceLocation opLoc,
4865 Expr *op) {
4866 assert(op->getType()->isObjCObjectPointerType());
4867 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4868 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4869 return false;
4870
4871 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
4872 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4873 << op->getSourceRange();
4874 return true;
4875}
4876
4877static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4878 auto *BaseNoParens = Base->IgnoreParens();
4879 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
4880 return MSProp->getPropertyDecl()->getType()->isArrayType();
4881 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
4882}
4883
4884// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4885// Typically this is DependentTy, but can sometimes be more precise.
4886//
4887// There are cases when we could determine a non-dependent type:
4888// - LHS and RHS may have non-dependent types despite being type-dependent
4889// (e.g. unbounded array static members of the current instantiation)
4890// - one may be a dependent-sized array with known element type
4891// - one may be a dependent-typed valid index (enum in current instantiation)
4892//
4893// We *always* return a dependent type, in such cases it is DependentTy.
4894// This avoids creating type-dependent expressions with non-dependent types.
4895// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4896static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4897 const ASTContext &Ctx) {
4898 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4899 QualType LTy = LHS->getType(), RTy = RHS->getType();
4900 QualType Result = Ctx.DependentTy;
4901 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4902 if (const PointerType *PT = LTy->getAs<PointerType>())
4903 Result = PT->getPointeeType();
4904 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4905 Result = AT->getElementType();
4906 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4907 if (const PointerType *PT = RTy->getAs<PointerType>())
4908 Result = PT->getPointeeType();
4909 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4910 Result = AT->getElementType();
4911 }
4912 // Ensure we return a dependent type.
4913 return Result->isDependentType() ? Result : Ctx.DependentTy;
4914}
4915
4916ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4917 SourceLocation lbLoc,
4918 MultiExprArg ArgExprs,
4919 SourceLocation rbLoc) {
4920
4921 if (base && !base->getType().isNull() &&
4922 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
4923 auto *AS = cast<ArraySectionExpr>(Val: base);
4924 if (AS->isOMPArraySection())
4925 return OpenMP().ActOnOMPArraySectionExpr(
4926 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
4927 /*Length*/ nullptr,
4928 /*Stride=*/nullptr, RBLoc: rbLoc);
4929
4930 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
4931 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
4932 RBLoc: rbLoc);
4933 }
4934
4935 // Since this might be a postfix expression, get rid of ParenListExprs.
4936 if (isa<ParenListExpr>(Val: base)) {
4937 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
4938 if (result.isInvalid())
4939 return ExprError();
4940 base = result.get();
4941 }
4942
4943 // Check if base and idx form a MatrixSubscriptExpr.
4944 //
4945 // Helper to check for comma expressions, which are not allowed as indices for
4946 // matrix subscript expressions.
4947 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4948 if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) {
4949 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
4950 << SourceRange(base->getBeginLoc(), rbLoc);
4951 return true;
4952 }
4953 return false;
4954 };
4955 // The matrix subscript operator ([][])is considered a single operator.
4956 // Separating the index expressions by parenthesis is not allowed.
4957 if (base && !base->getType().isNull() &&
4958 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
4959 !isa<MatrixSubscriptExpr>(Val: base)) {
4960 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
4961 << SourceRange(base->getBeginLoc(), rbLoc);
4962 return ExprError();
4963 }
4964 // If the base is a MatrixSubscriptExpr, try to create a new
4965 // MatrixSubscriptExpr.
4966 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
4967 if (matSubscriptE) {
4968 assert(ArgExprs.size() == 1);
4969 if (CheckAndReportCommaError(ArgExprs.front()))
4970 return ExprError();
4971
4972 assert(matSubscriptE->isIncomplete() &&
4973 "base has to be an incomplete matrix subscript");
4974 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
4975 RowIdx: matSubscriptE->getRowIdx(),
4976 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
4977 }
4978 if (base->getType()->isWebAssemblyTableType()) {
4979 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
4980 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4981 return ExprError();
4982 }
4983
4984 CheckInvalidBuiltinCountedByRef(E: base,
4985 K: BuiltinCountedByRefKind::ArraySubscript);
4986
4987 // Handle any non-overload placeholder types in the base and index
4988 // expressions. We can't handle overloads here because the other
4989 // operand might be an overloadable type, in which case the overload
4990 // resolution for the operator overload should get the first crack
4991 // at the overload.
4992 bool IsMSPropertySubscript = false;
4993 if (base->getType()->isNonOverloadPlaceholderType()) {
4994 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
4995 if (!IsMSPropertySubscript) {
4996 ExprResult result = CheckPlaceholderExpr(E: base);
4997 if (result.isInvalid())
4998 return ExprError();
4999 base = result.get();
5000 }
5001 }
5002
5003 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5004 if (base->getType()->isMatrixType()) {
5005 assert(ArgExprs.size() == 1);
5006 if (CheckAndReportCommaError(ArgExprs.front()))
5007 return ExprError();
5008
5009 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5010 RBLoc: rbLoc);
5011 }
5012
5013 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5014 Expr *idx = ArgExprs[0];
5015 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5016 (isa<CXXOperatorCallExpr>(Val: idx) &&
5017 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5018 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5019 << SourceRange(base->getBeginLoc(), rbLoc);
5020 }
5021 }
5022
5023 if (ArgExprs.size() == 1 &&
5024 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5025 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5026 if (result.isInvalid())
5027 return ExprError();
5028 ArgExprs[0] = result.get();
5029 } else {
5030 if (CheckArgsForPlaceholders(args: ArgExprs))
5031 return ExprError();
5032 }
5033
5034 // Build an unanalyzed expression if either operand is type-dependent.
5035 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5036 (base->isTypeDependent() ||
5037 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5038 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5039 return new (Context) ArraySubscriptExpr(
5040 base, ArgExprs.front(),
5041 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5042 VK_LValue, OK_Ordinary, rbLoc);
5043 }
5044
5045 // MSDN, property (C++)
5046 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5047 // This attribute can also be used in the declaration of an empty array in a
5048 // class or structure definition. For example:
5049 // __declspec(property(get=GetX, put=PutX)) int x[];
5050 // The above statement indicates that x[] can be used with one or more array
5051 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5052 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5053 if (IsMSPropertySubscript) {
5054 assert(ArgExprs.size() == 1);
5055 // Build MS property subscript expression if base is MS property reference
5056 // or MS property subscript.
5057 return new (Context)
5058 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5059 VK_LValue, OK_Ordinary, rbLoc);
5060 }
5061
5062 // Use C++ overloaded-operator rules if either operand has record
5063 // type. The spec says to do this if either type is *overloadable*,
5064 // but enum types can't declare subscript operators or conversion
5065 // operators, so there's nothing interesting for overload resolution
5066 // to do if there aren't any record types involved.
5067 //
5068 // ObjC pointers have their own subscripting logic that is not tied
5069 // to overload resolution and so should not take this path.
5070 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5071 ((base->getType()->isRecordType() ||
5072 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5073 ArgExprs[0]->getType()->isRecordType())))) {
5074 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5075 }
5076
5077 ExprResult Res =
5078 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5079
5080 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5081 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5082
5083 return Res;
5084}
5085
5086ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5087 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5088 InitializationKind Kind =
5089 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5090 InitializationSequence InitSeq(*this, Entity, Kind, E);
5091 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5092}
5093
5094ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5095 Expr *RowIdx,
5096 SourceLocation RBLoc) {
5097 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5098 if (BaseR.isInvalid())
5099 return BaseR;
5100 Base = BaseR.get();
5101
5102 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5103 if (RowR.isInvalid())
5104 return RowR;
5105 RowIdx = RowR.get();
5106
5107 // Build an unanalyzed expression if any of the operands is type-dependent.
5108 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5109 return new (Context)
5110 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5111
5112 // Check that IndexExpr is an integer expression. If it is a constant
5113 // expression, check that it is less than Dim (= the number of elements in the
5114 // corresponding dimension).
5115 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5116 bool IsColumnIdx) -> Expr * {
5117 if (!IndexExpr->getType()->isIntegerType() &&
5118 !IndexExpr->isTypeDependent()) {
5119 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5120 << IsColumnIdx;
5121 return nullptr;
5122 }
5123
5124 if (std::optional<llvm::APSInt> Idx =
5125 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5126 if ((*Idx < 0 || *Idx >= Dim)) {
5127 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5128 << IsColumnIdx << Dim;
5129 return nullptr;
5130 }
5131 }
5132
5133 ExprResult ConvExpr = IndexExpr;
5134 assert(!ConvExpr.isInvalid() &&
5135 "should be able to convert any integer type to size type");
5136 return ConvExpr.get();
5137 };
5138
5139 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5140 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5141 if (!RowIdx)
5142 return ExprError();
5143
5144 QualType RowVecQT =
5145 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5146
5147 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5148}
5149
5150ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5151 Expr *ColumnIdx,
5152 SourceLocation RBLoc) {
5153 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5154 if (BaseR.isInvalid())
5155 return BaseR;
5156 Base = BaseR.get();
5157
5158 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5159 if (RowR.isInvalid())
5160 return RowR;
5161 RowIdx = RowR.get();
5162
5163 if (!ColumnIdx)
5164 return new (Context) MatrixSubscriptExpr(
5165 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5166
5167 // Build an unanalyzed expression if any of the operands is type-dependent.
5168 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5169 ColumnIdx->isTypeDependent())
5170 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5171 Context.DependentTy, RBLoc);
5172
5173 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5174 if (ColumnR.isInvalid())
5175 return ColumnR;
5176 ColumnIdx = ColumnR.get();
5177
5178 // Check that IndexExpr is an integer expression. If it is a constant
5179 // expression, check that it is less than Dim (= the number of elements in the
5180 // corresponding dimension).
5181 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5182 bool IsColumnIdx) -> Expr * {
5183 if (!IndexExpr->getType()->isIntegerType() &&
5184 !IndexExpr->isTypeDependent()) {
5185 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5186 << IsColumnIdx;
5187 return nullptr;
5188 }
5189
5190 if (std::optional<llvm::APSInt> Idx =
5191 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5192 if ((*Idx < 0 || *Idx >= Dim)) {
5193 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5194 << IsColumnIdx << Dim;
5195 return nullptr;
5196 }
5197 }
5198
5199 ExprResult ConvExpr = IndexExpr;
5200 assert(!ConvExpr.isInvalid() &&
5201 "should be able to convert any integer type to size type");
5202 return ConvExpr.get();
5203 };
5204
5205 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5206 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5207 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5208 if (!RowIdx || !ColumnIdx)
5209 return ExprError();
5210
5211 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5212 MTy->getElementType(), RBLoc);
5213}
5214
5215void Sema::CheckAddressOfNoDeref(const Expr *E) {
5216 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5217 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5218
5219 // For expressions like `&(*s).b`, the base is recorded and what should be
5220 // checked.
5221 const MemberExpr *Member = nullptr;
5222 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5223 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5224
5225 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5226}
5227
5228void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5229 if (isUnevaluatedContext())
5230 return;
5231
5232 QualType ResultTy = E->getType();
5233 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5234
5235 // Bail if the element is an array since it is not memory access.
5236 if (isa<ArrayType>(Val: ResultTy))
5237 return;
5238
5239 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5240 LastRecord.PossibleDerefs.insert(Ptr: E);
5241 return;
5242 }
5243
5244 // Check if the base type is a pointer to a member access of a struct
5245 // marked with noderef.
5246 const Expr *Base = E->getBase();
5247 QualType BaseTy = Base->getType();
5248 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5249 // Not a pointer access
5250 return;
5251
5252 const MemberExpr *Member = nullptr;
5253 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5254 Member->isArrow())
5255 Base = Member->getBase();
5256
5257 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5258 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5259 LastRecord.PossibleDerefs.insert(Ptr: E);
5260 }
5261}
5262
5263ExprResult
5264Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5265 Expr *Idx, SourceLocation RLoc) {
5266 Expr *LHSExp = Base;
5267 Expr *RHSExp = Idx;
5268
5269 ExprValueKind VK = VK_LValue;
5270 ExprObjectKind OK = OK_Ordinary;
5271
5272 // Per C++ core issue 1213, the result is an xvalue if either operand is
5273 // a non-lvalue array, and an lvalue otherwise.
5274 if (getLangOpts().CPlusPlus11) {
5275 for (auto *Op : {LHSExp, RHSExp}) {
5276 Op = Op->IgnoreImplicit();
5277 if (Op->getType()->isArrayType() && !Op->isLValue())
5278 VK = VK_XValue;
5279 }
5280 }
5281
5282 // Perform default conversions.
5283 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5284 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5285 if (Result.isInvalid())
5286 return ExprError();
5287 LHSExp = Result.get();
5288 }
5289 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5290 if (Result.isInvalid())
5291 return ExprError();
5292 RHSExp = Result.get();
5293
5294 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5295
5296 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5297 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5298 // in the subscript position. As a result, we need to derive the array base
5299 // and index from the expression types.
5300 Expr *BaseExpr, *IndexExpr;
5301 QualType ResultType;
5302 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5303 BaseExpr = LHSExp;
5304 IndexExpr = RHSExp;
5305 ResultType =
5306 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5307 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5308 BaseExpr = LHSExp;
5309 IndexExpr = RHSExp;
5310 ResultType = PTy->getPointeeType();
5311 } else if (const ObjCObjectPointerType *PTy =
5312 LHSTy->getAs<ObjCObjectPointerType>()) {
5313 BaseExpr = LHSExp;
5314 IndexExpr = RHSExp;
5315
5316 // Use custom logic if this should be the pseudo-object subscript
5317 // expression.
5318 if (!LangOpts.isSubscriptPointerArithmetic())
5319 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5320 getterMethod: nullptr, setterMethod: nullptr);
5321
5322 ResultType = PTy->getPointeeType();
5323 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5324 // Handle the uncommon case of "123[Ptr]".
5325 BaseExpr = RHSExp;
5326 IndexExpr = LHSExp;
5327 ResultType = PTy->getPointeeType();
5328 } else if (const ObjCObjectPointerType *PTy =
5329 RHSTy->getAs<ObjCObjectPointerType>()) {
5330 // Handle the uncommon case of "123[Ptr]".
5331 BaseExpr = RHSExp;
5332 IndexExpr = LHSExp;
5333 ResultType = PTy->getPointeeType();
5334 if (!LangOpts.isSubscriptPointerArithmetic()) {
5335 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5336 << ResultType << BaseExpr->getSourceRange();
5337 return ExprError();
5338 }
5339 } else if (LHSTy->isSubscriptableVectorType()) {
5340 if (LHSTy->isBuiltinType() &&
5341 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5342 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5343 if (BTy->isSVEBool())
5344 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5345 << LHSExp->getSourceRange()
5346 << RHSExp->getSourceRange());
5347 ResultType = BTy->getSveEltType(Ctx: Context);
5348 } else {
5349 const VectorType *VTy = LHSTy->getAs<VectorType>();
5350 ResultType = VTy->getElementType();
5351 }
5352 BaseExpr = LHSExp; // vectors: V[123]
5353 IndexExpr = RHSExp;
5354 // We apply C++ DR1213 to vector subscripting too.
5355 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5356 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5357 if (Materialized.isInvalid())
5358 return ExprError();
5359 LHSExp = Materialized.get();
5360 }
5361 VK = LHSExp->getValueKind();
5362 if (VK != VK_PRValue)
5363 OK = OK_VectorComponent;
5364
5365 QualType BaseType = BaseExpr->getType();
5366 Qualifiers BaseQuals = BaseType.getQualifiers();
5367 Qualifiers MemberQuals = ResultType.getQualifiers();
5368 Qualifiers Combined = BaseQuals + MemberQuals;
5369 if (Combined != MemberQuals)
5370 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5371 } else if (LHSTy->isArrayType()) {
5372 // If we see an array that wasn't promoted by
5373 // DefaultFunctionArrayLvalueConversion, it must be an array that
5374 // wasn't promoted because of the C90 rule that doesn't
5375 // allow promoting non-lvalue arrays. Warn, then
5376 // force the promotion here.
5377 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5378 << LHSExp->getSourceRange();
5379 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5380 CK: CK_ArrayToPointerDecay).get();
5381 LHSTy = LHSExp->getType();
5382
5383 BaseExpr = LHSExp;
5384 IndexExpr = RHSExp;
5385 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5386 } else if (RHSTy->isArrayType()) {
5387 // Same as previous, except for 123[f().a] case
5388 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5389 << RHSExp->getSourceRange();
5390 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5391 CK: CK_ArrayToPointerDecay).get();
5392 RHSTy = RHSExp->getType();
5393
5394 BaseExpr = RHSExp;
5395 IndexExpr = LHSExp;
5396 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5397 } else {
5398 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5399 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5400 }
5401 // C99 6.5.2.1p1
5402 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5403 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5404 << IndexExpr->getSourceRange());
5405
5406 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5407 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5408 !IndexExpr->isTypeDependent()) {
5409 std::optional<llvm::APSInt> IntegerContantExpr =
5410 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5411 if (!IntegerContantExpr.has_value() ||
5412 IntegerContantExpr.value().isNegative())
5413 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5414 }
5415
5416 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5417 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5418 // type. Note that Functions are not objects, and that (in C99 parlance)
5419 // incomplete types are not object types.
5420 if (ResultType->isFunctionType()) {
5421 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5422 << ResultType << BaseExpr->getSourceRange();
5423 return ExprError();
5424 }
5425
5426 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5427 // GNU extension: subscripting on pointer to void
5428 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5429 << BaseExpr->getSourceRange();
5430
5431 // C forbids expressions of unqualified void type from being l-values.
5432 // See IsCForbiddenLValueType.
5433 if (!ResultType.hasQualifiers())
5434 VK = VK_PRValue;
5435 } else if (!ResultType->isDependentType() &&
5436 !ResultType.isWebAssemblyReferenceType() &&
5437 RequireCompleteSizedType(
5438 Loc: LLoc, T: ResultType,
5439 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5440 return ExprError();
5441
5442 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5443 !ResultType.isCForbiddenLValueType());
5444
5445 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5446 FunctionScopes.size() > 1) {
5447 if (auto *TT =
5448 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5449 for (auto I = FunctionScopes.rbegin(),
5450 E = std::prev(x: FunctionScopes.rend());
5451 I != E; ++I) {
5452 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5453 if (CSI == nullptr)
5454 break;
5455 DeclContext *DC = nullptr;
5456 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5457 DC = LSI->CallOperator;
5458 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5459 DC = CRSI->TheCapturedDecl;
5460 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5461 DC = BSI->TheDecl;
5462 if (DC) {
5463 if (DC->containsDecl(D: TT->getDecl()))
5464 break;
5465 captureVariablyModifiedType(
5466 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5467 }
5468 }
5469 }
5470 }
5471
5472 return new (Context)
5473 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5474}
5475
5476bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5477 ParmVarDecl *Param, Expr *RewrittenInit,
5478 bool SkipImmediateInvocations) {
5479 if (Param->hasUnparsedDefaultArg()) {
5480 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5481 // If we've already cleared out the location for the default argument,
5482 // that means we're parsing it right now.
5483 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5484 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5485 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5486 Param->setInvalidDecl();
5487 return true;
5488 }
5489
5490 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5491 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5492 Diag(Loc: UnparsedDefaultArgLocs[Param],
5493 DiagID: diag::note_default_argument_declared_here);
5494 return true;
5495 }
5496
5497 if (Param->hasUninstantiatedDefaultArg()) {
5498 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5499 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5500 return true;
5501 }
5502
5503 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5504 assert(Init && "default argument but no initializer?");
5505
5506 // If the default expression creates temporaries, we need to
5507 // push them to the current stack of expression temporaries so they'll
5508 // be properly destroyed.
5509 // FIXME: We should really be rebuilding the default argument with new
5510 // bound temporaries; see the comment in PR5810.
5511 // We don't need to do that with block decls, though, because
5512 // blocks in default argument expression can never capture anything.
5513 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5514 // Set the "needs cleanups" bit regardless of whether there are
5515 // any explicit objects.
5516 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5517 // Append all the objects to the cleanup list. Right now, this
5518 // should always be a no-op, because blocks in default argument
5519 // expressions should never be able to capture anything.
5520 assert(!InitWithCleanup->getNumObjects() &&
5521 "default argument expression has capturing blocks?");
5522 }
5523 // C++ [expr.const]p15.1:
5524 // An expression or conversion is in an immediate function context if it is
5525 // potentially evaluated and [...] its innermost enclosing non-block scope
5526 // is a function parameter scope of an immediate function.
5527 EnterExpressionEvaluationContext EvalContext(
5528 *this,
5529 FD->isImmediateFunction()
5530 ? ExpressionEvaluationContext::ImmediateFunctionContext
5531 : ExpressionEvaluationContext::PotentiallyEvaluated,
5532 Param);
5533 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5534 SkipImmediateInvocations;
5535 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5536 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5537 });
5538 return false;
5539}
5540
5541struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5542 const ASTContext &Context;
5543 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5544 ShouldVisitImplicitCode = true;
5545 }
5546
5547 bool HasImmediateCalls = false;
5548
5549 bool VisitCallExpr(CallExpr *E) override {
5550 if (const FunctionDecl *FD = E->getDirectCallee())
5551 HasImmediateCalls |= FD->isImmediateFunction();
5552 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5553 }
5554
5555 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5556 if (const FunctionDecl *FD = E->getConstructor())
5557 HasImmediateCalls |= FD->isImmediateFunction();
5558 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5559 }
5560
5561 // SourceLocExpr are not immediate invocations
5562 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5563 // need to be rebuilt so that they refer to the correct SourceLocation and
5564 // DeclContext.
5565 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5566 HasImmediateCalls = true;
5567 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5568 }
5569
5570 // A nested lambda might have parameters with immediate invocations
5571 // in their default arguments.
5572 // The compound statement is not visited (as it does not constitute a
5573 // subexpression).
5574 // FIXME: We should consider visiting and transforming captures
5575 // with init expressions.
5576 bool VisitLambdaExpr(LambdaExpr *E) override {
5577 return VisitCXXMethodDecl(D: E->getCallOperator());
5578 }
5579
5580 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5581 return TraverseStmt(S: E->getExpr());
5582 }
5583
5584 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5585 return TraverseStmt(S: E->getExpr());
5586 }
5587};
5588
5589struct EnsureImmediateInvocationInDefaultArgs
5590 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5591 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5592 : TreeTransform(SemaRef) {}
5593
5594 bool AlwaysRebuild() { return true; }
5595
5596 // Lambda can only have immediate invocations in the default
5597 // args of their parameters, which is transformed upon calling the closure.
5598 // The body is not a subexpression, so we have nothing to do.
5599 // FIXME: Immediate calls in capture initializers should be transformed.
5600 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5601 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5602
5603 // Make sure we don't rebuild the this pointer as it would
5604 // cause it to incorrectly point it to the outermost class
5605 // in the case of nested struct initialization.
5606 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5607
5608 // Rewrite to source location to refer to the context in which they are used.
5609 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5610 DeclContext *DC = E->getParentContext();
5611 if (DC == SemaRef.CurContext)
5612 return E;
5613
5614 // FIXME: During instantiation, because the rebuild of defaults arguments
5615 // is not always done in the context of the template instantiator,
5616 // we run the risk of producing a dependent source location
5617 // that would never be rebuilt.
5618 // This usually happens during overload resolution, or in contexts
5619 // where the value of the source location does not matter.
5620 // However, we should find a better way to deal with source location
5621 // of function templates.
5622 if (!SemaRef.CurrentInstantiationScope ||
5623 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5624 DC = SemaRef.CurContext;
5625
5626 return getDerived().RebuildSourceLocExpr(
5627 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5628 }
5629};
5630
5631ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5632 FunctionDecl *FD, ParmVarDecl *Param,
5633 Expr *Init) {
5634 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5635
5636 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5637 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5638 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5639 InitializationContext =
5640 OutermostDeclarationWithDelayedImmediateInvocations();
5641 if (!InitializationContext.has_value())
5642 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5643
5644 if (!Init && !Param->hasUnparsedDefaultArg()) {
5645 // Mark that we are replacing a default argument first.
5646 // If we are instantiating a template we won't have to
5647 // retransform immediate calls.
5648 // C++ [expr.const]p15.1:
5649 // An expression or conversion is in an immediate function context if it
5650 // is potentially evaluated and [...] its innermost enclosing non-block
5651 // scope is a function parameter scope of an immediate function.
5652 EnterExpressionEvaluationContext EvalContext(
5653 *this,
5654 FD->isImmediateFunction()
5655 ? ExpressionEvaluationContext::ImmediateFunctionContext
5656 : ExpressionEvaluationContext::PotentiallyEvaluated,
5657 Param);
5658
5659 if (Param->hasUninstantiatedDefaultArg()) {
5660 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5661 return ExprError();
5662 }
5663 // CWG2631
5664 // An immediate invocation that is not evaluated where it appears is
5665 // evaluated and checked for whether it is a constant expression at the
5666 // point where the enclosing initializer is used in a function call.
5667 ImmediateCallVisitor V(getASTContext());
5668 if (!NestedDefaultChecking)
5669 V.TraverseDecl(D: Param);
5670
5671 // Rewrite the call argument that was created from the corresponding
5672 // parameter's default argument.
5673 if (V.HasImmediateCalls ||
5674 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5675 if (V.HasImmediateCalls)
5676 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5677 CallLoc, Param, CurContext};
5678 // Pass down lifetime extending flag, and collect temporaries in
5679 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5680 currentEvaluationContext().InLifetimeExtendingContext =
5681 parentEvaluationContext().InLifetimeExtendingContext;
5682 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5683 ExprResult Res;
5684 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5685 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5686 /*NotCopy=*/NotCopyInit: false);
5687 });
5688 if (Res.isInvalid())
5689 return ExprError();
5690 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5691 EqualLoc: Res.get()->getBeginLoc());
5692 if (Res.isInvalid())
5693 return ExprError();
5694 Init = Res.get();
5695 }
5696 }
5697
5698 if (CheckCXXDefaultArgExpr(
5699 CallLoc, FD, Param, RewrittenInit: Init,
5700 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5701 return ExprError();
5702
5703 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5704 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5705}
5706
5707static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5708 FieldDecl *Field) {
5709 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5710 return Pattern;
5711 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5712 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5713 DeclContext::lookup_result Lookup =
5714 ClassPattern->lookup(Name: Field->getDeclName());
5715 auto Rng = llvm::make_filter_range(
5716 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5717 if (Rng.empty())
5718 return nullptr;
5719 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5720 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5721 // && "Duplicated instantiation pattern for field decl");
5722 return cast<FieldDecl>(Val: *Rng.begin());
5723}
5724
5725ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5726 assert(Field->hasInClassInitializer());
5727
5728 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5729
5730 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5731
5732 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5733 InitializationContext =
5734 OutermostDeclarationWithDelayedImmediateInvocations();
5735 if (!InitializationContext.has_value())
5736 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5737
5738 Expr *Init = nullptr;
5739
5740 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5741 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5742 EnterExpressionEvaluationContext EvalContext(
5743 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5744
5745 if (!Field->getInClassInitializer()) {
5746 // Maybe we haven't instantiated the in-class initializer. Go check the
5747 // pattern FieldDecl to see if it has one.
5748 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5749 FieldDecl *Pattern =
5750 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5751 assert(Pattern && "We must have set the Pattern!");
5752 if (!Pattern->hasInClassInitializer() ||
5753 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5754 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5755 Field->setInvalidDecl();
5756 return ExprError();
5757 }
5758 }
5759 }
5760
5761 // CWG2631
5762 // An immediate invocation that is not evaluated where it appears is
5763 // evaluated and checked for whether it is a constant expression at the
5764 // point where the enclosing initializer is used in a [...] a constructor
5765 // definition, or an aggregate initialization.
5766 ImmediateCallVisitor V(getASTContext());
5767 if (!NestedDefaultChecking)
5768 V.TraverseDecl(D: Field);
5769
5770 // CWG1815
5771 // Support lifetime extension of temporary created by aggregate
5772 // initialization using a default member initializer. We should rebuild
5773 // the initializer in a lifetime extension context if the initializer
5774 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5775 // extension code recurses into the default initializer and does lifetime
5776 // extension when warranted.
5777 bool ContainsAnyTemporaries =
5778 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5779 if (Field->getInClassInitializer() &&
5780 !Field->getInClassInitializer()->containsErrors() &&
5781 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5782 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5783 CurContext};
5784 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5785 NestedDefaultChecking;
5786 // Pass down lifetime extending flag, and collect temporaries in
5787 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5788 currentEvaluationContext().InLifetimeExtendingContext =
5789 parentEvaluationContext().InLifetimeExtendingContext;
5790 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5791 ExprResult Res;
5792 runWithSufficientStackSpace(Loc, Fn: [&] {
5793 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5794 /*CXXDirectInit=*/NotCopyInit: false);
5795 });
5796 if (!Res.isInvalid())
5797 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5798 if (Res.isInvalid()) {
5799 Field->setInvalidDecl();
5800 return ExprError();
5801 }
5802 Init = Res.get();
5803 }
5804
5805 if (Field->getInClassInitializer()) {
5806 Expr *E = Init ? Init : Field->getInClassInitializer();
5807 if (!NestedDefaultChecking)
5808 runWithSufficientStackSpace(Loc, Fn: [&] {
5809 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5810 });
5811 if (isInLifetimeExtendingContext())
5812 DiscardCleanupsInEvaluationContext();
5813 // C++11 [class.base.init]p7:
5814 // The initialization of each base and member constitutes a
5815 // full-expression.
5816 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5817 if (Res.isInvalid()) {
5818 Field->setInvalidDecl();
5819 return ExprError();
5820 }
5821 Init = Res.get();
5822
5823 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5824 Field, UsedContext: InitializationContext->Context,
5825 RewrittenInitExpr: Init);
5826 }
5827
5828 // DR1351:
5829 // If the brace-or-equal-initializer of a non-static data member
5830 // invokes a defaulted default constructor of its class or of an
5831 // enclosing class in a potentially evaluated subexpression, the
5832 // program is ill-formed.
5833 //
5834 // This resolution is unworkable: the exception specification of the
5835 // default constructor can be needed in an unevaluated context, in
5836 // particular, in the operand of a noexcept-expression, and we can be
5837 // unable to compute an exception specification for an enclosed class.
5838 //
5839 // Any attempt to resolve the exception specification of a defaulted default
5840 // constructor before the initializer is lexically complete will ultimately
5841 // come here at which point we can diagnose it.
5842 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5843 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5844 << OutermostClass << Field;
5845 Diag(Loc: Field->getEndLoc(),
5846 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5847 // Recover by marking the field invalid, unless we're in a SFINAE context.
5848 if (!isSFINAEContext())
5849 Field->setInvalidDecl();
5850 return ExprError();
5851}
5852
5853VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
5854 const FunctionProtoType *Proto,
5855 Expr *Fn) {
5856 if (Proto && Proto->isVariadic()) {
5857 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
5858 return VariadicCallType::Constructor;
5859 else if (Fn && Fn->getType()->isBlockPointerType())
5860 return VariadicCallType::Block;
5861 else if (FDecl) {
5862 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
5863 if (Method->isInstance())
5864 return VariadicCallType::Method;
5865 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5866 return VariadicCallType::Method;
5867 return VariadicCallType::Function;
5868 }
5869 return VariadicCallType::DoesNotApply;
5870}
5871
5872namespace {
5873class FunctionCallCCC final : public FunctionCallFilterCCC {
5874public:
5875 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5876 unsigned NumArgs, MemberExpr *ME)
5877 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5878 FunctionName(FuncName) {}
5879
5880 bool ValidateCandidate(const TypoCorrection &candidate) override {
5881 if (!candidate.getCorrectionSpecifier() ||
5882 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5883 return false;
5884 }
5885
5886 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5887 }
5888
5889 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5890 return std::make_unique<FunctionCallCCC>(args&: *this);
5891 }
5892
5893private:
5894 const IdentifierInfo *const FunctionName;
5895};
5896}
5897
5898static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5899 FunctionDecl *FDecl,
5900 ArrayRef<Expr *> Args) {
5901 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
5902 DeclarationName FuncName = FDecl->getDeclName();
5903 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5904
5905 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5906 if (TypoCorrection Corrected = S.CorrectTypo(
5907 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
5908 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
5909 Mode: CorrectTypoKind::ErrorRecovery)) {
5910 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5911 if (Corrected.isOverloaded()) {
5912 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5913 OverloadCandidateSet::iterator Best;
5914 for (NamedDecl *CD : Corrected) {
5915 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
5916 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
5917 CandidateSet&: OCS);
5918 }
5919 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
5920 case OR_Success:
5921 ND = Best->FoundDecl;
5922 Corrected.setCorrectionDecl(ND);
5923 break;
5924 default:
5925 break;
5926 }
5927 }
5928 ND = ND->getUnderlyingDecl();
5929 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
5930 return Corrected;
5931 }
5932 }
5933 return TypoCorrection();
5934}
5935
5936// [C++26][[expr.unary.op]/p4
5937// A pointer to member is only formed when an explicit &
5938// is used and its operand is a qualified-id not enclosed in parentheses.
5939static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
5940 if (!isa<ParenExpr>(Val: Fn))
5941 return false;
5942
5943 Fn = Fn->IgnoreParens();
5944
5945 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
5946 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5947 return false;
5948 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
5949 return DRE->hasQualifier();
5950 }
5951 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
5952 return bool(OVL->getQualifier());
5953 return false;
5954}
5955
5956bool
5957Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5958 FunctionDecl *FDecl,
5959 const FunctionProtoType *Proto,
5960 ArrayRef<Expr *> Args,
5961 SourceLocation RParenLoc,
5962 bool IsExecConfig) {
5963 // Bail out early if calling a builtin with custom typechecking.
5964 if (FDecl)
5965 if (unsigned ID = FDecl->getBuiltinID())
5966 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5967 return false;
5968
5969 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5970 // assignment, to the types of the corresponding parameter, ...
5971
5972 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5973 bool HasExplicitObjectParameter =
5974 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5975 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5976 unsigned NumParams = Proto->getNumParams();
5977 bool Invalid = false;
5978 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5979 unsigned FnKind = Fn->getType()->isBlockPointerType()
5980 ? 1 /* block */
5981 : (IsExecConfig ? 3 /* kernel function (exec config) */
5982 : 0 /* function */);
5983
5984 // If too few arguments are available (and we don't have default
5985 // arguments for the remaining parameters), don't make the call.
5986 if (Args.size() < NumParams) {
5987 if (Args.size() < MinArgs) {
5988 TypoCorrection TC;
5989 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
5990 unsigned diag_id =
5991 MinArgs == NumParams && !Proto->isVariadic()
5992 ? diag::err_typecheck_call_too_few_args_suggest
5993 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5994 diagnoseTypo(
5995 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
5996 << FnKind << MinArgs - ExplicitObjectParameterOffset
5997 << static_cast<unsigned>(Args.size()) -
5998 ExplicitObjectParameterOffset
5999 << HasExplicitObjectParameter << TC.getCorrectionRange());
6000 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6001 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6002 ->getDeclName())
6003 Diag(Loc: RParenLoc,
6004 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6005 ? diag::err_typecheck_call_too_few_args_one
6006 : diag::err_typecheck_call_too_few_args_at_least_one)
6007 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6008 << HasExplicitObjectParameter << Fn->getSourceRange();
6009 else
6010 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6011 ? diag::err_typecheck_call_too_few_args
6012 : diag::err_typecheck_call_too_few_args_at_least)
6013 << FnKind << MinArgs - ExplicitObjectParameterOffset
6014 << static_cast<unsigned>(Args.size()) -
6015 ExplicitObjectParameterOffset
6016 << HasExplicitObjectParameter << Fn->getSourceRange();
6017
6018 // Emit the location of the prototype.
6019 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6020 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6021 << FDecl << FDecl->getParametersSourceRange();
6022
6023 return true;
6024 }
6025 // We reserve space for the default arguments when we create
6026 // the call expression, before calling ConvertArgumentsForCall.
6027 assert((Call->getNumArgs() == NumParams) &&
6028 "We should have reserved space for the default arguments before!");
6029 }
6030
6031 // If too many are passed and not variadic, error on the extras and drop
6032 // them.
6033 if (Args.size() > NumParams) {
6034 if (!Proto->isVariadic()) {
6035 TypoCorrection TC;
6036 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6037 unsigned diag_id =
6038 MinArgs == NumParams && !Proto->isVariadic()
6039 ? diag::err_typecheck_call_too_many_args_suggest
6040 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6041 diagnoseTypo(
6042 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6043 << FnKind << NumParams - ExplicitObjectParameterOffset
6044 << static_cast<unsigned>(Args.size()) -
6045 ExplicitObjectParameterOffset
6046 << HasExplicitObjectParameter << TC.getCorrectionRange());
6047 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6048 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6049 ->getDeclName())
6050 Diag(Loc: Args[NumParams]->getBeginLoc(),
6051 DiagID: MinArgs == NumParams
6052 ? diag::err_typecheck_call_too_many_args_one
6053 : diag::err_typecheck_call_too_many_args_at_most_one)
6054 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6055 << static_cast<unsigned>(Args.size()) -
6056 ExplicitObjectParameterOffset
6057 << HasExplicitObjectParameter << Fn->getSourceRange()
6058 << SourceRange(Args[NumParams]->getBeginLoc(),
6059 Args.back()->getEndLoc());
6060 else
6061 Diag(Loc: Args[NumParams]->getBeginLoc(),
6062 DiagID: MinArgs == NumParams
6063 ? diag::err_typecheck_call_too_many_args
6064 : diag::err_typecheck_call_too_many_args_at_most)
6065 << FnKind << NumParams - ExplicitObjectParameterOffset
6066 << static_cast<unsigned>(Args.size()) -
6067 ExplicitObjectParameterOffset
6068 << HasExplicitObjectParameter << Fn->getSourceRange()
6069 << SourceRange(Args[NumParams]->getBeginLoc(),
6070 Args.back()->getEndLoc());
6071
6072 // Emit the location of the prototype.
6073 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6074 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6075 << FDecl << FDecl->getParametersSourceRange();
6076
6077 // This deletes the extra arguments.
6078 Call->shrinkNumArgs(NewNumArgs: NumParams);
6079 return true;
6080 }
6081 }
6082 SmallVector<Expr *, 8> AllArgs;
6083 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6084
6085 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6086 AllArgs, CallType);
6087 if (Invalid)
6088 return true;
6089 unsigned TotalNumArgs = AllArgs.size();
6090 for (unsigned i = 0; i < TotalNumArgs; ++i)
6091 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6092
6093 Call->computeDependence();
6094 return false;
6095}
6096
6097bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6098 const FunctionProtoType *Proto,
6099 unsigned FirstParam, ArrayRef<Expr *> Args,
6100 SmallVectorImpl<Expr *> &AllArgs,
6101 VariadicCallType CallType, bool AllowExplicit,
6102 bool IsListInitialization) {
6103 unsigned NumParams = Proto->getNumParams();
6104 bool Invalid = false;
6105 size_t ArgIx = 0;
6106 // Continue to check argument types (even if we have too few/many args).
6107 for (unsigned i = FirstParam; i < NumParams; i++) {
6108 QualType ProtoArgType = Proto->getParamType(i);
6109
6110 Expr *Arg;
6111 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6112 if (ArgIx < Args.size()) {
6113 Arg = Args[ArgIx++];
6114
6115 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6116 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6117 return true;
6118
6119 // Strip the unbridged-cast placeholder expression off, if applicable.
6120 bool CFAudited = false;
6121 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6122 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6123 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6124 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6125 else if (getLangOpts().ObjCAutoRefCount &&
6126 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6127 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6128 CFAudited = true;
6129
6130 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6131 ProtoArgType->isBlockPointerType())
6132 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6133 BE->getBlockDecl()->setDoesNotEscape();
6134 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6135 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6136 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6137 if (ArgExpr.isInvalid())
6138 return true;
6139 Arg = ArgExpr.getAs<Expr>();
6140 }
6141
6142 InitializedEntity Entity =
6143 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6144 Type: ProtoArgType)
6145 : InitializedEntity::InitializeParameter(
6146 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6147
6148 // Remember that parameter belongs to a CF audited API.
6149 if (CFAudited)
6150 Entity.setParameterCFAudited();
6151
6152 ExprResult ArgE = PerformCopyInitialization(
6153 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6154 if (ArgE.isInvalid())
6155 return true;
6156
6157 Arg = ArgE.getAs<Expr>();
6158 } else {
6159 assert(Param && "can't use default arguments without a known callee");
6160
6161 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6162 if (ArgExpr.isInvalid())
6163 return true;
6164
6165 Arg = ArgExpr.getAs<Expr>();
6166 }
6167
6168 // Check for array bounds violations for each argument to the call. This
6169 // check only triggers warnings when the argument isn't a more complex Expr
6170 // with its own checking, such as a BinaryOperator.
6171 CheckArrayAccess(E: Arg);
6172
6173 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6174 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6175
6176 AllArgs.push_back(Elt: Arg);
6177 }
6178
6179 // If this is a variadic call, handle args passed through "...".
6180 if (CallType != VariadicCallType::DoesNotApply) {
6181 // Assume that extern "C" functions with variadic arguments that
6182 // return __unknown_anytype aren't *really* variadic.
6183 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6184 FDecl->isExternC()) {
6185 for (Expr *A : Args.slice(N: ArgIx)) {
6186 QualType paramType; // ignored
6187 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6188 Invalid |= arg.isInvalid();
6189 AllArgs.push_back(Elt: arg.get());
6190 }
6191
6192 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6193 } else {
6194 for (Expr *A : Args.slice(N: ArgIx)) {
6195 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6196 Invalid |= Arg.isInvalid();
6197 AllArgs.push_back(Elt: Arg.get());
6198 }
6199 }
6200
6201 // Check for array bounds violations.
6202 for (Expr *A : Args.slice(N: ArgIx))
6203 CheckArrayAccess(E: A);
6204 }
6205 return Invalid;
6206}
6207
6208static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6209 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6210 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6211 TL = DTL.getOriginalLoc();
6212 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6213 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6214 << ATL.getLocalSourceRange();
6215}
6216
6217void
6218Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6219 ParmVarDecl *Param,
6220 const Expr *ArgExpr) {
6221 // Static array parameters are not supported in C++.
6222 if (!Param || getLangOpts().CPlusPlus)
6223 return;
6224
6225 QualType OrigTy = Param->getOriginalType();
6226
6227 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6228 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6229 return;
6230
6231 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6232 NPC: Expr::NPC_NeverValueDependent)) {
6233 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6234 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6235 return;
6236 }
6237
6238 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6239 if (!CAT)
6240 return;
6241
6242 const ConstantArrayType *ArgCAT =
6243 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6244 if (!ArgCAT)
6245 return;
6246
6247 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6248 T2: ArgCAT->getElementType())) {
6249 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6250 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6251 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6252 << (unsigned)CAT->getZExtSize() << 0;
6253 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6254 }
6255 return;
6256 }
6257
6258 std::optional<CharUnits> ArgSize =
6259 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6260 std::optional<CharUnits> ParmSize =
6261 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6262 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6263 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6264 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6265 << (unsigned)ParmSize->getQuantity() << 1;
6266 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6267 }
6268}
6269
6270/// Given a function expression of unknown-any type, try to rebuild it
6271/// to have a function type.
6272static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6273
6274/// Is the given type a placeholder that we need to lower out
6275/// immediately during argument processing?
6276static bool isPlaceholderToRemoveAsArg(QualType type) {
6277 // Placeholders are never sugared.
6278 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6279 if (!placeholder) return false;
6280
6281 switch (placeholder->getKind()) {
6282 // Ignore all the non-placeholder types.
6283#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6284 case BuiltinType::Id:
6285#include "clang/Basic/OpenCLImageTypes.def"
6286#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6287 case BuiltinType::Id:
6288#include "clang/Basic/OpenCLExtensionTypes.def"
6289 // In practice we'll never use this, since all SVE types are sugared
6290 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6291#define SVE_TYPE(Name, Id, SingletonId) \
6292 case BuiltinType::Id:
6293#include "clang/Basic/AArch64ACLETypes.def"
6294#define PPC_VECTOR_TYPE(Name, Id, Size) \
6295 case BuiltinType::Id:
6296#include "clang/Basic/PPCTypes.def"
6297#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6298#include "clang/Basic/RISCVVTypes.def"
6299#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6300#include "clang/Basic/WebAssemblyReferenceTypes.def"
6301#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6302#include "clang/Basic/AMDGPUTypes.def"
6303#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6304#include "clang/Basic/HLSLIntangibleTypes.def"
6305#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6306#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6307#include "clang/AST/BuiltinTypes.def"
6308 return false;
6309
6310 case BuiltinType::UnresolvedTemplate:
6311 // We cannot lower out overload sets; they might validly be resolved
6312 // by the call machinery.
6313 case BuiltinType::Overload:
6314 return false;
6315
6316 // Unbridged casts in ARC can be handled in some call positions and
6317 // should be left in place.
6318 case BuiltinType::ARCUnbridgedCast:
6319 return false;
6320
6321 // Pseudo-objects should be converted as soon as possible.
6322 case BuiltinType::PseudoObject:
6323 return true;
6324
6325 // The debugger mode could theoretically but currently does not try
6326 // to resolve unknown-typed arguments based on known parameter types.
6327 case BuiltinType::UnknownAny:
6328 return true;
6329
6330 // These are always invalid as call arguments and should be reported.
6331 case BuiltinType::BoundMember:
6332 case BuiltinType::BuiltinFn:
6333 case BuiltinType::IncompleteMatrixIdx:
6334 case BuiltinType::ArraySection:
6335 case BuiltinType::OMPArrayShaping:
6336 case BuiltinType::OMPIterator:
6337 return true;
6338
6339 }
6340 llvm_unreachable("bad builtin type kind");
6341}
6342
6343bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6344 // Apply this processing to all the arguments at once instead of
6345 // dying at the first failure.
6346 bool hasInvalid = false;
6347 for (size_t i = 0, e = args.size(); i != e; i++) {
6348 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6349 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6350 if (result.isInvalid()) hasInvalid = true;
6351 else args[i] = result.get();
6352 }
6353 }
6354 return hasInvalid;
6355}
6356
6357/// If a builtin function has a pointer argument with no explicit address
6358/// space, then it should be able to accept a pointer to any address
6359/// space as input. In order to do this, we need to replace the
6360/// standard builtin declaration with one that uses the same address space
6361/// as the call.
6362///
6363/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6364/// it does not contain any pointer arguments without
6365/// an address space qualifer. Otherwise the rewritten
6366/// FunctionDecl is returned.
6367/// TODO: Handle pointer return types.
6368static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6369 FunctionDecl *FDecl,
6370 MultiExprArg ArgExprs) {
6371
6372 QualType DeclType = FDecl->getType();
6373 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6374
6375 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6376 ArgExprs.size() < FT->getNumParams())
6377 return nullptr;
6378
6379 bool NeedsNewDecl = false;
6380 unsigned i = 0;
6381 SmallVector<QualType, 8> OverloadParams;
6382
6383 {
6384 // The lvalue conversions in this loop are only for type resolution and
6385 // don't actually occur.
6386 EnterExpressionEvaluationContext Unevaluated(
6387 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6388 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6389
6390 for (QualType ParamType : FT->param_types()) {
6391
6392 // Convert array arguments to pointer to simplify type lookup.
6393 ExprResult ArgRes =
6394 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6395 if (ArgRes.isInvalid())
6396 return nullptr;
6397 Expr *Arg = ArgRes.get();
6398 QualType ArgType = Arg->getType();
6399 if (!ParamType->isPointerType() ||
6400 ParamType->getPointeeType().hasAddressSpace() ||
6401 !ArgType->isPointerType() ||
6402 !ArgType->getPointeeType().hasAddressSpace() ||
6403 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6404 OverloadParams.push_back(Elt: ParamType);
6405 continue;
6406 }
6407
6408 QualType PointeeType = ParamType->getPointeeType();
6409 NeedsNewDecl = true;
6410 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6411
6412 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6413 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6414 }
6415 }
6416
6417 if (!NeedsNewDecl)
6418 return nullptr;
6419
6420 FunctionProtoType::ExtProtoInfo EPI;
6421 EPI.Variadic = FT->isVariadic();
6422 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6423 Args: OverloadParams, EPI);
6424 DeclContext *Parent = FDecl->getParent();
6425 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6426 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6427 N: FDecl->getIdentifier(), T: OverloadTy,
6428 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6429 isInlineSpecified: false,
6430 /*hasPrototype=*/hasWrittenPrototype: true);
6431 SmallVector<ParmVarDecl*, 16> Params;
6432 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6433 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6434 QualType ParamType = FT->getParamType(i);
6435 ParmVarDecl *Parm =
6436 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6437 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6438 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6439 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6440 Params.push_back(Elt: Parm);
6441 }
6442 OverloadDecl->setParams(Params);
6443 // We cannot merge host/device attributes of redeclarations. They have to
6444 // be consistent when created.
6445 if (Sema->LangOpts.CUDA) {
6446 if (FDecl->hasAttr<CUDAHostAttr>())
6447 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6448 if (FDecl->hasAttr<CUDADeviceAttr>())
6449 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6450 }
6451 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6452 return OverloadDecl;
6453}
6454
6455static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6456 FunctionDecl *Callee,
6457 MultiExprArg ArgExprs) {
6458 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6459 // similar attributes) really don't like it when functions are called with an
6460 // invalid number of args.
6461 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6462 /*PartialOverloading=*/false) &&
6463 !Callee->isVariadic())
6464 return;
6465 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6466 return;
6467
6468 if (const EnableIfAttr *Attr =
6469 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6470 S.Diag(Loc: Fn->getBeginLoc(),
6471 DiagID: isa<CXXMethodDecl>(Val: Callee)
6472 ? diag::err_ovl_no_viable_member_function_in_call
6473 : diag::err_ovl_no_viable_function_in_call)
6474 << Callee << Callee->getSourceRange();
6475 S.Diag(Loc: Callee->getLocation(),
6476 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6477 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6478 return;
6479 }
6480}
6481
6482static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6483 const UnresolvedMemberExpr *const UME, Sema &S) {
6484
6485 const auto GetFunctionLevelDCIfCXXClass =
6486 [](Sema &S) -> const CXXRecordDecl * {
6487 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6488 if (!DC || !DC->getParent())
6489 return nullptr;
6490
6491 // If the call to some member function was made from within a member
6492 // function body 'M' return return 'M's parent.
6493 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6494 return MD->getParent()->getCanonicalDecl();
6495 // else the call was made from within a default member initializer of a
6496 // class, so return the class.
6497 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6498 return RD->getCanonicalDecl();
6499 return nullptr;
6500 };
6501 // If our DeclContext is neither a member function nor a class (in the
6502 // case of a lambda in a default member initializer), we can't have an
6503 // enclosing 'this'.
6504
6505 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6506 if (!CurParentClass)
6507 return false;
6508
6509 // The naming class for implicit member functions call is the class in which
6510 // name lookup starts.
6511 const CXXRecordDecl *const NamingClass =
6512 UME->getNamingClass()->getCanonicalDecl();
6513 assert(NamingClass && "Must have naming class even for implicit access");
6514
6515 // If the unresolved member functions were found in a 'naming class' that is
6516 // related (either the same or derived from) to the class that contains the
6517 // member function that itself contained the implicit member access.
6518
6519 return CurParentClass == NamingClass ||
6520 CurParentClass->isDerivedFrom(Base: NamingClass);
6521}
6522
6523static void
6524tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6525 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6526
6527 if (!UME)
6528 return;
6529
6530 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6531 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6532 // already been captured, or if this is an implicit member function call (if
6533 // it isn't, an attempt to capture 'this' should already have been made).
6534 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6535 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6536 return;
6537
6538 // Check if the naming class in which the unresolved members were found is
6539 // related (same as or is a base of) to the enclosing class.
6540
6541 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6542 return;
6543
6544
6545 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6546 // If the enclosing function is not dependent, then this lambda is
6547 // capture ready, so if we can capture this, do so.
6548 if (!EnclosingFunctionCtx->isDependentContext()) {
6549 // If the current lambda and all enclosing lambdas can capture 'this' -
6550 // then go ahead and capture 'this' (since our unresolved overload set
6551 // contains at least one non-static member function).
6552 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6553 S.CheckCXXThisCapture(Loc: CallLoc);
6554 } else if (S.CurContext->isDependentContext()) {
6555 // ... since this is an implicit member reference, that might potentially
6556 // involve a 'this' capture, mark 'this' for potential capture in
6557 // enclosing lambdas.
6558 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6559 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6560 }
6561}
6562
6563// Once a call is fully resolved, warn for unqualified calls to specific
6564// C++ standard functions, like move and forward.
6565static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6566 const CallExpr *Call) {
6567 // We are only checking unary move and forward so exit early here.
6568 if (Call->getNumArgs() != 1)
6569 return;
6570
6571 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6572 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6573 return;
6574 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6575 if (!DRE || !DRE->getLocation().isValid())
6576 return;
6577
6578 if (DRE->getQualifier())
6579 return;
6580
6581 const FunctionDecl *FD = Call->getDirectCallee();
6582 if (!FD)
6583 return;
6584
6585 // Only warn for some functions deemed more frequent or problematic.
6586 unsigned BuiltinID = FD->getBuiltinID();
6587 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6588 return;
6589
6590 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6591 << FD->getQualifiedNameAsString()
6592 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6593}
6594
6595ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6596 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6597 Expr *ExecConfig) {
6598 ExprResult Call =
6599 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6600 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6601 if (Call.isInvalid())
6602 return Call;
6603
6604 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6605 // language modes.
6606 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6607 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6608 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6609 << ULE->getName();
6610 }
6611
6612 if (LangOpts.OpenMP)
6613 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6614 ExecConfig);
6615 if (LangOpts.CPlusPlus) {
6616 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6617 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6618
6619 // If we previously found that the id-expression of this call refers to a
6620 // consteval function but the call is dependent, we should not treat is an
6621 // an invalid immediate call.
6622 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6623 DRE && Call.get()->isValueDependent()) {
6624 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6625 }
6626 }
6627 return Call;
6628}
6629
6630// Any type that could be used to form a callable expression
6631static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6632 QualType T = E->getType();
6633 if (T->isDependentType())
6634 return true;
6635
6636 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6637 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6638 T->isFunctionType() || T->isFunctionReferenceType() ||
6639 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6640 T->isBlockPointerType() || T->isRecordType())
6641 return true;
6642
6643 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6644 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6645}
6646
6647ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6648 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6649 Expr *ExecConfig, bool IsExecConfig,
6650 bool AllowRecovery) {
6651 // Since this might be a postfix expression, get rid of ParenListExprs.
6652 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6653 if (Result.isInvalid()) return ExprError();
6654 Fn = Result.get();
6655
6656 if (CheckArgsForPlaceholders(args: ArgExprs))
6657 return ExprError();
6658
6659 // The result of __builtin_counted_by_ref cannot be used as a function
6660 // argument. It allows leaking and modification of bounds safety information.
6661 for (const Expr *Arg : ArgExprs)
6662 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6663 K: BuiltinCountedByRefKind::FunctionArg))
6664 return ExprError();
6665
6666 if (getLangOpts().CPlusPlus) {
6667 // If this is a pseudo-destructor expression, build the call immediately.
6668 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6669 if (!ArgExprs.empty()) {
6670 // Pseudo-destructor calls should not have any arguments.
6671 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6672 << FixItHint::CreateRemoval(
6673 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6674 ArgExprs.back()->getEndLoc()));
6675 }
6676
6677 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6678 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6679 }
6680 if (Fn->getType() == Context.PseudoObjectTy) {
6681 ExprResult result = CheckPlaceholderExpr(E: Fn);
6682 if (result.isInvalid()) return ExprError();
6683 Fn = result.get();
6684 }
6685
6686 // Determine whether this is a dependent call inside a C++ template,
6687 // in which case we won't do any semantic analysis now.
6688 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6689 if (ExecConfig) {
6690 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6691 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6692 Ty: Context.DependentTy, VK: VK_PRValue,
6693 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6694 } else {
6695
6696 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6697 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6698 CallLoc: Fn->getBeginLoc());
6699
6700 // If the type of the function itself is not dependent
6701 // check that it is a reasonable as a function, as type deduction
6702 // later assume the CallExpr has a sensible TYPE.
6703 if (!MayBeFunctionType(Context, E: Fn))
6704 return ExprError(
6705 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6706 << Fn->getType() << Fn->getSourceRange());
6707
6708 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6709 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6710 }
6711 }
6712
6713 // Determine whether this is a call to an object (C++ [over.call.object]).
6714 if (Fn->getType()->isRecordType())
6715 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6716 RParenLoc);
6717
6718 if (Fn->getType() == Context.UnknownAnyTy) {
6719 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6720 if (result.isInvalid()) return ExprError();
6721 Fn = result.get();
6722 }
6723
6724 if (Fn->getType() == Context.BoundMemberTy) {
6725 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6726 RParenLoc, ExecConfig, IsExecConfig,
6727 AllowRecovery);
6728 }
6729 }
6730
6731 // Check for overloaded calls. This can happen even in C due to extensions.
6732 if (Fn->getType() == Context.OverloadTy) {
6733 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6734
6735 // We aren't supposed to apply this logic if there's an '&' involved.
6736 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6737 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6738 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6739 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6740 OverloadExpr *ovl = find.Expression;
6741 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6742 return BuildOverloadedCallExpr(
6743 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6744 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6745 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6746 RParenLoc, ExecConfig, IsExecConfig,
6747 AllowRecovery);
6748 }
6749 }
6750
6751 // If we're directly calling a function, get the appropriate declaration.
6752 if (Fn->getType() == Context.UnknownAnyTy) {
6753 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6754 if (result.isInvalid()) return ExprError();
6755 Fn = result.get();
6756 }
6757
6758 Expr *NakedFn = Fn->IgnoreParens();
6759
6760 bool CallingNDeclIndirectly = false;
6761 NamedDecl *NDecl = nullptr;
6762 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6763 if (UnOp->getOpcode() == UO_AddrOf) {
6764 CallingNDeclIndirectly = true;
6765 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6766 }
6767 }
6768
6769 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6770 NDecl = DRE->getDecl();
6771
6772 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6773 if (FDecl && FDecl->getBuiltinID()) {
6774 // Rewrite the function decl for this builtin by replacing parameters
6775 // with no explicit address space with the address space of the arguments
6776 // in ArgExprs.
6777 if ((FDecl =
6778 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6779 NDecl = FDecl;
6780 Fn = DeclRefExpr::Create(
6781 Context, QualifierLoc: FDecl->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6782 NameLoc: SourceLocation(), T: FDecl->getType(), VK: Fn->getValueKind(), FoundD: FDecl,
6783 TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6784 }
6785 }
6786 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6787 NDecl = ME->getMemberDecl();
6788
6789 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6790 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6791 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6792 return ExprError();
6793
6794 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
6795
6796 // If this expression is a call to a builtin function in HIP compilation,
6797 // allow a pointer-type argument to default address space to be passed as a
6798 // pointer-type parameter to a non-default address space. If Arg is declared
6799 // in the default address space and Param is declared in a non-default
6800 // address space, perform an implicit address space cast to the parameter
6801 // type.
6802 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6803 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6804 ++Idx) {
6805 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
6806 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6807 !ArgExprs[Idx]->getType()->isPointerType())
6808 continue;
6809
6810 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6811 auto ArgTy = ArgExprs[Idx]->getType();
6812 auto ArgPtTy = ArgTy->getPointeeType();
6813 auto ArgAS = ArgPtTy.getAddressSpace();
6814
6815 // Add address space cast if target address spaces are different
6816 bool NeedImplicitASC =
6817 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6818 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6819 // or from specific AS which has target AS matching that of Param.
6820 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
6821 if (!NeedImplicitASC)
6822 continue;
6823
6824 // First, ensure that the Arg is an RValue.
6825 if (ArgExprs[Idx]->isGLValue()) {
6826 ArgExprs[Idx] = ImplicitCastExpr::Create(
6827 Context, T: ArgExprs[Idx]->getType(), Kind: CK_NoOp, Operand: ArgExprs[Idx],
6828 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
6829 }
6830
6831 // Construct a new arg type with address space of Param
6832 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6833 ArgPtQuals.setAddressSpace(ParamAS);
6834 auto NewArgPtTy =
6835 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
6836 auto NewArgTy =
6837 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
6838 Qs: ArgTy.getQualifiers());
6839
6840 // Finally perform an implicit address space cast
6841 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
6842 CK: CK_AddressSpaceConversion)
6843 .get();
6844 }
6845 }
6846 }
6847
6848 if (Context.isDependenceAllowed() &&
6849 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
6850 assert(!getLangOpts().CPlusPlus);
6851 assert((Fn->containsErrors() ||
6852 llvm::any_of(ArgExprs,
6853 [](clang::Expr *E) { return E->containsErrors(); })) &&
6854 "should only occur in error-recovery path.");
6855 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6856 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6857 }
6858 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
6859 Config: ExecConfig, IsExecConfig);
6860}
6861
6862Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6863 MultiExprArg CallArgs) {
6864 std::string Name = Context.BuiltinInfo.getName(ID: Id);
6865 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6866 Sema::LookupOrdinaryName);
6867 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
6868
6869 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6870 assert(BuiltInDecl && "failed to find builtin declaration");
6871
6872 ExprResult DeclRef =
6873 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
6874 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6875
6876 ExprResult Call =
6877 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
6878
6879 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6880 return Call.get();
6881}
6882
6883ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6884 SourceLocation BuiltinLoc,
6885 SourceLocation RParenLoc) {
6886 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
6887 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
6888}
6889
6890ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6891 SourceLocation BuiltinLoc,
6892 SourceLocation RParenLoc) {
6893 ExprValueKind VK = VK_PRValue;
6894 ExprObjectKind OK = OK_Ordinary;
6895 QualType SrcTy = E->getType();
6896 if (!SrcTy->isDependentType() &&
6897 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
6898 return ExprError(
6899 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
6900 << DestTy << SrcTy << E->getSourceRange());
6901 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6902}
6903
6904ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6905 SourceLocation BuiltinLoc,
6906 SourceLocation RParenLoc) {
6907 TypeSourceInfo *TInfo;
6908 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
6909 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6910}
6911
6912ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6913 SourceLocation LParenLoc,
6914 ArrayRef<Expr *> Args,
6915 SourceLocation RParenLoc, Expr *Config,
6916 bool IsExecConfig, ADLCallKind UsesADL) {
6917 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
6918 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6919
6920 auto IsSJLJ = [&] {
6921 switch (BuiltinID) {
6922 case Builtin::BI__builtin_longjmp:
6923 case Builtin::BI__builtin_setjmp:
6924 case Builtin::BI__sigsetjmp:
6925 case Builtin::BI_longjmp:
6926 case Builtin::BI_setjmp:
6927 case Builtin::BIlongjmp:
6928 case Builtin::BIsetjmp:
6929 case Builtin::BIsiglongjmp:
6930 case Builtin::BIsigsetjmp:
6931 return true;
6932 default:
6933 return false;
6934 }
6935 };
6936
6937 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
6938 if (!CurrentDefer.empty() && IsSJLJ()) {
6939 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
6940 // for more than just blocks (e.g. lambdas, nested classes...).
6941 Scope *DeferParent = CurrentDefer.back().first;
6942 Scope *Block = CurScope->getBlockParent();
6943 if (DeferParent->Contains(rhs: *CurScope) &&
6944 (!Block || !DeferParent->Contains(rhs: *Block)))
6945 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
6946 }
6947
6948 // Functions with 'interrupt' attribute cannot be called directly.
6949 if (FDecl) {
6950 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6951 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
6952 return ExprError();
6953 }
6954 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6955 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
6956 return ExprError();
6957 }
6958 }
6959
6960 // X86 interrupt handlers may only call routines with attribute
6961 // no_caller_saved_registers since there is no efficient way to
6962 // save and restore the non-GPR state.
6963 if (auto *Caller = getCurFunctionDecl()) {
6964 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6965 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6966 const TargetInfo &TI = Context.getTargetInfo();
6967 bool HasNonGPRRegisters =
6968 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
6969 if (HasNonGPRRegisters &&
6970 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6971 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
6972 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6973 if (FDecl)
6974 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
6975 }
6976 }
6977 }
6978
6979 // Promote the function operand.
6980 // We special-case function promotion here because we only allow promoting
6981 // builtin functions to function pointers in the callee of a call.
6982 ExprResult Result;
6983 QualType ResultTy;
6984 if (BuiltinID &&
6985 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
6986 // Extract the return type from the (builtin) function pointer type.
6987 // FIXME Several builtins still have setType in
6988 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6989 // Builtins.td to ensure they are correct before removing setType calls.
6990 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
6991 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6992 ResultTy = FDecl->getCallResultType();
6993 } else {
6994 Result = CallExprUnaryConversions(E: Fn);
6995 ResultTy = Context.BoolTy;
6996 }
6997 if (Result.isInvalid())
6998 return ExprError();
6999 Fn = Result.get();
7000
7001 // Check for a valid function type, but only if it is not a builtin which
7002 // requires custom type checking. These will be handled by
7003 // CheckBuiltinFunctionCall below just after creation of the call expression.
7004 const FunctionType *FuncT = nullptr;
7005 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7006 retry:
7007 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7008 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7009 // have type pointer to function".
7010 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7011 if (!FuncT)
7012 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7013 << Fn->getType() << Fn->getSourceRange());
7014 } else if (const BlockPointerType *BPT =
7015 Fn->getType()->getAs<BlockPointerType>()) {
7016 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7017 } else {
7018 // Handle calls to expressions of unknown-any type.
7019 if (Fn->getType() == Context.UnknownAnyTy) {
7020 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7021 if (rewrite.isInvalid())
7022 return ExprError();
7023 Fn = rewrite.get();
7024 goto retry;
7025 }
7026
7027 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7028 << Fn->getType() << Fn->getSourceRange());
7029 }
7030 }
7031
7032 // Get the number of parameters in the function prototype, if any.
7033 // We will allocate space for max(Args.size(), NumParams) arguments
7034 // in the call expression.
7035 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7036 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7037
7038 CallExpr *TheCall;
7039 if (Config) {
7040 assert(UsesADL == ADLCallKind::NotADL &&
7041 "CUDAKernelCallExpr should not use ADL");
7042 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7043 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7044 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7045 } else {
7046 TheCall =
7047 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7048 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7049 }
7050
7051 // Bail out early if calling a builtin with custom type checking.
7052 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7053 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7054 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7055 E = CheckForImmediateInvocation(E, Decl: FDecl);
7056 return E;
7057 }
7058
7059 if (getLangOpts().CUDA) {
7060 if (Config) {
7061 // CUDA: Kernel calls must be to global functions
7062 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7063 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7064 << FDecl << Fn->getSourceRange());
7065
7066 // CUDA: Kernel function must have 'void' return type
7067 if (!FuncT->getReturnType()->isVoidType() &&
7068 !FuncT->getReturnType()->getAs<AutoType>() &&
7069 !FuncT->getReturnType()->isInstantiationDependentType())
7070 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7071 << Fn->getType() << Fn->getSourceRange());
7072 } else {
7073 // CUDA: Calls to global functions must be configured
7074 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7075 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7076 << FDecl << Fn->getSourceRange());
7077 }
7078 }
7079
7080 // Check for a valid return type
7081 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7082 FD: FDecl))
7083 return ExprError();
7084
7085 // We know the result type of the call, set it.
7086 TheCall->setType(FuncT->getCallResultType(Context));
7087 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7088
7089 // WebAssembly tables can't be used as arguments.
7090 if (Context.getTargetInfo().getTriple().isWasm()) {
7091 for (const Expr *Arg : Args) {
7092 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7093 return ExprError(Diag(Loc: Arg->getExprLoc(),
7094 DiagID: diag::err_wasm_table_as_function_parameter));
7095 }
7096 }
7097 }
7098
7099 if (Proto) {
7100 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7101 IsExecConfig))
7102 return ExprError();
7103 } else {
7104 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7105
7106 if (FDecl) {
7107 // Check if we have too few/too many template arguments, based
7108 // on our knowledge of the function definition.
7109 const FunctionDecl *Def = nullptr;
7110 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7111 Proto = Def->getType()->getAs<FunctionProtoType>();
7112 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7113 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7114 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7115 }
7116
7117 // If the function we're calling isn't a function prototype, but we have
7118 // a function prototype from a prior declaratiom, use that prototype.
7119 if (!FDecl->hasPrototype())
7120 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7121 }
7122
7123 // If we still haven't found a prototype to use but there are arguments to
7124 // the call, diagnose this as calling a function without a prototype.
7125 // However, if we found a function declaration, check to see if
7126 // -Wdeprecated-non-prototype was disabled where the function was declared.
7127 // If so, we will silence the diagnostic here on the assumption that this
7128 // interface is intentional and the user knows what they're doing. We will
7129 // also silence the diagnostic if there is a function declaration but it
7130 // was implicitly defined (the user already gets diagnostics about the
7131 // creation of the implicit function declaration, so the additional warning
7132 // is not helpful).
7133 if (!Proto && !Args.empty() &&
7134 (!FDecl || (!FDecl->isImplicit() &&
7135 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7136 Loc: FDecl->getLocation()))))
7137 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7138 << (FDecl != nullptr) << FDecl;
7139
7140 // Promote the arguments (C99 6.5.2.2p6).
7141 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7142 Expr *Arg = Args[i];
7143
7144 if (Proto && i < Proto->getNumParams()) {
7145 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7146 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7147 ExprResult ArgE =
7148 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7149 if (ArgE.isInvalid())
7150 return true;
7151
7152 Arg = ArgE.getAs<Expr>();
7153
7154 } else {
7155 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7156
7157 if (ArgE.isInvalid())
7158 return true;
7159
7160 Arg = ArgE.getAs<Expr>();
7161 }
7162
7163 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7164 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7165 return ExprError();
7166
7167 TheCall->setArg(Arg: i, ArgExpr: Arg);
7168 }
7169 TheCall->computeDependence();
7170 }
7171
7172 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7173 if (Method->isImplicitObjectMemberFunction())
7174 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7175 << Fn->getSourceRange() << 0);
7176
7177 // Check for sentinels
7178 if (NDecl)
7179 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7180
7181 // Warn for unions passing across security boundary (CMSE).
7182 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7183 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7184 if (const auto *RT =
7185 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7186 if (RT->getDecl()->isOrContainsUnion())
7187 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7188 << 0 << i;
7189 }
7190 }
7191 }
7192
7193 // Do special checking on direct calls to functions.
7194 if (FDecl) {
7195 if (CheckFunctionCall(FDecl, TheCall, Proto))
7196 return ExprError();
7197
7198 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7199
7200 if (BuiltinID)
7201 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7202 } else if (NDecl) {
7203 if (CheckPointerCall(NDecl, TheCall, Proto))
7204 return ExprError();
7205 } else {
7206 if (CheckOtherCall(TheCall, Proto))
7207 return ExprError();
7208 }
7209
7210 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7211}
7212
7213ExprResult
7214Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7215 SourceLocation RParenLoc, Expr *InitExpr) {
7216 assert(Ty && "ActOnCompoundLiteral(): missing type");
7217 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7218
7219 TypeSourceInfo *TInfo;
7220 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7221 if (!TInfo)
7222 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7223
7224 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7225}
7226
7227ExprResult
7228Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7229 SourceLocation RParenLoc, Expr *LiteralExpr) {
7230 QualType literalType = TInfo->getType();
7231
7232 if (literalType->isArrayType()) {
7233 if (RequireCompleteSizedType(
7234 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7235 DiagID: diag::err_array_incomplete_or_sizeless_type,
7236 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7237 return ExprError();
7238 if (literalType->isVariableArrayType()) {
7239 // C23 6.7.10p4: An entity of variable length array type shall not be
7240 // initialized except by an empty initializer.
7241 //
7242 // The C extension warnings are issued from ParseBraceInitializer() and
7243 // do not need to be issued here. However, we continue to issue an error
7244 // in the case there are initializers or we are compiling C++. We allow
7245 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7246 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7247 // FIXME: should we allow this construct in C++ when it makes sense to do
7248 // so?
7249 //
7250 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7251 // shall specify an object type or an array of unknown size, but not a
7252 // variable length array type. This seems odd, as it allows 'int a[size] =
7253 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7254 // says, this is what's implemented here for C (except for the extension
7255 // that permits constant foldable size arrays)
7256
7257 auto diagID = LangOpts.CPlusPlus
7258 ? diag::err_variable_object_no_init
7259 : diag::err_compound_literal_with_vla_type;
7260 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7261 FailedFoldDiagID: diagID))
7262 return ExprError();
7263 }
7264 } else if (!literalType->isDependentType() &&
7265 RequireCompleteType(Loc: LParenLoc, T: literalType,
7266 DiagID: diag::err_typecheck_decl_incomplete_type,
7267 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7268 return ExprError();
7269
7270 InitializedEntity Entity
7271 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7272 InitializationKind Kind
7273 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7274 TypeRange: SourceRange(LParenLoc, RParenLoc),
7275 /*InitList=*/true);
7276 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7277 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7278 ResultType: &literalType);
7279 if (Result.isInvalid())
7280 return ExprError();
7281 LiteralExpr = Result.get();
7282
7283 // We treat the compound literal as being at file scope if it's not in a
7284 // function or method body, or within the function's prototype scope. This
7285 // means the following compound literal is not at file scope:
7286 // void func(char *para[(int [1]){ 0 }[0]);
7287 const Scope *S = getCurScope();
7288 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7289 !S->isInCFunctionScope() &&
7290 (!S || !S->isFunctionPrototypeScope());
7291
7292 // In C, compound literals are l-values for some reason.
7293 // For GCC compatibility, in C++, file-scope array compound literals with
7294 // constant initializers are also l-values, and compound literals are
7295 // otherwise prvalues.
7296 //
7297 // (GCC also treats C++ list-initialized file-scope array prvalues with
7298 // constant initializers as l-values, but that's non-conforming, so we don't
7299 // follow it there.)
7300 //
7301 // FIXME: It would be better to handle the lvalue cases as materializing and
7302 // lifetime-extending a temporary object, but our materialized temporaries
7303 // representation only supports lifetime extension from a variable, not "out
7304 // of thin air".
7305 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7306 // is bound to the result of applying array-to-pointer decay to the compound
7307 // literal.
7308 // FIXME: GCC supports compound literals of reference type, which should
7309 // obviously have a value kind derived from the kind of reference involved.
7310 ExprValueKind VK =
7311 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7312 ? VK_PRValue
7313 : VK_LValue;
7314
7315 // C99 6.5.2.5
7316 // "If the compound literal occurs outside the body of a function, the
7317 // initializer list shall consist of constant expressions."
7318 if (IsFileScope)
7319 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7320 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7321 Expr *Init = ILE->getInit(Init: i);
7322 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7323 !Init->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false)) {
7324 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7325 << Init->getSourceBitField();
7326 return ExprError();
7327 }
7328
7329 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7330 }
7331
7332 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7333 LiteralExpr, IsFileScope);
7334 if (IsFileScope) {
7335 if (!LiteralExpr->isTypeDependent() &&
7336 !LiteralExpr->isValueDependent() &&
7337 !literalType->isDependentType()) // C99 6.5.2.5p3
7338 if (CheckForConstantInitializer(Init: LiteralExpr))
7339 return ExprError();
7340 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7341 literalType.getAddressSpace() != LangAS::Default) {
7342 // Embedded-C extensions to C99 6.5.2.5:
7343 // "If the compound literal occurs inside the body of a function, the
7344 // type name shall not be qualified by an address-space qualifier."
7345 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7346 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7347 return ExprError();
7348 }
7349
7350 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7351 // Compound literals that have automatic storage duration are destroyed at
7352 // the end of the scope in C; in C++, they're just temporaries.
7353
7354 // Emit diagnostics if it is or contains a C union type that is non-trivial
7355 // to destruct.
7356 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7357 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7358 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7359 NonTrivialKind: NTCUK_Destruct);
7360
7361 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7362 if (literalType.isDestructedType()) {
7363 Cleanup.setExprNeedsCleanups(true);
7364 ExprCleanupObjects.push_back(Elt: E);
7365 getCurFunction()->setHasBranchProtectedScope();
7366 }
7367 }
7368
7369 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7370 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7371 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7372 Loc: E->getInitializer()->getExprLoc());
7373
7374 return MaybeBindToTemporary(E);
7375}
7376
7377ExprResult
7378Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7379 SourceLocation RBraceLoc) {
7380 // Only produce each kind of designated initialization diagnostic once.
7381 SourceLocation FirstDesignator;
7382 bool DiagnosedArrayDesignator = false;
7383 bool DiagnosedNestedDesignator = false;
7384 bool DiagnosedMixedDesignator = false;
7385
7386 // Check that any designated initializers are syntactically valid in the
7387 // current language mode.
7388 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7389 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7390 if (FirstDesignator.isInvalid())
7391 FirstDesignator = DIE->getBeginLoc();
7392
7393 if (!getLangOpts().CPlusPlus)
7394 break;
7395
7396 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7397 DiagnosedNestedDesignator = true;
7398 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7399 << DIE->getDesignatorsSourceRange();
7400 }
7401
7402 for (auto &Desig : DIE->designators()) {
7403 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7404 DiagnosedArrayDesignator = true;
7405 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7406 << Desig.getSourceRange();
7407 }
7408 }
7409
7410 if (!DiagnosedMixedDesignator &&
7411 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7412 DiagnosedMixedDesignator = true;
7413 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7414 << DIE->getSourceRange();
7415 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7416 << InitArgList[0]->getSourceRange();
7417 }
7418 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7419 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7420 DiagnosedMixedDesignator = true;
7421 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7422 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7423 << DIE->getSourceRange();
7424 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7425 << InitArgList[I]->getSourceRange();
7426 }
7427 }
7428
7429 if (FirstDesignator.isValid()) {
7430 // Only diagnose designated initiaization as a C++20 extension if we didn't
7431 // already diagnose use of (non-C++20) C99 designator syntax.
7432 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7433 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7434 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7435 ? diag::warn_cxx17_compat_designated_init
7436 : diag::ext_cxx_designated_init);
7437 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7438 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7439 }
7440 }
7441
7442 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7443}
7444
7445ExprResult
7446Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7447 SourceLocation RBraceLoc) {
7448 // Semantic analysis for initializers is done by ActOnDeclarator() and
7449 // CheckInitializer() - it requires knowledge of the object being initialized.
7450
7451 // Immediately handle non-overload placeholders. Overloads can be
7452 // resolved contextually, but everything else here can't.
7453 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7454 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7455 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7456
7457 // Ignore failures; dropping the entire initializer list because
7458 // of one failure would be terrible for indexing/etc.
7459 if (result.isInvalid()) continue;
7460
7461 InitArgList[I] = result.get();
7462 }
7463 }
7464
7465 InitListExpr *E =
7466 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7467 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7468 return E;
7469}
7470
7471void Sema::maybeExtendBlockObject(ExprResult &E) {
7472 assert(E.get()->getType()->isBlockPointerType());
7473 assert(E.get()->isPRValue());
7474
7475 // Only do this in an r-value context.
7476 if (!getLangOpts().ObjCAutoRefCount) return;
7477
7478 E = ImplicitCastExpr::Create(
7479 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7480 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7481 Cleanup.setExprNeedsCleanups(true);
7482}
7483
7484CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7485 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7486 // Also, callers should have filtered out the invalid cases with
7487 // pointers. Everything else should be possible.
7488
7489 QualType SrcTy = Src.get()->getType();
7490 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7491 return CK_NoOp;
7492
7493 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7494 case Type::STK_MemberPointer:
7495 llvm_unreachable("member pointer type in C");
7496
7497 case Type::STK_CPointer:
7498 case Type::STK_BlockPointer:
7499 case Type::STK_ObjCObjectPointer:
7500 switch (DestTy->getScalarTypeKind()) {
7501 case Type::STK_CPointer: {
7502 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7503 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7504 if (SrcAS != DestAS)
7505 return CK_AddressSpaceConversion;
7506 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7507 return CK_NoOp;
7508 return CK_BitCast;
7509 }
7510 case Type::STK_BlockPointer:
7511 return (SrcKind == Type::STK_BlockPointer
7512 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7513 case Type::STK_ObjCObjectPointer:
7514 if (SrcKind == Type::STK_ObjCObjectPointer)
7515 return CK_BitCast;
7516 if (SrcKind == Type::STK_CPointer)
7517 return CK_CPointerToObjCPointerCast;
7518 maybeExtendBlockObject(E&: Src);
7519 return CK_BlockPointerToObjCPointerCast;
7520 case Type::STK_Bool:
7521 return CK_PointerToBoolean;
7522 case Type::STK_Integral:
7523 return CK_PointerToIntegral;
7524 case Type::STK_Floating:
7525 case Type::STK_FloatingComplex:
7526 case Type::STK_IntegralComplex:
7527 case Type::STK_MemberPointer:
7528 case Type::STK_FixedPoint:
7529 llvm_unreachable("illegal cast from pointer");
7530 }
7531 llvm_unreachable("Should have returned before this");
7532
7533 case Type::STK_FixedPoint:
7534 switch (DestTy->getScalarTypeKind()) {
7535 case Type::STK_FixedPoint:
7536 return CK_FixedPointCast;
7537 case Type::STK_Bool:
7538 return CK_FixedPointToBoolean;
7539 case Type::STK_Integral:
7540 return CK_FixedPointToIntegral;
7541 case Type::STK_Floating:
7542 return CK_FixedPointToFloating;
7543 case Type::STK_IntegralComplex:
7544 case Type::STK_FloatingComplex:
7545 Diag(Loc: Src.get()->getExprLoc(),
7546 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7547 << DestTy;
7548 return CK_IntegralCast;
7549 case Type::STK_CPointer:
7550 case Type::STK_ObjCObjectPointer:
7551 case Type::STK_BlockPointer:
7552 case Type::STK_MemberPointer:
7553 llvm_unreachable("illegal cast to pointer type");
7554 }
7555 llvm_unreachable("Should have returned before this");
7556
7557 case Type::STK_Bool: // casting from bool is like casting from an integer
7558 case Type::STK_Integral:
7559 switch (DestTy->getScalarTypeKind()) {
7560 case Type::STK_CPointer:
7561 case Type::STK_ObjCObjectPointer:
7562 case Type::STK_BlockPointer:
7563 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7564 NPC: Expr::NPC_ValueDependentIsNull))
7565 return CK_NullToPointer;
7566 return CK_IntegralToPointer;
7567 case Type::STK_Bool:
7568 return CK_IntegralToBoolean;
7569 case Type::STK_Integral:
7570 return CK_IntegralCast;
7571 case Type::STK_Floating:
7572 return CK_IntegralToFloating;
7573 case Type::STK_IntegralComplex:
7574 Src = ImpCastExprToType(E: Src.get(),
7575 Type: DestTy->castAs<ComplexType>()->getElementType(),
7576 CK: CK_IntegralCast);
7577 return CK_IntegralRealToComplex;
7578 case Type::STK_FloatingComplex:
7579 Src = ImpCastExprToType(E: Src.get(),
7580 Type: DestTy->castAs<ComplexType>()->getElementType(),
7581 CK: CK_IntegralToFloating);
7582 return CK_FloatingRealToComplex;
7583 case Type::STK_MemberPointer:
7584 llvm_unreachable("member pointer type in C");
7585 case Type::STK_FixedPoint:
7586 return CK_IntegralToFixedPoint;
7587 }
7588 llvm_unreachable("Should have returned before this");
7589
7590 case Type::STK_Floating:
7591 switch (DestTy->getScalarTypeKind()) {
7592 case Type::STK_Floating:
7593 return CK_FloatingCast;
7594 case Type::STK_Bool:
7595 return CK_FloatingToBoolean;
7596 case Type::STK_Integral:
7597 return CK_FloatingToIntegral;
7598 case Type::STK_FloatingComplex:
7599 Src = ImpCastExprToType(E: Src.get(),
7600 Type: DestTy->castAs<ComplexType>()->getElementType(),
7601 CK: CK_FloatingCast);
7602 return CK_FloatingRealToComplex;
7603 case Type::STK_IntegralComplex:
7604 Src = ImpCastExprToType(E: Src.get(),
7605 Type: DestTy->castAs<ComplexType>()->getElementType(),
7606 CK: CK_FloatingToIntegral);
7607 return CK_IntegralRealToComplex;
7608 case Type::STK_CPointer:
7609 case Type::STK_ObjCObjectPointer:
7610 case Type::STK_BlockPointer:
7611 llvm_unreachable("valid float->pointer cast?");
7612 case Type::STK_MemberPointer:
7613 llvm_unreachable("member pointer type in C");
7614 case Type::STK_FixedPoint:
7615 return CK_FloatingToFixedPoint;
7616 }
7617 llvm_unreachable("Should have returned before this");
7618
7619 case Type::STK_FloatingComplex:
7620 switch (DestTy->getScalarTypeKind()) {
7621 case Type::STK_FloatingComplex:
7622 return CK_FloatingComplexCast;
7623 case Type::STK_IntegralComplex:
7624 return CK_FloatingComplexToIntegralComplex;
7625 case Type::STK_Floating: {
7626 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7627 if (Context.hasSameType(T1: ET, T2: DestTy))
7628 return CK_FloatingComplexToReal;
7629 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7630 return CK_FloatingCast;
7631 }
7632 case Type::STK_Bool:
7633 return CK_FloatingComplexToBoolean;
7634 case Type::STK_Integral:
7635 Src = ImpCastExprToType(E: Src.get(),
7636 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7637 CK: CK_FloatingComplexToReal);
7638 return CK_FloatingToIntegral;
7639 case Type::STK_CPointer:
7640 case Type::STK_ObjCObjectPointer:
7641 case Type::STK_BlockPointer:
7642 llvm_unreachable("valid complex float->pointer cast?");
7643 case Type::STK_MemberPointer:
7644 llvm_unreachable("member pointer type in C");
7645 case Type::STK_FixedPoint:
7646 Diag(Loc: Src.get()->getExprLoc(),
7647 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7648 << SrcTy;
7649 return CK_IntegralCast;
7650 }
7651 llvm_unreachable("Should have returned before this");
7652
7653 case Type::STK_IntegralComplex:
7654 switch (DestTy->getScalarTypeKind()) {
7655 case Type::STK_FloatingComplex:
7656 return CK_IntegralComplexToFloatingComplex;
7657 case Type::STK_IntegralComplex:
7658 return CK_IntegralComplexCast;
7659 case Type::STK_Integral: {
7660 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7661 if (Context.hasSameType(T1: ET, T2: DestTy))
7662 return CK_IntegralComplexToReal;
7663 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7664 return CK_IntegralCast;
7665 }
7666 case Type::STK_Bool:
7667 return CK_IntegralComplexToBoolean;
7668 case Type::STK_Floating:
7669 Src = ImpCastExprToType(E: Src.get(),
7670 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7671 CK: CK_IntegralComplexToReal);
7672 return CK_IntegralToFloating;
7673 case Type::STK_CPointer:
7674 case Type::STK_ObjCObjectPointer:
7675 case Type::STK_BlockPointer:
7676 llvm_unreachable("valid complex int->pointer cast?");
7677 case Type::STK_MemberPointer:
7678 llvm_unreachable("member pointer type in C");
7679 case Type::STK_FixedPoint:
7680 Diag(Loc: Src.get()->getExprLoc(),
7681 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7682 << SrcTy;
7683 return CK_IntegralCast;
7684 }
7685 llvm_unreachable("Should have returned before this");
7686 }
7687
7688 llvm_unreachable("Unhandled scalar cast");
7689}
7690
7691static bool breakDownVectorType(QualType type, uint64_t &len,
7692 QualType &eltType) {
7693 // Vectors are simple.
7694 if (const VectorType *vecType = type->getAs<VectorType>()) {
7695 len = vecType->getNumElements();
7696 eltType = vecType->getElementType();
7697 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7698 return true;
7699 }
7700
7701 // We allow lax conversion to and from non-vector types, but only if
7702 // they're real types (i.e. non-complex, non-pointer scalar types).
7703 if (!type->isRealType()) return false;
7704
7705 len = 1;
7706 eltType = type;
7707 return true;
7708}
7709
7710bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7711 assert(srcTy->isVectorType() || destTy->isVectorType());
7712
7713 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7714 if (!FirstType->isSVESizelessBuiltinType())
7715 return false;
7716
7717 const auto *VecTy = SecondType->getAs<VectorType>();
7718 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7719 };
7720
7721 return ValidScalableConversion(srcTy, destTy) ||
7722 ValidScalableConversion(destTy, srcTy);
7723}
7724
7725bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7726 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7727 return false;
7728
7729 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7730 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7731
7732 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7733 matSrcType->getNumColumns() == matDestType->getNumColumns();
7734}
7735
7736bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7737 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7738
7739 uint64_t SrcLen, DestLen;
7740 QualType SrcEltTy, DestEltTy;
7741 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7742 return false;
7743 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7744 return false;
7745
7746 // ASTContext::getTypeSize will return the size rounded up to a
7747 // power of 2, so instead of using that, we need to use the raw
7748 // element size multiplied by the element count.
7749 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7750 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7751
7752 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7753}
7754
7755bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7756 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7757 "expected at least one type to be a vector here");
7758
7759 bool IsSrcTyAltivec =
7760 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7761 VectorKind::AltiVecVector) ||
7762 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7763 VectorKind::AltiVecBool) ||
7764 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7765 VectorKind::AltiVecPixel));
7766
7767 bool IsDestTyAltivec = DestTy->isVectorType() &&
7768 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7769 VectorKind::AltiVecVector) ||
7770 (DestTy->castAs<VectorType>()->getVectorKind() ==
7771 VectorKind::AltiVecBool) ||
7772 (DestTy->castAs<VectorType>()->getVectorKind() ==
7773 VectorKind::AltiVecPixel));
7774
7775 return (IsSrcTyAltivec || IsDestTyAltivec);
7776}
7777
7778bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7779 assert(destTy->isVectorType() || srcTy->isVectorType());
7780
7781 // Disallow lax conversions between scalars and ExtVectors (these
7782 // conversions are allowed for other vector types because common headers
7783 // depend on them). Most scalar OP ExtVector cases are handled by the
7784 // splat path anyway, which does what we want (convert, not bitcast).
7785 // What this rules out for ExtVectors is crazy things like char4*float.
7786 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7787 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7788
7789 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
7790}
7791
7792bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7793 assert(destTy->isVectorType() || srcTy->isVectorType());
7794
7795 switch (Context.getLangOpts().getLaxVectorConversions()) {
7796 case LangOptions::LaxVectorConversionKind::None:
7797 return false;
7798
7799 case LangOptions::LaxVectorConversionKind::Integer:
7800 if (!srcTy->isIntegralOrEnumerationType()) {
7801 auto *Vec = srcTy->getAs<VectorType>();
7802 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7803 return false;
7804 }
7805 if (!destTy->isIntegralOrEnumerationType()) {
7806 auto *Vec = destTy->getAs<VectorType>();
7807 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7808 return false;
7809 }
7810 // OK, integer (vector) -> integer (vector) bitcast.
7811 break;
7812
7813 case LangOptions::LaxVectorConversionKind::All:
7814 break;
7815 }
7816
7817 return areLaxCompatibleVectorTypes(srcTy, destTy);
7818}
7819
7820bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7821 CastKind &Kind) {
7822 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7823 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
7824 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
7825 << DestTy << SrcTy << R;
7826 }
7827 } else if (SrcTy->isMatrixType()) {
7828 return Diag(Loc: R.getBegin(),
7829 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7830 << SrcTy << DestTy << R;
7831 } else if (DestTy->isMatrixType()) {
7832 return Diag(Loc: R.getBegin(),
7833 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7834 << DestTy << SrcTy << R;
7835 }
7836
7837 Kind = CK_MatrixCast;
7838 return false;
7839}
7840
7841bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7842 CastKind &Kind) {
7843 assert(VectorTy->isVectorType() && "Not a vector type!");
7844
7845 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
7846 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
7847 return Diag(Loc: R.getBegin(),
7848 DiagID: Ty->isVectorType() ?
7849 diag::err_invalid_conversion_between_vectors :
7850 diag::err_invalid_conversion_between_vector_and_integer)
7851 << VectorTy << Ty << R;
7852 } else
7853 return Diag(Loc: R.getBegin(),
7854 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
7855 << VectorTy << Ty << R;
7856
7857 Kind = CK_BitCast;
7858 return false;
7859}
7860
7861ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7862 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7863
7864 if (DestElemTy == SplattedExpr->getType())
7865 return SplattedExpr;
7866
7867 assert(DestElemTy->isFloatingType() ||
7868 DestElemTy->isIntegralOrEnumerationType());
7869
7870 CastKind CK;
7871 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7872 // OpenCL requires that we convert `true` boolean expressions to -1, but
7873 // only when splatting vectors.
7874 if (DestElemTy->isFloatingType()) {
7875 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7876 // in two steps: boolean to signed integral, then to floating.
7877 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
7878 CK: CK_BooleanToSignedIntegral);
7879 SplattedExpr = CastExprRes.get();
7880 CK = CK_IntegralToFloating;
7881 } else {
7882 CK = CK_BooleanToSignedIntegral;
7883 }
7884 } else {
7885 ExprResult CastExprRes = SplattedExpr;
7886 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
7887 if (CastExprRes.isInvalid())
7888 return ExprError();
7889 SplattedExpr = CastExprRes.get();
7890 }
7891 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
7892}
7893
7894ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
7895 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
7896
7897 if (DestElemTy == SplattedExpr->getType())
7898 return SplattedExpr;
7899
7900 assert(DestElemTy->isFloatingType() ||
7901 DestElemTy->isIntegralOrEnumerationType());
7902
7903 ExprResult CastExprRes = SplattedExpr;
7904 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
7905 if (CastExprRes.isInvalid())
7906 return ExprError();
7907 SplattedExpr = CastExprRes.get();
7908
7909 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
7910}
7911
7912ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7913 Expr *CastExpr, CastKind &Kind) {
7914 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7915
7916 QualType SrcTy = CastExpr->getType();
7917
7918 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7919 // an ExtVectorType.
7920 // In OpenCL, casts between vectors of different types are not allowed.
7921 // (See OpenCL 6.2).
7922 if (SrcTy->isVectorType()) {
7923 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
7924 (getLangOpts().OpenCL &&
7925 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
7926 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
7927 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
7928 << DestTy << SrcTy << R;
7929 return ExprError();
7930 }
7931 Kind = CK_BitCast;
7932 return CastExpr;
7933 }
7934
7935 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7936 // conversion will take place first from scalar to elt type, and then
7937 // splat from elt type to vector.
7938 if (SrcTy->isPointerType())
7939 return Diag(Loc: R.getBegin(),
7940 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
7941 << DestTy << SrcTy << R;
7942
7943 Kind = CK_VectorSplat;
7944 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
7945}
7946
7947/// Check that a call to alloc_size function specifies sufficient space for the
7948/// destination type.
7949static void CheckSufficientAllocSize(Sema &S, QualType DestType,
7950 const Expr *E) {
7951 QualType SourceType = E->getType();
7952 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
7953 DestType == SourceType)
7954 return;
7955
7956 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
7957 if (!CE)
7958 return;
7959
7960 // Find the total size allocated by the function call.
7961 if (!CE->getCalleeAllocSizeAttr())
7962 return;
7963 std::optional<llvm::APInt> AllocSize =
7964 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
7965 // Allocations of size zero are permitted as a special case. They are usually
7966 // done intentionally.
7967 if (!AllocSize || AllocSize->isZero())
7968 return;
7969 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
7970
7971 QualType TargetType = DestType->getPointeeType();
7972 // Find the destination size. As a special case function types have size of
7973 // one byte to match the sizeof operator behavior.
7974 auto LhsSize = TargetType->isFunctionType()
7975 ? CharUnits::One()
7976 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
7977 if (LhsSize && Size < LhsSize)
7978 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
7979 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
7980}
7981
7982ExprResult
7983Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7984 Declarator &D, ParsedType &Ty,
7985 SourceLocation RParenLoc, Expr *CastExpr) {
7986 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7987 "ActOnCastExpr(): missing type or expr");
7988
7989 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
7990 if (D.isInvalidType())
7991 return ExprError();
7992
7993 if (getLangOpts().CPlusPlus) {
7994 // Check that there are no default arguments (C++ only).
7995 CheckExtraCXXDefaultArguments(D);
7996 }
7997
7998 checkUnusedDeclAttributes(D);
7999
8000 QualType castType = castTInfo->getType();
8001 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8002
8003 bool isVectorLiteral = false;
8004
8005 // Check for an altivec or OpenCL literal,
8006 // i.e. all the elements are integer constants.
8007 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8008 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8009 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8010 && castType->isVectorType() && (PE || PLE)) {
8011 if (PLE && PLE->getNumExprs() == 0) {
8012 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8013 return ExprError();
8014 }
8015 if (PE || PLE->getNumExprs() == 1) {
8016 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8017 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8018 isVectorLiteral = true;
8019 }
8020 else
8021 isVectorLiteral = true;
8022 }
8023
8024 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8025 // then handle it as such.
8026 if (isVectorLiteral)
8027 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8028
8029 // If the Expr being casted is a ParenListExpr, handle it specially.
8030 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8031 // sequence of BinOp comma operators.
8032 if (isa<ParenListExpr>(Val: CastExpr)) {
8033 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8034 if (Result.isInvalid()) return ExprError();
8035 CastExpr = Result.get();
8036 }
8037
8038 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8039 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8040
8041 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8042
8043 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8044
8045 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8046
8047 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8048
8049 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8050}
8051
8052ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8053 SourceLocation RParenLoc, Expr *E,
8054 TypeSourceInfo *TInfo) {
8055 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8056 "Expected paren or paren list expression");
8057
8058 Expr **exprs;
8059 unsigned numExprs;
8060 Expr *subExpr;
8061 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8062 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8063 LiteralLParenLoc = PE->getLParenLoc();
8064 LiteralRParenLoc = PE->getRParenLoc();
8065 exprs = PE->getExprs();
8066 numExprs = PE->getNumExprs();
8067 } else { // isa<ParenExpr> by assertion at function entrance
8068 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8069 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8070 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8071 exprs = &subExpr;
8072 numExprs = 1;
8073 }
8074
8075 QualType Ty = TInfo->getType();
8076 assert(Ty->isVectorType() && "Expected vector type");
8077
8078 SmallVector<Expr *, 8> initExprs;
8079 const VectorType *VTy = Ty->castAs<VectorType>();
8080 unsigned numElems = VTy->getNumElements();
8081
8082 // '(...)' form of vector initialization in AltiVec: the number of
8083 // initializers must be one or must match the size of the vector.
8084 // If a single value is specified in the initializer then it will be
8085 // replicated to all the components of the vector
8086 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8087 SrcTy: VTy->getElementType()))
8088 return ExprError();
8089 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8090 // The number of initializers must be one or must match the size of the
8091 // vector. If a single value is specified in the initializer then it will
8092 // be replicated to all the components of the vector
8093 if (numExprs == 1) {
8094 QualType ElemTy = VTy->getElementType();
8095 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8096 if (Literal.isInvalid())
8097 return ExprError();
8098 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8099 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8100 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8101 }
8102 else if (numExprs < numElems) {
8103 Diag(Loc: E->getExprLoc(),
8104 DiagID: diag::err_incorrect_number_of_vector_initializers);
8105 return ExprError();
8106 }
8107 else
8108 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8109 }
8110 else {
8111 // For OpenCL, when the number of initializers is a single value,
8112 // it will be replicated to all components of the vector.
8113 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8114 numExprs == 1) {
8115 QualType ElemTy = VTy->getElementType();
8116 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8117 if (Literal.isInvalid())
8118 return ExprError();
8119 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8120 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8121 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8122 }
8123
8124 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8125 }
8126 // FIXME: This means that pretty-printing the final AST will produce curly
8127 // braces instead of the original commas.
8128 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8129 initExprs, LiteralRParenLoc);
8130 initE->setType(Ty);
8131 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8132}
8133
8134ExprResult
8135Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8136 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8137 if (!E)
8138 return OrigExpr;
8139
8140 ExprResult Result(E->getExpr(Init: 0));
8141
8142 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8143 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8144 RHSExpr: E->getExpr(Init: i));
8145
8146 if (Result.isInvalid()) return ExprError();
8147
8148 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8149}
8150
8151ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8152 SourceLocation R,
8153 MultiExprArg Val) {
8154 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8155}
8156
8157ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8158 unsigned NumUserSpecifiedExprs,
8159 SourceLocation InitLoc,
8160 SourceLocation LParenLoc,
8161 SourceLocation RParenLoc) {
8162 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8163 InitLoc, LParenLoc, RParenLoc);
8164}
8165
8166bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8167 SourceLocation QuestionLoc) {
8168 const Expr *NullExpr = LHSExpr;
8169 const Expr *NonPointerExpr = RHSExpr;
8170 Expr::NullPointerConstantKind NullKind =
8171 NullExpr->isNullPointerConstant(Ctx&: Context,
8172 NPC: Expr::NPC_ValueDependentIsNotNull);
8173
8174 if (NullKind == Expr::NPCK_NotNull) {
8175 NullExpr = RHSExpr;
8176 NonPointerExpr = LHSExpr;
8177 NullKind =
8178 NullExpr->isNullPointerConstant(Ctx&: Context,
8179 NPC: Expr::NPC_ValueDependentIsNotNull);
8180 }
8181
8182 if (NullKind == Expr::NPCK_NotNull)
8183 return false;
8184
8185 if (NullKind == Expr::NPCK_ZeroExpression)
8186 return false;
8187
8188 if (NullKind == Expr::NPCK_ZeroLiteral) {
8189 // In this case, check to make sure that we got here from a "NULL"
8190 // string in the source code.
8191 NullExpr = NullExpr->IgnoreParenImpCasts();
8192 SourceLocation loc = NullExpr->getExprLoc();
8193 if (!findMacroSpelling(loc, name: "NULL"))
8194 return false;
8195 }
8196
8197 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8198 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8199 << NonPointerExpr->getType() << DiagType
8200 << NonPointerExpr->getSourceRange();
8201 return true;
8202}
8203
8204/// Return false if the condition expression is valid, true otherwise.
8205static bool checkCondition(Sema &S, const Expr *Cond,
8206 SourceLocation QuestionLoc) {
8207 QualType CondTy = Cond->getType();
8208
8209 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8210 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8211 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8212 << CondTy << Cond->getSourceRange();
8213 return true;
8214 }
8215
8216 // C99 6.5.15p2
8217 if (CondTy->isScalarType()) return false;
8218
8219 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8220 << CondTy << Cond->getSourceRange();
8221 return true;
8222}
8223
8224/// Return false if the NullExpr can be promoted to PointerTy,
8225/// true otherwise.
8226static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8227 QualType PointerTy) {
8228 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8229 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8230 NPC: Expr::NPC_ValueDependentIsNull))
8231 return true;
8232
8233 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8234 return false;
8235}
8236
8237/// Checks compatibility between two pointers and return the resulting
8238/// type.
8239static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8240 ExprResult &RHS,
8241 SourceLocation Loc) {
8242 QualType LHSTy = LHS.get()->getType();
8243 QualType RHSTy = RHS.get()->getType();
8244
8245 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8246 // Two identical pointers types are always compatible.
8247 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8248 }
8249
8250 QualType lhptee, rhptee;
8251
8252 // Get the pointee types.
8253 bool IsBlockPointer = false;
8254 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8255 lhptee = LHSBTy->getPointeeType();
8256 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8257 IsBlockPointer = true;
8258 } else {
8259 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8260 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8261 }
8262
8263 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8264 // differently qualified versions of compatible types, the result type is
8265 // a pointer to an appropriately qualified version of the composite
8266 // type.
8267
8268 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8269 // clause doesn't make sense for our extensions. E.g. address space 2 should
8270 // be incompatible with address space 3: they may live on different devices or
8271 // anything.
8272 Qualifiers lhQual = lhptee.getQualifiers();
8273 Qualifiers rhQual = rhptee.getQualifiers();
8274
8275 LangAS ResultAddrSpace = LangAS::Default;
8276 LangAS LAddrSpace = lhQual.getAddressSpace();
8277 LangAS RAddrSpace = rhQual.getAddressSpace();
8278
8279 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8280 // spaces is disallowed.
8281 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8282 ResultAddrSpace = LAddrSpace;
8283 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8284 ResultAddrSpace = RAddrSpace;
8285 else {
8286 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8287 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8288 << RHS.get()->getSourceRange();
8289 return QualType();
8290 }
8291
8292 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8293 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8294 lhQual.removeCVRQualifiers();
8295 rhQual.removeCVRQualifiers();
8296
8297 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8298 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8299 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8300 << RHS.get()->getSourceRange();
8301 return QualType();
8302 }
8303
8304 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8305 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8306 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8307 // qual types are compatible iff
8308 // * corresponded types are compatible
8309 // * CVR qualifiers are equal
8310 // * address spaces are equal
8311 // Thus for conditional operator we merge CVR and address space unqualified
8312 // pointees and if there is a composite type we return a pointer to it with
8313 // merged qualifiers.
8314 LHSCastKind =
8315 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8316 RHSCastKind =
8317 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8318 lhQual.removeAddressSpace();
8319 rhQual.removeAddressSpace();
8320
8321 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8322 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8323
8324 QualType CompositeTy = S.Context.mergeTypes(
8325 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8326 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8327
8328 if (CompositeTy.isNull()) {
8329 // In this situation, we assume void* type. No especially good
8330 // reason, but this is what gcc does, and we do have to pick
8331 // to get a consistent AST.
8332 QualType incompatTy;
8333 incompatTy = S.Context.getPointerType(
8334 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8335 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8336 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8337
8338 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8339 // for casts between types with incompatible address space qualifiers.
8340 // For the following code the compiler produces casts between global and
8341 // local address spaces of the corresponded innermost pointees:
8342 // local int *global *a;
8343 // global int *global *b;
8344 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8345 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8346 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8347 << RHS.get()->getSourceRange();
8348
8349 return incompatTy;
8350 }
8351
8352 // The pointer types are compatible.
8353 // In case of OpenCL ResultTy should have the address space qualifier
8354 // which is a superset of address spaces of both the 2nd and the 3rd
8355 // operands of the conditional operator.
8356 QualType ResultTy = [&, ResultAddrSpace]() {
8357 if (S.getLangOpts().OpenCL) {
8358 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8359 CompositeQuals.setAddressSpace(ResultAddrSpace);
8360 return S.Context
8361 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8362 .withCVRQualifiers(CVR: MergedCVRQual);
8363 }
8364 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8365 }();
8366 if (IsBlockPointer)
8367 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8368 else
8369 ResultTy = S.Context.getPointerType(T: ResultTy);
8370
8371 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8372 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8373 return ResultTy;
8374}
8375
8376/// Return the resulting type when the operands are both block pointers.
8377static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8378 ExprResult &LHS,
8379 ExprResult &RHS,
8380 SourceLocation Loc) {
8381 QualType LHSTy = LHS.get()->getType();
8382 QualType RHSTy = RHS.get()->getType();
8383
8384 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8385 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8386 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8387 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8388 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8389 return destType;
8390 }
8391 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8392 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8393 << RHS.get()->getSourceRange();
8394 return QualType();
8395 }
8396
8397 // We have 2 block pointer types.
8398 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8399}
8400
8401/// Return the resulting type when the operands are both pointers.
8402static QualType
8403checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8404 ExprResult &RHS,
8405 SourceLocation Loc) {
8406 // get the pointer types
8407 QualType LHSTy = LHS.get()->getType();
8408 QualType RHSTy = RHS.get()->getType();
8409
8410 // get the "pointed to" types
8411 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8412 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8413
8414 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8415 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8416 // Figure out necessary qualifiers (C99 6.5.15p6)
8417 QualType destPointee
8418 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8419 QualType destType = S.Context.getPointerType(T: destPointee);
8420 // Add qualifiers if necessary.
8421 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8422 // Promote to void*.
8423 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8424 return destType;
8425 }
8426 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8427 QualType destPointee
8428 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8429 QualType destType = S.Context.getPointerType(T: destPointee);
8430 // Add qualifiers if necessary.
8431 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8432 // Promote to void*.
8433 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8434 return destType;
8435 }
8436
8437 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8438}
8439
8440/// Return false if the first expression is not an integer and the second
8441/// expression is not a pointer, true otherwise.
8442static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8443 Expr* PointerExpr, SourceLocation Loc,
8444 bool IsIntFirstExpr) {
8445 if (!PointerExpr->getType()->isPointerType() ||
8446 !Int.get()->getType()->isIntegerType())
8447 return false;
8448
8449 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8450 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8451
8452 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8453 << Expr1->getType() << Expr2->getType()
8454 << Expr1->getSourceRange() << Expr2->getSourceRange();
8455 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8456 CK: CK_IntegralToPointer);
8457 return true;
8458}
8459
8460/// Simple conversion between integer and floating point types.
8461///
8462/// Used when handling the OpenCL conditional operator where the
8463/// condition is a vector while the other operands are scalar.
8464///
8465/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8466/// types are either integer or floating type. Between the two
8467/// operands, the type with the higher rank is defined as the "result
8468/// type". The other operand needs to be promoted to the same type. No
8469/// other type promotion is allowed. We cannot use
8470/// UsualArithmeticConversions() for this purpose, since it always
8471/// promotes promotable types.
8472static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8473 ExprResult &RHS,
8474 SourceLocation QuestionLoc) {
8475 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8476 if (LHS.isInvalid())
8477 return QualType();
8478 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8479 if (RHS.isInvalid())
8480 return QualType();
8481
8482 // For conversion purposes, we ignore any qualifiers.
8483 // For example, "const float" and "float" are equivalent.
8484 QualType LHSType =
8485 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8486 QualType RHSType =
8487 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8488
8489 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8490 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8491 << LHSType << LHS.get()->getSourceRange();
8492 return QualType();
8493 }
8494
8495 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8496 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8497 << RHSType << RHS.get()->getSourceRange();
8498 return QualType();
8499 }
8500
8501 // If both types are identical, no conversion is needed.
8502 if (LHSType == RHSType)
8503 return LHSType;
8504
8505 // Now handle "real" floating types (i.e. float, double, long double).
8506 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8507 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8508 /*IsCompAssign = */ false);
8509
8510 // Finally, we have two differing integer types.
8511 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8512 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8513}
8514
8515/// Convert scalar operands to a vector that matches the
8516/// condition in length.
8517///
8518/// Used when handling the OpenCL conditional operator where the
8519/// condition is a vector while the other operands are scalar.
8520///
8521/// We first compute the "result type" for the scalar operands
8522/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8523/// into a vector of that type where the length matches the condition
8524/// vector type. s6.11.6 requires that the element types of the result
8525/// and the condition must have the same number of bits.
8526static QualType
8527OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8528 QualType CondTy, SourceLocation QuestionLoc) {
8529 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8530 if (ResTy.isNull()) return QualType();
8531
8532 const VectorType *CV = CondTy->getAs<VectorType>();
8533 assert(CV);
8534
8535 // Determine the vector result type
8536 unsigned NumElements = CV->getNumElements();
8537 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8538
8539 // Ensure that all types have the same number of bits
8540 if (S.Context.getTypeSize(T: CV->getElementType())
8541 != S.Context.getTypeSize(T: ResTy)) {
8542 // Since VectorTy is created internally, it does not pretty print
8543 // with an OpenCL name. Instead, we just print a description.
8544 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8545 SmallString<64> Str;
8546 llvm::raw_svector_ostream OS(Str);
8547 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8548 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8549 << CondTy << OS.str();
8550 return QualType();
8551 }
8552
8553 // Convert operands to the vector result type
8554 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8555 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8556
8557 return VectorTy;
8558}
8559
8560/// Return false if this is a valid OpenCL condition vector
8561static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8562 SourceLocation QuestionLoc) {
8563 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8564 // integral type.
8565 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8566 assert(CondTy);
8567 QualType EleTy = CondTy->getElementType();
8568 if (EleTy->isIntegerType()) return false;
8569
8570 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8571 << Cond->getType() << Cond->getSourceRange();
8572 return true;
8573}
8574
8575/// Return false if the vector condition type and the vector
8576/// result type are compatible.
8577///
8578/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8579/// number of elements, and their element types have the same number
8580/// of bits.
8581static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8582 SourceLocation QuestionLoc) {
8583 const VectorType *CV = CondTy->getAs<VectorType>();
8584 const VectorType *RV = VecResTy->getAs<VectorType>();
8585 assert(CV && RV);
8586
8587 if (CV->getNumElements() != RV->getNumElements()) {
8588 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8589 << CondTy << VecResTy;
8590 return true;
8591 }
8592
8593 QualType CVE = CV->getElementType();
8594 QualType RVE = RV->getElementType();
8595
8596 // Boolean vectors are permitted outside of OpenCL mode.
8597 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8598 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8599 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8600 << CondTy << VecResTy;
8601 return true;
8602 }
8603
8604 return false;
8605}
8606
8607/// Return the resulting type for the conditional operator in
8608/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8609/// s6.3.i) when the condition is a vector type.
8610static QualType
8611OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8612 ExprResult &LHS, ExprResult &RHS,
8613 SourceLocation QuestionLoc) {
8614 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8615 if (Cond.isInvalid())
8616 return QualType();
8617 QualType CondTy = Cond.get()->getType();
8618
8619 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8620 return QualType();
8621
8622 // If either operand is a vector then find the vector type of the
8623 // result as specified in OpenCL v1.1 s6.3.i.
8624 if (LHS.get()->getType()->isVectorType() ||
8625 RHS.get()->getType()->isVectorType()) {
8626 bool IsBoolVecLang =
8627 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8628 QualType VecResTy =
8629 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8630 /*isCompAssign*/ IsCompAssign: false,
8631 /*AllowBothBool*/ true,
8632 /*AllowBoolConversions*/ AllowBoolConversion: false,
8633 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8634 /*ReportInvalid*/ true);
8635 if (VecResTy.isNull())
8636 return QualType();
8637 // The result type must match the condition type as specified in
8638 // OpenCL v1.1 s6.11.6.
8639 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8640 return QualType();
8641 return VecResTy;
8642 }
8643
8644 // Both operands are scalar.
8645 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8646}
8647
8648/// Return true if the Expr is block type
8649static bool checkBlockType(Sema &S, const Expr *E) {
8650 if (E->getType()->isBlockPointerType()) {
8651 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8652 return true;
8653 }
8654
8655 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8656 QualType Ty = CE->getCallee()->getType();
8657 if (Ty->isBlockPointerType()) {
8658 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8659 return true;
8660 }
8661 }
8662 return false;
8663}
8664
8665/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8666/// In that case, LHS = cond.
8667/// C99 6.5.15
8668QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8669 ExprResult &RHS, ExprValueKind &VK,
8670 ExprObjectKind &OK,
8671 SourceLocation QuestionLoc) {
8672
8673 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8674 if (!LHSResult.isUsable()) return QualType();
8675 LHS = LHSResult;
8676
8677 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8678 if (!RHSResult.isUsable()) return QualType();
8679 RHS = RHSResult;
8680
8681 // C++ is sufficiently different to merit its own checker.
8682 if (getLangOpts().CPlusPlus)
8683 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8684
8685 VK = VK_PRValue;
8686 OK = OK_Ordinary;
8687
8688 if (Context.isDependenceAllowed() &&
8689 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8690 RHS.get()->isTypeDependent())) {
8691 assert(!getLangOpts().CPlusPlus);
8692 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8693 RHS.get()->containsErrors()) &&
8694 "should only occur in error-recovery path.");
8695 return Context.DependentTy;
8696 }
8697
8698 // The OpenCL operator with a vector condition is sufficiently
8699 // different to merit its own checker.
8700 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8701 Cond.get()->getType()->isExtVectorType())
8702 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8703
8704 // First, check the condition.
8705 Cond = UsualUnaryConversions(E: Cond.get());
8706 if (Cond.isInvalid())
8707 return QualType();
8708 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8709 return QualType();
8710
8711 // Handle vectors.
8712 if (LHS.get()->getType()->isVectorType() ||
8713 RHS.get()->getType()->isVectorType())
8714 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8715 /*AllowBothBool*/ true,
8716 /*AllowBoolConversions*/ AllowBoolConversion: false,
8717 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8718 /*ReportInvalid*/ true);
8719
8720 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8721 ACK: ArithConvKind::Conditional);
8722 if (LHS.isInvalid() || RHS.isInvalid())
8723 return QualType();
8724
8725 // WebAssembly tables are not allowed as conditional LHS or RHS.
8726 QualType LHSTy = LHS.get()->getType();
8727 QualType RHSTy = RHS.get()->getType();
8728 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8729 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8730 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8731 return QualType();
8732 }
8733
8734 // Diagnose attempts to convert between __ibm128, __float128 and long double
8735 // where such conversions currently can't be handled.
8736 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8737 Diag(Loc: QuestionLoc,
8738 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8740 return QualType();
8741 }
8742
8743 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8744 // selection operator (?:).
8745 if (getLangOpts().OpenCL &&
8746 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8747 return QualType();
8748 }
8749
8750 // If both operands have arithmetic type, do the usual arithmetic conversions
8751 // to find a common type: C99 6.5.15p3,5.
8752 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8753 // Disallow invalid arithmetic conversions, such as those between bit-
8754 // precise integers types of different sizes, or between a bit-precise
8755 // integer and another type.
8756 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8757 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8758 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8759 << RHS.get()->getSourceRange();
8760 return QualType();
8761 }
8762
8763 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8764 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
8765
8766 return ResTy;
8767 }
8768
8769 // If both operands are the same structure or union type, the result is that
8770 // type.
8771 // FIXME: Type of conditional expression must be complete in C mode.
8772 if (LHSTy->isRecordType() &&
8773 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
8774 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
8775 Y: RHSTy.getUnqualifiedType());
8776
8777 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8778 // The following || allows only one side to be void (a GCC-ism).
8779 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8780 QualType ResTy;
8781 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8782 ResTy = Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8783 } else if (RHSTy->isVoidType()) {
8784 ResTy = RHSTy;
8785 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8786 << RHS.get()->getSourceRange();
8787 } else {
8788 ResTy = LHSTy;
8789 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8790 << LHS.get()->getSourceRange();
8791 }
8792 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
8793 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
8794 return ResTy;
8795 }
8796
8797 // C23 6.5.15p7:
8798 // ... if both the second and third operands have nullptr_t type, the
8799 // result also has that type.
8800 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
8801 return ResTy;
8802
8803 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8804 // the type of the other operand."
8805 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
8806 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
8807
8808 // All objective-c pointer type analysis is done here.
8809 QualType compositeType =
8810 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8811 if (LHS.isInvalid() || RHS.isInvalid())
8812 return QualType();
8813 if (!compositeType.isNull())
8814 return compositeType;
8815
8816
8817 // Handle block pointer types.
8818 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8819 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
8820 Loc: QuestionLoc);
8821
8822 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8823 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8824 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
8825 Loc: QuestionLoc);
8826
8827 // GCC compatibility: soften pointer/integer mismatch. Note that
8828 // null pointers have been filtered out by this point.
8829 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
8830 /*IsIntFirstExpr=*/true))
8831 return RHSTy;
8832 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
8833 /*IsIntFirstExpr=*/false))
8834 return LHSTy;
8835
8836 // Emit a better diagnostic if one of the expressions is a null pointer
8837 // constant and the other is not a pointer type. In this case, the user most
8838 // likely forgot to take the address of the other expression.
8839 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
8840 return QualType();
8841
8842 // Finally, if the LHS and RHS types are canonically the same type, we can
8843 // use the common sugared type.
8844 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
8845 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8846
8847 // Otherwise, the operands are not compatible.
8848 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8849 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8850 << RHS.get()->getSourceRange();
8851 return QualType();
8852}
8853
8854/// SuggestParentheses - Emit a note with a fixit hint that wraps
8855/// ParenRange in parentheses.
8856static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8857 const PartialDiagnostic &Note,
8858 SourceRange ParenRange) {
8859 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
8860 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8861 EndLoc.isValid()) {
8862 Self.Diag(Loc, PD: Note)
8863 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
8864 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
8865 } else {
8866 // We can't display the parentheses, so just show the bare note.
8867 Self.Diag(Loc, PD: Note) << ParenRange;
8868 }
8869}
8870
8871static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8872 return BinaryOperator::isAdditiveOp(Opc) ||
8873 BinaryOperator::isMultiplicativeOp(Opc) ||
8874 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8875 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8876 // not any of the logical operators. Bitwise-xor is commonly used as a
8877 // logical-xor because there is no logical-xor operator. The logical
8878 // operators, including uses of xor, have a high false positive rate for
8879 // precedence warnings.
8880}
8881
8882/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8883/// expression, either using a built-in or overloaded operator,
8884/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8885/// expression.
8886static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8887 const Expr **RHSExprs) {
8888 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8889 E = E->IgnoreImpCasts();
8890 E = E->IgnoreConversionOperatorSingleStep();
8891 E = E->IgnoreImpCasts();
8892 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
8893 E = MTE->getSubExpr();
8894 E = E->IgnoreImpCasts();
8895 }
8896
8897 // Built-in binary operator.
8898 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
8899 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
8900 *Opcode = OP->getOpcode();
8901 *RHSExprs = OP->getRHS();
8902 return true;
8903 }
8904
8905 // Overloaded operator.
8906 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
8907 if (Call->getNumArgs() != 2)
8908 return false;
8909
8910 // Make sure this is really a binary operator that is safe to pass into
8911 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8912 OverloadedOperatorKind OO = Call->getOperator();
8913 if (OO < OO_Plus || OO > OO_Arrow ||
8914 OO == OO_PlusPlus || OO == OO_MinusMinus)
8915 return false;
8916
8917 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8918 if (IsArithmeticOp(Opc: OpKind)) {
8919 *Opcode = OpKind;
8920 *RHSExprs = Call->getArg(Arg: 1);
8921 return true;
8922 }
8923 }
8924
8925 return false;
8926}
8927
8928/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8929/// or is a logical expression such as (x==y) which has int type, but is
8930/// commonly interpreted as boolean.
8931static bool ExprLooksBoolean(const Expr *E) {
8932 E = E->IgnoreParenImpCasts();
8933
8934 if (E->getType()->isBooleanType())
8935 return true;
8936 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
8937 return OP->isComparisonOp() || OP->isLogicalOp();
8938 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
8939 return OP->getOpcode() == UO_LNot;
8940 if (E->getType()->isPointerType())
8941 return true;
8942 // FIXME: What about overloaded operator calls returning "unspecified boolean
8943 // type"s (commonly pointer-to-members)?
8944
8945 return false;
8946}
8947
8948/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8949/// and binary operator are mixed in a way that suggests the programmer assumed
8950/// the conditional operator has higher precedence, for example:
8951/// "int x = a + someBinaryCondition ? 1 : 2".
8952static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
8953 Expr *Condition, const Expr *LHSExpr,
8954 const Expr *RHSExpr) {
8955 BinaryOperatorKind CondOpcode;
8956 const Expr *CondRHS;
8957
8958 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
8959 return;
8960 if (!ExprLooksBoolean(E: CondRHS))
8961 return;
8962
8963 // The condition is an arithmetic binary expression, with a right-
8964 // hand side that looks boolean, so warn.
8965
8966 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
8967 ? diag::warn_precedence_bitwise_conditional
8968 : diag::warn_precedence_conditional;
8969
8970 Self.Diag(Loc: OpLoc, DiagID)
8971 << Condition->getSourceRange()
8972 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
8973
8974 SuggestParentheses(
8975 Self, Loc: OpLoc,
8976 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
8977 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
8978 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8979
8980 SuggestParentheses(Self, Loc: OpLoc,
8981 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
8982 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8983}
8984
8985/// Compute the nullability of a conditional expression.
8986static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8987 QualType LHSTy, QualType RHSTy,
8988 ASTContext &Ctx) {
8989 if (!ResTy->isAnyPointerType())
8990 return ResTy;
8991
8992 auto GetNullability = [](QualType Ty) {
8993 std::optional<NullabilityKind> Kind = Ty->getNullability();
8994 if (Kind) {
8995 // For our purposes, treat _Nullable_result as _Nullable.
8996 if (*Kind == NullabilityKind::NullableResult)
8997 return NullabilityKind::Nullable;
8998 return *Kind;
8999 }
9000 return NullabilityKind::Unspecified;
9001 };
9002
9003 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9004 NullabilityKind MergedKind;
9005
9006 // Compute nullability of a binary conditional expression.
9007 if (IsBin) {
9008 if (LHSKind == NullabilityKind::NonNull)
9009 MergedKind = NullabilityKind::NonNull;
9010 else
9011 MergedKind = RHSKind;
9012 // Compute nullability of a normal conditional expression.
9013 } else {
9014 if (LHSKind == NullabilityKind::Nullable ||
9015 RHSKind == NullabilityKind::Nullable)
9016 MergedKind = NullabilityKind::Nullable;
9017 else if (LHSKind == NullabilityKind::NonNull)
9018 MergedKind = RHSKind;
9019 else if (RHSKind == NullabilityKind::NonNull)
9020 MergedKind = LHSKind;
9021 else
9022 MergedKind = NullabilityKind::Unspecified;
9023 }
9024
9025 // Return if ResTy already has the correct nullability.
9026 if (GetNullability(ResTy) == MergedKind)
9027 return ResTy;
9028
9029 // Strip all nullability from ResTy.
9030 while (ResTy->getNullability())
9031 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9032
9033 // Create a new AttributedType with the new nullability kind.
9034 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9035}
9036
9037ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9038 SourceLocation ColonLoc,
9039 Expr *CondExpr, Expr *LHSExpr,
9040 Expr *RHSExpr) {
9041 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9042 // was the condition.
9043 OpaqueValueExpr *opaqueValue = nullptr;
9044 Expr *commonExpr = nullptr;
9045 if (!LHSExpr) {
9046 commonExpr = CondExpr;
9047 // Lower out placeholder types first. This is important so that we don't
9048 // try to capture a placeholder. This happens in few cases in C++; such
9049 // as Objective-C++'s dictionary subscripting syntax.
9050 if (commonExpr->hasPlaceholderType()) {
9051 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9052 if (!result.isUsable()) return ExprError();
9053 commonExpr = result.get();
9054 }
9055 // We usually want to apply unary conversions *before* saving, except
9056 // in the special case of a C++ l-value conditional.
9057 if (!(getLangOpts().CPlusPlus
9058 && !commonExpr->isTypeDependent()
9059 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9060 && commonExpr->isGLValue()
9061 && commonExpr->isOrdinaryOrBitFieldObject()
9062 && RHSExpr->isOrdinaryOrBitFieldObject()
9063 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9064 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9065 if (commonRes.isInvalid())
9066 return ExprError();
9067 commonExpr = commonRes.get();
9068 }
9069
9070 // If the common expression is a class or array prvalue, materialize it
9071 // so that we can safely refer to it multiple times.
9072 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9073 commonExpr->getType()->isArrayType())) {
9074 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9075 if (MatExpr.isInvalid())
9076 return ExprError();
9077 commonExpr = MatExpr.get();
9078 }
9079
9080 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9081 commonExpr->getType(),
9082 commonExpr->getValueKind(),
9083 commonExpr->getObjectKind(),
9084 commonExpr);
9085 LHSExpr = CondExpr = opaqueValue;
9086 }
9087
9088 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9089 ExprValueKind VK = VK_PRValue;
9090 ExprObjectKind OK = OK_Ordinary;
9091 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9092 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9093 VK, OK, QuestionLoc);
9094 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9095 RHS.isInvalid())
9096 return ExprError();
9097
9098 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9099 RHSExpr: RHS.get());
9100
9101 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9102
9103 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9104 Ctx&: Context);
9105
9106 if (!commonExpr)
9107 return new (Context)
9108 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9109 RHS.get(), result, VK, OK);
9110
9111 return new (Context) BinaryConditionalOperator(
9112 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9113 ColonLoc, result, VK, OK);
9114}
9115
9116bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9117 unsigned FromAttributes = 0, ToAttributes = 0;
9118 if (const auto *FromFn =
9119 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9120 FromAttributes =
9121 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9122 if (const auto *ToFn =
9123 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9124 ToAttributes =
9125 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9126
9127 return FromAttributes != ToAttributes;
9128}
9129
9130// checkPointerTypesForAssignment - This is a very tricky routine (despite
9131// being closely modeled after the C99 spec:-). The odd characteristic of this
9132// routine is it effectively iqnores the qualifiers on the top level pointee.
9133// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9134// FIXME: add a couple examples in this comment.
9135static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9136 QualType LHSType,
9137 QualType RHSType,
9138 SourceLocation Loc) {
9139 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9140 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9141
9142 // get the "pointed to" type (ignoring qualifiers at the top level)
9143 const Type *lhptee, *rhptee;
9144 Qualifiers lhq, rhq;
9145 std::tie(args&: lhptee, args&: lhq) =
9146 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9147 std::tie(args&: rhptee, args&: rhq) =
9148 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9149
9150 AssignConvertType ConvTy = AssignConvertType::Compatible;
9151
9152 // C99 6.5.16.1p1: This following citation is common to constraints
9153 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9154 // qualifiers of the type *pointed to* by the right;
9155
9156 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9157 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9158 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9159 // Ignore lifetime for further calculation.
9160 lhq.removeObjCLifetime();
9161 rhq.removeObjCLifetime();
9162 }
9163
9164 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9165 // Treat address-space mismatches as fatal.
9166 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9167 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9168
9169 // It's okay to add or remove GC or lifetime qualifiers when converting to
9170 // and from void*.
9171 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9172 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9173 Ctx: S.getASTContext()) &&
9174 (lhptee->isVoidType() || rhptee->isVoidType()))
9175 ; // keep old
9176
9177 // Treat lifetime mismatches as fatal.
9178 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9179 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9180
9181 // Treat pointer-auth mismatches as fatal.
9182 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9183 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9184
9185 // For GCC/MS compatibility, other qualifier mismatches are treated
9186 // as still compatible in C.
9187 else
9188 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9189 }
9190
9191 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9192 // incomplete type and the other is a pointer to a qualified or unqualified
9193 // version of void...
9194 if (lhptee->isVoidType()) {
9195 if (rhptee->isIncompleteOrObjectType())
9196 return ConvTy;
9197
9198 // As an extension, we allow cast to/from void* to function pointer.
9199 assert(rhptee->isFunctionType());
9200 return AssignConvertType::FunctionVoidPointer;
9201 }
9202
9203 if (rhptee->isVoidType()) {
9204 // In C, void * to another pointer type is compatible, but we want to note
9205 // that there will be an implicit conversion happening here.
9206 if (lhptee->isIncompleteOrObjectType())
9207 return ConvTy == AssignConvertType::Compatible &&
9208 !S.getLangOpts().CPlusPlus
9209 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9210 : ConvTy;
9211
9212 // As an extension, we allow cast to/from void* to function pointer.
9213 assert(lhptee->isFunctionType());
9214 return AssignConvertType::FunctionVoidPointer;
9215 }
9216
9217 if (!S.Diags.isIgnored(
9218 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9219 Loc) &&
9220 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9221 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9222 return AssignConvertType::IncompatibleFunctionPointerStrict;
9223
9224 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9225 // unqualified versions of compatible types, ...
9226 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9227 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9228 // Check if the pointee types are compatible ignoring the sign.
9229 // We explicitly check for char so that we catch "char" vs
9230 // "unsigned char" on systems where "char" is unsigned.
9231 if (lhptee->isCharType())
9232 ltrans = S.Context.UnsignedCharTy;
9233 else if (lhptee->hasSignedIntegerRepresentation())
9234 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9235
9236 if (rhptee->isCharType())
9237 rtrans = S.Context.UnsignedCharTy;
9238 else if (rhptee->hasSignedIntegerRepresentation())
9239 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9240
9241 if (ltrans == rtrans) {
9242 // Types are compatible ignoring the sign. Qualifier incompatibility
9243 // takes priority over sign incompatibility because the sign
9244 // warning can be disabled.
9245 if (!S.IsAssignConvertCompatible(ConvTy))
9246 return ConvTy;
9247
9248 return AssignConvertType::IncompatiblePointerSign;
9249 }
9250
9251 // If we are a multi-level pointer, it's possible that our issue is simply
9252 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9253 // the eventual target type is the same and the pointers have the same
9254 // level of indirection, this must be the issue.
9255 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9256 do {
9257 std::tie(args&: lhptee, args&: lhq) =
9258 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9259 std::tie(args&: rhptee, args&: rhq) =
9260 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9261
9262 // Inconsistent address spaces at this point is invalid, even if the
9263 // address spaces would be compatible.
9264 // FIXME: This doesn't catch address space mismatches for pointers of
9265 // different nesting levels, like:
9266 // __local int *** a;
9267 // int ** b = a;
9268 // It's not clear how to actually determine when such pointers are
9269 // invalidly incompatible.
9270 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9271 return AssignConvertType::
9272 IncompatibleNestedPointerAddressSpaceMismatch;
9273
9274 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9275
9276 if (lhptee == rhptee)
9277 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9278 }
9279
9280 // General pointer incompatibility takes priority over qualifiers.
9281 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9282 return AssignConvertType::IncompatibleFunctionPointer;
9283 return AssignConvertType::IncompatiblePointer;
9284 }
9285 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9286 // hasSameType, so we can skip further checks.
9287 const auto *LFT = ltrans->getAs<FunctionType>();
9288 const auto *RFT = rtrans->getAs<FunctionType>();
9289 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9290 // The invocation of IsFunctionConversion below will try to transform rtrans
9291 // to obtain an exact match for ltrans. This should not fail because of
9292 // mismatches in result type and parameter types, they were already checked
9293 // by typesAreCompatible above. So we will recreate rtrans (or where
9294 // appropriate ltrans) using the result type and parameter types from ltrans
9295 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9296 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9297 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9298 if (LFPT && RFPT) {
9299 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9300 Args: LFPT->getParamTypes(),
9301 EPI: RFPT->getExtProtoInfo());
9302 } else if (LFPT) {
9303 FunctionProtoType::ExtProtoInfo EPI;
9304 EPI.ExtInfo = RFT->getExtInfo();
9305 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9306 Args: LFPT->getParamTypes(), EPI);
9307 } else if (RFPT) {
9308 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9309 // all of its ExtProtoInfo. Transform ltrans instead.
9310 FunctionProtoType::ExtProtoInfo EPI;
9311 EPI.ExtInfo = LFT->getExtInfo();
9312 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9313 Args: RFPT->getParamTypes(), EPI);
9314 } else {
9315 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9316 Info: RFT->getExtInfo());
9317 }
9318 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9319 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9320 return AssignConvertType::IncompatibleFunctionPointer;
9321 }
9322 return ConvTy;
9323}
9324
9325/// checkBlockPointerTypesForAssignment - This routine determines whether two
9326/// block pointer types are compatible or whether a block and normal pointer
9327/// are compatible. It is more restrict than comparing two function pointer
9328// types.
9329static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9330 QualType LHSType,
9331 QualType RHSType) {
9332 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9333 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9334
9335 QualType lhptee, rhptee;
9336
9337 // get the "pointed to" type (ignoring qualifiers at the top level)
9338 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9339 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9340
9341 // In C++, the types have to match exactly.
9342 if (S.getLangOpts().CPlusPlus)
9343 return AssignConvertType::IncompatibleBlockPointer;
9344
9345 AssignConvertType ConvTy = AssignConvertType::Compatible;
9346
9347 // For blocks we enforce that qualifiers are identical.
9348 Qualifiers LQuals = lhptee.getLocalQualifiers();
9349 Qualifiers RQuals = rhptee.getLocalQualifiers();
9350 if (S.getLangOpts().OpenCL) {
9351 LQuals.removeAddressSpace();
9352 RQuals.removeAddressSpace();
9353 }
9354 if (LQuals != RQuals)
9355 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9356
9357 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9358 // assignment.
9359 // The current behavior is similar to C++ lambdas. A block might be
9360 // assigned to a variable iff its return type and parameters are compatible
9361 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9362 // an assignment. Presumably it should behave in way that a function pointer
9363 // assignment does in C, so for each parameter and return type:
9364 // * CVR and address space of LHS should be a superset of CVR and address
9365 // space of RHS.
9366 // * unqualified types should be compatible.
9367 if (S.getLangOpts().OpenCL) {
9368 if (!S.Context.typesAreBlockPointerCompatible(
9369 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9370 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9371 return AssignConvertType::IncompatibleBlockPointer;
9372 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9373 return AssignConvertType::IncompatibleBlockPointer;
9374
9375 return ConvTy;
9376}
9377
9378/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9379/// for assignment compatibility.
9380static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9381 QualType LHSType,
9382 QualType RHSType) {
9383 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9384 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9385
9386 if (LHSType->isObjCBuiltinType()) {
9387 // Class is not compatible with ObjC object pointers.
9388 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9389 !RHSType->isObjCQualifiedClassType())
9390 return AssignConvertType::IncompatiblePointer;
9391 return AssignConvertType::Compatible;
9392 }
9393 if (RHSType->isObjCBuiltinType()) {
9394 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9395 !LHSType->isObjCQualifiedClassType())
9396 return AssignConvertType::IncompatiblePointer;
9397 return AssignConvertType::Compatible;
9398 }
9399 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9400 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9401
9402 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9403 // make an exception for id<P>
9404 !LHSType->isObjCQualifiedIdType())
9405 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9406
9407 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9408 return AssignConvertType::Compatible;
9409 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9410 return AssignConvertType::IncompatibleObjCQualifiedId;
9411 return AssignConvertType::IncompatiblePointer;
9412}
9413
9414AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9415 QualType LHSType,
9416 QualType RHSType) {
9417 // Fake up an opaque expression. We don't actually care about what
9418 // cast operations are required, so if CheckAssignmentConstraints
9419 // adds casts to this they'll be wasted, but fortunately that doesn't
9420 // usually happen on valid code.
9421 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9422 ExprResult RHSPtr = &RHSExpr;
9423 CastKind K;
9424
9425 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9426}
9427
9428/// This helper function returns true if QT is a vector type that has element
9429/// type ElementType.
9430static bool isVector(QualType QT, QualType ElementType) {
9431 if (const VectorType *VT = QT->getAs<VectorType>())
9432 return VT->getElementType().getCanonicalType() == ElementType;
9433 return false;
9434}
9435
9436/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9437/// has code to accommodate several GCC extensions when type checking
9438/// pointers. Here are some objectionable examples that GCC considers warnings:
9439///
9440/// int a, *pint;
9441/// short *pshort;
9442/// struct foo *pfoo;
9443///
9444/// pint = pshort; // warning: assignment from incompatible pointer type
9445/// a = pint; // warning: assignment makes integer from pointer without a cast
9446/// pint = a; // warning: assignment makes pointer from integer without a cast
9447/// pint = pfoo; // warning: assignment from incompatible pointer type
9448///
9449/// As a result, the code for dealing with pointers is more complex than the
9450/// C99 spec dictates.
9451///
9452/// Sets 'Kind' for any result kind except Incompatible.
9453AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9454 ExprResult &RHS,
9455 CastKind &Kind,
9456 bool ConvertRHS) {
9457 QualType RHSType = RHS.get()->getType();
9458 QualType OrigLHSType = LHSType;
9459
9460 // Get canonical types. We're not formatting these types, just comparing
9461 // them.
9462 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9463 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9464
9465 // Common case: no conversion required.
9466 if (LHSType == RHSType) {
9467 Kind = CK_NoOp;
9468 return AssignConvertType::Compatible;
9469 }
9470
9471 // If the LHS has an __auto_type, there are no additional type constraints
9472 // to be worried about.
9473 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9474 if (AT->isGNUAutoType()) {
9475 Kind = CK_NoOp;
9476 return AssignConvertType::Compatible;
9477 }
9478 }
9479
9480 // If we have an atomic type, try a non-atomic assignment, then just add an
9481 // atomic qualification step.
9482 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9483 AssignConvertType Result =
9484 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9485 if (!IsAssignConvertCompatible(ConvTy: Result))
9486 return Result;
9487 if (Kind != CK_NoOp && ConvertRHS)
9488 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9489 Kind = CK_NonAtomicToAtomic;
9490 return Result;
9491 }
9492
9493 // If the left-hand side is a reference type, then we are in a
9494 // (rare!) case where we've allowed the use of references in C,
9495 // e.g., as a parameter type in a built-in function. In this case,
9496 // just make sure that the type referenced is compatible with the
9497 // right-hand side type. The caller is responsible for adjusting
9498 // LHSType so that the resulting expression does not have reference
9499 // type.
9500 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9501 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9502 Kind = CK_LValueBitCast;
9503 return AssignConvertType::Compatible;
9504 }
9505 return AssignConvertType::Incompatible;
9506 }
9507
9508 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9509 // of an ExtVector type to the same ExtVector type.
9510 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9511 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9512 // Implicit conversions require the same number of elements.
9513 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9514 return AssignConvertType::Incompatible;
9515
9516 if (LHSType->isExtVectorBoolType() &&
9517 RHSExtType->getElementType()->isIntegerType()) {
9518 Kind = CK_IntegralToBoolean;
9519 return AssignConvertType::Compatible;
9520 }
9521 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9522 if (Context.getLangOpts().OpenCL &&
9523 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9524 Kind = CK_BitCast;
9525 return AssignConvertType::Compatible;
9526 }
9527 return AssignConvertType::Incompatible;
9528 }
9529 if (RHSType->isArithmeticType()) {
9530 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9531 if (ConvertRHS)
9532 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9533 Kind = CK_VectorSplat;
9534 return AssignConvertType::Compatible;
9535 }
9536 }
9537
9538 // Conversions to or from vector type.
9539 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9540 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9541 // Allow assignments of an AltiVec vector type to an equivalent GCC
9542 // vector type and vice versa
9543 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9544 Kind = CK_BitCast;
9545 return AssignConvertType::Compatible;
9546 }
9547
9548 // If we are allowing lax vector conversions, and LHS and RHS are both
9549 // vectors, the total size only needs to be the same. This is a bitcast;
9550 // no bits are changed but the result type is different.
9551 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9552 // The default for lax vector conversions with Altivec vectors will
9553 // change, so if we are converting between vector types where
9554 // at least one is an Altivec vector, emit a warning.
9555 if (Context.getTargetInfo().getTriple().isPPC() &&
9556 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9557 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9558 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9559 << RHSType << LHSType;
9560 Kind = CK_BitCast;
9561 return AssignConvertType::IncompatibleVectors;
9562 }
9563 }
9564
9565 // When the RHS comes from another lax conversion (e.g. binops between
9566 // scalars and vectors) the result is canonicalized as a vector. When the
9567 // LHS is also a vector, the lax is allowed by the condition above. Handle
9568 // the case where LHS is a scalar.
9569 if (LHSType->isScalarType()) {
9570 const VectorType *VecType = RHSType->getAs<VectorType>();
9571 if (VecType && VecType->getNumElements() == 1 &&
9572 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9573 if (Context.getTargetInfo().getTriple().isPPC() &&
9574 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9575 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9576 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9577 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9578 << RHSType << LHSType;
9579 ExprResult *VecExpr = &RHS;
9580 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9581 Kind = CK_BitCast;
9582 return AssignConvertType::Compatible;
9583 }
9584 }
9585
9586 // Allow assignments between fixed-length and sizeless SVE vectors.
9587 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9588 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9589 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9590 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9591 Kind = CK_BitCast;
9592 return AssignConvertType::Compatible;
9593 }
9594
9595 // Allow assignments between fixed-length and sizeless RVV vectors.
9596 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9597 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9598 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9599 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9600 Kind = CK_BitCast;
9601 return AssignConvertType::Compatible;
9602 }
9603 }
9604
9605 return AssignConvertType::Incompatible;
9606 }
9607
9608 // Diagnose attempts to convert between __ibm128, __float128 and long double
9609 // where such conversions currently can't be handled.
9610 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9611 return AssignConvertType::Incompatible;
9612
9613 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9614 // discards the imaginary part.
9615 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9616 !LHSType->getAs<ComplexType>())
9617 return AssignConvertType::Incompatible;
9618
9619 // Arithmetic conversions.
9620 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9621 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9622 if (ConvertRHS)
9623 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9624 return AssignConvertType::Compatible;
9625 }
9626
9627 // Conversions to normal pointers.
9628 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9629 // U* -> T*
9630 if (isa<PointerType>(Val: RHSType)) {
9631 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9632 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9633 if (AddrSpaceL != AddrSpaceR)
9634 Kind = CK_AddressSpaceConversion;
9635 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9636 Kind = CK_NoOp;
9637 else
9638 Kind = CK_BitCast;
9639 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9640 Loc: RHS.get()->getBeginLoc());
9641 }
9642
9643 // int -> T*
9644 if (RHSType->isIntegerType()) {
9645 Kind = CK_IntegralToPointer; // FIXME: null?
9646 return AssignConvertType::IntToPointer;
9647 }
9648
9649 // C pointers are not compatible with ObjC object pointers,
9650 // with two exceptions:
9651 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9652 // - conversions to void*
9653 if (LHSPointer->getPointeeType()->isVoidType()) {
9654 Kind = CK_BitCast;
9655 return AssignConvertType::Compatible;
9656 }
9657
9658 // - conversions from 'Class' to the redefinition type
9659 if (RHSType->isObjCClassType() &&
9660 Context.hasSameType(T1: LHSType,
9661 T2: Context.getObjCClassRedefinitionType())) {
9662 Kind = CK_BitCast;
9663 return AssignConvertType::Compatible;
9664 }
9665
9666 Kind = CK_BitCast;
9667 return AssignConvertType::IncompatiblePointer;
9668 }
9669
9670 // U^ -> void*
9671 if (RHSType->getAs<BlockPointerType>()) {
9672 if (LHSPointer->getPointeeType()->isVoidType()) {
9673 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9674 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9675 ->getPointeeType()
9676 .getAddressSpace();
9677 Kind =
9678 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9679 return AssignConvertType::Compatible;
9680 }
9681 }
9682
9683 return AssignConvertType::Incompatible;
9684 }
9685
9686 // Conversions to block pointers.
9687 if (isa<BlockPointerType>(Val: LHSType)) {
9688 // U^ -> T^
9689 if (RHSType->isBlockPointerType()) {
9690 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9691 ->getPointeeType()
9692 .getAddressSpace();
9693 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9694 ->getPointeeType()
9695 .getAddressSpace();
9696 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9697 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9698 }
9699
9700 // int or null -> T^
9701 if (RHSType->isIntegerType()) {
9702 Kind = CK_IntegralToPointer; // FIXME: null
9703 return AssignConvertType::IntToBlockPointer;
9704 }
9705
9706 // id -> T^
9707 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9708 Kind = CK_AnyPointerToBlockPointerCast;
9709 return AssignConvertType::Compatible;
9710 }
9711
9712 // void* -> T^
9713 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9714 if (RHSPT->getPointeeType()->isVoidType()) {
9715 Kind = CK_AnyPointerToBlockPointerCast;
9716 return AssignConvertType::Compatible;
9717 }
9718
9719 return AssignConvertType::Incompatible;
9720 }
9721
9722 // Conversions to Objective-C pointers.
9723 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
9724 // A* -> B*
9725 if (RHSType->isObjCObjectPointerType()) {
9726 Kind = CK_BitCast;
9727 AssignConvertType result =
9728 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9729 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9730 result == AssignConvertType::Compatible &&
9731 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
9732 result = AssignConvertType::IncompatibleObjCWeakRef;
9733 return result;
9734 }
9735
9736 // int or null -> A*
9737 if (RHSType->isIntegerType()) {
9738 Kind = CK_IntegralToPointer; // FIXME: null
9739 return AssignConvertType::IntToPointer;
9740 }
9741
9742 // In general, C pointers are not compatible with ObjC object pointers,
9743 // with two exceptions:
9744 if (isa<PointerType>(Val: RHSType)) {
9745 Kind = CK_CPointerToObjCPointerCast;
9746
9747 // - conversions from 'void*'
9748 if (RHSType->isVoidPointerType()) {
9749 return AssignConvertType::Compatible;
9750 }
9751
9752 // - conversions to 'Class' from its redefinition type
9753 if (LHSType->isObjCClassType() &&
9754 Context.hasSameType(T1: RHSType,
9755 T2: Context.getObjCClassRedefinitionType())) {
9756 return AssignConvertType::Compatible;
9757 }
9758
9759 return AssignConvertType::IncompatiblePointer;
9760 }
9761
9762 // Only under strict condition T^ is compatible with an Objective-C pointer.
9763 if (RHSType->isBlockPointerType() &&
9764 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
9765 if (ConvertRHS)
9766 maybeExtendBlockObject(E&: RHS);
9767 Kind = CK_BlockPointerToObjCPointerCast;
9768 return AssignConvertType::Compatible;
9769 }
9770
9771 return AssignConvertType::Incompatible;
9772 }
9773
9774 // Conversion to nullptr_t (C23 only)
9775 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9776 RHS.get()->isNullPointerConstant(Ctx&: Context,
9777 NPC: Expr::NPC_ValueDependentIsNull)) {
9778 // null -> nullptr_t
9779 Kind = CK_NullToPointer;
9780 return AssignConvertType::Compatible;
9781 }
9782
9783 // Conversions from pointers that are not covered by the above.
9784 if (isa<PointerType>(Val: RHSType)) {
9785 // T* -> _Bool
9786 if (LHSType == Context.BoolTy) {
9787 Kind = CK_PointerToBoolean;
9788 return AssignConvertType::Compatible;
9789 }
9790
9791 // T* -> int
9792 if (LHSType->isIntegerType()) {
9793 Kind = CK_PointerToIntegral;
9794 return AssignConvertType::PointerToInt;
9795 }
9796
9797 return AssignConvertType::Incompatible;
9798 }
9799
9800 // Conversions from Objective-C pointers that are not covered by the above.
9801 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9802 // T* -> _Bool
9803 if (LHSType == Context.BoolTy) {
9804 Kind = CK_PointerToBoolean;
9805 return AssignConvertType::Compatible;
9806 }
9807
9808 // T* -> int
9809 if (LHSType->isIntegerType()) {
9810 Kind = CK_PointerToIntegral;
9811 return AssignConvertType::PointerToInt;
9812 }
9813
9814 return AssignConvertType::Incompatible;
9815 }
9816
9817 // struct A -> struct B
9818 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
9819 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
9820 Kind = CK_NoOp;
9821 return AssignConvertType::Compatible;
9822 }
9823 }
9824
9825 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9826 Kind = CK_IntToOCLSampler;
9827 return AssignConvertType::Compatible;
9828 }
9829
9830 return AssignConvertType::Incompatible;
9831}
9832
9833/// Constructs a transparent union from an expression that is
9834/// used to initialize the transparent union.
9835static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9836 ExprResult &EResult, QualType UnionType,
9837 FieldDecl *Field) {
9838 // Build an initializer list that designates the appropriate member
9839 // of the transparent union.
9840 Expr *E = EResult.get();
9841 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9842 E, SourceLocation());
9843 Initializer->setType(UnionType);
9844 Initializer->setInitializedFieldInUnion(Field);
9845
9846 // Build a compound literal constructing a value of the transparent
9847 // union type from this initializer list.
9848 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
9849 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9850 VK_PRValue, Initializer, false);
9851}
9852
9853AssignConvertType
9854Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9855 ExprResult &RHS) {
9856 QualType RHSType = RHS.get()->getType();
9857
9858 // If the ArgType is a Union type, we want to handle a potential
9859 // transparent_union GCC extension.
9860 const RecordType *UT = ArgType->getAsUnionType();
9861 if (!UT)
9862 return AssignConvertType::Incompatible;
9863
9864 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
9865 if (!UD->hasAttr<TransparentUnionAttr>())
9866 return AssignConvertType::Incompatible;
9867
9868 // The field to initialize within the transparent union.
9869 FieldDecl *InitField = nullptr;
9870 // It's compatible if the expression matches any of the fields.
9871 for (auto *it : UD->fields()) {
9872 if (it->getType()->isPointerType()) {
9873 // If the transparent union contains a pointer type, we allow:
9874 // 1) void pointer
9875 // 2) null pointer constant
9876 if (RHSType->isPointerType())
9877 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9878 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
9879 InitField = it;
9880 break;
9881 }
9882
9883 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
9884 NPC: Expr::NPC_ValueDependentIsNull)) {
9885 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
9886 CK: CK_NullToPointer);
9887 InitField = it;
9888 break;
9889 }
9890 }
9891
9892 CastKind Kind;
9893 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
9894 AssignConvertType::Compatible) {
9895 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
9896 InitField = it;
9897 break;
9898 }
9899 }
9900
9901 if (!InitField)
9902 return AssignConvertType::Incompatible;
9903
9904 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
9905 return AssignConvertType::Compatible;
9906}
9907
9908AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
9909 ExprResult &CallerRHS,
9910 bool Diagnose,
9911 bool DiagnoseCFAudited,
9912 bool ConvertRHS) {
9913 // We need to be able to tell the caller whether we diagnosed a problem, if
9914 // they ask us to issue diagnostics.
9915 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9916
9917 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9918 // we can't avoid *all* modifications at the moment, so we need some somewhere
9919 // to put the updated value.
9920 ExprResult LocalRHS = CallerRHS;
9921 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9922
9923 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9924 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9925 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
9926 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
9927 Diag(Loc: RHS.get()->getExprLoc(),
9928 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
9929 << RHS.get()->getSourceRange();
9930 }
9931 }
9932 }
9933
9934 if (getLangOpts().CPlusPlus) {
9935 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9936 // C++ 5.17p3: If the left operand is not of class type, the
9937 // expression is implicitly converted (C++ 4) to the
9938 // cv-unqualified type of the left operand.
9939 QualType RHSType = RHS.get()->getType();
9940 if (Diagnose) {
9941 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
9942 Action: AssignmentAction::Assigning);
9943 } else {
9944 ImplicitConversionSequence ICS =
9945 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
9946 /*SuppressUserConversions=*/false,
9947 AllowExplicit: AllowedExplicit::None,
9948 /*InOverloadResolution=*/false,
9949 /*CStyle=*/false,
9950 /*AllowObjCWritebackConversion=*/false);
9951 if (ICS.isFailure())
9952 return AssignConvertType::Incompatible;
9953 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
9954 ICS, Action: AssignmentAction::Assigning);
9955 }
9956 if (RHS.isInvalid())
9957 return AssignConvertType::Incompatible;
9958 AssignConvertType result = AssignConvertType::Compatible;
9959 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9960 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
9961 result = AssignConvertType::IncompatibleObjCWeakRef;
9962 return result;
9963 }
9964
9965 // FIXME: Currently, we fall through and treat C++ classes like C
9966 // structures.
9967 // FIXME: We also fall through for atomics; not sure what should
9968 // happen there, though.
9969 } else if (RHS.get()->getType() == Context.OverloadTy) {
9970 // As a set of extensions to C, we support overloading on functions. These
9971 // functions need to be resolved here.
9972 DeclAccessPair DAP;
9973 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9974 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
9975 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
9976 else
9977 return AssignConvertType::Incompatible;
9978 }
9979
9980 // This check seems unnatural, however it is necessary to ensure the proper
9981 // conversion of functions/arrays. If the conversion were done for all
9982 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9983 // expressions that suppress this implicit conversion (&, sizeof). This needs
9984 // to happen before we check for null pointer conversions because C does not
9985 // undergo the same implicit conversions as C++ does above (by the calls to
9986 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9987 // lvalue to rvalue cast before checking for null pointer constraints. This
9988 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9989 //
9990 // Suppress this for references: C++ 8.5.3p5.
9991 if (!LHSType->isReferenceType()) {
9992 // FIXME: We potentially allocate here even if ConvertRHS is false.
9993 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
9994 if (RHS.isInvalid())
9995 return AssignConvertType::Incompatible;
9996 }
9997
9998 // The constraints are expressed in terms of the atomic, qualified, or
9999 // unqualified type of the LHS.
10000 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10001
10002 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10003 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10004 if ((LHSTypeAfterConversion->isPointerType() ||
10005 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10006 LHSTypeAfterConversion->isBlockPointerType()) &&
10007 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10008 RHS.get()->isNullPointerConstant(Ctx&: Context,
10009 NPC: Expr::NPC_ValueDependentIsNull))) {
10010 AssignConvertType Ret = AssignConvertType::Compatible;
10011 if (Diagnose || ConvertRHS) {
10012 CastKind Kind;
10013 CXXCastPath Path;
10014 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10015 /*IgnoreBaseAccess=*/false, Diagnose);
10016
10017 // If there is a conversion of some kind, check to see what kind of
10018 // pointer conversion happened so we can diagnose a C++ compatibility
10019 // diagnostic if the conversion is invalid. This only matters if the RHS
10020 // is some kind of void pointer. We have a carve-out when the RHS is from
10021 // a macro expansion because the use of a macro may indicate different
10022 // code between C and C++. Consider: char *s = NULL; where NULL is
10023 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10024 // C++, which is valid in C++.
10025 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10026 !RHS.get()->getBeginLoc().isMacroID()) {
10027 QualType CanRHS =
10028 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10029 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10030 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10031 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10032 Loc: RHS.get()->getExprLoc());
10033 // Anything that's not considered perfectly compatible would be
10034 // incompatible in C++.
10035 if (Ret != AssignConvertType::Compatible)
10036 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10037 }
10038 }
10039
10040 if (ConvertRHS)
10041 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10042 }
10043 return Ret;
10044 }
10045 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10046 // unqualified bool, and the right operand is a pointer or its type is
10047 // nullptr_t.
10048 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10049 RHS.get()->getType()->isNullPtrType()) {
10050 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10051 // only handles nullptr -> _Bool due to needing an extra conversion
10052 // step.
10053 // We model this by converting from nullptr -> void * and then let the
10054 // conversion from void * -> _Bool happen naturally.
10055 if (Diagnose || ConvertRHS) {
10056 CastKind Kind;
10057 CXXCastPath Path;
10058 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10059 /*IgnoreBaseAccess=*/false, Diagnose);
10060 if (ConvertRHS)
10061 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10062 BasePath: &Path);
10063 }
10064 }
10065
10066 // OpenCL queue_t type assignment.
10067 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10068 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10069 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10070 return AssignConvertType::Compatible;
10071 }
10072
10073 CastKind Kind;
10074 AssignConvertType result =
10075 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10076
10077 // If assigning a void * created by an allocation function call to some other
10078 // type, check that the allocated size is sufficient for that type.
10079 if (result != AssignConvertType::Incompatible &&
10080 RHS.get()->getType()->isVoidPointerType())
10081 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10082
10083 // C99 6.5.16.1p2: The value of the right operand is converted to the
10084 // type of the assignment expression.
10085 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10086 // so that we can use references in built-in functions even in C.
10087 // The getNonReferenceType() call makes sure that the resulting expression
10088 // does not have reference type.
10089 if (result != AssignConvertType::Incompatible &&
10090 RHS.get()->getType() != LHSType) {
10091 QualType Ty = LHSType.getNonLValueExprType(Context);
10092 Expr *E = RHS.get();
10093
10094 // Check for various Objective-C errors. If we are not reporting
10095 // diagnostics and just checking for errors, e.g., during overload
10096 // resolution, return Incompatible to indicate the failure.
10097 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10098 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10099 CCK: CheckedConversionKind::Implicit, Diagnose,
10100 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10101 if (!Diagnose)
10102 return AssignConvertType::Incompatible;
10103 }
10104 if (getLangOpts().ObjC &&
10105 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10106 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10107 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10108 if (!Diagnose)
10109 return AssignConvertType::Incompatible;
10110 // Replace the expression with a corrected version and continue so we
10111 // can find further errors.
10112 RHS = E;
10113 return AssignConvertType::Compatible;
10114 }
10115
10116 if (ConvertRHS)
10117 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10118 }
10119
10120 return result;
10121}
10122
10123namespace {
10124/// The original operand to an operator, prior to the application of the usual
10125/// arithmetic conversions and converting the arguments of a builtin operator
10126/// candidate.
10127struct OriginalOperand {
10128 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10129 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10130 Op = MTE->getSubExpr();
10131 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10132 Op = BTE->getSubExpr();
10133 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10134 Orig = ICE->getSubExprAsWritten();
10135 Conversion = ICE->getConversionFunction();
10136 }
10137 }
10138
10139 QualType getType() const { return Orig->getType(); }
10140
10141 Expr *Orig;
10142 NamedDecl *Conversion;
10143};
10144}
10145
10146QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10147 ExprResult &RHS) {
10148 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10149
10150 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10151 << OrigLHS.getType() << OrigRHS.getType()
10152 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10153
10154 // If a user-defined conversion was applied to either of the operands prior
10155 // to applying the built-in operator rules, tell the user about it.
10156 if (OrigLHS.Conversion) {
10157 Diag(Loc: OrigLHS.Conversion->getLocation(),
10158 DiagID: diag::note_typecheck_invalid_operands_converted)
10159 << 0 << LHS.get()->getType();
10160 }
10161 if (OrigRHS.Conversion) {
10162 Diag(Loc: OrigRHS.Conversion->getLocation(),
10163 DiagID: diag::note_typecheck_invalid_operands_converted)
10164 << 1 << RHS.get()->getType();
10165 }
10166
10167 return QualType();
10168}
10169
10170QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10171 ExprResult &RHS) {
10172 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10173 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10174
10175 bool LHSNatVec = LHSType->isVectorType();
10176 bool RHSNatVec = RHSType->isVectorType();
10177
10178 if (!(LHSNatVec && RHSNatVec)) {
10179 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10180 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10181 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10182 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10183 << Vector->getSourceRange();
10184 return QualType();
10185 }
10186
10187 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10188 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10189 << RHS.get()->getSourceRange();
10190
10191 return QualType();
10192}
10193
10194/// Try to convert a value of non-vector type to a vector type by converting
10195/// the type to the element type of the vector and then performing a splat.
10196/// If the language is OpenCL, we only use conversions that promote scalar
10197/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10198/// for float->int.
10199///
10200/// OpenCL V2.0 6.2.6.p2:
10201/// An error shall occur if any scalar operand type has greater rank
10202/// than the type of the vector element.
10203///
10204/// \param scalar - if non-null, actually perform the conversions
10205/// \return true if the operation fails (but without diagnosing the failure)
10206static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10207 QualType scalarTy,
10208 QualType vectorEltTy,
10209 QualType vectorTy,
10210 unsigned &DiagID) {
10211 // The conversion to apply to the scalar before splatting it,
10212 // if necessary.
10213 CastKind scalarCast = CK_NoOp;
10214
10215 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10216 scalarCast = CK_IntegralToBoolean;
10217 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10218 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10219 (scalarTy->isIntegerType() &&
10220 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10221 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10222 return true;
10223 }
10224 if (!scalarTy->isIntegralType(Ctx: S.Context))
10225 return true;
10226 scalarCast = CK_IntegralCast;
10227 } else if (vectorEltTy->isRealFloatingType()) {
10228 if (scalarTy->isRealFloatingType()) {
10229 if (S.getLangOpts().OpenCL &&
10230 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10231 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10232 return true;
10233 }
10234 scalarCast = CK_FloatingCast;
10235 }
10236 else if (scalarTy->isIntegralType(Ctx: S.Context))
10237 scalarCast = CK_IntegralToFloating;
10238 else
10239 return true;
10240 } else {
10241 return true;
10242 }
10243
10244 // Adjust scalar if desired.
10245 if (scalar) {
10246 if (scalarCast != CK_NoOp)
10247 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10248 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10249 }
10250 return false;
10251}
10252
10253/// Convert vector E to a vector with the same number of elements but different
10254/// element type.
10255static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10256 const auto *VecTy = E->getType()->getAs<VectorType>();
10257 assert(VecTy && "Expression E must be a vector");
10258 QualType NewVecTy =
10259 VecTy->isExtVectorType()
10260 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10261 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10262 VecKind: VecTy->getVectorKind());
10263
10264 // Look through the implicit cast. Return the subexpression if its type is
10265 // NewVecTy.
10266 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10267 if (ICE->getSubExpr()->getType() == NewVecTy)
10268 return ICE->getSubExpr();
10269
10270 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10271 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10272}
10273
10274/// Test if a (constant) integer Int can be casted to another integer type
10275/// IntTy without losing precision.
10276static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10277 QualType OtherIntTy) {
10278 Expr *E = Int->get();
10279 if (E->containsErrors() || E->isInstantiationDependent())
10280 return false;
10281
10282 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10283
10284 // Reject cases where the value of the Int is unknown as that would
10285 // possibly cause truncation, but accept cases where the scalar can be
10286 // demoted without loss of precision.
10287 Expr::EvalResult EVResult;
10288 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10289 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10290 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10291 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10292
10293 if (CstInt) {
10294 // If the scalar is constant and is of a higher order and has more active
10295 // bits that the vector element type, reject it.
10296 llvm::APSInt Result = EVResult.Val.getInt();
10297 unsigned NumBits = IntSigned
10298 ? (Result.isNegative() ? Result.getSignificantBits()
10299 : Result.getActiveBits())
10300 : Result.getActiveBits();
10301 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10302 return true;
10303
10304 // If the signedness of the scalar type and the vector element type
10305 // differs and the number of bits is greater than that of the vector
10306 // element reject it.
10307 return (IntSigned != OtherIntSigned &&
10308 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10309 }
10310
10311 // Reject cases where the value of the scalar is not constant and it's
10312 // order is greater than that of the vector element type.
10313 return (Order < 0);
10314}
10315
10316/// Test if a (constant) integer Int can be casted to floating point type
10317/// FloatTy without losing precision.
10318static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10319 QualType FloatTy) {
10320 if (Int->get()->containsErrors())
10321 return false;
10322
10323 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10324
10325 // Determine if the integer constant can be expressed as a floating point
10326 // number of the appropriate type.
10327 Expr::EvalResult EVResult;
10328 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10329
10330 uint64_t Bits = 0;
10331 if (CstInt) {
10332 // Reject constants that would be truncated if they were converted to
10333 // the floating point type. Test by simple to/from conversion.
10334 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10335 // could be avoided if there was a convertFromAPInt method
10336 // which could signal back if implicit truncation occurred.
10337 llvm::APSInt Result = EVResult.Val.getInt();
10338 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10339 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10340 RM: llvm::APFloat::rmTowardZero);
10341 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10342 !IntTy->hasSignedIntegerRepresentation());
10343 bool Ignored = false;
10344 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10345 IsExact: &Ignored);
10346 if (Result != ConvertBack)
10347 return true;
10348 } else {
10349 // Reject types that cannot be fully encoded into the mantissa of
10350 // the float.
10351 Bits = S.Context.getTypeSize(T: IntTy);
10352 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10353 S.Context.getFloatTypeSemantics(T: FloatTy));
10354 if (Bits > FloatPrec)
10355 return true;
10356 }
10357
10358 return false;
10359}
10360
10361/// Attempt to convert and splat Scalar into a vector whose types matches
10362/// Vector following GCC conversion rules. The rule is that implicit
10363/// conversion can occur when Scalar can be casted to match Vector's element
10364/// type without causing truncation of Scalar.
10365static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10366 ExprResult *Vector) {
10367 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10368 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10369 QualType VectorEltTy;
10370
10371 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10372 assert(!isa<ExtVectorType>(VT) &&
10373 "ExtVectorTypes should not be handled here!");
10374 VectorEltTy = VT->getElementType();
10375 } else if (VectorTy->isSveVLSBuiltinType()) {
10376 VectorEltTy =
10377 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10378 } else {
10379 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10380 }
10381
10382 // Reject cases where the vector element type or the scalar element type are
10383 // not integral or floating point types.
10384 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10385 return true;
10386
10387 // The conversion to apply to the scalar before splatting it,
10388 // if necessary.
10389 CastKind ScalarCast = CK_NoOp;
10390
10391 // Accept cases where the vector elements are integers and the scalar is
10392 // an integer.
10393 // FIXME: Notionally if the scalar was a floating point value with a precise
10394 // integral representation, we could cast it to an appropriate integer
10395 // type and then perform the rest of the checks here. GCC will perform
10396 // this conversion in some cases as determined by the input language.
10397 // We should accept it on a language independent basis.
10398 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10399 ScalarTy->isIntegralType(Ctx: S.Context) &&
10400 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10401
10402 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10403 return true;
10404
10405 ScalarCast = CK_IntegralCast;
10406 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10407 ScalarTy->isRealFloatingType()) {
10408 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10409 ScalarCast = CK_FloatingToIntegral;
10410 else
10411 return true;
10412 } else if (VectorEltTy->isRealFloatingType()) {
10413 if (ScalarTy->isRealFloatingType()) {
10414
10415 // Reject cases where the scalar type is not a constant and has a higher
10416 // Order than the vector element type.
10417 llvm::APFloat Result(0.0);
10418
10419 // Determine whether this is a constant scalar. In the event that the
10420 // value is dependent (and thus cannot be evaluated by the constant
10421 // evaluator), skip the evaluation. This will then diagnose once the
10422 // expression is instantiated.
10423 bool CstScalar = Scalar->get()->isValueDependent() ||
10424 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10425 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10426 if (!CstScalar && Order < 0)
10427 return true;
10428
10429 // If the scalar cannot be safely casted to the vector element type,
10430 // reject it.
10431 if (CstScalar) {
10432 bool Truncated = false;
10433 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10434 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10435 if (Truncated)
10436 return true;
10437 }
10438
10439 ScalarCast = CK_FloatingCast;
10440 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10441 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10442 return true;
10443
10444 ScalarCast = CK_IntegralToFloating;
10445 } else
10446 return true;
10447 } else if (ScalarTy->isEnumeralType())
10448 return true;
10449
10450 // Adjust scalar if desired.
10451 if (ScalarCast != CK_NoOp)
10452 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10453 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10454 return false;
10455}
10456
10457QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10458 SourceLocation Loc, bool IsCompAssign,
10459 bool AllowBothBool,
10460 bool AllowBoolConversions,
10461 bool AllowBoolOperation,
10462 bool ReportInvalid) {
10463 if (!IsCompAssign) {
10464 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10465 if (LHS.isInvalid())
10466 return QualType();
10467 }
10468 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10469 if (RHS.isInvalid())
10470 return QualType();
10471
10472 // For conversion purposes, we ignore any qualifiers.
10473 // For example, "const float" and "float" are equivalent.
10474 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10475 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10476
10477 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10478 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10479 assert(LHSVecType || RHSVecType);
10480
10481 if (getLangOpts().HLSL)
10482 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10483 IsCompAssign);
10484
10485 // Any operation with MFloat8 type is only possible with C intrinsics
10486 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10487 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10488 return InvalidOperands(Loc, LHS, RHS);
10489
10490 // AltiVec-style "vector bool op vector bool" combinations are allowed
10491 // for some operators but not others.
10492 if (!AllowBothBool && LHSVecType &&
10493 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10494 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10495 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10496
10497 // This operation may not be performed on boolean vectors.
10498 if (!AllowBoolOperation &&
10499 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10500 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10501
10502 // If the vector types are identical, return.
10503 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10504 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10505
10506 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10507 if (LHSVecType && RHSVecType &&
10508 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10509 if (isa<ExtVectorType>(Val: LHSVecType)) {
10510 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10511 return LHSType;
10512 }
10513
10514 if (!IsCompAssign)
10515 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10516 return RHSType;
10517 }
10518
10519 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10520 // can be mixed, with the result being the non-bool type. The non-bool
10521 // operand must have integer element type.
10522 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10523 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10524 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10525 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10526 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10527 LHSVecType->getElementType()->isIntegerType() &&
10528 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10529 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10530 return LHSType;
10531 }
10532 if (!IsCompAssign &&
10533 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10534 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10535 RHSVecType->getElementType()->isIntegerType()) {
10536 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10537 return RHSType;
10538 }
10539 }
10540
10541 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10542 // invalid since the ambiguity can affect the ABI.
10543 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10544 unsigned &SVEorRVV) {
10545 const VectorType *VecType = SecondType->getAs<VectorType>();
10546 SVEorRVV = 0;
10547 if (FirstType->isSizelessBuiltinType() && VecType) {
10548 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10549 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10550 return true;
10551 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10552 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10553 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10554 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10555 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10556 SVEorRVV = 1;
10557 return true;
10558 }
10559 }
10560
10561 return false;
10562 };
10563
10564 unsigned SVEorRVV;
10565 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10566 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10567 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10568 << SVEorRVV << LHSType << RHSType;
10569 return QualType();
10570 }
10571
10572 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10573 // invalid since the ambiguity can affect the ABI.
10574 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10575 unsigned &SVEorRVV) {
10576 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10577 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10578
10579 SVEorRVV = 0;
10580 if (FirstVecType && SecondVecType) {
10581 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10582 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10583 SecondVecType->getVectorKind() ==
10584 VectorKind::SveFixedLengthPredicate)
10585 return true;
10586 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10587 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10588 SecondVecType->getVectorKind() ==
10589 VectorKind::RVVFixedLengthMask_1 ||
10590 SecondVecType->getVectorKind() ==
10591 VectorKind::RVVFixedLengthMask_2 ||
10592 SecondVecType->getVectorKind() ==
10593 VectorKind::RVVFixedLengthMask_4) {
10594 SVEorRVV = 1;
10595 return true;
10596 }
10597 }
10598 return false;
10599 }
10600
10601 if (SecondVecType &&
10602 SecondVecType->getVectorKind() == VectorKind::Generic) {
10603 if (FirstType->isSVESizelessBuiltinType())
10604 return true;
10605 if (FirstType->isRVVSizelessBuiltinType()) {
10606 SVEorRVV = 1;
10607 return true;
10608 }
10609 }
10610
10611 return false;
10612 };
10613
10614 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10615 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10616 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10617 << SVEorRVV << LHSType << RHSType;
10618 return QualType();
10619 }
10620
10621 // If there's a vector type and a scalar, try to convert the scalar to
10622 // the vector element type and splat.
10623 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10624 if (!RHSVecType) {
10625 if (isa<ExtVectorType>(Val: LHSVecType)) {
10626 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10627 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10628 DiagID))
10629 return LHSType;
10630 } else {
10631 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10632 return LHSType;
10633 }
10634 }
10635 if (!LHSVecType) {
10636 if (isa<ExtVectorType>(Val: RHSVecType)) {
10637 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10638 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10639 vectorTy: RHSType, DiagID))
10640 return RHSType;
10641 } else {
10642 if (LHS.get()->isLValue() ||
10643 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10644 return RHSType;
10645 }
10646 }
10647
10648 // FIXME: The code below also handles conversion between vectors and
10649 // non-scalars, we should break this down into fine grained specific checks
10650 // and emit proper diagnostics.
10651 QualType VecType = LHSVecType ? LHSType : RHSType;
10652 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10653 QualType OtherType = LHSVecType ? RHSType : LHSType;
10654 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10655 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10656 if (Context.getTargetInfo().getTriple().isPPC() &&
10657 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10658 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10659 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10660 // If we're allowing lax vector conversions, only the total (data) size
10661 // needs to be the same. For non compound assignment, if one of the types is
10662 // scalar, the result is always the vector type.
10663 if (!IsCompAssign) {
10664 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10665 return VecType;
10666 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10667 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10668 // type. Note that this is already done by non-compound assignments in
10669 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10670 // <1 x T> -> T. The result is also a vector type.
10671 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10672 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10673 ExprResult *RHSExpr = &RHS;
10674 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10675 return VecType;
10676 }
10677 }
10678
10679 // Okay, the expression is invalid.
10680
10681 // If there's a non-vector, non-real operand, diagnose that.
10682 if ((!RHSVecType && !RHSType->isRealType()) ||
10683 (!LHSVecType && !LHSType->isRealType())) {
10684 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10685 << LHSType << RHSType
10686 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10687 return QualType();
10688 }
10689
10690 // OpenCL V1.1 6.2.6.p1:
10691 // If the operands are of more than one vector type, then an error shall
10692 // occur. Implicit conversions between vector types are not permitted, per
10693 // section 6.2.1.
10694 if (getLangOpts().OpenCL &&
10695 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
10696 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
10697 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
10698 << RHSType;
10699 return QualType();
10700 }
10701
10702
10703 // If there is a vector type that is not a ExtVector and a scalar, we reach
10704 // this point if scalar could not be converted to the vector's element type
10705 // without truncation.
10706 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
10707 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
10708 QualType Scalar = LHSVecType ? RHSType : LHSType;
10709 QualType Vector = LHSVecType ? LHSType : RHSType;
10710 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10711 Diag(Loc,
10712 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10713 << ScalarOrVector << Scalar << Vector;
10714
10715 return QualType();
10716 }
10717
10718 // Otherwise, use the generic diagnostic.
10719 Diag(Loc, DiagID)
10720 << LHSType << RHSType
10721 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10722 return QualType();
10723}
10724
10725QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10726 SourceLocation Loc,
10727 bool IsCompAssign,
10728 ArithConvKind OperationKind) {
10729 if (!IsCompAssign) {
10730 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10731 if (LHS.isInvalid())
10732 return QualType();
10733 }
10734 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10735 if (RHS.isInvalid())
10736 return QualType();
10737
10738 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10739 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10740
10741 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10742 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10743
10744 unsigned DiagID = diag::err_typecheck_invalid_operands;
10745 if ((OperationKind == ArithConvKind::Arithmetic) &&
10746 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10747 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10748 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10749 << RHS.get()->getSourceRange();
10750 return QualType();
10751 }
10752
10753 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10754 return LHSType;
10755
10756 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10757 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10758 return LHSType;
10759 }
10760 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10761 if (LHS.get()->isLValue() ||
10762 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10763 return RHSType;
10764 }
10765
10766 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10767 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10768 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10769 << LHSType << RHSType << LHS.get()->getSourceRange()
10770 << RHS.get()->getSourceRange();
10771 return QualType();
10772 }
10773
10774 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10775 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
10776 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
10777 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
10778 << LHSType << RHSType << LHS.get()->getSourceRange()
10779 << RHS.get()->getSourceRange();
10780 return QualType();
10781 }
10782
10783 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10784 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10785 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10786 bool ScalarOrVector =
10787 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10788
10789 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10790 << ScalarOrVector << Scalar << Vector;
10791
10792 return QualType();
10793 }
10794
10795 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10796 << RHS.get()->getSourceRange();
10797 return QualType();
10798}
10799
10800// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10801// expression. These are mainly cases where the null pointer is used as an
10802// integer instead of a pointer.
10803static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10804 SourceLocation Loc, bool IsCompare) {
10805 // The canonical way to check for a GNU null is with isNullPointerConstant,
10806 // but we use a bit of a hack here for speed; this is a relatively
10807 // hot path, and isNullPointerConstant is slow.
10808 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
10809 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
10810
10811 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10812
10813 // Avoid analyzing cases where the result will either be invalid (and
10814 // diagnosed as such) or entirely valid and not something to warn about.
10815 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10816 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10817 return;
10818
10819 // Comparison operations would not make sense with a null pointer no matter
10820 // what the other expression is.
10821 if (!IsCompare) {
10822 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
10823 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10824 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10825 return;
10826 }
10827
10828 // The rest of the operations only make sense with a null pointer
10829 // if the other expression is a pointer.
10830 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10831 NonNullType->canDecayToPointerType())
10832 return;
10833
10834 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
10835 << LHSNull /* LHS is NULL */ << NonNullType
10836 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10837}
10838
10839static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
10840 SourceLocation OpLoc) {
10841 // If the divisor is real, then this is real/real or complex/real division.
10842 // Either way there can be no precision loss.
10843 auto *CT = DivisorTy->getAs<ComplexType>();
10844 if (!CT)
10845 return;
10846
10847 QualType ElementType = CT->getElementType().getCanonicalType();
10848 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
10849 LangOptions::ComplexRangeKind::CX_Promoted;
10850 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
10851 return;
10852
10853 ASTContext &Ctx = S.getASTContext();
10854 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
10855 const llvm::fltSemantics &ElementTypeSemantics =
10856 Ctx.getFloatTypeSemantics(T: ElementType);
10857 const llvm::fltSemantics &HigherElementTypeSemantics =
10858 Ctx.getFloatTypeSemantics(T: HigherElementType);
10859
10860 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
10861 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
10862 (HigherElementType == Ctx.LongDoubleTy &&
10863 !Ctx.getTargetInfo().hasLongDoubleType())) {
10864 // Retain the location of the first use of higher precision type.
10865 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
10866 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
10867 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
10868 if (Type == HigherElementType) {
10869 Num++;
10870 return;
10871 }
10872 }
10873 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
10874 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
10875 }
10876}
10877
10878static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10879 SourceLocation Loc) {
10880 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
10881 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
10882 if (!LUE || !RUE)
10883 return;
10884 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10885 RUE->getKind() != UETT_SizeOf)
10886 return;
10887
10888 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10889 QualType LHSTy = LHSArg->getType();
10890 QualType RHSTy;
10891
10892 if (RUE->isArgumentType())
10893 RHSTy = RUE->getArgumentType().getNonReferenceType();
10894 else
10895 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10896
10897 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10898 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
10899 return;
10900
10901 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10902 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
10903 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10904 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
10905 << LHSArgDecl;
10906 }
10907 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
10908 QualType ArrayElemTy = ArrayTy->getElementType();
10909 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
10910 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10911 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10912 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
10913 return;
10914 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
10915 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10916 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
10917 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10918 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
10919 << LHSArgDecl;
10920 }
10921
10922 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
10923 }
10924}
10925
10926static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10927 ExprResult &RHS,
10928 SourceLocation Loc, bool IsDiv) {
10929 // Check for division/remainder by zero.
10930 Expr::EvalResult RHSValue;
10931 if (!RHS.get()->isValueDependent() &&
10932 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
10933 RHSValue.Val.getInt() == 0)
10934 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
10935 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
10936 << IsDiv << RHS.get()->getSourceRange());
10937}
10938
10939static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
10940 const ExprResult &LHS, const ExprResult &RHS,
10941 BinaryOperatorKind Opc) {
10942 if (!LHS.isUsable() || !RHS.isUsable())
10943 return;
10944 const Expr *LHSExpr = LHS.get();
10945 const Expr *RHSExpr = RHS.get();
10946 const QualType LHSType = LHSExpr->getType();
10947 const QualType RHSType = RHSExpr->getType();
10948 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
10949 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
10950 if (!LHSIsScoped && !RHSIsScoped)
10951 return;
10952 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
10953 return;
10954 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
10955 return;
10956 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
10957 return;
10958 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
10959 SourceLocation BeginLoc = expr->getBeginLoc();
10960 QualType IntType = type->castAs<EnumType>()
10961 ->getDecl()
10962 ->getDefinitionOrSelf()
10963 ->getIntegerType();
10964 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
10965 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
10966 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
10967 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
10968 };
10969 if (LHSIsScoped) {
10970 DiagnosticHelper(LHSExpr, LHSType);
10971 }
10972 if (RHSIsScoped) {
10973 DiagnosticHelper(RHSExpr, RHSType);
10974 }
10975}
10976
10977QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10978 SourceLocation Loc,
10979 BinaryOperatorKind Opc) {
10980 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
10981 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
10982
10983 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
10984
10985 QualType LHSTy = LHS.get()->getType();
10986 QualType RHSTy = RHS.get()->getType();
10987 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10988 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10989 /*AllowBothBool*/ getLangOpts().AltiVec,
10990 /*AllowBoolConversions*/ false,
10991 /*AllowBooleanOperation*/ AllowBoolOperation: false,
10992 /*ReportInvalid*/ true);
10993 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10994 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10995 OperationKind: ArithConvKind::Arithmetic);
10996 if (!IsDiv &&
10997 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10998 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10999 // For division, only matrix-by-scalar is supported. Other combinations with
11000 // matrix types are invalid.
11001 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11002 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11003
11004 QualType compType = UsualArithmeticConversions(
11005 LHS, RHS, Loc,
11006 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11007 if (LHS.isInvalid() || RHS.isInvalid())
11008 return QualType();
11009
11010 if (compType.isNull() || !compType->isArithmeticType()) {
11011 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11012 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11013 return ResultTy;
11014 }
11015 if (IsDiv) {
11016 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11017 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11018 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11019 }
11020 return compType;
11021}
11022
11023QualType Sema::CheckRemainderOperands(
11024 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11025 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11026
11027 // Note: This check is here to simplify the double exclusions of
11028 // scalar and vector HLSL checks. No getLangOpts().HLSL
11029 // is needed since all languages exlcude doubles.
11030 if (LHS.get()->getType()->isDoubleType() ||
11031 RHS.get()->getType()->isDoubleType() ||
11032 (LHS.get()->getType()->isVectorType() && LHS.get()
11033 ->getType()
11034 ->getAs<VectorType>()
11035 ->getElementType()
11036 ->isDoubleType()) ||
11037 (RHS.get()->getType()->isVectorType() && RHS.get()
11038 ->getType()
11039 ->getAs<VectorType>()
11040 ->getElementType()
11041 ->isDoubleType()))
11042 return InvalidOperands(Loc, LHS, RHS);
11043
11044 if (LHS.get()->getType()->isVectorType() ||
11045 RHS.get()->getType()->isVectorType()) {
11046 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11047 RHS.get()->getType()->hasIntegerRepresentation()) ||
11048 (getLangOpts().HLSL &&
11049 (LHS.get()->getType()->hasFloatingRepresentation() ||
11050 RHS.get()->getType()->hasFloatingRepresentation())))
11051 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11052 /*AllowBothBool*/ getLangOpts().AltiVec,
11053 /*AllowBoolConversions*/ false,
11054 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11055 /*ReportInvalid*/ true);
11056 return InvalidOperands(Loc, LHS, RHS);
11057 }
11058
11059 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11060 RHS.get()->getType()->isSveVLSBuiltinType()) {
11061 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11062 RHS.get()->getType()->hasIntegerRepresentation())
11063 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11064 OperationKind: ArithConvKind::Arithmetic);
11065
11066 return InvalidOperands(Loc, LHS, RHS);
11067 }
11068
11069 QualType compType = UsualArithmeticConversions(
11070 LHS, RHS, Loc,
11071 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11072 if (LHS.isInvalid() || RHS.isInvalid())
11073 return QualType();
11074
11075 if (compType.isNull() ||
11076 (!compType->isIntegerType() &&
11077 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11078 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11079 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11080 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11081 return ResultTy;
11082 }
11083 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11084 return compType;
11085}
11086
11087/// Diagnose invalid arithmetic on two void pointers.
11088static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11089 Expr *LHSExpr, Expr *RHSExpr) {
11090 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11091 ? diag::err_typecheck_pointer_arith_void_type
11092 : diag::ext_gnu_void_ptr)
11093 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11094 << RHSExpr->getSourceRange();
11095}
11096
11097/// Diagnose invalid arithmetic on a void pointer.
11098static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11099 Expr *Pointer) {
11100 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11101 ? diag::err_typecheck_pointer_arith_void_type
11102 : diag::ext_gnu_void_ptr)
11103 << 0 /* one pointer */ << Pointer->getSourceRange();
11104}
11105
11106/// Diagnose invalid arithmetic on a null pointer.
11107///
11108/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11109/// idiom, which we recognize as a GNU extension.
11110///
11111static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11112 Expr *Pointer, bool IsGNUIdiom) {
11113 if (IsGNUIdiom)
11114 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11115 << Pointer->getSourceRange();
11116 else
11117 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11118 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11119}
11120
11121/// Diagnose invalid subraction on a null pointer.
11122///
11123static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11124 Expr *Pointer, bool BothNull) {
11125 // Null - null is valid in C++ [expr.add]p7
11126 if (BothNull && S.getLangOpts().CPlusPlus)
11127 return;
11128
11129 // Is this s a macro from a system header?
11130 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11131 return;
11132
11133 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11134 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11135 << S.getLangOpts().CPlusPlus
11136 << Pointer->getSourceRange());
11137}
11138
11139/// Diagnose invalid arithmetic on two function pointers.
11140static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11141 Expr *LHS, Expr *RHS) {
11142 assert(LHS->getType()->isAnyPointerType());
11143 assert(RHS->getType()->isAnyPointerType());
11144 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11145 ? diag::err_typecheck_pointer_arith_function_type
11146 : diag::ext_gnu_ptr_func_arith)
11147 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11148 // We only show the second type if it differs from the first.
11149 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11150 T2: RHS->getType())
11151 << RHS->getType()->getPointeeType()
11152 << LHS->getSourceRange() << RHS->getSourceRange();
11153}
11154
11155/// Diagnose invalid arithmetic on a function pointer.
11156static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11157 Expr *Pointer) {
11158 assert(Pointer->getType()->isAnyPointerType());
11159 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11160 ? diag::err_typecheck_pointer_arith_function_type
11161 : diag::ext_gnu_ptr_func_arith)
11162 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11163 << 0 /* one pointer, so only one type */
11164 << Pointer->getSourceRange();
11165}
11166
11167/// Emit error if Operand is incomplete pointer type
11168///
11169/// \returns True if pointer has incomplete type
11170static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11171 Expr *Operand) {
11172 QualType ResType = Operand->getType();
11173 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11174 ResType = ResAtomicType->getValueType();
11175
11176 assert(ResType->isAnyPointerType());
11177 QualType PointeeTy = ResType->getPointeeType();
11178 return S.RequireCompleteSizedType(
11179 Loc, T: PointeeTy,
11180 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11181 Args: Operand->getSourceRange());
11182}
11183
11184/// Check the validity of an arithmetic pointer operand.
11185///
11186/// If the operand has pointer type, this code will check for pointer types
11187/// which are invalid in arithmetic operations. These will be diagnosed
11188/// appropriately, including whether or not the use is supported as an
11189/// extension.
11190///
11191/// \returns True when the operand is valid to use (even if as an extension).
11192static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11193 Expr *Operand) {
11194 QualType ResType = Operand->getType();
11195 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11196 ResType = ResAtomicType->getValueType();
11197
11198 if (!ResType->isAnyPointerType()) return true;
11199
11200 QualType PointeeTy = ResType->getPointeeType();
11201 if (PointeeTy->isVoidType()) {
11202 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11203 return !S.getLangOpts().CPlusPlus;
11204 }
11205 if (PointeeTy->isFunctionType()) {
11206 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11207 return !S.getLangOpts().CPlusPlus;
11208 }
11209
11210 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11211
11212 return true;
11213}
11214
11215/// Check the validity of a binary arithmetic operation w.r.t. pointer
11216/// operands.
11217///
11218/// This routine will diagnose any invalid arithmetic on pointer operands much
11219/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11220/// for emitting a single diagnostic even for operations where both LHS and RHS
11221/// are (potentially problematic) pointers.
11222///
11223/// \returns True when the operand is valid to use (even if as an extension).
11224static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11225 Expr *LHSExpr, Expr *RHSExpr) {
11226 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11227 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11228 if (!isLHSPointer && !isRHSPointer) return true;
11229
11230 QualType LHSPointeeTy, RHSPointeeTy;
11231 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11232 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11233
11234 // if both are pointers check if operation is valid wrt address spaces
11235 if (isLHSPointer && isRHSPointer) {
11236 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11237 Ctx: S.getASTContext())) {
11238 S.Diag(Loc,
11239 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11240 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11241 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11242 return false;
11243 }
11244 }
11245
11246 // Check for arithmetic on pointers to incomplete types.
11247 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11248 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11249 if (isLHSVoidPtr || isRHSVoidPtr) {
11250 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11251 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11252 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11253
11254 return !S.getLangOpts().CPlusPlus;
11255 }
11256
11257 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11258 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11259 if (isLHSFuncPtr || isRHSFuncPtr) {
11260 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11261 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11262 Pointer: RHSExpr);
11263 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11264
11265 return !S.getLangOpts().CPlusPlus;
11266 }
11267
11268 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11269 return false;
11270 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11271 return false;
11272
11273 return true;
11274}
11275
11276/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11277/// literal.
11278static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11279 Expr *LHSExpr, Expr *RHSExpr) {
11280 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11281 Expr* IndexExpr = RHSExpr;
11282 if (!StrExpr) {
11283 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11284 IndexExpr = LHSExpr;
11285 }
11286
11287 bool IsStringPlusInt = StrExpr &&
11288 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11289 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11290 return;
11291
11292 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11293 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11294 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11295
11296 // Only print a fixit for "str" + int, not for int + "str".
11297 if (IndexExpr == RHSExpr) {
11298 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11299 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11300 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11301 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11302 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11303 } else
11304 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11305}
11306
11307/// Emit a warning when adding a char literal to a string.
11308static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11309 Expr *LHSExpr, Expr *RHSExpr) {
11310 const Expr *StringRefExpr = LHSExpr;
11311 const CharacterLiteral *CharExpr =
11312 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11313
11314 if (!CharExpr) {
11315 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11316 StringRefExpr = RHSExpr;
11317 }
11318
11319 if (!CharExpr || !StringRefExpr)
11320 return;
11321
11322 const QualType StringType = StringRefExpr->getType();
11323
11324 // Return if not a PointerType.
11325 if (!StringType->isAnyPointerType())
11326 return;
11327
11328 // Return if not a CharacterType.
11329 if (!StringType->getPointeeType()->isAnyCharacterType())
11330 return;
11331
11332 ASTContext &Ctx = Self.getASTContext();
11333 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11334
11335 const QualType CharType = CharExpr->getType();
11336 if (!CharType->isAnyCharacterType() &&
11337 CharType->isIntegerType() &&
11338 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11339 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11340 << DiagRange << Ctx.CharTy;
11341 } else {
11342 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11343 << DiagRange << CharExpr->getType();
11344 }
11345
11346 // Only print a fixit for str + char, not for char + str.
11347 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11348 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11349 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11350 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11351 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11352 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11353 } else {
11354 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11355 }
11356}
11357
11358/// Emit error when two pointers are incompatible.
11359static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11360 Expr *LHSExpr, Expr *RHSExpr) {
11361 assert(LHSExpr->getType()->isAnyPointerType());
11362 assert(RHSExpr->getType()->isAnyPointerType());
11363 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11364 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11365 << RHSExpr->getSourceRange();
11366}
11367
11368// C99 6.5.6
11369QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11370 SourceLocation Loc, BinaryOperatorKind Opc,
11371 QualType* CompLHSTy) {
11372 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11373
11374 if (LHS.get()->getType()->isVectorType() ||
11375 RHS.get()->getType()->isVectorType()) {
11376 QualType compType =
11377 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11378 /*AllowBothBool*/ getLangOpts().AltiVec,
11379 /*AllowBoolConversions*/ getLangOpts().ZVector,
11380 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11381 /*ReportInvalid*/ true);
11382 if (CompLHSTy) *CompLHSTy = compType;
11383 return compType;
11384 }
11385
11386 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11387 RHS.get()->getType()->isSveVLSBuiltinType()) {
11388 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11389 OperationKind: ArithConvKind::Arithmetic);
11390 if (CompLHSTy)
11391 *CompLHSTy = compType;
11392 return compType;
11393 }
11394
11395 if (LHS.get()->getType()->isConstantMatrixType() ||
11396 RHS.get()->getType()->isConstantMatrixType()) {
11397 QualType compType =
11398 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11399 if (CompLHSTy)
11400 *CompLHSTy = compType;
11401 return compType;
11402 }
11403
11404 QualType compType = UsualArithmeticConversions(
11405 LHS, RHS, Loc,
11406 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11407 if (LHS.isInvalid() || RHS.isInvalid())
11408 return QualType();
11409
11410 // Diagnose "string literal" '+' int and string '+' "char literal".
11411 if (Opc == BO_Add) {
11412 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11413 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11414 }
11415
11416 // handle the common case first (both operands are arithmetic).
11417 if (!compType.isNull() && compType->isArithmeticType()) {
11418 if (CompLHSTy) *CompLHSTy = compType;
11419 return compType;
11420 }
11421
11422 // Type-checking. Ultimately the pointer's going to be in PExp;
11423 // note that we bias towards the LHS being the pointer.
11424 Expr *PExp = LHS.get(), *IExp = RHS.get();
11425
11426 bool isObjCPointer;
11427 if (PExp->getType()->isPointerType()) {
11428 isObjCPointer = false;
11429 } else if (PExp->getType()->isObjCObjectPointerType()) {
11430 isObjCPointer = true;
11431 } else {
11432 std::swap(a&: PExp, b&: IExp);
11433 if (PExp->getType()->isPointerType()) {
11434 isObjCPointer = false;
11435 } else if (PExp->getType()->isObjCObjectPointerType()) {
11436 isObjCPointer = true;
11437 } else {
11438 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11439 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11440 return ResultTy;
11441 }
11442 }
11443 assert(PExp->getType()->isAnyPointerType());
11444
11445 if (!IExp->getType()->isIntegerType())
11446 return InvalidOperands(Loc, LHS, RHS);
11447
11448 // Adding to a null pointer results in undefined behavior.
11449 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11450 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11451 // In C++ adding zero to a null pointer is defined.
11452 Expr::EvalResult KnownVal;
11453 if (!getLangOpts().CPlusPlus ||
11454 (!IExp->isValueDependent() &&
11455 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11456 KnownVal.Val.getInt() != 0))) {
11457 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11458 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11459 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11460 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11461 }
11462 }
11463
11464 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11465 return QualType();
11466
11467 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11468 return QualType();
11469
11470 // Arithmetic on label addresses is normally allowed, except when we add
11471 // a ptrauth signature to the addresses.
11472 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11473 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11474 << /*addition*/ 1;
11475 return QualType();
11476 }
11477
11478 // Check array bounds for pointer arithemtic
11479 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11480
11481 if (CompLHSTy) {
11482 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11483 if (LHSTy.isNull()) {
11484 LHSTy = LHS.get()->getType();
11485 if (Context.isPromotableIntegerType(T: LHSTy))
11486 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11487 }
11488 *CompLHSTy = LHSTy;
11489 }
11490
11491 return PExp->getType();
11492}
11493
11494// C99 6.5.6
11495QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11496 SourceLocation Loc,
11497 BinaryOperatorKind Opc,
11498 QualType *CompLHSTy) {
11499 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11500
11501 if (LHS.get()->getType()->isVectorType() ||
11502 RHS.get()->getType()->isVectorType()) {
11503 QualType compType =
11504 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11505 /*AllowBothBool*/ getLangOpts().AltiVec,
11506 /*AllowBoolConversions*/ getLangOpts().ZVector,
11507 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11508 /*ReportInvalid*/ true);
11509 if (CompLHSTy) *CompLHSTy = compType;
11510 return compType;
11511 }
11512
11513 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11514 RHS.get()->getType()->isSveVLSBuiltinType()) {
11515 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11516 OperationKind: ArithConvKind::Arithmetic);
11517 if (CompLHSTy)
11518 *CompLHSTy = compType;
11519 return compType;
11520 }
11521
11522 if (LHS.get()->getType()->isConstantMatrixType() ||
11523 RHS.get()->getType()->isConstantMatrixType()) {
11524 QualType compType =
11525 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11526 if (CompLHSTy)
11527 *CompLHSTy = compType;
11528 return compType;
11529 }
11530
11531 QualType compType = UsualArithmeticConversions(
11532 LHS, RHS, Loc,
11533 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11534 if (LHS.isInvalid() || RHS.isInvalid())
11535 return QualType();
11536
11537 // Enforce type constraints: C99 6.5.6p3.
11538
11539 // Handle the common case first (both operands are arithmetic).
11540 if (!compType.isNull() && compType->isArithmeticType()) {
11541 if (CompLHSTy) *CompLHSTy = compType;
11542 return compType;
11543 }
11544
11545 // Either ptr - int or ptr - ptr.
11546 if (LHS.get()->getType()->isAnyPointerType()) {
11547 QualType lpointee = LHS.get()->getType()->getPointeeType();
11548
11549 // Diagnose bad cases where we step over interface counts.
11550 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11551 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11552 return QualType();
11553
11554 // Arithmetic on label addresses is normally allowed, except when we add
11555 // a ptrauth signature to the addresses.
11556 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11557 getLangOpts().PointerAuthIndirectGotos) {
11558 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11559 << /*subtraction*/ 0;
11560 return QualType();
11561 }
11562
11563 // The result type of a pointer-int computation is the pointer type.
11564 if (RHS.get()->getType()->isIntegerType()) {
11565 // Subtracting from a null pointer should produce a warning.
11566 // The last argument to the diagnose call says this doesn't match the
11567 // GNU int-to-pointer idiom.
11568 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11569 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11570 // In C++ adding zero to a null pointer is defined.
11571 Expr::EvalResult KnownVal;
11572 if (!getLangOpts().CPlusPlus ||
11573 (!RHS.get()->isValueDependent() &&
11574 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11575 KnownVal.Val.getInt() != 0))) {
11576 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11577 }
11578 }
11579
11580 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11581 return QualType();
11582
11583 // Check array bounds for pointer arithemtic
11584 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11585 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11586
11587 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11588 return LHS.get()->getType();
11589 }
11590
11591 // Handle pointer-pointer subtractions.
11592 if (const PointerType *RHSPTy
11593 = RHS.get()->getType()->getAs<PointerType>()) {
11594 QualType rpointee = RHSPTy->getPointeeType();
11595
11596 if (getLangOpts().CPlusPlus) {
11597 // Pointee types must be the same: C++ [expr.add]
11598 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11599 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11600 }
11601 } else {
11602 // Pointee types must be compatible C99 6.5.6p3
11603 if (!Context.typesAreCompatible(
11604 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11605 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11606 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11607 return QualType();
11608 }
11609 }
11610
11611 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11612 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11613 return QualType();
11614
11615 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11616 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11617 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11618 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11619
11620 // Subtracting nullptr or from nullptr is suspect
11621 if (LHSIsNullPtr)
11622 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11623 if (RHSIsNullPtr)
11624 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11625
11626 // The pointee type may have zero size. As an extension, a structure or
11627 // union may have zero size or an array may have zero length. In this
11628 // case subtraction does not make sense.
11629 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11630 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11631 if (ElementSize.isZero()) {
11632 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11633 << rpointee.getUnqualifiedType()
11634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11635 }
11636 }
11637
11638 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11639 return Context.getPointerDiffType();
11640 }
11641 }
11642
11643 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11644 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11645 return ResultTy;
11646}
11647
11648static bool isScopedEnumerationType(QualType T) {
11649 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11650 return ET->getDecl()->isScoped();
11651 return false;
11652}
11653
11654static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11655 SourceLocation Loc, BinaryOperatorKind Opc,
11656 QualType LHSType) {
11657 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11658 // so skip remaining warnings as we don't want to modify values within Sema.
11659 if (S.getLangOpts().OpenCL)
11660 return;
11661
11662 if (Opc == BO_Shr &&
11663 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11664 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11665
11666 // Check right/shifter operand
11667 Expr::EvalResult RHSResult;
11668 if (RHS.get()->isValueDependent() ||
11669 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11670 return;
11671 llvm::APSInt Right = RHSResult.Val.getInt();
11672
11673 if (Right.isNegative()) {
11674 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11675 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11676 << RHS.get()->getSourceRange());
11677 return;
11678 }
11679
11680 QualType LHSExprType = LHS.get()->getType();
11681 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11682 if (LHSExprType->isBitIntType())
11683 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11684 else if (LHSExprType->isFixedPointType()) {
11685 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11686 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11687 }
11688 if (Right.uge(RHS: LeftSize)) {
11689 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11690 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
11691 << RHS.get()->getSourceRange());
11692 return;
11693 }
11694
11695 // FIXME: We probably need to handle fixed point types specially here.
11696 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11697 return;
11698
11699 // When left shifting an ICE which is signed, we can check for overflow which
11700 // according to C++ standards prior to C++2a has undefined behavior
11701 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11702 // more than the maximum value representable in the result type, so never
11703 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11704 // expression is still probably a bug.)
11705 Expr::EvalResult LHSResult;
11706 if (LHS.get()->isValueDependent() ||
11707 LHSType->hasUnsignedIntegerRepresentation() ||
11708 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
11709 return;
11710 llvm::APSInt Left = LHSResult.Val.getInt();
11711
11712 // Don't warn if signed overflow is defined, then all the rest of the
11713 // diagnostics will not be triggered because the behavior is defined.
11714 // Also don't warn in C++20 mode (and newer), as signed left shifts
11715 // always wrap and never overflow.
11716 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11717 return;
11718
11719 // If LHS does not have a non-negative value then, the
11720 // behavior is undefined before C++2a. Warn about it.
11721 if (Left.isNegative()) {
11722 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
11723 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
11724 << LHS.get()->getSourceRange());
11725 return;
11726 }
11727
11728 llvm::APInt ResultBits =
11729 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11730 if (ResultBits.ule(RHS: LeftSize))
11731 return;
11732 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
11733 Result = Result.shl(ShiftAmt: Right);
11734
11735 // Print the bit representation of the signed integer as an unsigned
11736 // hexadecimal number.
11737 SmallString<40> HexResult;
11738 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
11739
11740 // If we are only missing a sign bit, this is less likely to result in actual
11741 // bugs -- if the result is cast back to an unsigned type, it will have the
11742 // expected value. Thus we place this behind a different warning that can be
11743 // turned off separately if needed.
11744 if (ResultBits - 1 == LeftSize) {
11745 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
11746 << HexResult << LHSType
11747 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11748 return;
11749 }
11750
11751 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
11752 << HexResult.str() << Result.getSignificantBits() << LHSType
11753 << Left.getBitWidth() << LHS.get()->getSourceRange()
11754 << RHS.get()->getSourceRange();
11755}
11756
11757/// Return the resulting type when a vector is shifted
11758/// by a scalar or vector shift amount.
11759static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11760 SourceLocation Loc, bool IsCompAssign) {
11761 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11762 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11763 !LHS.get()->getType()->isVectorType()) {
11764 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
11765 << RHS.get()->getType() << LHS.get()->getType()
11766 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11767 return QualType();
11768 }
11769
11770 if (!IsCompAssign) {
11771 LHS = S.UsualUnaryConversions(E: LHS.get());
11772 if (LHS.isInvalid()) return QualType();
11773 }
11774
11775 RHS = S.UsualUnaryConversions(E: RHS.get());
11776 if (RHS.isInvalid()) return QualType();
11777
11778 QualType LHSType = LHS.get()->getType();
11779 // Note that LHS might be a scalar because the routine calls not only in
11780 // OpenCL case.
11781 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11782 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11783
11784 // Note that RHS might not be a vector.
11785 QualType RHSType = RHS.get()->getType();
11786 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11787 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11788
11789 // Do not allow shifts for boolean vectors.
11790 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11791 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11792 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
11793 << LHS.get()->getType() << RHS.get()->getType()
11794 << LHS.get()->getSourceRange();
11795 return QualType();
11796 }
11797
11798 // The operands need to be integers.
11799 if (!LHSEleType->isIntegerType()) {
11800 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11801 << LHS.get()->getType() << LHS.get()->getSourceRange();
11802 return QualType();
11803 }
11804
11805 if (!RHSEleType->isIntegerType()) {
11806 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11807 << RHS.get()->getType() << RHS.get()->getSourceRange();
11808 return QualType();
11809 }
11810
11811 if (!LHSVecTy) {
11812 assert(RHSVecTy);
11813 if (IsCompAssign)
11814 return RHSType;
11815 if (LHSEleType != RHSEleType) {
11816 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
11817 LHSEleType = RHSEleType;
11818 }
11819 QualType VecTy =
11820 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
11821 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
11822 LHSType = VecTy;
11823 } else if (RHSVecTy) {
11824 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11825 // are applied component-wise. So if RHS is a vector, then ensure
11826 // that the number of elements is the same as LHS...
11827 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11828 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11829 << LHS.get()->getType() << RHS.get()->getType()
11830 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11831 return QualType();
11832 }
11833 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11834 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11835 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11836 if (LHSBT != RHSBT &&
11837 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
11838 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
11839 << LHS.get()->getType() << RHS.get()->getType()
11840 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11841 }
11842 }
11843 } else {
11844 // ...else expand RHS to match the number of elements in LHS.
11845 QualType VecTy =
11846 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
11847 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
11848 }
11849
11850 return LHSType;
11851}
11852
11853static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11854 ExprResult &RHS, SourceLocation Loc,
11855 bool IsCompAssign) {
11856 if (!IsCompAssign) {
11857 LHS = S.UsualUnaryConversions(E: LHS.get());
11858 if (LHS.isInvalid())
11859 return QualType();
11860 }
11861
11862 RHS = S.UsualUnaryConversions(E: RHS.get());
11863 if (RHS.isInvalid())
11864 return QualType();
11865
11866 QualType LHSType = LHS.get()->getType();
11867 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11868 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11869 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
11870 : LHSType;
11871
11872 // Note that RHS might not be a vector
11873 QualType RHSType = RHS.get()->getType();
11874 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11875 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11876 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
11877 : RHSType;
11878
11879 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11880 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11881 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
11882 << LHSType << RHSType << LHS.get()->getSourceRange();
11883 return QualType();
11884 }
11885
11886 if (!LHSEleType->isIntegerType()) {
11887 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11888 << LHS.get()->getType() << LHS.get()->getSourceRange();
11889 return QualType();
11890 }
11891
11892 if (!RHSEleType->isIntegerType()) {
11893 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11894 << RHS.get()->getType() << RHS.get()->getSourceRange();
11895 return QualType();
11896 }
11897
11898 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11899 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11900 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
11901 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
11902 << LHSType << RHSType << LHS.get()->getSourceRange()
11903 << RHS.get()->getSourceRange();
11904 return QualType();
11905 }
11906
11907 if (!LHSType->isSveVLSBuiltinType()) {
11908 assert(RHSType->isSveVLSBuiltinType());
11909 if (IsCompAssign)
11910 return RHSType;
11911 if (LHSEleType != RHSEleType) {
11912 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
11913 LHSEleType = RHSEleType;
11914 }
11915 const llvm::ElementCount VecSize =
11916 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
11917 QualType VecTy =
11918 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
11919 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
11920 LHSType = VecTy;
11921 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11922 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
11923 S.Context.getTypeSize(T: LHSBuiltinTy)) {
11924 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11925 << LHSType << RHSType << LHS.get()->getSourceRange()
11926 << RHS.get()->getSourceRange();
11927 return QualType();
11928 }
11929 } else {
11930 const llvm::ElementCount VecSize =
11931 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
11932 if (LHSEleType != RHSEleType) {
11933 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
11934 RHSEleType = LHSEleType;
11935 }
11936 QualType VecTy =
11937 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
11938 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
11939 }
11940
11941 return LHSType;
11942}
11943
11944// C99 6.5.7
11945QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11946 SourceLocation Loc, BinaryOperatorKind Opc,
11947 bool IsCompAssign) {
11948 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11949
11950 // Vector shifts promote their scalar inputs to vector type.
11951 if (LHS.get()->getType()->isVectorType() ||
11952 RHS.get()->getType()->isVectorType()) {
11953 if (LangOpts.ZVector) {
11954 // The shift operators for the z vector extensions work basically
11955 // like general shifts, except that neither the LHS nor the RHS is
11956 // allowed to be a "vector bool".
11957 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11958 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11959 return InvalidOperands(Loc, LHS, RHS);
11960 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11961 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11962 return InvalidOperands(Loc, LHS, RHS);
11963 }
11964 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
11965 }
11966
11967 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11968 RHS.get()->getType()->isSveVLSBuiltinType())
11969 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
11970
11971 // Shifts don't perform usual arithmetic conversions, they just do integer
11972 // promotions on each operand. C99 6.5.7p3
11973
11974 // For the LHS, do usual unary conversions, but then reset them away
11975 // if this is a compound assignment.
11976 ExprResult OldLHS = LHS;
11977 LHS = UsualUnaryConversions(E: LHS.get());
11978 if (LHS.isInvalid())
11979 return QualType();
11980 QualType LHSType = LHS.get()->getType();
11981 if (IsCompAssign) LHS = OldLHS;
11982
11983 // The RHS is simpler.
11984 RHS = UsualUnaryConversions(E: RHS.get());
11985 if (RHS.isInvalid())
11986 return QualType();
11987 QualType RHSType = RHS.get()->getType();
11988
11989 // C99 6.5.7p2: Each of the operands shall have integer type.
11990 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11991 if ((!LHSType->isFixedPointOrIntegerType() &&
11992 !LHSType->hasIntegerRepresentation()) ||
11993 !RHSType->hasIntegerRepresentation()) {
11994 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11995 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11996 return ResultTy;
11997 }
11998
11999 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12000
12001 // "The type of the result is that of the promoted left operand."
12002 return LHSType;
12003}
12004
12005/// Diagnose bad pointer comparisons.
12006static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12007 ExprResult &LHS, ExprResult &RHS,
12008 bool IsError) {
12009 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12010 : diag::ext_typecheck_comparison_of_distinct_pointers)
12011 << LHS.get()->getType() << RHS.get()->getType()
12012 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12013}
12014
12015/// Returns false if the pointers are converted to a composite type,
12016/// true otherwise.
12017static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12018 ExprResult &LHS, ExprResult &RHS) {
12019 // C++ [expr.rel]p2:
12020 // [...] Pointer conversions (4.10) and qualification
12021 // conversions (4.4) are performed on pointer operands (or on
12022 // a pointer operand and a null pointer constant) to bring
12023 // them to their composite pointer type. [...]
12024 //
12025 // C++ [expr.eq]p1 uses the same notion for (in)equality
12026 // comparisons of pointers.
12027
12028 QualType LHSType = LHS.get()->getType();
12029 QualType RHSType = RHS.get()->getType();
12030 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12031 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12032
12033 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12034 if (T.isNull()) {
12035 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12036 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12037 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12038 else
12039 S.InvalidOperands(Loc, LHS, RHS);
12040 return true;
12041 }
12042
12043 return false;
12044}
12045
12046static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12047 ExprResult &LHS,
12048 ExprResult &RHS,
12049 bool IsError) {
12050 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12051 : diag::ext_typecheck_comparison_of_fptr_to_void)
12052 << LHS.get()->getType() << RHS.get()->getType()
12053 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12054}
12055
12056static bool isObjCObjectLiteral(ExprResult &E) {
12057 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12058 case Stmt::ObjCArrayLiteralClass:
12059 case Stmt::ObjCDictionaryLiteralClass:
12060 case Stmt::ObjCStringLiteralClass:
12061 case Stmt::ObjCBoxedExprClass:
12062 return true;
12063 default:
12064 // Note that ObjCBoolLiteral is NOT an object literal!
12065 return false;
12066 }
12067}
12068
12069static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12070 const ObjCObjectPointerType *Type =
12071 LHS->getType()->getAs<ObjCObjectPointerType>();
12072
12073 // If this is not actually an Objective-C object, bail out.
12074 if (!Type)
12075 return false;
12076
12077 // Get the LHS object's interface type.
12078 QualType InterfaceType = Type->getPointeeType();
12079
12080 // If the RHS isn't an Objective-C object, bail out.
12081 if (!RHS->getType()->isObjCObjectPointerType())
12082 return false;
12083
12084 // Try to find the -isEqual: method.
12085 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12086 ObjCMethodDecl *Method =
12087 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12088 /*IsInstance=*/true);
12089 if (!Method) {
12090 if (Type->isObjCIdType()) {
12091 // For 'id', just check the global pool.
12092 Method =
12093 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12094 /*receiverId=*/receiverIdOrClass: true);
12095 } else {
12096 // Check protocols.
12097 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12098 /*IsInstance=*/true);
12099 }
12100 }
12101
12102 if (!Method)
12103 return false;
12104
12105 QualType T = Method->parameters()[0]->getType();
12106 if (!T->isObjCObjectPointerType())
12107 return false;
12108
12109 QualType R = Method->getReturnType();
12110 if (!R->isScalarType())
12111 return false;
12112
12113 return true;
12114}
12115
12116static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12117 ExprResult &LHS, ExprResult &RHS,
12118 BinaryOperator::Opcode Opc){
12119 Expr *Literal;
12120 Expr *Other;
12121 if (isObjCObjectLiteral(E&: LHS)) {
12122 Literal = LHS.get();
12123 Other = RHS.get();
12124 } else {
12125 Literal = RHS.get();
12126 Other = LHS.get();
12127 }
12128
12129 // Don't warn on comparisons against nil.
12130 Other = Other->IgnoreParenCasts();
12131 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12132 NPC: Expr::NPC_ValueDependentIsNotNull))
12133 return;
12134
12135 // This should be kept in sync with warn_objc_literal_comparison.
12136 // LK_String should always be after the other literals, since it has its own
12137 // warning flag.
12138 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12139 assert(LiteralKind != SemaObjC::LK_Block);
12140 if (LiteralKind == SemaObjC::LK_None) {
12141 llvm_unreachable("Unknown Objective-C object literal kind");
12142 }
12143
12144 if (LiteralKind == SemaObjC::LK_String)
12145 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12146 << Literal->getSourceRange();
12147 else
12148 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12149 << LiteralKind << Literal->getSourceRange();
12150
12151 if (BinaryOperator::isEqualityOp(Opc) &&
12152 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12153 SourceLocation Start = LHS.get()->getBeginLoc();
12154 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12155 CharSourceRange OpRange =
12156 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12157
12158 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12159 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12160 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12161 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12162 }
12163}
12164
12165/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12166static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12167 ExprResult &RHS, SourceLocation Loc,
12168 BinaryOperatorKind Opc) {
12169 // Check that left hand side is !something.
12170 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12171 if (!UO || UO->getOpcode() != UO_LNot) return;
12172
12173 // Only check if the right hand side is non-bool arithmetic type.
12174 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12175
12176 // Make sure that the something in !something is not bool.
12177 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12178 if (SubExpr->isKnownToHaveBooleanValue()) return;
12179
12180 // Emit warning.
12181 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12182 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12183 << Loc << IsBitwiseOp;
12184
12185 // First note suggest !(x < y)
12186 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12187 SourceLocation FirstClose = RHS.get()->getEndLoc();
12188 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12189 if (FirstClose.isInvalid())
12190 FirstOpen = SourceLocation();
12191 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12192 << IsBitwiseOp
12193 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12194 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12195
12196 // Second note suggests (!x) < y
12197 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12198 SourceLocation SecondClose = LHS.get()->getEndLoc();
12199 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12200 if (SecondClose.isInvalid())
12201 SecondOpen = SourceLocation();
12202 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12203 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12204 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12205}
12206
12207// Returns true if E refers to a non-weak array.
12208static bool checkForArray(const Expr *E) {
12209 const ValueDecl *D = nullptr;
12210 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12211 D = DR->getDecl();
12212 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12213 if (Mem->isImplicitAccess())
12214 D = Mem->getMemberDecl();
12215 }
12216 if (!D)
12217 return false;
12218 return D->getType()->isArrayType() && !D->isWeak();
12219}
12220
12221/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12222/// pointer and size is an unsigned integer. Return whether the result is
12223/// always true/false.
12224static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12225 const Expr *RHS,
12226 BinaryOperatorKind Opc) {
12227 if (!LHS->getType()->isPointerType() ||
12228 S.getLangOpts().PointerOverflowDefined)
12229 return std::nullopt;
12230
12231 // Canonicalize to >= or < predicate.
12232 switch (Opc) {
12233 case BO_GE:
12234 case BO_LT:
12235 break;
12236 case BO_GT:
12237 std::swap(a&: LHS, b&: RHS);
12238 Opc = BO_LT;
12239 break;
12240 case BO_LE:
12241 std::swap(a&: LHS, b&: RHS);
12242 Opc = BO_GE;
12243 break;
12244 default:
12245 return std::nullopt;
12246 }
12247
12248 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12249 if (!BO || BO->getOpcode() != BO_Add)
12250 return std::nullopt;
12251
12252 Expr *Other;
12253 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12254 Other = BO->getRHS();
12255 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12256 Other = BO->getLHS();
12257 else
12258 return std::nullopt;
12259
12260 if (!Other->getType()->isUnsignedIntegerType())
12261 return std::nullopt;
12262
12263 return Opc == BO_GE;
12264}
12265
12266/// Diagnose some forms of syntactically-obvious tautological comparison.
12267static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12268 Expr *LHS, Expr *RHS,
12269 BinaryOperatorKind Opc) {
12270 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12271 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12272
12273 QualType LHSType = LHS->getType();
12274 QualType RHSType = RHS->getType();
12275 if (LHSType->hasFloatingRepresentation() ||
12276 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12277 S.inTemplateInstantiation())
12278 return;
12279
12280 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12281 // Tautological diagnostics.
12282 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12283 return;
12284
12285 // Comparisons between two array types are ill-formed for operator<=>, so
12286 // we shouldn't emit any additional warnings about it.
12287 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12288 return;
12289
12290 // For non-floating point types, check for self-comparisons of the form
12291 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12292 // often indicate logic errors in the program.
12293 //
12294 // NOTE: Don't warn about comparison expressions resulting from macro
12295 // expansion. Also don't warn about comparisons which are only self
12296 // comparisons within a template instantiation. The warnings should catch
12297 // obvious cases in the definition of the template anyways. The idea is to
12298 // warn when the typed comparison operator will always evaluate to the same
12299 // result.
12300
12301 // Used for indexing into %select in warn_comparison_always
12302 enum {
12303 AlwaysConstant,
12304 AlwaysTrue,
12305 AlwaysFalse,
12306 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12307 };
12308
12309 // C++1a [array.comp]:
12310 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12311 // operands of array type.
12312 // C++2a [depr.array.comp]:
12313 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12314 // operands of array type are deprecated.
12315 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12316 RHSStripped->getType()->isArrayType()) {
12317 auto IsDeprArrayComparionIgnored =
12318 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12319 auto DiagID = S.getLangOpts().CPlusPlus26
12320 ? diag::warn_array_comparison_cxx26
12321 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12322 ? diag::warn_array_comparison
12323 : diag::warn_depr_array_comparison;
12324 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12325 << LHSStripped->getType() << RHSStripped->getType();
12326 // Carry on to produce the tautological comparison warning, if this
12327 // expression is potentially-evaluated, we can resolve the array to a
12328 // non-weak declaration, and so on.
12329 }
12330
12331 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12332 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12333 unsigned Result;
12334 switch (Opc) {
12335 case BO_EQ:
12336 case BO_LE:
12337 case BO_GE:
12338 Result = AlwaysTrue;
12339 break;
12340 case BO_NE:
12341 case BO_LT:
12342 case BO_GT:
12343 Result = AlwaysFalse;
12344 break;
12345 case BO_Cmp:
12346 Result = AlwaysEqual;
12347 break;
12348 default:
12349 Result = AlwaysConstant;
12350 break;
12351 }
12352 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12353 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12354 << 0 /*self-comparison*/
12355 << Result);
12356 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12357 // What is it always going to evaluate to?
12358 unsigned Result;
12359 switch (Opc) {
12360 case BO_EQ: // e.g. array1 == array2
12361 Result = AlwaysFalse;
12362 break;
12363 case BO_NE: // e.g. array1 != array2
12364 Result = AlwaysTrue;
12365 break;
12366 default: // e.g. array1 <= array2
12367 // The best we can say is 'a constant'
12368 Result = AlwaysConstant;
12369 break;
12370 }
12371 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12372 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12373 << 1 /*array comparison*/
12374 << Result);
12375 } else if (std::optional<bool> Res =
12376 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12377 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12378 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12379 << 2 /*pointer comparison*/
12380 << (*Res ? AlwaysTrue : AlwaysFalse));
12381 }
12382 }
12383
12384 if (isa<CastExpr>(Val: LHSStripped))
12385 LHSStripped = LHSStripped->IgnoreParenCasts();
12386 if (isa<CastExpr>(Val: RHSStripped))
12387 RHSStripped = RHSStripped->IgnoreParenCasts();
12388
12389 // Warn about comparisons against a string constant (unless the other
12390 // operand is null); the user probably wants string comparison function.
12391 Expr *LiteralString = nullptr;
12392 Expr *LiteralStringStripped = nullptr;
12393 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12394 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12395 NPC: Expr::NPC_ValueDependentIsNull)) {
12396 LiteralString = LHS;
12397 LiteralStringStripped = LHSStripped;
12398 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12399 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12400 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12401 NPC: Expr::NPC_ValueDependentIsNull)) {
12402 LiteralString = RHS;
12403 LiteralStringStripped = RHSStripped;
12404 }
12405
12406 if (LiteralString) {
12407 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12408 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12409 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12410 << LiteralString->getSourceRange());
12411 }
12412}
12413
12414static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12415 switch (CK) {
12416 default: {
12417#ifndef NDEBUG
12418 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12419 << "\n";
12420#endif
12421 llvm_unreachable("unhandled cast kind");
12422 }
12423 case CK_UserDefinedConversion:
12424 return ICK_Identity;
12425 case CK_LValueToRValue:
12426 return ICK_Lvalue_To_Rvalue;
12427 case CK_ArrayToPointerDecay:
12428 return ICK_Array_To_Pointer;
12429 case CK_FunctionToPointerDecay:
12430 return ICK_Function_To_Pointer;
12431 case CK_IntegralCast:
12432 return ICK_Integral_Conversion;
12433 case CK_FloatingCast:
12434 return ICK_Floating_Conversion;
12435 case CK_IntegralToFloating:
12436 case CK_FloatingToIntegral:
12437 return ICK_Floating_Integral;
12438 case CK_IntegralComplexCast:
12439 case CK_FloatingComplexCast:
12440 case CK_FloatingComplexToIntegralComplex:
12441 case CK_IntegralComplexToFloatingComplex:
12442 return ICK_Complex_Conversion;
12443 case CK_FloatingComplexToReal:
12444 case CK_FloatingRealToComplex:
12445 case CK_IntegralComplexToReal:
12446 case CK_IntegralRealToComplex:
12447 return ICK_Complex_Real;
12448 case CK_HLSLArrayRValue:
12449 return ICK_HLSL_Array_RValue;
12450 }
12451}
12452
12453static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12454 QualType FromType,
12455 SourceLocation Loc) {
12456 // Check for a narrowing implicit conversion.
12457 StandardConversionSequence SCS;
12458 SCS.setAsIdentityConversion();
12459 SCS.setToType(Idx: 0, T: FromType);
12460 SCS.setToType(Idx: 1, T: ToType);
12461 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12462 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12463
12464 APValue PreNarrowingValue;
12465 QualType PreNarrowingType;
12466 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12467 ConstantType&: PreNarrowingType,
12468 /*IgnoreFloatToIntegralConversion*/ true)) {
12469 case NK_Dependent_Narrowing:
12470 // Implicit conversion to a narrower type, but the expression is
12471 // value-dependent so we can't tell whether it's actually narrowing.
12472 case NK_Not_Narrowing:
12473 return false;
12474
12475 case NK_Constant_Narrowing:
12476 // Implicit conversion to a narrower type, and the value is not a constant
12477 // expression.
12478 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12479 << /*Constant*/ 1
12480 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12481 return true;
12482
12483 case NK_Variable_Narrowing:
12484 // Implicit conversion to a narrower type, and the value is not a constant
12485 // expression.
12486 case NK_Type_Narrowing:
12487 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12488 << /*Constant*/ 0 << FromType << ToType;
12489 // TODO: It's not a constant expression, but what if the user intended it
12490 // to be? Can we produce notes to help them figure out why it isn't?
12491 return true;
12492 }
12493 llvm_unreachable("unhandled case in switch");
12494}
12495
12496static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12497 ExprResult &LHS,
12498 ExprResult &RHS,
12499 SourceLocation Loc) {
12500 QualType LHSType = LHS.get()->getType();
12501 QualType RHSType = RHS.get()->getType();
12502 // Dig out the original argument type and expression before implicit casts
12503 // were applied. These are the types/expressions we need to check the
12504 // [expr.spaceship] requirements against.
12505 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12506 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12507 QualType LHSStrippedType = LHSStripped.get()->getType();
12508 QualType RHSStrippedType = RHSStripped.get()->getType();
12509
12510 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12511 // other is not, the program is ill-formed.
12512 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12513 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12514 return QualType();
12515 }
12516
12517 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12518 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12519 RHSStrippedType->isEnumeralType();
12520 if (NumEnumArgs == 1) {
12521 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12522 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12523 if (OtherTy->hasFloatingRepresentation()) {
12524 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12525 return QualType();
12526 }
12527 }
12528 if (NumEnumArgs == 2) {
12529 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12530 // type E, the operator yields the result of converting the operands
12531 // to the underlying type of E and applying <=> to the converted operands.
12532 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12533 S.InvalidOperands(Loc, LHS, RHS);
12534 return QualType();
12535 }
12536 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12537 assert(IntType->isArithmeticType());
12538
12539 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12540 // promote the boolean type, and all other promotable integer types, to
12541 // avoid this.
12542 if (S.Context.isPromotableIntegerType(T: IntType))
12543 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12544
12545 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12546 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12547 LHSType = RHSType = IntType;
12548 }
12549
12550 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12551 // usual arithmetic conversions are applied to the operands.
12552 QualType Type =
12553 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12554 if (LHS.isInvalid() || RHS.isInvalid())
12555 return QualType();
12556 if (Type.isNull()) {
12557 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12558 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12559 return ResultTy;
12560 }
12561
12562 std::optional<ComparisonCategoryType> CCT =
12563 getComparisonCategoryForBuiltinCmp(T: Type);
12564 if (!CCT)
12565 return S.InvalidOperands(Loc, LHS, RHS);
12566
12567 bool HasNarrowing = checkThreeWayNarrowingConversion(
12568 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12569 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12570 Loc: RHS.get()->getBeginLoc());
12571 if (HasNarrowing)
12572 return QualType();
12573
12574 assert(!Type.isNull() && "composite type for <=> has not been set");
12575
12576 return S.CheckComparisonCategoryType(
12577 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12578}
12579
12580static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12581 ExprResult &RHS,
12582 SourceLocation Loc,
12583 BinaryOperatorKind Opc) {
12584 if (Opc == BO_Cmp)
12585 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12586
12587 // C99 6.5.8p3 / C99 6.5.9p4
12588 QualType Type =
12589 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12590 if (LHS.isInvalid() || RHS.isInvalid())
12591 return QualType();
12592 if (Type.isNull()) {
12593 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12594 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12595 return ResultTy;
12596 }
12597 assert(Type->isArithmeticType() || Type->isEnumeralType());
12598
12599 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12600 return S.InvalidOperands(Loc, LHS, RHS);
12601
12602 // Check for comparisons of floating point operands using != and ==.
12603 if (Type->hasFloatingRepresentation())
12604 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12605
12606 // The result of comparisons is 'bool' in C++, 'int' in C.
12607 return S.Context.getLogicalOperationType();
12608}
12609
12610void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12611 if (!NullE.get()->getType()->isAnyPointerType())
12612 return;
12613 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12614 if (!E.get()->getType()->isAnyPointerType() &&
12615 E.get()->isNullPointerConstant(Ctx&: Context,
12616 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12617 Expr::NPCK_ZeroExpression) {
12618 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12619 if (CL->getValue() == 0)
12620 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12621 << NullValue
12622 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12623 Code: NullValue ? "NULL" : "(void *)0");
12624 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12625 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12626 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12627 if (T == Context.CharTy)
12628 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12629 << NullValue
12630 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12631 Code: NullValue ? "NULL" : "(void *)0");
12632 }
12633 }
12634}
12635
12636// C99 6.5.8, C++ [expr.rel]
12637QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12638 SourceLocation Loc,
12639 BinaryOperatorKind Opc) {
12640 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12641 bool IsThreeWay = Opc == BO_Cmp;
12642 bool IsOrdered = IsRelational || IsThreeWay;
12643 auto IsAnyPointerType = [](ExprResult E) {
12644 QualType Ty = E.get()->getType();
12645 return Ty->isPointerType() || Ty->isMemberPointerType();
12646 };
12647
12648 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12649 // type, array-to-pointer, ..., conversions are performed on both operands to
12650 // bring them to their composite type.
12651 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12652 // any type-related checks.
12653 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12654 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12655 if (LHS.isInvalid())
12656 return QualType();
12657 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12658 if (RHS.isInvalid())
12659 return QualType();
12660 } else {
12661 LHS = DefaultLvalueConversion(E: LHS.get());
12662 if (LHS.isInvalid())
12663 return QualType();
12664 RHS = DefaultLvalueConversion(E: RHS.get());
12665 if (RHS.isInvalid())
12666 return QualType();
12667 }
12668
12669 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12670 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12671 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12672 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12673 }
12674
12675 // Handle vector comparisons separately.
12676 if (LHS.get()->getType()->isVectorType() ||
12677 RHS.get()->getType()->isVectorType())
12678 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12679
12680 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12681 RHS.get()->getType()->isSveVLSBuiltinType())
12682 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12683
12684 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12685 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12686
12687 QualType LHSType = LHS.get()->getType();
12688 QualType RHSType = RHS.get()->getType();
12689 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12690 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12691 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
12692
12693 if ((LHSType->isPointerType() &&
12694 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12695 (RHSType->isPointerType() &&
12696 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12697 return InvalidOperands(Loc, LHS, RHS);
12698
12699 const Expr::NullPointerConstantKind LHSNullKind =
12700 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12701 const Expr::NullPointerConstantKind RHSNullKind =
12702 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12703 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12704 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12705
12706 auto computeResultTy = [&]() {
12707 if (Opc != BO_Cmp)
12708 return QualType(Context.getLogicalOperationType());
12709 assert(getLangOpts().CPlusPlus);
12710 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12711
12712 QualType CompositeTy = LHS.get()->getType();
12713 assert(!CompositeTy->isReferenceType());
12714
12715 std::optional<ComparisonCategoryType> CCT =
12716 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
12717 if (!CCT)
12718 return InvalidOperands(Loc, LHS, RHS);
12719
12720 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12721 // P0946R0: Comparisons between a null pointer constant and an object
12722 // pointer result in std::strong_equality, which is ill-formed under
12723 // P1959R0.
12724 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12725 << (LHSIsNull ? LHS.get()->getSourceRange()
12726 : RHS.get()->getSourceRange());
12727 return QualType();
12728 }
12729
12730 return CheckComparisonCategoryType(
12731 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
12732 };
12733
12734 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12735 bool IsEquality = Opc == BO_EQ;
12736 if (RHSIsNull)
12737 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
12738 Range: RHS.get()->getSourceRange());
12739 else
12740 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
12741 Range: LHS.get()->getSourceRange());
12742 }
12743
12744 if (IsOrdered && LHSType->isFunctionPointerType() &&
12745 RHSType->isFunctionPointerType()) {
12746 // Valid unless a relational comparison of function pointers
12747 bool IsError = Opc == BO_Cmp;
12748 auto DiagID =
12749 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12750 : getLangOpts().CPlusPlus
12751 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12752 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12753 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12754 << RHS.get()->getSourceRange();
12755 if (IsError)
12756 return QualType();
12757 }
12758
12759 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12760 (RHSType->isIntegerType() && !RHSIsNull)) {
12761 // Skip normal pointer conversion checks in this case; we have better
12762 // diagnostics for this below.
12763 } else if (getLangOpts().CPlusPlus) {
12764 // Equality comparison of a function pointer to a void pointer is invalid,
12765 // but we allow it as an extension.
12766 // FIXME: If we really want to allow this, should it be part of composite
12767 // pointer type computation so it works in conditionals too?
12768 if (!IsOrdered &&
12769 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12770 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12771 // This is a gcc extension compatibility comparison.
12772 // In a SFINAE context, we treat this as a hard error to maintain
12773 // conformance with the C++ standard.
12774 bool IsError = isSFINAEContext();
12775 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
12776
12777 if (IsError)
12778 return QualType();
12779
12780 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
12781 return computeResultTy();
12782 }
12783
12784 // C++ [expr.eq]p2:
12785 // If at least one operand is a pointer [...] bring them to their
12786 // composite pointer type.
12787 // C++ [expr.spaceship]p6
12788 // If at least one of the operands is of pointer type, [...] bring them
12789 // to their composite pointer type.
12790 // C++ [expr.rel]p2:
12791 // If both operands are pointers, [...] bring them to their composite
12792 // pointer type.
12793 // For <=>, the only valid non-pointer types are arrays and functions, and
12794 // we already decayed those, so this is really the same as the relational
12795 // comparison rule.
12796 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12797 (IsOrdered ? 2 : 1) &&
12798 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12799 RHSType->isObjCObjectPointerType()))) {
12800 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
12801 return QualType();
12802 return computeResultTy();
12803 }
12804 } else if (LHSType->isPointerType() &&
12805 RHSType->isPointerType()) { // C99 6.5.8p2
12806 // All of the following pointer-related warnings are GCC extensions, except
12807 // when handling null pointer constants.
12808 QualType LCanPointeeTy =
12809 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12810 QualType RCanPointeeTy =
12811 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12812
12813 // C99 6.5.9p2 and C99 6.5.8p2
12814 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
12815 T2: RCanPointeeTy.getUnqualifiedType())) {
12816 if (IsRelational) {
12817 // Pointers both need to point to complete or incomplete types
12818 if ((LCanPointeeTy->isIncompleteType() !=
12819 RCanPointeeTy->isIncompleteType()) &&
12820 !getLangOpts().C11) {
12821 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
12822 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12823 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12824 << RCanPointeeTy->isIncompleteType();
12825 }
12826 }
12827 } else if (!IsRelational &&
12828 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12829 // Valid unless comparison between non-null pointer and function pointer
12830 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12831 && !LHSIsNull && !RHSIsNull)
12832 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
12833 /*isError*/IsError: false);
12834 } else {
12835 // Invalid
12836 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
12837 }
12838 if (LCanPointeeTy != RCanPointeeTy) {
12839 // Treat NULL constant as a special case in OpenCL.
12840 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12841 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
12842 Ctx: getASTContext())) {
12843 Diag(Loc,
12844 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12845 << LHSType << RHSType << 0 /* comparison */
12846 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12847 }
12848 }
12849 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12850 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12851 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12852 : CK_BitCast;
12853
12854 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
12855 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
12856 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
12857 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
12858 bool ChangingCFIUncheckedCallee =
12859 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
12860
12861 if (LHSIsNull && !RHSIsNull)
12862 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
12863 else if (!ChangingCFIUncheckedCallee)
12864 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
12865 }
12866 return computeResultTy();
12867 }
12868
12869
12870 // C++ [expr.eq]p4:
12871 // Two operands of type std::nullptr_t or one operand of type
12872 // std::nullptr_t and the other a null pointer constant compare
12873 // equal.
12874 // C23 6.5.9p5:
12875 // If both operands have type nullptr_t or one operand has type nullptr_t
12876 // and the other is a null pointer constant, they compare equal if the
12877 // former is a null pointer.
12878 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12879 if (LHSType->isNullPtrType()) {
12880 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12881 return computeResultTy();
12882 }
12883 if (RHSType->isNullPtrType()) {
12884 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
12885 return computeResultTy();
12886 }
12887 }
12888
12889 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12890 // C23 6.5.9p6:
12891 // Otherwise, at least one operand is a pointer. If one is a pointer and
12892 // the other is a null pointer constant or has type nullptr_t, they
12893 // compare equal
12894 if (LHSIsNull && RHSType->isPointerType()) {
12895 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
12896 return computeResultTy();
12897 }
12898 if (RHSIsNull && LHSType->isPointerType()) {
12899 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12900 return computeResultTy();
12901 }
12902 }
12903
12904 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12905 // These aren't covered by the composite pointer type rules.
12906 if (!IsOrdered && RHSType->isNullPtrType() &&
12907 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12908 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12909 return computeResultTy();
12910 }
12911 if (!IsOrdered && LHSType->isNullPtrType() &&
12912 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12913 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
12914 return computeResultTy();
12915 }
12916
12917 if (getLangOpts().CPlusPlus) {
12918 if (IsRelational &&
12919 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12920 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12921 // HACK: Relational comparison of nullptr_t against a pointer type is
12922 // invalid per DR583, but we allow it within std::less<> and friends,
12923 // since otherwise common uses of it break.
12924 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12925 // friends to have std::nullptr_t overload candidates.
12926 DeclContext *DC = CurContext;
12927 if (isa<FunctionDecl>(Val: DC))
12928 DC = DC->getParent();
12929 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
12930 if (CTSD->isInStdNamespace() &&
12931 llvm::StringSwitch<bool>(CTSD->getName())
12932 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
12933 .Default(Value: false)) {
12934 if (RHSType->isNullPtrType())
12935 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12936 else
12937 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
12938 return computeResultTy();
12939 }
12940 }
12941 }
12942
12943 // C++ [expr.eq]p2:
12944 // If at least one operand is a pointer to member, [...] bring them to
12945 // their composite pointer type.
12946 if (!IsOrdered &&
12947 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12948 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
12949 return QualType();
12950 else
12951 return computeResultTy();
12952 }
12953 }
12954
12955 // Handle block pointer types.
12956 if (!IsOrdered && LHSType->isBlockPointerType() &&
12957 RHSType->isBlockPointerType()) {
12958 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12959 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12960
12961 if (!LHSIsNull && !RHSIsNull &&
12962 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
12963 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
12964 << LHSType << RHSType << LHS.get()->getSourceRange()
12965 << RHS.get()->getSourceRange();
12966 }
12967 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
12968 return computeResultTy();
12969 }
12970
12971 // Allow block pointers to be compared with null pointer constants.
12972 if (!IsOrdered
12973 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12974 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12975 if (!LHSIsNull && !RHSIsNull) {
12976 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12977 ->getPointeeType()->isVoidType())
12978 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12979 ->getPointeeType()->isVoidType())))
12980 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
12981 << LHSType << RHSType << LHS.get()->getSourceRange()
12982 << RHS.get()->getSourceRange();
12983 }
12984 if (LHSIsNull && !RHSIsNull)
12985 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
12986 CK: RHSType->isPointerType() ? CK_BitCast
12987 : CK_AnyPointerToBlockPointerCast);
12988 else
12989 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
12990 CK: LHSType->isPointerType() ? CK_BitCast
12991 : CK_AnyPointerToBlockPointerCast);
12992 return computeResultTy();
12993 }
12994
12995 if (LHSType->isObjCObjectPointerType() ||
12996 RHSType->isObjCObjectPointerType()) {
12997 const PointerType *LPT = LHSType->getAs<PointerType>();
12998 const PointerType *RPT = RHSType->getAs<PointerType>();
12999 if (LPT || RPT) {
13000 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13001 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13002
13003 if (!LPtrToVoid && !RPtrToVoid &&
13004 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13005 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13006 /*isError*/IsError: false);
13007 }
13008 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13009 // the RHS, but we have test coverage for this behavior.
13010 // FIXME: Consider using convertPointersToCompositeType in C++.
13011 if (LHSIsNull && !RHSIsNull) {
13012 Expr *E = LHS.get();
13013 if (getLangOpts().ObjCAutoRefCount)
13014 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13015 CCK: CheckedConversionKind::Implicit);
13016 LHS = ImpCastExprToType(E, Type: RHSType,
13017 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13018 }
13019 else {
13020 Expr *E = RHS.get();
13021 if (getLangOpts().ObjCAutoRefCount)
13022 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13023 CCK: CheckedConversionKind::Implicit,
13024 /*Diagnose=*/true,
13025 /*DiagnoseCFAudited=*/false, Opc);
13026 RHS = ImpCastExprToType(E, Type: LHSType,
13027 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13028 }
13029 return computeResultTy();
13030 }
13031 if (LHSType->isObjCObjectPointerType() &&
13032 RHSType->isObjCObjectPointerType()) {
13033 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13034 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13035 /*isError*/IsError: false);
13036 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13037 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13038
13039 if (LHSIsNull && !RHSIsNull)
13040 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13041 else
13042 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13043 return computeResultTy();
13044 }
13045
13046 if (!IsOrdered && LHSType->isBlockPointerType() &&
13047 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13048 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13049 CK: CK_BlockPointerToObjCPointerCast);
13050 return computeResultTy();
13051 } else if (!IsOrdered &&
13052 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13053 RHSType->isBlockPointerType()) {
13054 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13055 CK: CK_BlockPointerToObjCPointerCast);
13056 return computeResultTy();
13057 }
13058 }
13059 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13060 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13061 unsigned DiagID = 0;
13062 bool isError = false;
13063 if (LangOpts.DebuggerSupport) {
13064 // Under a debugger, allow the comparison of pointers to integers,
13065 // since users tend to want to compare addresses.
13066 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13067 (RHSIsNull && RHSType->isIntegerType())) {
13068 if (IsOrdered) {
13069 isError = getLangOpts().CPlusPlus;
13070 DiagID =
13071 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13072 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13073 }
13074 } else if (getLangOpts().CPlusPlus) {
13075 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13076 isError = true;
13077 } else if (IsOrdered)
13078 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13079 else
13080 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13081
13082 if (DiagID) {
13083 Diag(Loc, DiagID)
13084 << LHSType << RHSType << LHS.get()->getSourceRange()
13085 << RHS.get()->getSourceRange();
13086 if (isError)
13087 return QualType();
13088 }
13089
13090 if (LHSType->isIntegerType())
13091 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13092 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13093 else
13094 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13095 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13096 return computeResultTy();
13097 }
13098
13099 // Handle block pointers.
13100 if (!IsOrdered && RHSIsNull
13101 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13102 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13103 return computeResultTy();
13104 }
13105 if (!IsOrdered && LHSIsNull
13106 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13107 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13108 return computeResultTy();
13109 }
13110
13111 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13112 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13113 return computeResultTy();
13114 }
13115
13116 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13117 return computeResultTy();
13118 }
13119
13120 if (LHSIsNull && RHSType->isQueueT()) {
13121 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13122 return computeResultTy();
13123 }
13124
13125 if (LHSType->isQueueT() && RHSIsNull) {
13126 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13127 return computeResultTy();
13128 }
13129 }
13130
13131 return InvalidOperands(Loc, LHS, RHS);
13132}
13133
13134QualType Sema::GetSignedVectorType(QualType V) {
13135 const VectorType *VTy = V->castAs<VectorType>();
13136 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13137
13138 if (isa<ExtVectorType>(Val: VTy)) {
13139 if (VTy->isExtVectorBoolType())
13140 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13141 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13142 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13143 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13144 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13145 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13146 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13147 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13148 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13149 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13150 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13151 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13152 "Unhandled vector element size in vector compare");
13153 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13154 }
13155
13156 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13157 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13158 VecKind: VectorKind::Generic);
13159 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13160 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13161 VecKind: VectorKind::Generic);
13162 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13163 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13164 VecKind: VectorKind::Generic);
13165 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13166 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13167 VecKind: VectorKind::Generic);
13168 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13169 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13170 VecKind: VectorKind::Generic);
13171 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13172 "Unhandled vector element size in vector compare");
13173 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13174 VecKind: VectorKind::Generic);
13175}
13176
13177QualType Sema::GetSignedSizelessVectorType(QualType V) {
13178 const BuiltinType *VTy = V->castAs<BuiltinType>();
13179 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13180
13181 const QualType ETy = V->getSveEltType(Ctx: Context);
13182 const auto TypeSize = Context.getTypeSize(T: ETy);
13183
13184 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13185 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13186 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13187}
13188
13189QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13190 SourceLocation Loc,
13191 BinaryOperatorKind Opc) {
13192 if (Opc == BO_Cmp) {
13193 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13194 return QualType();
13195 }
13196
13197 // Check to make sure we're operating on vectors of the same type and width,
13198 // Allowing one side to be a scalar of element type.
13199 QualType vType =
13200 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13201 /*AllowBothBool*/ true,
13202 /*AllowBoolConversions*/ getLangOpts().ZVector,
13203 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13204 /*ReportInvalid*/ true);
13205 if (vType.isNull())
13206 return vType;
13207
13208 QualType LHSType = LHS.get()->getType();
13209
13210 // Determine the return type of a vector compare. By default clang will return
13211 // a scalar for all vector compares except vector bool and vector pixel.
13212 // With the gcc compiler we will always return a vector type and with the xl
13213 // compiler we will always return a scalar type. This switch allows choosing
13214 // which behavior is prefered.
13215 if (getLangOpts().AltiVec) {
13216 switch (getLangOpts().getAltivecSrcCompat()) {
13217 case LangOptions::AltivecSrcCompatKind::Mixed:
13218 // If AltiVec, the comparison results in a numeric type, i.e.
13219 // bool for C++, int for C
13220 if (vType->castAs<VectorType>()->getVectorKind() ==
13221 VectorKind::AltiVecVector)
13222 return Context.getLogicalOperationType();
13223 else
13224 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13225 break;
13226 case LangOptions::AltivecSrcCompatKind::GCC:
13227 // For GCC we always return the vector type.
13228 break;
13229 case LangOptions::AltivecSrcCompatKind::XL:
13230 return Context.getLogicalOperationType();
13231 break;
13232 }
13233 }
13234
13235 // For non-floating point types, check for self-comparisons of the form
13236 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13237 // often indicate logic errors in the program.
13238 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13239
13240 // Check for comparisons of floating point operands using != and ==.
13241 if (LHSType->hasFloatingRepresentation()) {
13242 assert(RHS.get()->getType()->hasFloatingRepresentation());
13243 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13244 }
13245
13246 // Return a signed type for the vector.
13247 return GetSignedVectorType(V: vType);
13248}
13249
13250QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13251 ExprResult &RHS,
13252 SourceLocation Loc,
13253 BinaryOperatorKind Opc) {
13254 if (Opc == BO_Cmp) {
13255 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13256 return QualType();
13257 }
13258
13259 // Check to make sure we're operating on vectors of the same type and width,
13260 // Allowing one side to be a scalar of element type.
13261 QualType vType = CheckSizelessVectorOperands(
13262 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13263
13264 if (vType.isNull())
13265 return vType;
13266
13267 QualType LHSType = LHS.get()->getType();
13268
13269 // For non-floating point types, check for self-comparisons of the form
13270 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13271 // often indicate logic errors in the program.
13272 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13273
13274 // Check for comparisons of floating point operands using != and ==.
13275 if (LHSType->hasFloatingRepresentation()) {
13276 assert(RHS.get()->getType()->hasFloatingRepresentation());
13277 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13278 }
13279
13280 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13281 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13282
13283 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13284 RHSBuiltinTy->isSVEBool())
13285 return LHSType;
13286
13287 // Return a signed type for the vector.
13288 return GetSignedSizelessVectorType(V: vType);
13289}
13290
13291static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13292 const ExprResult &XorRHS,
13293 const SourceLocation Loc) {
13294 // Do not diagnose macros.
13295 if (Loc.isMacroID())
13296 return;
13297
13298 // Do not diagnose if both LHS and RHS are macros.
13299 if (XorLHS.get()->getExprLoc().isMacroID() &&
13300 XorRHS.get()->getExprLoc().isMacroID())
13301 return;
13302
13303 bool Negative = false;
13304 bool ExplicitPlus = false;
13305 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13306 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13307
13308 if (!LHSInt)
13309 return;
13310 if (!RHSInt) {
13311 // Check negative literals.
13312 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13313 UnaryOperatorKind Opc = UO->getOpcode();
13314 if (Opc != UO_Minus && Opc != UO_Plus)
13315 return;
13316 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13317 if (!RHSInt)
13318 return;
13319 Negative = (Opc == UO_Minus);
13320 ExplicitPlus = !Negative;
13321 } else {
13322 return;
13323 }
13324 }
13325
13326 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13327 llvm::APInt RightSideValue = RHSInt->getValue();
13328 if (LeftSideValue != 2 && LeftSideValue != 10)
13329 return;
13330
13331 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13332 return;
13333
13334 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13335 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13336 llvm::StringRef ExprStr =
13337 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13338
13339 CharSourceRange XorRange =
13340 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13341 llvm::StringRef XorStr =
13342 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13343 // Do not diagnose if xor keyword/macro is used.
13344 if (XorStr == "xor")
13345 return;
13346
13347 std::string LHSStr = std::string(Lexer::getSourceText(
13348 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13349 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13350 std::string RHSStr = std::string(Lexer::getSourceText(
13351 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13352 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13353
13354 if (Negative) {
13355 RightSideValue = -RightSideValue;
13356 RHSStr = "-" + RHSStr;
13357 } else if (ExplicitPlus) {
13358 RHSStr = "+" + RHSStr;
13359 }
13360
13361 StringRef LHSStrRef = LHSStr;
13362 StringRef RHSStrRef = RHSStr;
13363 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13364 // literals.
13365 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13366 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13367 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13368 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13369 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13370 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13371 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13372 return;
13373
13374 bool SuggestXor =
13375 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13376 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13377 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13378 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13379 std::string SuggestedExpr = "1 << " + RHSStr;
13380 bool Overflow = false;
13381 llvm::APInt One = (LeftSideValue - 1);
13382 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13383 if (Overflow) {
13384 if (RightSideIntValue < 64)
13385 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13386 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13387 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13388 else if (RightSideIntValue == 64)
13389 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13390 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13391 else
13392 return;
13393 } else {
13394 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13395 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13396 << toString(I: PowValue, Radix: 10, Signed: true)
13397 << FixItHint::CreateReplacement(
13398 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13399 }
13400
13401 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13402 << ("0x2 ^ " + RHSStr) << SuggestXor;
13403 } else if (LeftSideValue == 10) {
13404 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13405 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13406 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13407 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13408 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13409 << ("0xA ^ " + RHSStr) << SuggestXor;
13410 }
13411}
13412
13413QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13414 SourceLocation Loc,
13415 BinaryOperatorKind Opc) {
13416 // Ensure that either both operands are of the same vector type, or
13417 // one operand is of a vector type and the other is of its element type.
13418 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13419 /*AllowBothBool*/ true,
13420 /*AllowBoolConversions*/ false,
13421 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13422 /*ReportInvalid*/ false);
13423 if (vType.isNull())
13424 return InvalidOperands(Loc, LHS, RHS);
13425 if (getLangOpts().OpenCL &&
13426 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13427 vType->hasFloatingRepresentation())
13428 return InvalidOperands(Loc, LHS, RHS);
13429 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13430 // usage of the logical operators && and || with vectors in C. This
13431 // check could be notionally dropped.
13432 if (!getLangOpts().CPlusPlus &&
13433 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13434 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13435 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13436 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13437 // `select` functions.
13438 if (getLangOpts().HLSL &&
13439 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13440 (void)InvalidOperands(Loc, LHS, RHS);
13441 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13442 return QualType();
13443 }
13444
13445 return GetSignedVectorType(V: LHS.get()->getType());
13446}
13447
13448QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13449 SourceLocation Loc,
13450 BinaryOperatorKind Opc) {
13451
13452 if (!getLangOpts().HLSL) {
13453 assert(false && "Logical operands are not supported in C\\C++");
13454 return QualType();
13455 }
13456
13457 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13458 (void)InvalidOperands(Loc, LHS, RHS);
13459 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13460 return QualType();
13461 }
13462 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13463 << getLangOpts().getHLSLVersion();
13464 return QualType();
13465}
13466
13467QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13468 SourceLocation Loc,
13469 bool IsCompAssign) {
13470 if (!IsCompAssign) {
13471 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13472 if (LHS.isInvalid())
13473 return QualType();
13474 }
13475 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13476 if (RHS.isInvalid())
13477 return QualType();
13478
13479 // For conversion purposes, we ignore any qualifiers.
13480 // For example, "const float" and "float" are equivalent.
13481 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13482 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13483
13484 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13485 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13486 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13487
13488 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13489 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13490
13491 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13492 // case we have to return InvalidOperands.
13493 ExprResult OriginalLHS = LHS;
13494 ExprResult OriginalRHS = RHS;
13495 if (LHSMatType && !RHSMatType) {
13496 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13497 if (!RHS.isInvalid())
13498 return LHSType;
13499
13500 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13501 }
13502
13503 if (!LHSMatType && RHSMatType) {
13504 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13505 if (!LHS.isInvalid())
13506 return RHSType;
13507 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13508 }
13509
13510 return InvalidOperands(Loc, LHS, RHS);
13511}
13512
13513QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13514 SourceLocation Loc,
13515 bool IsCompAssign) {
13516 if (!IsCompAssign) {
13517 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13518 if (LHS.isInvalid())
13519 return QualType();
13520 }
13521 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13522 if (RHS.isInvalid())
13523 return QualType();
13524
13525 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13526 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13527 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13528
13529 if (LHSMatType && RHSMatType) {
13530 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13531 return InvalidOperands(Loc, LHS, RHS);
13532
13533 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13534 return Context.getCommonSugaredType(
13535 X: LHS.get()->getType().getUnqualifiedType(),
13536 Y: RHS.get()->getType().getUnqualifiedType());
13537
13538 QualType LHSELTy = LHSMatType->getElementType(),
13539 RHSELTy = RHSMatType->getElementType();
13540 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13541 return InvalidOperands(Loc, LHS, RHS);
13542
13543 return Context.getConstantMatrixType(
13544 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13545 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13546 }
13547 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13548}
13549
13550static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13551 switch (Opc) {
13552 default:
13553 return false;
13554 case BO_And:
13555 case BO_AndAssign:
13556 case BO_Or:
13557 case BO_OrAssign:
13558 case BO_Xor:
13559 case BO_XorAssign:
13560 return true;
13561 }
13562}
13563
13564inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13565 SourceLocation Loc,
13566 BinaryOperatorKind Opc) {
13567 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13568
13569 bool IsCompAssign =
13570 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13571
13572 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13573
13574 if (LHS.get()->getType()->isVectorType() ||
13575 RHS.get()->getType()->isVectorType()) {
13576 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13577 RHS.get()->getType()->hasIntegerRepresentation())
13578 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13579 /*AllowBothBool*/ true,
13580 /*AllowBoolConversions*/ getLangOpts().ZVector,
13581 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13582 /*ReportInvalid*/ true);
13583 return InvalidOperands(Loc, LHS, RHS);
13584 }
13585
13586 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13587 RHS.get()->getType()->isSveVLSBuiltinType()) {
13588 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13589 RHS.get()->getType()->hasIntegerRepresentation())
13590 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13591 OperationKind: ArithConvKind::BitwiseOp);
13592 return InvalidOperands(Loc, LHS, RHS);
13593 }
13594
13595 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13596 RHS.get()->getType()->isSveVLSBuiltinType()) {
13597 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13598 RHS.get()->getType()->hasIntegerRepresentation())
13599 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13600 OperationKind: ArithConvKind::BitwiseOp);
13601 return InvalidOperands(Loc, LHS, RHS);
13602 }
13603
13604 if (Opc == BO_And)
13605 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13606
13607 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13608 RHS.get()->getType()->hasFloatingRepresentation())
13609 return InvalidOperands(Loc, LHS, RHS);
13610
13611 ExprResult LHSResult = LHS, RHSResult = RHS;
13612 QualType compType = UsualArithmeticConversions(
13613 LHS&: LHSResult, RHS&: RHSResult, Loc,
13614 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13615 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13616 return QualType();
13617 LHS = LHSResult.get();
13618 RHS = RHSResult.get();
13619
13620 if (Opc == BO_Xor)
13621 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13622
13623 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13624 return compType;
13625 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13626 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13627 return ResultTy;
13628}
13629
13630// C99 6.5.[13,14]
13631inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13632 SourceLocation Loc,
13633 BinaryOperatorKind Opc) {
13634 // Check vector operands differently.
13635 if (LHS.get()->getType()->isVectorType() ||
13636 RHS.get()->getType()->isVectorType())
13637 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13638
13639 if (LHS.get()->getType()->isConstantMatrixType() ||
13640 RHS.get()->getType()->isConstantMatrixType())
13641 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13642
13643 bool EnumConstantInBoolContext = false;
13644 for (const ExprResult &HS : {LHS, RHS}) {
13645 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13646 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13647 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13648 EnumConstantInBoolContext = true;
13649 }
13650 }
13651
13652 if (EnumConstantInBoolContext)
13653 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13654
13655 // WebAssembly tables can't be used with logical operators.
13656 QualType LHSTy = LHS.get()->getType();
13657 QualType RHSTy = RHS.get()->getType();
13658 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13659 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13660 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13661 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13662 return InvalidOperands(Loc, LHS, RHS);
13663 }
13664
13665 // Diagnose cases where the user write a logical and/or but probably meant a
13666 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13667 // is a constant.
13668 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13669 !LHS.get()->getType()->isBooleanType() &&
13670 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13671 // Don't warn in macros or template instantiations.
13672 !Loc.isMacroID() && !inTemplateInstantiation()) {
13673 // If the RHS can be constant folded, and if it constant folds to something
13674 // that isn't 0 or 1 (which indicate a potential logical operation that
13675 // happened to fold to true/false) then warn.
13676 // Parens on the RHS are ignored.
13677 Expr::EvalResult EVResult;
13678 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
13679 llvm::APSInt Result = EVResult.Val.getInt();
13680 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13681 !RHS.get()->getExprLoc().isMacroID()) ||
13682 (Result != 0 && Result != 1)) {
13683 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
13684 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13685 // Suggest replacing the logical operator with the bitwise version
13686 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
13687 << (Opc == BO_LAnd ? "&" : "|")
13688 << FixItHint::CreateReplacement(
13689 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
13690 Code: Opc == BO_LAnd ? "&" : "|");
13691 if (Opc == BO_LAnd)
13692 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13693 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
13694 << FixItHint::CreateRemoval(
13695 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
13696 RHS.get()->getEndLoc()));
13697 }
13698 }
13699 }
13700
13701 if (!Context.getLangOpts().CPlusPlus) {
13702 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13703 // not operate on the built-in scalar and vector float types.
13704 if (Context.getLangOpts().OpenCL &&
13705 Context.getLangOpts().OpenCLVersion < 120) {
13706 if (LHS.get()->getType()->isFloatingType() ||
13707 RHS.get()->getType()->isFloatingType())
13708 return InvalidOperands(Loc, LHS, RHS);
13709 }
13710
13711 LHS = UsualUnaryConversions(E: LHS.get());
13712 if (LHS.isInvalid())
13713 return QualType();
13714
13715 RHS = UsualUnaryConversions(E: RHS.get());
13716 if (RHS.isInvalid())
13717 return QualType();
13718
13719 if (!LHS.get()->getType()->isScalarType() ||
13720 !RHS.get()->getType()->isScalarType())
13721 return InvalidOperands(Loc, LHS, RHS);
13722
13723 return Context.IntTy;
13724 }
13725
13726 // The following is safe because we only use this method for
13727 // non-overloadable operands.
13728
13729 // C++ [expr.log.and]p1
13730 // C++ [expr.log.or]p1
13731 // The operands are both contextually converted to type bool.
13732 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
13733 if (LHSRes.isInvalid()) {
13734 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13735 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13736 return ResultTy;
13737 }
13738 LHS = LHSRes;
13739
13740 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
13741 if (RHSRes.isInvalid()) {
13742 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13743 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13744 return ResultTy;
13745 }
13746 RHS = RHSRes;
13747
13748 // C++ [expr.log.and]p2
13749 // C++ [expr.log.or]p2
13750 // The result is a bool.
13751 return Context.BoolTy;
13752}
13753
13754static bool IsReadonlyMessage(Expr *E, Sema &S) {
13755 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
13756 if (!ME) return false;
13757 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
13758 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13759 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13760 if (!Base) return false;
13761 return Base->getMethodDecl() != nullptr;
13762}
13763
13764/// Is the given expression (which must be 'const') a reference to a
13765/// variable which was originally non-const, but which has become
13766/// 'const' due to being captured within a block?
13767enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13768static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13769 assert(E->isLValue() && E->getType().isConstQualified());
13770 E = E->IgnoreParens();
13771
13772 // Must be a reference to a declaration from an enclosing scope.
13773 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
13774 if (!DRE) return NCCK_None;
13775 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13776
13777 ValueDecl *Value = dyn_cast<ValueDecl>(Val: DRE->getDecl());
13778
13779 // The declaration must be a value which is not declared 'const'.
13780 if (!Value || Value->getType().isConstQualified())
13781 return NCCK_None;
13782
13783 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
13784 if (Binding) {
13785 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13786 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13787 return NCCK_Lambda;
13788 }
13789
13790 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
13791 if (!Var)
13792 return NCCK_None;
13793 if (Var->getType()->isReferenceType())
13794 return NCCK_None;
13795
13796 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13797
13798 // Decide whether the first capture was for a block or a lambda.
13799 DeclContext *DC = S.CurContext, *Prev = nullptr;
13800 // Decide whether the first capture was for a block or a lambda.
13801 while (DC) {
13802 // For init-capture, it is possible that the variable belongs to the
13803 // template pattern of the current context.
13804 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
13805 if (Var->isInitCapture() &&
13806 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13807 break;
13808 if (DC == Var->getDeclContext())
13809 break;
13810 Prev = DC;
13811 DC = DC->getParent();
13812 }
13813 // Unless we have an init-capture, we've gone one step too far.
13814 if (!Var->isInitCapture())
13815 DC = Prev;
13816 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
13817}
13818
13819static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13820 Ty = Ty.getNonReferenceType();
13821 if (IsDereference && Ty->isPointerType())
13822 Ty = Ty->getPointeeType();
13823 return !Ty.isConstQualified();
13824}
13825
13826// Update err_typecheck_assign_const and note_typecheck_assign_const
13827// when this enum is changed.
13828enum {
13829 ConstFunction,
13830 ConstVariable,
13831 ConstMember,
13832 ConstMethod,
13833 NestedConstMember,
13834 ConstUnknown, // Keep as last element
13835};
13836
13837/// Emit the "read-only variable not assignable" error and print notes to give
13838/// more information about why the variable is not assignable, such as pointing
13839/// to the declaration of a const variable, showing that a method is const, or
13840/// that the function is returning a const reference.
13841static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13842 SourceLocation Loc) {
13843 SourceRange ExprRange = E->getSourceRange();
13844
13845 // Only emit one error on the first const found. All other consts will emit
13846 // a note to the error.
13847 bool DiagnosticEmitted = false;
13848
13849 // Track if the current expression is the result of a dereference, and if the
13850 // next checked expression is the result of a dereference.
13851 bool IsDereference = false;
13852 bool NextIsDereference = false;
13853
13854 // Loop to process MemberExpr chains.
13855 while (true) {
13856 IsDereference = NextIsDereference;
13857
13858 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13859 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
13860 NextIsDereference = ME->isArrow();
13861 const ValueDecl *VD = ME->getMemberDecl();
13862 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
13863 // Mutable fields can be modified even if the class is const.
13864 if (Field->isMutable()) {
13865 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13866 break;
13867 }
13868
13869 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
13870 if (!DiagnosticEmitted) {
13871 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
13872 << ExprRange << ConstMember << false /*static*/ << Field
13873 << Field->getType();
13874 DiagnosticEmitted = true;
13875 }
13876 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
13877 << ConstMember << false /*static*/ << Field << Field->getType()
13878 << Field->getSourceRange();
13879 }
13880 E = ME->getBase();
13881 continue;
13882 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
13883 if (VDecl->getType().isConstQualified()) {
13884 if (!DiagnosticEmitted) {
13885 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
13886 << ExprRange << ConstMember << true /*static*/ << VDecl
13887 << VDecl->getType();
13888 DiagnosticEmitted = true;
13889 }
13890 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
13891 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13892 << VDecl->getSourceRange();
13893 }
13894 // Static fields do not inherit constness from parents.
13895 break;
13896 }
13897 break; // End MemberExpr
13898 } else if (const ArraySubscriptExpr *ASE =
13899 dyn_cast<ArraySubscriptExpr>(Val: E)) {
13900 E = ASE->getBase()->IgnoreParenImpCasts();
13901 continue;
13902 } else if (const ExtVectorElementExpr *EVE =
13903 dyn_cast<ExtVectorElementExpr>(Val: E)) {
13904 E = EVE->getBase()->IgnoreParenImpCasts();
13905 continue;
13906 }
13907 break;
13908 }
13909
13910 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
13911 // Function calls
13912 const FunctionDecl *FD = CE->getDirectCallee();
13913 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
13914 if (!DiagnosticEmitted) {
13915 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
13916 << ConstFunction << FD;
13917 DiagnosticEmitted = true;
13918 }
13919 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
13920 DiagID: diag::note_typecheck_assign_const)
13921 << ConstFunction << FD << FD->getReturnType()
13922 << FD->getReturnTypeSourceRange();
13923 }
13924 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13925 // Point to variable declaration.
13926 if (const ValueDecl *VD = DRE->getDecl()) {
13927 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
13928 if (!DiagnosticEmitted) {
13929 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
13930 << ExprRange << ConstVariable << VD << VD->getType();
13931 DiagnosticEmitted = true;
13932 }
13933 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
13934 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13935 }
13936 }
13937 } else if (isa<CXXThisExpr>(Val: E)) {
13938 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13939 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
13940 if (MD->isConst()) {
13941 if (!DiagnosticEmitted) {
13942 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
13943 << ConstMethod << MD;
13944 DiagnosticEmitted = true;
13945 }
13946 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const)
13947 << ConstMethod << MD << MD->getSourceRange();
13948 }
13949 }
13950 }
13951 }
13952
13953 if (DiagnosticEmitted)
13954 return;
13955
13956 // Can't determine a more specific message, so display the generic error.
13957 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13958}
13959
13960enum OriginalExprKind {
13961 OEK_Variable,
13962 OEK_Member,
13963 OEK_LValue
13964};
13965
13966static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13967 const RecordType *Ty,
13968 SourceLocation Loc, SourceRange Range,
13969 OriginalExprKind OEK,
13970 bool &DiagnosticEmitted) {
13971 std::vector<const RecordType *> RecordTypeList;
13972 RecordTypeList.push_back(x: Ty);
13973 unsigned NextToCheckIndex = 0;
13974 // We walk the record hierarchy breadth-first to ensure that we print
13975 // diagnostics in field nesting order.
13976 while (RecordTypeList.size() > NextToCheckIndex) {
13977 bool IsNested = NextToCheckIndex > 0;
13978 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
13979 ->getDecl()
13980 ->getDefinitionOrSelf()
13981 ->fields()) {
13982 // First, check every field for constness.
13983 QualType FieldTy = Field->getType();
13984 if (FieldTy.isConstQualified()) {
13985 if (!DiagnosticEmitted) {
13986 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
13987 << Range << NestedConstMember << OEK << VD
13988 << IsNested << Field;
13989 DiagnosticEmitted = true;
13990 }
13991 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
13992 << NestedConstMember << IsNested << Field
13993 << FieldTy << Field->getSourceRange();
13994 }
13995
13996 // Then we append it to the list to check next in order.
13997 FieldTy = FieldTy.getCanonicalType();
13998 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
13999 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14000 RecordTypeList.push_back(x: FieldRecTy);
14001 }
14002 }
14003 ++NextToCheckIndex;
14004 }
14005}
14006
14007/// Emit an error for the case where a record we are trying to assign to has a
14008/// const-qualified field somewhere in its hierarchy.
14009static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14010 SourceLocation Loc) {
14011 QualType Ty = E->getType();
14012 assert(Ty->isRecordType() && "lvalue was not record?");
14013 SourceRange Range = E->getSourceRange();
14014 const auto *RTy = Ty->getAsCanonical<RecordType>();
14015 bool DiagEmitted = false;
14016
14017 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14018 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14019 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14020 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14021 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14022 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14023 else
14024 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14025 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14026 if (!DiagEmitted)
14027 DiagnoseConstAssignment(S, E, Loc);
14028}
14029
14030/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14031/// emit an error and return true. If so, return false.
14032static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14033 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14034
14035 S.CheckShadowingDeclModification(E, Loc);
14036
14037 SourceLocation OrigLoc = Loc;
14038 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14039 Loc: &Loc);
14040 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14041 IsLV = Expr::MLV_InvalidMessageExpression;
14042 if (IsLV == Expr::MLV_Valid)
14043 return false;
14044
14045 unsigned DiagID = 0;
14046 bool NeedType = false;
14047 switch (IsLV) { // C99 6.5.16p2
14048 case Expr::MLV_ConstQualified:
14049 // Use a specialized diagnostic when we're assigning to an object
14050 // from an enclosing function or block.
14051 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14052 if (NCCK == NCCK_Block)
14053 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14054 else
14055 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14056 break;
14057 }
14058
14059 // In ARC, use some specialized diagnostics for occasions where we
14060 // infer 'const'. These are always pseudo-strong variables.
14061 if (S.getLangOpts().ObjCAutoRefCount) {
14062 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14063 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14064 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14065
14066 // Use the normal diagnostic if it's pseudo-__strong but the
14067 // user actually wrote 'const'.
14068 if (var->isARCPseudoStrong() &&
14069 (!var->getTypeSourceInfo() ||
14070 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14071 // There are three pseudo-strong cases:
14072 // - self
14073 ObjCMethodDecl *method = S.getCurMethodDecl();
14074 if (method && var == method->getSelfDecl()) {
14075 DiagID = method->isClassMethod()
14076 ? diag::err_typecheck_arc_assign_self_class_method
14077 : diag::err_typecheck_arc_assign_self;
14078
14079 // - Objective-C externally_retained attribute.
14080 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14081 isa<ParmVarDecl>(Val: var)) {
14082 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14083
14084 // - fast enumeration variables
14085 } else {
14086 DiagID = diag::err_typecheck_arr_assign_enumeration;
14087 }
14088
14089 SourceRange Assign;
14090 if (Loc != OrigLoc)
14091 Assign = SourceRange(OrigLoc, OrigLoc);
14092 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14093 // We need to preserve the AST regardless, so migration tool
14094 // can do its job.
14095 return false;
14096 }
14097 }
14098 }
14099
14100 // If none of the special cases above are triggered, then this is a
14101 // simple const assignment.
14102 if (DiagID == 0) {
14103 DiagnoseConstAssignment(S, E, Loc);
14104 return true;
14105 }
14106
14107 break;
14108 case Expr::MLV_ConstAddrSpace:
14109 DiagnoseConstAssignment(S, E, Loc);
14110 return true;
14111 case Expr::MLV_ConstQualifiedField:
14112 DiagnoseRecursiveConstFields(S, E, Loc);
14113 return true;
14114 case Expr::MLV_ArrayType:
14115 case Expr::MLV_ArrayTemporary:
14116 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14117 NeedType = true;
14118 break;
14119 case Expr::MLV_NotObjectType:
14120 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14121 NeedType = true;
14122 break;
14123 case Expr::MLV_LValueCast:
14124 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14125 break;
14126 case Expr::MLV_Valid:
14127 llvm_unreachable("did not take early return for MLV_Valid");
14128 case Expr::MLV_InvalidExpression:
14129 case Expr::MLV_MemberFunction:
14130 case Expr::MLV_ClassTemporary:
14131 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14132 break;
14133 case Expr::MLV_IncompleteType:
14134 case Expr::MLV_IncompleteVoidType:
14135 return S.RequireCompleteType(Loc, T: E->getType(),
14136 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14137 case Expr::MLV_DuplicateVectorComponents:
14138 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14139 break;
14140 case Expr::MLV_NoSetterProperty:
14141 llvm_unreachable("readonly properties should be processed differently");
14142 case Expr::MLV_InvalidMessageExpression:
14143 DiagID = diag::err_readonly_message_assignment;
14144 break;
14145 case Expr::MLV_SubObjCPropertySetting:
14146 DiagID = diag::err_no_subobject_property_setting;
14147 break;
14148 }
14149
14150 SourceRange Assign;
14151 if (Loc != OrigLoc)
14152 Assign = SourceRange(OrigLoc, OrigLoc);
14153 if (NeedType)
14154 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14155 else
14156 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14157 return true;
14158}
14159
14160static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14161 SourceLocation Loc,
14162 Sema &Sema) {
14163 if (Sema.inTemplateInstantiation())
14164 return;
14165 if (Sema.isUnevaluatedContext())
14166 return;
14167 if (Loc.isInvalid() || Loc.isMacroID())
14168 return;
14169 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14170 return;
14171
14172 // C / C++ fields
14173 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14174 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14175 if (ML && MR) {
14176 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14177 return;
14178 const ValueDecl *LHSDecl =
14179 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14180 const ValueDecl *RHSDecl =
14181 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14182 if (LHSDecl != RHSDecl)
14183 return;
14184 if (LHSDecl->getType().isVolatileQualified())
14185 return;
14186 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14187 if (RefTy->getPointeeType().isVolatileQualified())
14188 return;
14189
14190 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14191 }
14192
14193 // Objective-C instance variables
14194 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14195 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14196 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14197 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14198 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14199 if (RL && RR && RL->getDecl() == RR->getDecl())
14200 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14201 }
14202}
14203
14204// C99 6.5.16.1
14205QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14206 SourceLocation Loc,
14207 QualType CompoundType,
14208 BinaryOperatorKind Opc) {
14209 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14210
14211 // Verify that LHS is a modifiable lvalue, and emit error if not.
14212 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14213 return QualType();
14214
14215 QualType LHSType = LHSExpr->getType();
14216 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14217 CompoundType;
14218
14219 if (RHS.isUsable()) {
14220 // Even if this check fails don't return early to allow the best
14221 // possible error recovery and to allow any subsequent diagnostics to
14222 // work.
14223 const ValueDecl *Assignee = nullptr;
14224 bool ShowFullyQualifiedAssigneeName = false;
14225 // In simple cases describe what is being assigned to
14226 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14227 Assignee = DR->getDecl();
14228 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14229 Assignee = ME->getMemberDecl();
14230 ShowFullyQualifiedAssigneeName = true;
14231 }
14232
14233 BoundsSafetyCheckAssignmentToCountAttrPtr(
14234 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14235 ShowFullyQualifiedAssigneeName);
14236 }
14237
14238 // OpenCL v1.2 s6.1.1.1 p2:
14239 // The half data type can only be used to declare a pointer to a buffer that
14240 // contains half values
14241 if (getLangOpts().OpenCL &&
14242 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14243 LHSType->isHalfType()) {
14244 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14245 << LHSType.getUnqualifiedType();
14246 return QualType();
14247 }
14248
14249 // WebAssembly tables can't be used on RHS of an assignment expression.
14250 if (RHSType->isWebAssemblyTableType()) {
14251 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14252 return QualType();
14253 }
14254
14255 AssignConvertType ConvTy;
14256 if (CompoundType.isNull()) {
14257 Expr *RHSCheck = RHS.get();
14258
14259 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14260
14261 QualType LHSTy(LHSType);
14262 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14263 if (RHS.isInvalid())
14264 return QualType();
14265 // Special case of NSObject attributes on c-style pointer types.
14266 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14267 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14268 RHSType->isObjCObjectPointerType()) ||
14269 (Context.isObjCNSObjectType(Ty: RHSType) &&
14270 LHSType->isObjCObjectPointerType())))
14271 ConvTy = AssignConvertType::Compatible;
14272
14273 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14274 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14275
14276 // If the RHS is a unary plus or minus, check to see if they = and + are
14277 // right next to each other. If so, the user may have typo'd "x =+ 4"
14278 // instead of "x += 4".
14279 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14280 RHSCheck = ICE->getSubExpr();
14281 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14282 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14283 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14284 // Only if the two operators are exactly adjacent.
14285 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14286 // And there is a space or other character before the subexpr of the
14287 // unary +/-. We don't want to warn on "x=-1".
14288 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14289 UO->getSubExpr()->getBeginLoc().isFileID()) {
14290 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14291 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14292 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14293 }
14294 }
14295
14296 if (IsAssignConvertCompatible(ConvTy)) {
14297 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14298 // Warn about retain cycles where a block captures the LHS, but
14299 // not if the LHS is a simple variable into which the block is
14300 // being stored...unless that variable can be captured by reference!
14301 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14302 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14303 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14304 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14305 }
14306
14307 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14308 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14309 // It is safe to assign a weak reference into a strong variable.
14310 // Although this code can still have problems:
14311 // id x = self.weakProp;
14312 // id y = self.weakProp;
14313 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14314 // paths through the function. This should be revisited if
14315 // -Wrepeated-use-of-weak is made flow-sensitive.
14316 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14317 // variable, which will be valid for the current autorelease scope.
14318 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14319 Loc: RHS.get()->getBeginLoc()))
14320 getCurFunction()->markSafeWeakUse(E: RHS.get());
14321
14322 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14323 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14324 }
14325 }
14326 } else {
14327 // Compound assignment "x += y"
14328 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14329 }
14330
14331 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14332 Action: AssignmentAction::Assigning))
14333 return QualType();
14334
14335 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14336
14337 AssignedEntity AE{.LHS: LHSExpr};
14338 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14339
14340 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14341 if (CompoundType.isNull()) {
14342 // C++2a [expr.ass]p5:
14343 // A simple-assignment whose left operand is of a volatile-qualified
14344 // type is deprecated unless the assignment is either a discarded-value
14345 // expression or an unevaluated operand
14346 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14347 }
14348 }
14349
14350 // C11 6.5.16p3: The type of an assignment expression is the type of the
14351 // left operand would have after lvalue conversion.
14352 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14353 // qualified type, the value has the unqualified version of the type of the
14354 // lvalue; additionally, if the lvalue has atomic type, the value has the
14355 // non-atomic version of the type of the lvalue.
14356 // C++ 5.17p1: the type of the assignment expression is that of its left
14357 // operand.
14358 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14359}
14360
14361// Scenarios to ignore if expression E is:
14362// 1. an explicit cast expression into void
14363// 2. a function call expression that returns void
14364static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14365 E = E->IgnoreParens();
14366
14367 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14368 if (CE->getCastKind() == CK_ToVoid) {
14369 return true;
14370 }
14371
14372 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14373 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14374 CE->getSubExpr()->getType()->isDependentType()) {
14375 return true;
14376 }
14377 }
14378
14379 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14380 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14381 return false;
14382}
14383
14384void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14385 // No warnings in macros
14386 if (Loc.isMacroID())
14387 return;
14388
14389 // Don't warn in template instantiations.
14390 if (inTemplateInstantiation())
14391 return;
14392
14393 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14394 // instead, skip more than needed, then call back into here with the
14395 // CommaVisitor in SemaStmt.cpp.
14396 // The listed locations are the initialization and increment portions
14397 // of a for loop. The additional checks are on the condition of
14398 // if statements, do/while loops, and for loops.
14399 // Differences in scope flags for C89 mode requires the extra logic.
14400 const unsigned ForIncrementFlags =
14401 getLangOpts().C99 || getLangOpts().CPlusPlus
14402 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14403 : Scope::ContinueScope | Scope::BreakScope;
14404 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14405 const unsigned ScopeFlags = getCurScope()->getFlags();
14406 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14407 (ScopeFlags & ForInitFlags) == ForInitFlags)
14408 return;
14409
14410 // If there are multiple comma operators used together, get the RHS of the
14411 // of the comma operator as the LHS.
14412 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14413 if (BO->getOpcode() != BO_Comma)
14414 break;
14415 LHS = BO->getRHS();
14416 }
14417
14418 // Only allow some expressions on LHS to not warn.
14419 if (IgnoreCommaOperand(E: LHS, Context))
14420 return;
14421
14422 Diag(Loc, DiagID: diag::warn_comma_operator);
14423 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14424 << LHS->getSourceRange()
14425 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14426 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14427 : "(void)(")
14428 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14429 Code: ")");
14430}
14431
14432// C99 6.5.17
14433static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14434 SourceLocation Loc) {
14435 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14436 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14437 if (LHS.isInvalid() || RHS.isInvalid())
14438 return QualType();
14439
14440 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14441 // operands, but not unary promotions.
14442 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14443
14444 // So we treat the LHS as a ignored value, and in C++ we allow the
14445 // containing site to determine what should be done with the RHS.
14446 LHS = S.IgnoredValueConversions(E: LHS.get());
14447 if (LHS.isInvalid())
14448 return QualType();
14449
14450 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14451
14452 if (!S.getLangOpts().CPlusPlus) {
14453 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14454 if (RHS.isInvalid())
14455 return QualType();
14456 if (!RHS.get()->getType()->isVoidType())
14457 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14458 DiagID: diag::err_incomplete_type);
14459 }
14460
14461 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14462 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14463
14464 return RHS.get()->getType();
14465}
14466
14467/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14468/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14469static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14470 ExprValueKind &VK,
14471 ExprObjectKind &OK,
14472 SourceLocation OpLoc, bool IsInc,
14473 bool IsPrefix) {
14474 QualType ResType = Op->getType();
14475 // Atomic types can be used for increment / decrement where the non-atomic
14476 // versions can, so ignore the _Atomic() specifier for the purpose of
14477 // checking.
14478 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14479 ResType = ResAtomicType->getValueType();
14480
14481 assert(!ResType.isNull() && "no type for increment/decrement expression");
14482
14483 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14484 // Decrement of bool is not allowed.
14485 if (!IsInc) {
14486 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14487 return QualType();
14488 }
14489 // Increment of bool sets it to true, but is deprecated.
14490 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14491 : diag::warn_increment_bool)
14492 << Op->getSourceRange();
14493 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14494 // Error on enum increments and decrements in C++ mode
14495 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14496 return QualType();
14497 } else if (ResType->isRealType()) {
14498 // OK!
14499 } else if (ResType->isPointerType()) {
14500 // C99 6.5.2.4p2, 6.5.6p2
14501 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14502 return QualType();
14503 } else if (ResType->isObjCObjectPointerType()) {
14504 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14505 // Otherwise, we just need a complete type.
14506 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14507 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14508 return QualType();
14509 } else if (ResType->isAnyComplexType()) {
14510 // C99 does not support ++/-- on complex types, we allow as an extension.
14511 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14512 : diag::ext_c2y_increment_complex)
14513 << IsInc << Op->getSourceRange();
14514 } else if (ResType->isPlaceholderType()) {
14515 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14516 if (PR.isInvalid()) return QualType();
14517 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14518 IsInc, IsPrefix);
14519 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14520 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14521 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14522 (ResType->castAs<VectorType>()->getVectorKind() !=
14523 VectorKind::AltiVecBool)) {
14524 // The z vector extensions allow ++ and -- for non-bool vectors.
14525 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14526 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14527 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14528 } else {
14529 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14530 << ResType << int(IsInc) << Op->getSourceRange();
14531 return QualType();
14532 }
14533 // At this point, we know we have a real, complex or pointer type.
14534 // Now make sure the operand is a modifiable lvalue.
14535 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14536 return QualType();
14537 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14538 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14539 // An operand with volatile-qualified type is deprecated
14540 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14541 << IsInc << ResType;
14542 }
14543 // In C++, a prefix increment is the same type as the operand. Otherwise
14544 // (in C or with postfix), the increment is the unqualified type of the
14545 // operand.
14546 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14547 VK = VK_LValue;
14548 OK = Op->getObjectKind();
14549 return ResType;
14550 } else {
14551 VK = VK_PRValue;
14552 return ResType.getUnqualifiedType();
14553 }
14554}
14555
14556/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14557/// This routine allows us to typecheck complex/recursive expressions
14558/// where the declaration is needed for type checking. We only need to
14559/// handle cases when the expression references a function designator
14560/// or is an lvalue. Here are some examples:
14561/// - &(x) => x
14562/// - &*****f => f for f a function designator.
14563/// - &s.xx => s
14564/// - &s.zz[1].yy -> s, if zz is an array
14565/// - *(x + 1) -> x, if x is an array
14566/// - &"123"[2] -> 0
14567/// - & __real__ x -> x
14568///
14569/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14570/// members.
14571static ValueDecl *getPrimaryDecl(Expr *E) {
14572 switch (E->getStmtClass()) {
14573 case Stmt::DeclRefExprClass:
14574 return cast<DeclRefExpr>(Val: E)->getDecl();
14575 case Stmt::MemberExprClass:
14576 // If this is an arrow operator, the address is an offset from
14577 // the base's value, so the object the base refers to is
14578 // irrelevant.
14579 if (cast<MemberExpr>(Val: E)->isArrow())
14580 return nullptr;
14581 // Otherwise, the expression refers to a part of the base
14582 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14583 case Stmt::ArraySubscriptExprClass: {
14584 // FIXME: This code shouldn't be necessary! We should catch the implicit
14585 // promotion of register arrays earlier.
14586 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14587 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14588 if (ICE->getSubExpr()->getType()->isArrayType())
14589 return getPrimaryDecl(E: ICE->getSubExpr());
14590 }
14591 return nullptr;
14592 }
14593 case Stmt::UnaryOperatorClass: {
14594 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14595
14596 switch(UO->getOpcode()) {
14597 case UO_Real:
14598 case UO_Imag:
14599 case UO_Extension:
14600 return getPrimaryDecl(E: UO->getSubExpr());
14601 default:
14602 return nullptr;
14603 }
14604 }
14605 case Stmt::ParenExprClass:
14606 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14607 case Stmt::ImplicitCastExprClass:
14608 // If the result of an implicit cast is an l-value, we care about
14609 // the sub-expression; otherwise, the result here doesn't matter.
14610 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14611 case Stmt::CXXUuidofExprClass:
14612 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14613 default:
14614 return nullptr;
14615 }
14616}
14617
14618namespace {
14619enum {
14620 AO_Bit_Field = 0,
14621 AO_Vector_Element = 1,
14622 AO_Property_Expansion = 2,
14623 AO_Register_Variable = 3,
14624 AO_Matrix_Element = 4,
14625 AO_No_Error = 5
14626};
14627}
14628/// Diagnose invalid operand for address of operations.
14629///
14630/// \param Type The type of operand which cannot have its address taken.
14631static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14632 Expr *E, unsigned Type) {
14633 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14634}
14635
14636bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14637 const Expr *Op,
14638 const CXXMethodDecl *MD) {
14639 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14640
14641 if (Op != DRE)
14642 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14643 << Op->getSourceRange();
14644
14645 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14646 if (isa<CXXDestructorDecl>(Val: MD))
14647 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14648 << DRE->getSourceRange();
14649
14650 if (DRE->getQualifier())
14651 return false;
14652
14653 if (MD->getParent()->getName().empty())
14654 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14655 << DRE->getSourceRange();
14656
14657 SmallString<32> Str;
14658 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14659 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14660 << DRE->getSourceRange()
14661 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14662}
14663
14664QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14665 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14666 if (PTy->getKind() == BuiltinType::Overload) {
14667 Expr *E = OrigOp.get()->IgnoreParens();
14668 if (!isa<OverloadExpr>(Val: E)) {
14669 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14670 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14671 << OrigOp.get()->getSourceRange();
14672 return QualType();
14673 }
14674
14675 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
14676 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14677 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
14678 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14679 << OrigOp.get()->getSourceRange();
14680 return QualType();
14681 }
14682
14683 return Context.OverloadTy;
14684 }
14685
14686 if (PTy->getKind() == BuiltinType::UnknownAny)
14687 return Context.UnknownAnyTy;
14688
14689 if (PTy->getKind() == BuiltinType::BoundMember) {
14690 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14691 << OrigOp.get()->getSourceRange();
14692 return QualType();
14693 }
14694
14695 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
14696 if (OrigOp.isInvalid()) return QualType();
14697 }
14698
14699 if (OrigOp.get()->isTypeDependent())
14700 return Context.DependentTy;
14701
14702 assert(!OrigOp.get()->hasPlaceholderType());
14703
14704 // Make sure to ignore parentheses in subsequent checks
14705 Expr *op = OrigOp.get()->IgnoreParens();
14706
14707 // In OpenCL captures for blocks called as lambda functions
14708 // are located in the private address space. Blocks used in
14709 // enqueue_kernel can be located in a different address space
14710 // depending on a vendor implementation. Thus preventing
14711 // taking an address of the capture to avoid invalid AS casts.
14712 if (LangOpts.OpenCL) {
14713 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
14714 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14715 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
14716 return QualType();
14717 }
14718 }
14719
14720 if (getLangOpts().C99) {
14721 // Implement C99-only parts of addressof rules.
14722 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
14723 if (uOp->getOpcode() == UO_Deref)
14724 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14725 // (assuming the deref expression is valid).
14726 return uOp->getSubExpr()->getType();
14727 }
14728 // Technically, there should be a check for array subscript
14729 // expressions here, but the result of one is always an lvalue anyway.
14730 }
14731 ValueDecl *dcl = getPrimaryDecl(E: op);
14732
14733 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
14734 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14735 Loc: op->getBeginLoc()))
14736 return QualType();
14737
14738 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
14739 unsigned AddressOfError = AO_No_Error;
14740
14741 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14742 bool IsError = isSFINAEContext();
14743 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
14744 : diag::ext_typecheck_addrof_temporary)
14745 << op->getType() << op->getSourceRange();
14746 if (IsError)
14747 return QualType();
14748 // Materialize the temporary as an lvalue so that we can take its address.
14749 OrigOp = op =
14750 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
14751 } else if (isa<ObjCSelectorExpr>(Val: op)) {
14752 return Context.getPointerType(T: op->getType());
14753 } else if (lval == Expr::LV_MemberFunction) {
14754 // If it's an instance method, make a member pointer.
14755 // The expression must have exactly the form &A::foo.
14756
14757 // If the underlying expression isn't a decl ref, give up.
14758 if (!isa<DeclRefExpr>(Val: op)) {
14759 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14760 << OrigOp.get()->getSourceRange();
14761 return QualType();
14762 }
14763 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
14764 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
14765
14766 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14767 QualType MPTy = Context.getMemberPointerType(
14768 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
14769
14770 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14771 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14772 // When pointer authentication is enabled, argument and return types of
14773 // vitual member functions must be complete. This is because vitrual
14774 // member function pointers are implemented using virtual dispatch
14775 // thunks and the thunks cannot be emitted if the argument or return
14776 // types are incomplete.
14777 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14778 SourceLocation DeclRefLoc,
14779 SourceLocation RetArgTypeLoc) {
14780 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
14781 Diag(Loc: DeclRefLoc,
14782 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14783 Diag(Loc: RetArgTypeLoc,
14784 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14785 << T;
14786 return true;
14787 }
14788 return false;
14789 };
14790 QualType RetTy = MD->getReturnType();
14791 bool IsIncomplete =
14792 !RetTy->isVoidType() &&
14793 ReturnOrParamTypeIsIncomplete(
14794 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14795 for (auto *PVD : MD->parameters())
14796 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14797 PVD->getBeginLoc());
14798 if (IsIncomplete)
14799 return QualType();
14800 }
14801
14802 // Under the MS ABI, lock down the inheritance model now.
14803 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14804 (void)isCompleteType(Loc: OpLoc, T: MPTy);
14805 return MPTy;
14806 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14807 // C99 6.5.3.2p1
14808 // The operand must be either an l-value or a function designator
14809 if (!op->getType()->isFunctionType()) {
14810 // Use a special diagnostic for loads from property references.
14811 if (isa<PseudoObjectExpr>(Val: op)) {
14812 AddressOfError = AO_Property_Expansion;
14813 } else {
14814 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
14815 << op->getType() << op->getSourceRange();
14816 return QualType();
14817 }
14818 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
14819 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
14820 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14821 }
14822
14823 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14824 // The operand cannot be a bit-field
14825 AddressOfError = AO_Bit_Field;
14826 } else if (op->getObjectKind() == OK_VectorComponent) {
14827 // The operand cannot be an element of a vector
14828 AddressOfError = AO_Vector_Element;
14829 } else if (op->getObjectKind() == OK_MatrixComponent) {
14830 // The operand cannot be an element of a matrix.
14831 AddressOfError = AO_Matrix_Element;
14832 } else if (dcl) { // C99 6.5.3.2p1
14833 // We have an lvalue with a decl. Make sure the decl is not declared
14834 // with the register storage-class specifier.
14835 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
14836 // in C++ it is not error to take address of a register
14837 // variable (c++03 7.1.1P3)
14838 if (vd->getStorageClass() == SC_Register &&
14839 !getLangOpts().CPlusPlus) {
14840 AddressOfError = AO_Register_Variable;
14841 }
14842 } else if (isa<MSPropertyDecl>(Val: dcl)) {
14843 AddressOfError = AO_Property_Expansion;
14844 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
14845 return Context.OverloadTy;
14846 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
14847 // Okay: we can take the address of a field.
14848 // Could be a pointer to member, though, if there is an explicit
14849 // scope qualifier for the class.
14850
14851 // [C++26] [expr.prim.id.general]
14852 // If an id-expression E denotes a non-static non-type member
14853 // of some class C [...] and if E is a qualified-id, E is
14854 // not the un-parenthesized operand of the unary & operator [...]
14855 // the id-expression is transformed into a class member access expression.
14856 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
14857 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
14858 DeclContext *Ctx = dcl->getDeclContext();
14859 if (Ctx && Ctx->isRecord()) {
14860 if (dcl->getType()->isReferenceType()) {
14861 Diag(Loc: OpLoc,
14862 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
14863 << dcl->getDeclName() << dcl->getType();
14864 return QualType();
14865 }
14866
14867 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
14868 Ctx = Ctx->getParent();
14869
14870 QualType MPTy = Context.getMemberPointerType(
14871 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
14872 // Under the MS ABI, lock down the inheritance model now.
14873 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14874 (void)isCompleteType(Loc: OpLoc, T: MPTy);
14875 return MPTy;
14876 }
14877 }
14878 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
14879 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
14880 UnnamedGlobalConstantDecl>(Val: dcl))
14881 llvm_unreachable("Unknown/unexpected decl type");
14882 }
14883
14884 if (AddressOfError != AO_No_Error) {
14885 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
14886 return QualType();
14887 }
14888
14889 if (lval == Expr::LV_IncompleteVoidType) {
14890 // Taking the address of a void variable is technically illegal, but we
14891 // allow it in cases which are otherwise valid.
14892 // Example: "extern void x; void* y = &x;".
14893 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
14894 }
14895
14896 // If the operand has type "type", the result has type "pointer to type".
14897 if (op->getType()->isObjCObjectType())
14898 return Context.getObjCObjectPointerType(OIT: op->getType());
14899
14900 // Cannot take the address of WebAssembly references or tables.
14901 if (Context.getTargetInfo().getTriple().isWasm()) {
14902 QualType OpTy = op->getType();
14903 if (OpTy.isWebAssemblyReferenceType()) {
14904 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
14905 << 1 << OrigOp.get()->getSourceRange();
14906 return QualType();
14907 }
14908 if (OpTy->isWebAssemblyTableType()) {
14909 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
14910 << 1 << OrigOp.get()->getSourceRange();
14911 return QualType();
14912 }
14913 }
14914
14915 CheckAddressOfPackedMember(rhs: op);
14916
14917 return Context.getPointerType(T: op->getType());
14918}
14919
14920static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14921 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
14922 if (!DRE)
14923 return;
14924 const Decl *D = DRE->getDecl();
14925 if (!D)
14926 return;
14927 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
14928 if (!Param)
14929 return;
14930 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
14931 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14932 return;
14933 if (FunctionScopeInfo *FD = S.getCurFunction())
14934 FD->ModifiedNonNullParams.insert(Ptr: Param);
14935}
14936
14937/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14938static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14939 SourceLocation OpLoc,
14940 bool IsAfterAmp = false) {
14941 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
14942 if (ConvResult.isInvalid())
14943 return QualType();
14944 Op = ConvResult.get();
14945 QualType OpTy = Op->getType();
14946 QualType Result;
14947
14948 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
14949 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14950 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
14951 Range: Op->getSourceRange());
14952 }
14953
14954 if (const PointerType *PT = OpTy->getAs<PointerType>())
14955 {
14956 Result = PT->getPointeeType();
14957 }
14958 else if (const ObjCObjectPointerType *OPT =
14959 OpTy->getAs<ObjCObjectPointerType>())
14960 Result = OPT->getPointeeType();
14961 else {
14962 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14963 if (PR.isInvalid()) return QualType();
14964 if (PR.get() != Op)
14965 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
14966 }
14967
14968 if (Result.isNull()) {
14969 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
14970 << OpTy << Op->getSourceRange();
14971 return QualType();
14972 }
14973
14974 if (Result->isVoidType()) {
14975 // C++ [expr.unary.op]p1:
14976 // [...] the expression to which [the unary * operator] is applied shall
14977 // be a pointer to an object type, or a pointer to a function type
14978 LangOptions LO = S.getLangOpts();
14979 if (LO.CPlusPlus)
14980 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
14981 << OpTy << Op->getSourceRange();
14982 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14983 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
14984 << OpTy << Op->getSourceRange();
14985 }
14986
14987 // Dereferences are usually l-values...
14988 VK = VK_LValue;
14989
14990 // ...except that certain expressions are never l-values in C.
14991 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14992 VK = VK_PRValue;
14993
14994 return Result;
14995}
14996
14997BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14998 BinaryOperatorKind Opc;
14999 switch (Kind) {
15000 default: llvm_unreachable("Unknown binop!");
15001 case tok::periodstar: Opc = BO_PtrMemD; break;
15002 case tok::arrowstar: Opc = BO_PtrMemI; break;
15003 case tok::star: Opc = BO_Mul; break;
15004 case tok::slash: Opc = BO_Div; break;
15005 case tok::percent: Opc = BO_Rem; break;
15006 case tok::plus: Opc = BO_Add; break;
15007 case tok::minus: Opc = BO_Sub; break;
15008 case tok::lessless: Opc = BO_Shl; break;
15009 case tok::greatergreater: Opc = BO_Shr; break;
15010 case tok::lessequal: Opc = BO_LE; break;
15011 case tok::less: Opc = BO_LT; break;
15012 case tok::greaterequal: Opc = BO_GE; break;
15013 case tok::greater: Opc = BO_GT; break;
15014 case tok::exclaimequal: Opc = BO_NE; break;
15015 case tok::equalequal: Opc = BO_EQ; break;
15016 case tok::spaceship: Opc = BO_Cmp; break;
15017 case tok::amp: Opc = BO_And; break;
15018 case tok::caret: Opc = BO_Xor; break;
15019 case tok::pipe: Opc = BO_Or; break;
15020 case tok::ampamp: Opc = BO_LAnd; break;
15021 case tok::pipepipe: Opc = BO_LOr; break;
15022 case tok::equal: Opc = BO_Assign; break;
15023 case tok::starequal: Opc = BO_MulAssign; break;
15024 case tok::slashequal: Opc = BO_DivAssign; break;
15025 case tok::percentequal: Opc = BO_RemAssign; break;
15026 case tok::plusequal: Opc = BO_AddAssign; break;
15027 case tok::minusequal: Opc = BO_SubAssign; break;
15028 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15029 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15030 case tok::ampequal: Opc = BO_AndAssign; break;
15031 case tok::caretequal: Opc = BO_XorAssign; break;
15032 case tok::pipeequal: Opc = BO_OrAssign; break;
15033 case tok::comma: Opc = BO_Comma; break;
15034 }
15035 return Opc;
15036}
15037
15038static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15039 tok::TokenKind Kind) {
15040 UnaryOperatorKind Opc;
15041 switch (Kind) {
15042 default: llvm_unreachable("Unknown unary op!");
15043 case tok::plusplus: Opc = UO_PreInc; break;
15044 case tok::minusminus: Opc = UO_PreDec; break;
15045 case tok::amp: Opc = UO_AddrOf; break;
15046 case tok::star: Opc = UO_Deref; break;
15047 case tok::plus: Opc = UO_Plus; break;
15048 case tok::minus: Opc = UO_Minus; break;
15049 case tok::tilde: Opc = UO_Not; break;
15050 case tok::exclaim: Opc = UO_LNot; break;
15051 case tok::kw___real: Opc = UO_Real; break;
15052 case tok::kw___imag: Opc = UO_Imag; break;
15053 case tok::kw___extension__: Opc = UO_Extension; break;
15054 }
15055 return Opc;
15056}
15057
15058const FieldDecl *
15059Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15060 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15061 // common for setters.
15062 // struct A {
15063 // int X;
15064 // -void setX(int X) { X = X; }
15065 // +void setX(int X) { this->X = X; }
15066 // };
15067
15068 // Only consider parameters for self assignment fixes.
15069 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15070 return nullptr;
15071 const auto *Method =
15072 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15073 if (!Method)
15074 return nullptr;
15075
15076 const CXXRecordDecl *Parent = Method->getParent();
15077 // In theory this is fixable if the lambda explicitly captures this, but
15078 // that's added complexity that's rarely going to be used.
15079 if (Parent->isLambda())
15080 return nullptr;
15081
15082 // FIXME: Use an actual Lookup operation instead of just traversing fields
15083 // in order to get base class fields.
15084 auto Field =
15085 llvm::find_if(Range: Parent->fields(),
15086 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15087 return F->getDeclName() == Name;
15088 });
15089 return (Field != Parent->field_end()) ? *Field : nullptr;
15090}
15091
15092/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15093/// This warning suppressed in the event of macro expansions.
15094static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15095 SourceLocation OpLoc, bool IsBuiltin) {
15096 if (S.inTemplateInstantiation())
15097 return;
15098 if (S.isUnevaluatedContext())
15099 return;
15100 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15101 return;
15102 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15103 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15104 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15105 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15106 if (!LHSDeclRef || !RHSDeclRef ||
15107 LHSDeclRef->getLocation().isMacroID() ||
15108 RHSDeclRef->getLocation().isMacroID())
15109 return;
15110 const ValueDecl *LHSDecl =
15111 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15112 const ValueDecl *RHSDecl =
15113 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15114 if (LHSDecl != RHSDecl)
15115 return;
15116 if (LHSDecl->getType().isVolatileQualified())
15117 return;
15118 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15119 if (RefTy->getPointeeType().isVolatileQualified())
15120 return;
15121
15122 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15123 : diag::warn_self_assignment_overloaded)
15124 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15125 << RHSExpr->getSourceRange();
15126 if (const FieldDecl *SelfAssignField =
15127 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15128 Diag << 1 << SelfAssignField
15129 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15130 else
15131 Diag << 0;
15132}
15133
15134/// Check if a bitwise-& is performed on an Objective-C pointer. This
15135/// is usually indicative of introspection within the Objective-C pointer.
15136static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15137 SourceLocation OpLoc) {
15138 if (!S.getLangOpts().ObjC)
15139 return;
15140
15141 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15142 const Expr *LHS = L.get();
15143 const Expr *RHS = R.get();
15144
15145 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15146 ObjCPointerExpr = LHS;
15147 OtherExpr = RHS;
15148 }
15149 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15150 ObjCPointerExpr = RHS;
15151 OtherExpr = LHS;
15152 }
15153
15154 // This warning is deliberately made very specific to reduce false
15155 // positives with logic that uses '&' for hashing. This logic mainly
15156 // looks for code trying to introspect into tagged pointers, which
15157 // code should generally never do.
15158 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15159 unsigned Diag = diag::warn_objc_pointer_masking;
15160 // Determine if we are introspecting the result of performSelectorXXX.
15161 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15162 // Special case messages to -performSelector and friends, which
15163 // can return non-pointer values boxed in a pointer value.
15164 // Some clients may wish to silence warnings in this subcase.
15165 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15166 Selector S = ME->getSelector();
15167 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15168 if (SelArg0.starts_with(Prefix: "performSelector"))
15169 Diag = diag::warn_objc_pointer_masking_performSelector;
15170 }
15171
15172 S.Diag(Loc: OpLoc, DiagID: Diag)
15173 << ObjCPointerExpr->getSourceRange();
15174 }
15175}
15176
15177// This helper function promotes a binary operator's operands (which are of a
15178// half vector type) to a vector of floats and then truncates the result to
15179// a vector of either half or short.
15180static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15181 BinaryOperatorKind Opc, QualType ResultTy,
15182 ExprValueKind VK, ExprObjectKind OK,
15183 bool IsCompAssign, SourceLocation OpLoc,
15184 FPOptionsOverride FPFeatures) {
15185 auto &Context = S.getASTContext();
15186 assert((isVector(ResultTy, Context.HalfTy) ||
15187 isVector(ResultTy, Context.ShortTy)) &&
15188 "Result must be a vector of half or short");
15189 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15190 isVector(RHS.get()->getType(), Context.HalfTy) &&
15191 "both operands expected to be a half vector");
15192
15193 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15194 QualType BinOpResTy = RHS.get()->getType();
15195
15196 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15197 // change BinOpResTy to a vector of ints.
15198 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15199 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15200
15201 if (IsCompAssign)
15202 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15203 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15204 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15205
15206 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15207 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15208 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15209 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15210}
15211
15212/// Returns true if conversion between vectors of halfs and vectors of floats
15213/// is needed.
15214static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15215 Expr *E0, Expr *E1 = nullptr) {
15216 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15217 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15218 return false;
15219
15220 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15221 QualType Ty = E->IgnoreImplicit()->getType();
15222
15223 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15224 // to vectors of floats. Although the element type of the vectors is __fp16,
15225 // the vectors shouldn't be treated as storage-only types. See the
15226 // discussion here: https://reviews.llvm.org/rG825235c140e7
15227 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15228 if (VT->getVectorKind() == VectorKind::Neon)
15229 return false;
15230 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15231 }
15232 return false;
15233 };
15234
15235 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15236}
15237
15238ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15239 BinaryOperatorKind Opc, Expr *LHSExpr,
15240 Expr *RHSExpr, bool ForFoldExpression) {
15241 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15242 // The syntax only allows initializer lists on the RHS of assignment,
15243 // so we don't need to worry about accepting invalid code for
15244 // non-assignment operators.
15245 // C++11 5.17p9:
15246 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15247 // of x = {} is x = T().
15248 InitializationKind Kind = InitializationKind::CreateDirectList(
15249 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15250 InitializedEntity Entity =
15251 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15252 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15253 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15254 if (Init.isInvalid())
15255 return Init;
15256 RHSExpr = Init.get();
15257 }
15258
15259 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15260 QualType ResultTy; // Result type of the binary operator.
15261 // The following two variables are used for compound assignment operators
15262 QualType CompLHSTy; // Type of LHS after promotions for computation
15263 QualType CompResultTy; // Type of computation result
15264 ExprValueKind VK = VK_PRValue;
15265 ExprObjectKind OK = OK_Ordinary;
15266 bool ConvertHalfVec = false;
15267
15268 if (!LHS.isUsable() || !RHS.isUsable())
15269 return ExprError();
15270
15271 if (getLangOpts().OpenCL) {
15272 QualType LHSTy = LHSExpr->getType();
15273 QualType RHSTy = RHSExpr->getType();
15274 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15275 // the ATOMIC_VAR_INIT macro.
15276 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15277 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15278 if (BO_Assign == Opc)
15279 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15280 else
15281 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15282 return ExprError();
15283 }
15284
15285 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15286 // only with a builtin functions and therefore should be disallowed here.
15287 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15288 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15289 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15290 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15291 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15292 return ExprError();
15293 }
15294 }
15295
15296 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15297 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15298
15299 switch (Opc) {
15300 case BO_Assign:
15301 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15302 if (getLangOpts().CPlusPlus &&
15303 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15304 VK = LHS.get()->getValueKind();
15305 OK = LHS.get()->getObjectKind();
15306 }
15307 if (!ResultTy.isNull()) {
15308 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15309 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15310
15311 // Avoid copying a block to the heap if the block is assigned to a local
15312 // auto variable that is declared in the same scope as the block. This
15313 // optimization is unsafe if the local variable is declared in an outer
15314 // scope. For example:
15315 //
15316 // BlockTy b;
15317 // {
15318 // b = ^{...};
15319 // }
15320 // // It is unsafe to invoke the block here if it wasn't copied to the
15321 // // heap.
15322 // b();
15323
15324 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15325 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15326 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15327 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15328 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15329
15330 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15331 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15332 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15333 }
15334 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15335 break;
15336 case BO_PtrMemD:
15337 case BO_PtrMemI:
15338 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15339 isIndirect: Opc == BO_PtrMemI);
15340 break;
15341 case BO_Mul:
15342 case BO_Div:
15343 ConvertHalfVec = true;
15344 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15345 break;
15346 case BO_Rem:
15347 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15348 break;
15349 case BO_Add:
15350 ConvertHalfVec = true;
15351 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15352 break;
15353 case BO_Sub:
15354 ConvertHalfVec = true;
15355 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15356 break;
15357 case BO_Shl:
15358 case BO_Shr:
15359 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15360 break;
15361 case BO_LE:
15362 case BO_LT:
15363 case BO_GE:
15364 case BO_GT:
15365 ConvertHalfVec = true;
15366 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15367
15368 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15369 !ForFoldExpression && BI && BI->isComparisonOp())
15370 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15371 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15372
15373 break;
15374 case BO_EQ:
15375 case BO_NE:
15376 ConvertHalfVec = true;
15377 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15378 break;
15379 case BO_Cmp:
15380 ConvertHalfVec = true;
15381 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15382 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15383 break;
15384 case BO_And:
15385 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15386 [[fallthrough]];
15387 case BO_Xor:
15388 case BO_Or:
15389 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15390 break;
15391 case BO_LAnd:
15392 case BO_LOr:
15393 ConvertHalfVec = true;
15394 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15395 break;
15396 case BO_MulAssign:
15397 case BO_DivAssign:
15398 ConvertHalfVec = true;
15399 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15400 CompLHSTy = CompResultTy;
15401 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15402 ResultTy =
15403 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15404 break;
15405 case BO_RemAssign:
15406 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15407 CompLHSTy = CompResultTy;
15408 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15409 ResultTy =
15410 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15411 break;
15412 case BO_AddAssign:
15413 ConvertHalfVec = true;
15414 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15415 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15416 ResultTy =
15417 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15418 break;
15419 case BO_SubAssign:
15420 ConvertHalfVec = true;
15421 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15422 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15423 ResultTy =
15424 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15425 break;
15426 case BO_ShlAssign:
15427 case BO_ShrAssign:
15428 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15429 CompLHSTy = CompResultTy;
15430 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15431 ResultTy =
15432 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15433 break;
15434 case BO_AndAssign:
15435 case BO_OrAssign: // fallthrough
15436 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15437 [[fallthrough]];
15438 case BO_XorAssign:
15439 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15440 CompLHSTy = CompResultTy;
15441 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15442 ResultTy =
15443 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15444 break;
15445 case BO_Comma:
15446 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15447 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15448 VK = RHS.get()->getValueKind();
15449 OK = RHS.get()->getObjectKind();
15450 }
15451 break;
15452 }
15453 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15454 return ExprError();
15455
15456 // Some of the binary operations require promoting operands of half vector to
15457 // float vectors and truncating the result back to half vector. For now, we do
15458 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15459 // arm64).
15460 assert(
15461 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15462 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15463 "both sides are half vectors or neither sides are");
15464 ConvertHalfVec =
15465 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15466
15467 // Check for array bounds violations for both sides of the BinaryOperator
15468 CheckArrayAccess(E: LHS.get());
15469 CheckArrayAccess(E: RHS.get());
15470
15471 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15472 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15473 Name: &Context.Idents.get(Name: "object_setClass"),
15474 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15475 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15476 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15477 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15478 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15479 Code: "object_setClass(")
15480 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15481 Code: ",")
15482 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15483 }
15484 else
15485 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15486 }
15487 else if (const ObjCIvarRefExpr *OIRE =
15488 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15489 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15490
15491 // Opc is not a compound assignment if CompResultTy is null.
15492 if (CompResultTy.isNull()) {
15493 if (ConvertHalfVec)
15494 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15495 OpLoc, FPFeatures: CurFPFeatureOverrides());
15496 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15497 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15498 }
15499
15500 // Handle compound assignments.
15501 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15502 OK_ObjCProperty) {
15503 VK = VK_LValue;
15504 OK = LHS.get()->getObjectKind();
15505 }
15506
15507 // The LHS is not converted to the result type for fixed-point compound
15508 // assignment as the common type is computed on demand. Reset the CompLHSTy
15509 // to the LHS type we would have gotten after unary conversions.
15510 if (CompResultTy->isFixedPointType())
15511 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15512
15513 if (ConvertHalfVec)
15514 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15515 OpLoc, FPFeatures: CurFPFeatureOverrides());
15516
15517 return CompoundAssignOperator::Create(
15518 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15519 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15520}
15521
15522/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15523/// operators are mixed in a way that suggests that the programmer forgot that
15524/// comparison operators have higher precedence. The most typical example of
15525/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15526static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15527 SourceLocation OpLoc, Expr *LHSExpr,
15528 Expr *RHSExpr) {
15529 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15530 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15531
15532 // Check that one of the sides is a comparison operator and the other isn't.
15533 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15534 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15535 if (isLeftComp == isRightComp)
15536 return;
15537
15538 // Bitwise operations are sometimes used as eager logical ops.
15539 // Don't diagnose this.
15540 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15541 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15542 if (isLeftBitwise || isRightBitwise)
15543 return;
15544
15545 SourceRange DiagRange = isLeftComp
15546 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15547 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15548 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15549 SourceRange ParensRange =
15550 isLeftComp
15551 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15552 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15553
15554 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15555 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15556 SuggestParentheses(Self, Loc: OpLoc,
15557 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15558 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15559 SuggestParentheses(Self, Loc: OpLoc,
15560 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15561 << BinaryOperator::getOpcodeStr(Op: Opc),
15562 ParenRange: ParensRange);
15563}
15564
15565/// It accepts a '&&' expr that is inside a '||' one.
15566/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15567/// in parentheses.
15568static void
15569EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15570 BinaryOperator *Bop) {
15571 assert(Bop->getOpcode() == BO_LAnd);
15572 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15573 << Bop->getSourceRange() << OpLoc;
15574 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15575 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15576 << Bop->getOpcodeStr(),
15577 ParenRange: Bop->getSourceRange());
15578}
15579
15580/// Look for '&&' in the left hand of a '||' expr.
15581static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15582 Expr *LHSExpr, Expr *RHSExpr) {
15583 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15584 if (Bop->getOpcode() == BO_LAnd) {
15585 // If it's "string_literal && a || b" don't warn since the precedence
15586 // doesn't matter.
15587 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15588 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15589 } else if (Bop->getOpcode() == BO_LOr) {
15590 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15591 // If it's "a || b && string_literal || c" we didn't warn earlier for
15592 // "a || b && string_literal", but warn now.
15593 if (RBop->getOpcode() == BO_LAnd &&
15594 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15595 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15596 }
15597 }
15598 }
15599}
15600
15601/// Look for '&&' in the right hand of a '||' expr.
15602static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15603 Expr *LHSExpr, Expr *RHSExpr) {
15604 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15605 if (Bop->getOpcode() == BO_LAnd) {
15606 // If it's "a || b && string_literal" don't warn since the precedence
15607 // doesn't matter.
15608 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15609 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15610 }
15611 }
15612}
15613
15614/// Look for bitwise op in the left or right hand of a bitwise op with
15615/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15616/// the '&' expression in parentheses.
15617static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15618 SourceLocation OpLoc, Expr *SubExpr) {
15619 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15620 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15621 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15622 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15623 << Bop->getSourceRange() << OpLoc;
15624 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15625 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15626 << Bop->getOpcodeStr(),
15627 ParenRange: Bop->getSourceRange());
15628 }
15629 }
15630}
15631
15632static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15633 Expr *SubExpr, StringRef Shift) {
15634 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15635 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15636 StringRef Op = Bop->getOpcodeStr();
15637 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15638 << Bop->getSourceRange() << OpLoc << Shift << Op;
15639 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15640 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15641 ParenRange: Bop->getSourceRange());
15642 }
15643 }
15644}
15645
15646static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15647 Expr *LHSExpr, Expr *RHSExpr) {
15648 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15649 if (!OCE)
15650 return;
15651
15652 FunctionDecl *FD = OCE->getDirectCallee();
15653 if (!FD || !FD->isOverloadedOperator())
15654 return;
15655
15656 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15657 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15658 return;
15659
15660 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
15661 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15662 << (Kind == OO_LessLess);
15663 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
15664 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15665 << (Kind == OO_LessLess ? "<<" : ">>"),
15666 ParenRange: OCE->getSourceRange());
15667 SuggestParentheses(
15668 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
15669 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
15670}
15671
15672/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15673/// precedence.
15674static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15675 SourceLocation OpLoc, Expr *LHSExpr,
15676 Expr *RHSExpr){
15677 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15678 if (BinaryOperator::isBitwiseOp(Opc))
15679 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15680
15681 // Diagnose "arg1 & arg2 | arg3"
15682 if ((Opc == BO_Or || Opc == BO_Xor) &&
15683 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15684 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15685 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
15686 }
15687
15688 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15689 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15690 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15691 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15692 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15693 }
15694
15695 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
15696 || Opc == BO_Shr) {
15697 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
15698 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
15699 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
15700 }
15701
15702 // Warn on overloaded shift operators and comparisons, such as:
15703 // cout << 5 == 4;
15704 if (BinaryOperator::isComparisonOp(Opc))
15705 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
15706}
15707
15708ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15709 tok::TokenKind Kind,
15710 Expr *LHSExpr, Expr *RHSExpr) {
15711 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15712 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15713 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15714
15715 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15716 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
15717
15718 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
15719 ? BuiltinCountedByRefKind::Assignment
15720 : BuiltinCountedByRefKind::BinaryExpr;
15721
15722 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
15723 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
15724
15725 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
15726}
15727
15728void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15729 UnresolvedSetImpl &Functions) {
15730 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15731 if (OverOp != OO_None && OverOp != OO_Equal)
15732 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
15733
15734 // In C++20 onwards, we may have a second operator to look up.
15735 if (getLangOpts().CPlusPlus20) {
15736 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
15737 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
15738 }
15739}
15740
15741/// Build an overloaded binary operator expression in the given scope.
15742static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15743 BinaryOperatorKind Opc,
15744 Expr *LHS, Expr *RHS) {
15745 switch (Opc) {
15746 case BO_Assign:
15747 // In the non-overloaded case, we warn about self-assignment (x = x) for
15748 // both simple assignment and certain compound assignments where algebra
15749 // tells us the operation yields a constant result. When the operator is
15750 // overloaded, we can't do the latter because we don't want to assume that
15751 // those algebraic identities still apply; for example, a path-building
15752 // library might use operator/= to append paths. But it's still reasonable
15753 // to assume that simple assignment is just moving/copying values around
15754 // and so self-assignment is likely a bug.
15755 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
15756 [[fallthrough]];
15757 case BO_DivAssign:
15758 case BO_RemAssign:
15759 case BO_SubAssign:
15760 case BO_AndAssign:
15761 case BO_OrAssign:
15762 case BO_XorAssign:
15763 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
15764 break;
15765 default:
15766 break;
15767 }
15768
15769 // Find all of the overloaded operators visible from this point.
15770 UnresolvedSet<16> Functions;
15771 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
15772
15773 // Build the (potentially-overloaded, potentially-dependent)
15774 // binary operation.
15775 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
15776}
15777
15778ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15779 BinaryOperatorKind Opc, Expr *LHSExpr,
15780 Expr *RHSExpr, bool ForFoldExpression) {
15781 if (!LHSExpr || !RHSExpr)
15782 return ExprError();
15783
15784 // We want to end up calling one of SemaPseudoObject::checkAssignment
15785 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15786 // both expressions are overloadable or either is type-dependent),
15787 // or CreateBuiltinBinOp (in any other case). We also want to get
15788 // any placeholder types out of the way.
15789
15790 // Handle pseudo-objects in the LHS.
15791 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15792 // Assignments with a pseudo-object l-value need special analysis.
15793 if (pty->getKind() == BuiltinType::PseudoObject &&
15794 BinaryOperator::isAssignmentOp(Opc))
15795 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
15796
15797 // Don't resolve overloads if the other type is overloadable.
15798 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15799 // We can't actually test that if we still have a placeholder,
15800 // though. Fortunately, none of the exceptions we see in that
15801 // code below are valid when the LHS is an overload set. Note
15802 // that an overload set can be dependently-typed, but it never
15803 // instantiates to having an overloadable type.
15804 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
15805 if (resolvedRHS.isInvalid()) return ExprError();
15806 RHSExpr = resolvedRHS.get();
15807
15808 if (RHSExpr->isTypeDependent() ||
15809 RHSExpr->getType()->isOverloadableType())
15810 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15811 }
15812
15813 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15814 // template, diagnose the missing 'template' keyword instead of diagnosing
15815 // an invalid use of a bound member function.
15816 //
15817 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15818 // to C++1z [over.over]/1.4, but we already checked for that case above.
15819 if (Opc == BO_LT && inTemplateInstantiation() &&
15820 (pty->getKind() == BuiltinType::BoundMember ||
15821 pty->getKind() == BuiltinType::Overload)) {
15822 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
15823 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15824 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
15825 return isa<FunctionTemplateDecl>(Val: ND);
15826 })) {
15827 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15828 : OE->getNameLoc(),
15829 DiagID: diag::err_template_kw_missing)
15830 << OE->getName().getAsIdentifierInfo();
15831 return ExprError();
15832 }
15833 }
15834
15835 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
15836 if (LHS.isInvalid()) return ExprError();
15837 LHSExpr = LHS.get();
15838 }
15839
15840 // Handle pseudo-objects in the RHS.
15841 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15842 // An overload in the RHS can potentially be resolved by the type
15843 // being assigned to.
15844 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15845 if (getLangOpts().CPlusPlus &&
15846 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15847 LHSExpr->getType()->isOverloadableType()))
15848 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15849
15850 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
15851 ForFoldExpression);
15852 }
15853
15854 // Don't resolve overloads if the other type is overloadable.
15855 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15856 LHSExpr->getType()->isOverloadableType())
15857 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15858
15859 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
15860 if (!resolvedRHS.isUsable()) return ExprError();
15861 RHSExpr = resolvedRHS.get();
15862 }
15863
15864 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
15865 LHSExpr->getType()->isHLSLResourceRecordArray())) {
15866 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
15867 return ExprError();
15868 }
15869
15870 if (getLangOpts().CPlusPlus) {
15871 // Otherwise, build an overloaded op if either expression is type-dependent
15872 // or has an overloadable type.
15873 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15874 LHSExpr->getType()->isOverloadableType() ||
15875 RHSExpr->getType()->isOverloadableType())
15876 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15877 }
15878
15879 if (getLangOpts().RecoveryAST &&
15880 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15881 assert(!getLangOpts().CPlusPlus);
15882 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15883 "Should only occur in error-recovery path.");
15884 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15885 // C [6.15.16] p3:
15886 // An assignment expression has the value of the left operand after the
15887 // assignment, but is not an lvalue.
15888 return CompoundAssignOperator::Create(
15889 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
15890 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
15891 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15892 QualType ResultType;
15893 switch (Opc) {
15894 case BO_Assign:
15895 ResultType = LHSExpr->getType().getUnqualifiedType();
15896 break;
15897 case BO_LT:
15898 case BO_GT:
15899 case BO_LE:
15900 case BO_GE:
15901 case BO_EQ:
15902 case BO_NE:
15903 case BO_LAnd:
15904 case BO_LOr:
15905 // These operators have a fixed result type regardless of operands.
15906 ResultType = Context.IntTy;
15907 break;
15908 case BO_Comma:
15909 ResultType = RHSExpr->getType();
15910 break;
15911 default:
15912 ResultType = Context.DependentTy;
15913 break;
15914 }
15915 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
15916 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
15917 FPFeatures: CurFPFeatureOverrides());
15918 }
15919
15920 // Build a built-in binary operation.
15921 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
15922}
15923
15924static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15925 if (T.isNull() || T->isDependentType())
15926 return false;
15927
15928 if (!Ctx.isPromotableIntegerType(T))
15929 return true;
15930
15931 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
15932}
15933
15934ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15935 UnaryOperatorKind Opc, Expr *InputExpr,
15936 bool IsAfterAmp) {
15937 ExprResult Input = InputExpr;
15938 ExprValueKind VK = VK_PRValue;
15939 ExprObjectKind OK = OK_Ordinary;
15940 QualType resultType;
15941 bool CanOverflow = false;
15942
15943 bool ConvertHalfVec = false;
15944 if (getLangOpts().OpenCL) {
15945 QualType Ty = InputExpr->getType();
15946 // The only legal unary operation for atomics is '&'.
15947 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15948 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15949 // only with a builtin functions and therefore should be disallowed here.
15950 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15951 || Ty->isBlockPointerType())) {
15952 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
15953 << InputExpr->getType()
15954 << Input.get()->getSourceRange());
15955 }
15956 }
15957
15958 if (getLangOpts().HLSL && OpLoc.isValid()) {
15959 if (Opc == UO_AddrOf)
15960 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
15961 if (Opc == UO_Deref)
15962 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
15963 }
15964
15965 if (InputExpr->isTypeDependent() &&
15966 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
15967 resultType = Context.DependentTy;
15968 } else {
15969 switch (Opc) {
15970 case UO_PreInc:
15971 case UO_PreDec:
15972 case UO_PostInc:
15973 case UO_PostDec:
15974 resultType =
15975 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
15976 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
15977 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
15978 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
15979 break;
15980 case UO_AddrOf:
15981 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
15982 CheckAddressOfNoDeref(E: InputExpr);
15983 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
15984 break;
15985 case UO_Deref: {
15986 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
15987 if (Input.isInvalid())
15988 return ExprError();
15989 resultType =
15990 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
15991 break;
15992 }
15993 case UO_Plus:
15994 case UO_Minus:
15995 CanOverflow = Opc == UO_Minus &&
15996 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
15997 Input = UsualUnaryConversions(E: Input.get());
15998 if (Input.isInvalid())
15999 return ExprError();
16000 // Unary plus and minus require promoting an operand of half vector to a
16001 // float vector and truncating the result back to a half vector. For now,
16002 // we do this only when HalfArgsAndReturns is set (that is, when the
16003 // target is arm or arm64).
16004 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16005
16006 // If the operand is a half vector, promote it to a float vector.
16007 if (ConvertHalfVec)
16008 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16009 resultType = Input.get()->getType();
16010 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16011 break;
16012 else if (resultType->isVectorType() &&
16013 // The z vector extensions don't allow + or - with bool vectors.
16014 (!Context.getLangOpts().ZVector ||
16015 resultType->castAs<VectorType>()->getVectorKind() !=
16016 VectorKind::AltiVecBool))
16017 break;
16018 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16019 break;
16020 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16021 Opc == UO_Plus && resultType->isPointerType())
16022 break;
16023
16024 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16025 << resultType << Input.get()->getSourceRange());
16026
16027 case UO_Not: // bitwise complement
16028 Input = UsualUnaryConversions(E: Input.get());
16029 if (Input.isInvalid())
16030 return ExprError();
16031 resultType = Input.get()->getType();
16032 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16033 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16034 // C99 does not support '~' for complex conjugation.
16035 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16036 << resultType << Input.get()->getSourceRange();
16037 else if (resultType->hasIntegerRepresentation())
16038 break;
16039 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16040 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16041 // on vector float types.
16042 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16043 if (!T->isIntegerType())
16044 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16045 << resultType << Input.get()->getSourceRange());
16046 } else {
16047 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16048 << resultType << Input.get()->getSourceRange());
16049 }
16050 break;
16051
16052 case UO_LNot: // logical negation
16053 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16054 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16055 if (Input.isInvalid())
16056 return ExprError();
16057 resultType = Input.get()->getType();
16058
16059 // Though we still have to promote half FP to float...
16060 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16061 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16062 .get();
16063 resultType = Context.FloatTy;
16064 }
16065
16066 // WebAsembly tables can't be used in unary expressions.
16067 if (resultType->isPointerType() &&
16068 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16069 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16070 << resultType << Input.get()->getSourceRange());
16071 }
16072
16073 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16074 // C99 6.5.3.3p1: ok, fallthrough;
16075 if (Context.getLangOpts().CPlusPlus) {
16076 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16077 // operand contextually converted to bool.
16078 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16079 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16080 } else if (Context.getLangOpts().OpenCL &&
16081 Context.getLangOpts().OpenCLVersion < 120) {
16082 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16083 // operate on scalar float types.
16084 if (!resultType->isIntegerType() && !resultType->isPointerType())
16085 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16086 << resultType << Input.get()->getSourceRange());
16087 }
16088 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16089 !resultType->hasBooleanRepresentation()) {
16090 // HLSL unary logical 'not' behaves like C++, which states that the
16091 // operand is converted to bool and the result is bool, however HLSL
16092 // extends this property to vectors.
16093 const VectorType *VTy = resultType->castAs<VectorType>();
16094 resultType =
16095 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16096
16097 Input = ImpCastExprToType(
16098 E: Input.get(), Type: resultType,
16099 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16100 .get();
16101 break;
16102 } else if (resultType->isExtVectorType()) {
16103 if (Context.getLangOpts().OpenCL &&
16104 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16105 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16106 // operate on vector float types.
16107 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16108 if (!T->isIntegerType())
16109 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16110 << resultType << Input.get()->getSourceRange());
16111 }
16112 // Vector logical not returns the signed variant of the operand type.
16113 resultType = GetSignedVectorType(V: resultType);
16114 break;
16115 } else if (Context.getLangOpts().CPlusPlus &&
16116 resultType->isVectorType()) {
16117 const VectorType *VTy = resultType->castAs<VectorType>();
16118 if (VTy->getVectorKind() != VectorKind::Generic)
16119 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16120 << resultType << Input.get()->getSourceRange());
16121
16122 // Vector logical not returns the signed variant of the operand type.
16123 resultType = GetSignedVectorType(V: resultType);
16124 break;
16125 } else {
16126 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16127 << resultType << Input.get()->getSourceRange());
16128 }
16129
16130 // LNot always has type int. C99 6.5.3.3p5.
16131 // In C++, it's bool. C++ 5.3.1p8
16132 resultType = Context.getLogicalOperationType();
16133 break;
16134 case UO_Real:
16135 case UO_Imag:
16136 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16137 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16138 // ordinary complex l-values to ordinary l-values and all other values to
16139 // r-values.
16140 if (Input.isInvalid())
16141 return ExprError();
16142 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16143 if (Input.get()->isGLValue() &&
16144 Input.get()->getObjectKind() == OK_Ordinary)
16145 VK = Input.get()->getValueKind();
16146 } else if (!getLangOpts().CPlusPlus) {
16147 // In C, a volatile scalar is read by __imag. In C++, it is not.
16148 Input = DefaultLvalueConversion(E: Input.get());
16149 }
16150 break;
16151 case UO_Extension:
16152 resultType = Input.get()->getType();
16153 VK = Input.get()->getValueKind();
16154 OK = Input.get()->getObjectKind();
16155 break;
16156 case UO_Coawait:
16157 // It's unnecessary to represent the pass-through operator co_await in the
16158 // AST; just return the input expression instead.
16159 assert(!Input.get()->getType()->isDependentType() &&
16160 "the co_await expression must be non-dependant before "
16161 "building operator co_await");
16162 return Input;
16163 }
16164 }
16165 if (resultType.isNull() || Input.isInvalid())
16166 return ExprError();
16167
16168 // Check for array bounds violations in the operand of the UnaryOperator,
16169 // except for the '*' and '&' operators that have to be handled specially
16170 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16171 // that are explicitly defined as valid by the standard).
16172 if (Opc != UO_AddrOf && Opc != UO_Deref)
16173 CheckArrayAccess(E: Input.get());
16174
16175 auto *UO =
16176 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16177 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16178
16179 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16180 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16181 !isUnevaluatedContext())
16182 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16183
16184 // Convert the result back to a half vector.
16185 if (ConvertHalfVec)
16186 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16187 return UO;
16188}
16189
16190bool Sema::isQualifiedMemberAccess(Expr *E) {
16191 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16192 if (!DRE->getQualifier())
16193 return false;
16194
16195 ValueDecl *VD = DRE->getDecl();
16196 if (!VD->isCXXClassMember())
16197 return false;
16198
16199 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16200 return true;
16201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16202 return Method->isImplicitObjectMemberFunction();
16203
16204 return false;
16205 }
16206
16207 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16208 if (!ULE->getQualifier())
16209 return false;
16210
16211 for (NamedDecl *D : ULE->decls()) {
16212 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16213 if (Method->isImplicitObjectMemberFunction())
16214 return true;
16215 } else {
16216 // Overload set does not contain methods.
16217 break;
16218 }
16219 }
16220
16221 return false;
16222 }
16223
16224 return false;
16225}
16226
16227ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16228 UnaryOperatorKind Opc, Expr *Input,
16229 bool IsAfterAmp) {
16230 // First things first: handle placeholders so that the
16231 // overloaded-operator check considers the right type.
16232 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16233 // Increment and decrement of pseudo-object references.
16234 if (pty->getKind() == BuiltinType::PseudoObject &&
16235 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16236 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16237
16238 // extension is always a builtin operator.
16239 if (Opc == UO_Extension)
16240 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16241
16242 // & gets special logic for several kinds of placeholder.
16243 // The builtin code knows what to do.
16244 if (Opc == UO_AddrOf &&
16245 (pty->getKind() == BuiltinType::Overload ||
16246 pty->getKind() == BuiltinType::UnknownAny ||
16247 pty->getKind() == BuiltinType::BoundMember))
16248 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16249
16250 // Anything else needs to be handled now.
16251 ExprResult Result = CheckPlaceholderExpr(E: Input);
16252 if (Result.isInvalid()) return ExprError();
16253 Input = Result.get();
16254 }
16255
16256 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16257 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16258 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16259 // Find all of the overloaded operators visible from this point.
16260 UnresolvedSet<16> Functions;
16261 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16262 if (S && OverOp != OO_None)
16263 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16264
16265 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16266 }
16267
16268 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16269}
16270
16271ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16272 Expr *Input, bool IsAfterAmp) {
16273 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16274 IsAfterAmp);
16275}
16276
16277ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16278 LabelDecl *TheDecl) {
16279 TheDecl->markUsed(C&: Context);
16280 // Create the AST node. The address of a label always has type 'void*'.
16281 auto *Res = new (Context) AddrLabelExpr(
16282 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16283
16284 if (getCurFunction())
16285 getCurFunction()->AddrLabels.push_back(Elt: Res);
16286
16287 return Res;
16288}
16289
16290void Sema::ActOnStartStmtExpr() {
16291 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16292 // Make sure we diagnose jumping into a statement expression.
16293 setFunctionHasBranchProtectedScope();
16294}
16295
16296void Sema::ActOnStmtExprError() {
16297 // Note that function is also called by TreeTransform when leaving a
16298 // StmtExpr scope without rebuilding anything.
16299
16300 DiscardCleanupsInEvaluationContext();
16301 PopExpressionEvaluationContext();
16302}
16303
16304ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16305 SourceLocation RPLoc) {
16306 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16307}
16308
16309ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16310 SourceLocation RPLoc, unsigned TemplateDepth) {
16311 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16312 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16313
16314 if (hasAnyUnrecoverableErrorsInThisFunction())
16315 DiscardCleanupsInEvaluationContext();
16316 assert(!Cleanup.exprNeedsCleanups() &&
16317 "cleanups within StmtExpr not correctly bound!");
16318 PopExpressionEvaluationContext();
16319
16320 // FIXME: there are a variety of strange constraints to enforce here, for
16321 // example, it is not possible to goto into a stmt expression apparently.
16322 // More semantic analysis is needed.
16323
16324 // If there are sub-stmts in the compound stmt, take the type of the last one
16325 // as the type of the stmtexpr.
16326 QualType Ty = Context.VoidTy;
16327 bool StmtExprMayBindToTemp = false;
16328 if (!Compound->body_empty()) {
16329 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16330 if (const Expr *Value = LastStmt->getExprStmt()) {
16331 StmtExprMayBindToTemp = true;
16332 Ty = Value->getType();
16333 }
16334 }
16335 }
16336
16337 // FIXME: Check that expression type is complete/non-abstract; statement
16338 // expressions are not lvalues.
16339 Expr *ResStmtExpr =
16340 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16341 if (StmtExprMayBindToTemp)
16342 return MaybeBindToTemporary(E: ResStmtExpr);
16343 return ResStmtExpr;
16344}
16345
16346ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16347 if (ER.isInvalid())
16348 return ExprError();
16349
16350 // Do function/array conversion on the last expression, but not
16351 // lvalue-to-rvalue. However, initialize an unqualified type.
16352 ER = DefaultFunctionArrayConversion(E: ER.get());
16353 if (ER.isInvalid())
16354 return ExprError();
16355 Expr *E = ER.get();
16356
16357 if (E->isTypeDependent())
16358 return E;
16359
16360 // In ARC, if the final expression ends in a consume, splice
16361 // the consume out and bind it later. In the alternate case
16362 // (when dealing with a retainable type), the result
16363 // initialization will create a produce. In both cases the
16364 // result will be +1, and we'll need to balance that out with
16365 // a bind.
16366 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16367 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16368 return Cast->getSubExpr();
16369
16370 // FIXME: Provide a better location for the initialization.
16371 return PerformCopyInitialization(
16372 Entity: InitializedEntity::InitializeStmtExprResult(
16373 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16374 EqualLoc: SourceLocation(), Init: E);
16375}
16376
16377ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16378 TypeSourceInfo *TInfo,
16379 ArrayRef<OffsetOfComponent> Components,
16380 SourceLocation RParenLoc) {
16381 QualType ArgTy = TInfo->getType();
16382 bool Dependent = ArgTy->isDependentType();
16383 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16384
16385 // We must have at least one component that refers to the type, and the first
16386 // one is known to be a field designator. Verify that the ArgTy represents
16387 // a struct/union/class.
16388 if (!Dependent && !ArgTy->isRecordType())
16389 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16390 << ArgTy << TypeRange);
16391
16392 // Type must be complete per C99 7.17p3 because a declaring a variable
16393 // with an incomplete type would be ill-formed.
16394 if (!Dependent
16395 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16396 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16397 return ExprError();
16398
16399 bool DidWarnAboutNonPOD = false;
16400 QualType CurrentType = ArgTy;
16401 SmallVector<OffsetOfNode, 4> Comps;
16402 SmallVector<Expr*, 4> Exprs;
16403 for (const OffsetOfComponent &OC : Components) {
16404 if (OC.isBrackets) {
16405 // Offset of an array sub-field. TODO: Should we allow vector elements?
16406 if (!CurrentType->isDependentType()) {
16407 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16408 if(!AT)
16409 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_array_type)
16410 << CurrentType);
16411 CurrentType = AT->getElementType();
16412 } else
16413 CurrentType = Context.DependentTy;
16414
16415 ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E));
16416 if (IdxRval.isInvalid())
16417 return ExprError();
16418 Expr *Idx = IdxRval.get();
16419
16420 // The expression must be an integral expression.
16421 // FIXME: An integral constant expression?
16422 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16423 !Idx->getType()->isIntegerType())
16424 return ExprError(
16425 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16426 << Idx->getSourceRange());
16427
16428 // Record this array index.
16429 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16430 Exprs.push_back(Elt: Idx);
16431 continue;
16432 }
16433
16434 // Offset of a field.
16435 if (CurrentType->isDependentType()) {
16436 // We have the offset of a field, but we can't look into the dependent
16437 // type. Just record the identifier of the field.
16438 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16439 CurrentType = Context.DependentTy;
16440 continue;
16441 }
16442
16443 // We need to have a complete type to look into.
16444 if (RequireCompleteType(Loc: OC.LocStart, T: CurrentType,
16445 DiagID: diag::err_offsetof_incomplete_type))
16446 return ExprError();
16447
16448 // Look for the designated field.
16449 auto *RD = CurrentType->getAsRecordDecl();
16450 if (!RD)
16451 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_record_type)
16452 << CurrentType);
16453
16454 // C++ [lib.support.types]p5:
16455 // The macro offsetof accepts a restricted set of type arguments in this
16456 // International Standard. type shall be a POD structure or a POD union
16457 // (clause 9).
16458 // C++11 [support.types]p4:
16459 // If type is not a standard-layout class (Clause 9), the results are
16460 // undefined.
16461 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16462 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16463 unsigned DiagID =
16464 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16465 : diag::ext_offsetof_non_pod_type;
16466
16467 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16468 Diag(Loc: BuiltinLoc, DiagID)
16469 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16470 DidWarnAboutNonPOD = true;
16471 }
16472 }
16473
16474 // Look for the field.
16475 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16476 LookupQualifiedName(R, LookupCtx: RD);
16477 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16478 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16479 if (!MemberDecl) {
16480 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16481 MemberDecl = IndirectMemberDecl->getAnonField();
16482 }
16483
16484 if (!MemberDecl) {
16485 // Lookup could be ambiguous when looking up a placeholder variable
16486 // __builtin_offsetof(S, _).
16487 // In that case we would already have emitted a diagnostic
16488 if (!R.isAmbiguous())
16489 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16490 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16491 return ExprError();
16492 }
16493
16494 // C99 7.17p3:
16495 // (If the specified member is a bit-field, the behavior is undefined.)
16496 //
16497 // We diagnose this as an error.
16498 if (MemberDecl->isBitField()) {
16499 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_bitfield)
16500 << MemberDecl->getDeclName()
16501 << SourceRange(BuiltinLoc, RParenLoc);
16502 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16503 return ExprError();
16504 }
16505
16506 RecordDecl *Parent = MemberDecl->getParent();
16507 if (IndirectMemberDecl)
16508 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16509
16510 // If the member was found in a base class, introduce OffsetOfNodes for
16511 // the base class indirections.
16512 CXXBasePaths Paths;
16513 if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType,
16514 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16515 if (Paths.getDetectedVirtual()) {
16516 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_field_of_virtual_base)
16517 << MemberDecl->getDeclName()
16518 << SourceRange(BuiltinLoc, RParenLoc);
16519 return ExprError();
16520 }
16521
16522 CXXBasePath &Path = Paths.front();
16523 for (const CXXBasePathElement &B : Path)
16524 Comps.push_back(Elt: OffsetOfNode(B.Base));
16525 }
16526
16527 if (IndirectMemberDecl) {
16528 for (auto *FI : IndirectMemberDecl->chain()) {
16529 assert(isa<FieldDecl>(FI));
16530 Comps.push_back(Elt: OffsetOfNode(OC.LocStart,
16531 cast<FieldDecl>(Val: FI), OC.LocEnd));
16532 }
16533 } else
16534 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16535
16536 CurrentType = MemberDecl->getType().getNonReferenceType();
16537 }
16538
16539 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16540 comps: Comps, exprs: Exprs, RParenLoc);
16541}
16542
16543ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16544 SourceLocation BuiltinLoc,
16545 SourceLocation TypeLoc,
16546 ParsedType ParsedArgTy,
16547 ArrayRef<OffsetOfComponent> Components,
16548 SourceLocation RParenLoc) {
16549
16550 TypeSourceInfo *ArgTInfo;
16551 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16552 if (ArgTy.isNull())
16553 return ExprError();
16554
16555 if (!ArgTInfo)
16556 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16557
16558 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc);
16559}
16560
16561
16562ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16563 Expr *CondExpr,
16564 Expr *LHSExpr, Expr *RHSExpr,
16565 SourceLocation RPLoc) {
16566 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16567
16568 ExprValueKind VK = VK_PRValue;
16569 ExprObjectKind OK = OK_Ordinary;
16570 QualType resType;
16571 bool CondIsTrue = false;
16572 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16573 resType = Context.DependentTy;
16574 } else {
16575 // The conditional expression is required to be a constant expression.
16576 llvm::APSInt condEval(32);
16577 ExprResult CondICE = VerifyIntegerConstantExpression(
16578 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16579 if (CondICE.isInvalid())
16580 return ExprError();
16581 CondExpr = CondICE.get();
16582 CondIsTrue = condEval.getZExtValue();
16583
16584 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16585 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16586
16587 resType = ActiveExpr->getType();
16588 VK = ActiveExpr->getValueKind();
16589 OK = ActiveExpr->getObjectKind();
16590 }
16591
16592 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16593 resType, VK, OK, RPLoc, CondIsTrue);
16594}
16595
16596//===----------------------------------------------------------------------===//
16597// Clang Extensions.
16598//===----------------------------------------------------------------------===//
16599
16600void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16601 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16602
16603 if (LangOpts.CPlusPlus) {
16604 MangleNumberingContext *MCtx;
16605 Decl *ManglingContextDecl;
16606 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16607 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16608 if (MCtx) {
16609 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16610 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16611 }
16612 }
16613
16614 PushBlockScope(BlockScope: CurScope, Block);
16615 CurContext->addDecl(D: Block);
16616 if (CurScope)
16617 PushDeclContext(S: CurScope, DC: Block);
16618 else
16619 CurContext = Block;
16620
16621 getCurBlock()->HasImplicitReturnType = true;
16622
16623 // Enter a new evaluation context to insulate the block from any
16624 // cleanups from the enclosing full-expression.
16625 PushExpressionEvaluationContext(
16626 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16627}
16628
16629void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16630 Scope *CurScope) {
16631 assert(ParamInfo.getIdentifier() == nullptr &&
16632 "block-id should have no identifier!");
16633 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16634 BlockScopeInfo *CurBlock = getCurBlock();
16635
16636 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16637 QualType T = Sig->getType();
16638 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
16639
16640 // GetTypeForDeclarator always produces a function type for a block
16641 // literal signature. Furthermore, it is always a FunctionProtoType
16642 // unless the function was written with a typedef.
16643 assert(T->isFunctionType() &&
16644 "GetTypeForDeclarator made a non-function block signature");
16645
16646 // Look for an explicit signature in that function type.
16647 FunctionProtoTypeLoc ExplicitSignature;
16648
16649 if ((ExplicitSignature = Sig->getTypeLoc()
16650 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16651
16652 // Check whether that explicit signature was synthesized by
16653 // GetTypeForDeclarator. If so, don't save that as part of the
16654 // written signature.
16655 if (ExplicitSignature.getLocalRangeBegin() ==
16656 ExplicitSignature.getLocalRangeEnd()) {
16657 // This would be much cheaper if we stored TypeLocs instead of
16658 // TypeSourceInfos.
16659 TypeLoc Result = ExplicitSignature.getReturnLoc();
16660 unsigned Size = Result.getFullDataSize();
16661 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
16662 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
16663
16664 ExplicitSignature = FunctionProtoTypeLoc();
16665 }
16666 }
16667
16668 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16669 CurBlock->FunctionType = T;
16670
16671 const auto *Fn = T->castAs<FunctionType>();
16672 QualType RetTy = Fn->getReturnType();
16673 bool isVariadic =
16674 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
16675
16676 CurBlock->TheDecl->setIsVariadic(isVariadic);
16677
16678 // Context.DependentTy is used as a placeholder for a missing block
16679 // return type. TODO: what should we do with declarators like:
16680 // ^ * { ... }
16681 // If the answer is "apply template argument deduction"....
16682 if (RetTy != Context.DependentTy) {
16683 CurBlock->ReturnType = RetTy;
16684 CurBlock->TheDecl->setBlockMissingReturnType(false);
16685 CurBlock->HasImplicitReturnType = false;
16686 }
16687
16688 // Push block parameters from the declarator if we had them.
16689 SmallVector<ParmVarDecl*, 8> Params;
16690 if (ExplicitSignature) {
16691 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16692 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
16693 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16694 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16695 // Diagnose this as an extension in C17 and earlier.
16696 if (!getLangOpts().C23)
16697 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
16698 }
16699 Params.push_back(Elt: Param);
16700 }
16701
16702 // Fake up parameter variables if we have a typedef, like
16703 // ^ fntype { ... }
16704 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16705 for (const auto &I : Fn->param_types()) {
16706 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16707 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
16708 Params.push_back(Elt: Param);
16709 }
16710 }
16711
16712 // Set the parameters on the block decl.
16713 if (!Params.empty()) {
16714 CurBlock->TheDecl->setParams(Params);
16715 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
16716 /*CheckParameterNames=*/false);
16717 }
16718
16719 // Finally we can process decl attributes.
16720 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
16721
16722 // Put the parameter variables in scope.
16723 for (auto *AI : CurBlock->TheDecl->parameters()) {
16724 AI->setOwningFunction(CurBlock->TheDecl);
16725
16726 // If this has an identifier, add it to the scope stack.
16727 if (AI->getIdentifier()) {
16728 CheckShadow(S: CurBlock->TheScope, D: AI);
16729
16730 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
16731 }
16732
16733 if (AI->isInvalidDecl())
16734 CurBlock->TheDecl->setInvalidDecl();
16735 }
16736}
16737
16738void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16739 // Leave the expression-evaluation context.
16740 DiscardCleanupsInEvaluationContext();
16741 PopExpressionEvaluationContext();
16742
16743 // Pop off CurBlock, handle nested blocks.
16744 PopDeclContext();
16745 PopFunctionScopeInfo();
16746}
16747
16748ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16749 Stmt *Body, Scope *CurScope) {
16750 // If blocks are disabled, emit an error.
16751 if (!LangOpts.Blocks)
16752 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
16753
16754 // Leave the expression-evaluation context.
16755 if (hasAnyUnrecoverableErrorsInThisFunction())
16756 DiscardCleanupsInEvaluationContext();
16757 assert(!Cleanup.exprNeedsCleanups() &&
16758 "cleanups within block not correctly bound!");
16759 PopExpressionEvaluationContext();
16760
16761 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
16762 BlockDecl *BD = BSI->TheDecl;
16763
16764 maybeAddDeclWithEffects(D: BD);
16765
16766 if (BSI->HasImplicitReturnType)
16767 deduceClosureReturnType(CSI&: *BSI);
16768
16769 QualType RetTy = Context.VoidTy;
16770 if (!BSI->ReturnType.isNull())
16771 RetTy = BSI->ReturnType;
16772
16773 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16774 QualType BlockTy;
16775
16776 // If the user wrote a function type in some form, try to use that.
16777 if (!BSI->FunctionType.isNull()) {
16778 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16779
16780 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16781 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
16782
16783 // Turn protoless block types into nullary block types.
16784 if (isa<FunctionNoProtoType>(Val: FTy)) {
16785 FunctionProtoType::ExtProtoInfo EPI;
16786 EPI.ExtInfo = Ext;
16787 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
16788
16789 // Otherwise, if we don't need to change anything about the function type,
16790 // preserve its sugar structure.
16791 } else if (FTy->getReturnType() == RetTy &&
16792 (!NoReturn || FTy->getNoReturnAttr())) {
16793 BlockTy = BSI->FunctionType;
16794
16795 // Otherwise, make the minimal modifications to the function type.
16796 } else {
16797 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
16798 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16799 EPI.TypeQuals = Qualifiers();
16800 EPI.ExtInfo = Ext;
16801 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
16802 }
16803
16804 // If we don't have a function type, just build one from nothing.
16805 } else {
16806 FunctionProtoType::ExtProtoInfo EPI;
16807 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
16808 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
16809 }
16810
16811 DiagnoseUnusedParameters(Parameters: BD->parameters());
16812 BlockTy = Context.getBlockPointerType(T: BlockTy);
16813
16814 // If needed, diagnose invalid gotos and switches in the block.
16815 if (getCurFunction()->NeedsScopeChecking() &&
16816 !PP.isCodeCompletionEnabled())
16817 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
16818
16819 BD->setBody(cast<CompoundStmt>(Val: Body));
16820
16821 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16822 DiagnoseUnguardedAvailabilityViolations(FD: BD);
16823
16824 // Try to apply the named return value optimization. We have to check again
16825 // if we can do this, though, because blocks keep return statements around
16826 // to deduce an implicit return type.
16827 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16828 !BD->isDependentContext())
16829 computeNRVO(Body, Scope: BSI);
16830
16831 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16832 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16833 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
16834 UseContext: NonTrivialCUnionContext::FunctionReturn,
16835 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16836
16837 PopDeclContext();
16838
16839 // Set the captured variables on the block.
16840 SmallVector<BlockDecl::Capture, 4> Captures;
16841 for (Capture &Cap : BSI->Captures) {
16842 if (Cap.isInvalid() || Cap.isThisCapture())
16843 continue;
16844 // Cap.getVariable() is always a VarDecl because
16845 // blocks cannot capture structured bindings or other ValueDecl kinds.
16846 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
16847 Expr *CopyExpr = nullptr;
16848 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16849 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
16850 // The capture logic needs the destructor, so make sure we mark it.
16851 // Usually this is unnecessary because most local variables have
16852 // their destructors marked at declaration time, but parameters are
16853 // an exception because it's technically only the call site that
16854 // actually requires the destructor.
16855 if (isa<ParmVarDecl>(Val: Var))
16856 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
16857
16858 // Enter a separate potentially-evaluated context while building block
16859 // initializers to isolate their cleanups from those of the block
16860 // itself.
16861 // FIXME: Is this appropriate even when the block itself occurs in an
16862 // unevaluated operand?
16863 EnterExpressionEvaluationContext EvalContext(
16864 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16865
16866 SourceLocation Loc = Cap.getLocation();
16867
16868 ExprResult Result = BuildDeclarationNameExpr(
16869 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
16870
16871 // According to the blocks spec, the capture of a variable from
16872 // the stack requires a const copy constructor. This is not true
16873 // of the copy/move done to move a __block variable to the heap.
16874 if (!Result.isInvalid() &&
16875 !Result.get()->getType().isConstQualified()) {
16876 Result = ImpCastExprToType(E: Result.get(),
16877 Type: Result.get()->getType().withConst(),
16878 CK: CK_NoOp, VK: VK_LValue);
16879 }
16880
16881 if (!Result.isInvalid()) {
16882 Result = PerformCopyInitialization(
16883 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
16884 Type: Cap.getCaptureType()),
16885 EqualLoc: Loc, Init: Result.get());
16886 }
16887
16888 // Build a full-expression copy expression if initialization
16889 // succeeded and used a non-trivial constructor. Recover from
16890 // errors by pretending that the copy isn't necessary.
16891 if (!Result.isInvalid() &&
16892 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
16893 ->isTrivial()) {
16894 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
16895 CopyExpr = Result.get();
16896 }
16897 }
16898 }
16899
16900 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16901 CopyExpr);
16902 Captures.push_back(Elt: NewCap);
16903 }
16904 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
16905
16906 // Pop the block scope now but keep it alive to the end of this function.
16907 AnalysisBasedWarnings::Policy WP =
16908 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
16909 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
16910
16911 BlockExpr *Result = new (Context)
16912 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16913
16914 // If the block isn't obviously global, i.e. it captures anything at
16915 // all, then we need to do a few things in the surrounding context:
16916 if (Result->getBlockDecl()->hasCaptures()) {
16917 // First, this expression has a new cleanup object.
16918 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
16919 Cleanup.setExprNeedsCleanups(true);
16920
16921 // It also gets a branch-protected scope if any of the captured
16922 // variables needs destruction.
16923 for (const auto &CI : Result->getBlockDecl()->captures()) {
16924 const VarDecl *var = CI.getVariable();
16925 if (var->getType().isDestructedType() != QualType::DK_none) {
16926 setFunctionHasBranchProtectedScope();
16927 break;
16928 }
16929 }
16930 }
16931
16932 if (getCurFunction())
16933 getCurFunction()->addBlock(BD);
16934
16935 // This can happen if the block's return type is deduced, but
16936 // the return expression is invalid.
16937 if (BD->isInvalidDecl())
16938 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
16939 SubExprs: {Result}, T: Result->getType());
16940 return Result;
16941}
16942
16943ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16944 SourceLocation RPLoc) {
16945 TypeSourceInfo *TInfo;
16946 GetTypeFromParser(Ty, TInfo: &TInfo);
16947 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16948}
16949
16950ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16951 Expr *E, TypeSourceInfo *TInfo,
16952 SourceLocation RPLoc) {
16953 Expr *OrigExpr = E;
16954 bool IsMS = false;
16955
16956 // CUDA device global function does not support varargs.
16957 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16958 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
16959 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
16960 if (T == CUDAFunctionTarget::Global)
16961 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
16962 }
16963 }
16964
16965 // NVPTX does not support va_arg expression.
16966 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16967 Context.getTargetInfo().getTriple().isNVPTX())
16968 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
16969
16970 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16971 // as Microsoft ABI on an actual Microsoft platform, where
16972 // __builtin_ms_va_list and __builtin_va_list are the same.)
16973 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16974 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16975 QualType MSVaListType = Context.getBuiltinMSVaListType();
16976 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
16977 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
16978 return ExprError();
16979 IsMS = true;
16980 }
16981 }
16982
16983 // Get the va_list type
16984 QualType VaListType = Context.getBuiltinVaListType();
16985 if (!IsMS) {
16986 if (VaListType->isArrayType()) {
16987 // Deal with implicit array decay; for example, on x86-64,
16988 // va_list is an array, but it's supposed to decay to
16989 // a pointer for va_arg.
16990 VaListType = Context.getArrayDecayedType(T: VaListType);
16991 // Make sure the input expression also decays appropriately.
16992 ExprResult Result = UsualUnaryConversions(E);
16993 if (Result.isInvalid())
16994 return ExprError();
16995 E = Result.get();
16996 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16997 // If va_list is a record type and we are compiling in C++ mode,
16998 // check the argument using reference binding.
16999 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17000 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17001 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17002 if (Init.isInvalid())
17003 return ExprError();
17004 E = Init.getAs<Expr>();
17005 } else {
17006 // Otherwise, the va_list argument must be an l-value because
17007 // it is modified by va_arg.
17008 if (!E->isTypeDependent() &&
17009 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17010 return ExprError();
17011 }
17012 }
17013
17014 if (!IsMS && !E->isTypeDependent() &&
17015 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17016 return ExprError(
17017 Diag(Loc: E->getBeginLoc(),
17018 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17019 << OrigExpr->getType() << E->getSourceRange());
17020
17021 if (!TInfo->getType()->isDependentType()) {
17022 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17023 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17024 Args: TInfo->getTypeLoc()))
17025 return ExprError();
17026
17027 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17028 T: TInfo->getType(),
17029 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17030 Args: TInfo->getTypeLoc()))
17031 return ExprError();
17032
17033 if (!TInfo->getType().isPODType(Context)) {
17034 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17035 DiagID: TInfo->getType()->isObjCLifetimeType()
17036 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17037 : diag::warn_second_parameter_to_va_arg_not_pod)
17038 << TInfo->getType()
17039 << TInfo->getTypeLoc().getSourceRange();
17040 }
17041
17042 if (TInfo->getType()->isArrayType()) {
17043 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17044 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17045 << TInfo->getType()
17046 << TInfo->getTypeLoc().getSourceRange());
17047 }
17048
17049 // Check for va_arg where arguments of the given type will be promoted
17050 // (i.e. this va_arg is guaranteed to have undefined behavior).
17051 QualType PromoteType;
17052 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17053 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17054 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17055 // and C23 7.16.1.1p2 says, in part:
17056 // If type is not compatible with the type of the actual next argument
17057 // (as promoted according to the default argument promotions), the
17058 // behavior is undefined, except for the following cases:
17059 // - both types are pointers to qualified or unqualified versions of
17060 // compatible types;
17061 // - one type is compatible with a signed integer type, the other
17062 // type is compatible with the corresponding unsigned integer type,
17063 // and the value is representable in both types;
17064 // - one type is pointer to qualified or unqualified void and the
17065 // other is a pointer to a qualified or unqualified character type;
17066 // - or, the type of the next argument is nullptr_t and type is a
17067 // pointer type that has the same representation and alignment
17068 // requirements as a pointer to a character type.
17069 // Given that type compatibility is the primary requirement (ignoring
17070 // qualifications), you would think we could call typesAreCompatible()
17071 // directly to test this. However, in C++, that checks for *same type*,
17072 // which causes false positives when passing an enumeration type to
17073 // va_arg. Instead, get the underlying type of the enumeration and pass
17074 // that.
17075 QualType UnderlyingType = TInfo->getType();
17076 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17077 UnderlyingType = ED->getIntegerType();
17078 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17079 /*CompareUnqualified*/ true))
17080 PromoteType = QualType();
17081
17082 // If the types are still not compatible, we need to test whether the
17083 // promoted type and the underlying type are the same except for
17084 // signedness. Ask the AST for the correctly corresponding type and see
17085 // if that's compatible.
17086 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17087 PromoteType->isUnsignedIntegerType() !=
17088 UnderlyingType->isUnsignedIntegerType()) {
17089 UnderlyingType =
17090 UnderlyingType->isUnsignedIntegerType()
17091 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17092 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17093 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17094 /*CompareUnqualified*/ true))
17095 PromoteType = QualType();
17096 }
17097 }
17098 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17099 PromoteType = Context.DoubleTy;
17100 if (!PromoteType.isNull())
17101 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17102 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17103 << TInfo->getType()
17104 << PromoteType
17105 << TInfo->getTypeLoc().getSourceRange());
17106 }
17107
17108 QualType T = TInfo->getType().getNonLValueExprType(Context);
17109 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17110}
17111
17112ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17113 // The type of __null will be int or long, depending on the size of
17114 // pointers on the target.
17115 QualType Ty;
17116 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17117 if (pw == Context.getTargetInfo().getIntWidth())
17118 Ty = Context.IntTy;
17119 else if (pw == Context.getTargetInfo().getLongWidth())
17120 Ty = Context.LongTy;
17121 else if (pw == Context.getTargetInfo().getLongLongWidth())
17122 Ty = Context.LongLongTy;
17123 else {
17124 llvm_unreachable("I don't know size of pointer!");
17125 }
17126
17127 return new (Context) GNUNullExpr(Ty, TokenLoc);
17128}
17129
17130static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17131 CXXRecordDecl *ImplDecl = nullptr;
17132
17133 // Fetch the std::source_location::__impl decl.
17134 if (NamespaceDecl *Std = S.getStdNamespace()) {
17135 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17136 Loc, Sema::LookupOrdinaryName);
17137 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17138 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17139 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17140 Loc, Sema::LookupOrdinaryName);
17141 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17142 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17143 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17144 }
17145 }
17146 }
17147 }
17148
17149 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17150 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17151 return nullptr;
17152 }
17153
17154 // Verify that __impl is a trivial struct type, with no base classes, and with
17155 // only the four expected fields.
17156 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17157 ImplDecl->getNumBases() != 0) {
17158 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17159 return nullptr;
17160 }
17161
17162 unsigned Count = 0;
17163 for (FieldDecl *F : ImplDecl->fields()) {
17164 StringRef Name = F->getName();
17165
17166 if (Name == "_M_file_name") {
17167 if (F->getType() !=
17168 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17169 break;
17170 Count++;
17171 } else if (Name == "_M_function_name") {
17172 if (F->getType() !=
17173 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17174 break;
17175 Count++;
17176 } else if (Name == "_M_line") {
17177 if (!F->getType()->isIntegerType())
17178 break;
17179 Count++;
17180 } else if (Name == "_M_column") {
17181 if (!F->getType()->isIntegerType())
17182 break;
17183 Count++;
17184 } else {
17185 Count = 100; // invalid
17186 break;
17187 }
17188 }
17189 if (Count != 4) {
17190 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17191 return nullptr;
17192 }
17193
17194 return ImplDecl;
17195}
17196
17197ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17198 SourceLocation BuiltinLoc,
17199 SourceLocation RPLoc) {
17200 QualType ResultTy;
17201 switch (Kind) {
17202 case SourceLocIdentKind::File:
17203 case SourceLocIdentKind::FileName:
17204 case SourceLocIdentKind::Function:
17205 case SourceLocIdentKind::FuncSig: {
17206 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17207 ResultTy =
17208 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17209 break;
17210 }
17211 case SourceLocIdentKind::Line:
17212 case SourceLocIdentKind::Column:
17213 ResultTy = Context.UnsignedIntTy;
17214 break;
17215 case SourceLocIdentKind::SourceLocStruct:
17216 if (!StdSourceLocationImplDecl) {
17217 StdSourceLocationImplDecl =
17218 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17219 if (!StdSourceLocationImplDecl)
17220 return ExprError();
17221 }
17222 ResultTy = Context.getPointerType(
17223 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17224 break;
17225 }
17226
17227 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17228}
17229
17230ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17231 SourceLocation BuiltinLoc,
17232 SourceLocation RPLoc,
17233 DeclContext *ParentContext) {
17234 return new (Context)
17235 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17236}
17237
17238ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17239 StringLiteral *BinaryData, StringRef FileName) {
17240 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17241 Data->BinaryData = BinaryData;
17242 Data->FileName = FileName;
17243 return new (Context)
17244 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17245 Data->getDataElementCount());
17246}
17247
17248static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17249 const Expr *SrcExpr) {
17250 if (!DstType->isFunctionPointerType() ||
17251 !SrcExpr->getType()->isFunctionType())
17252 return false;
17253
17254 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17255 if (!DRE)
17256 return false;
17257
17258 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17259 if (!FD)
17260 return false;
17261
17262 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17263 /*Complain=*/true,
17264 Loc: SrcExpr->getBeginLoc());
17265}
17266
17267bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17268 SourceLocation Loc,
17269 QualType DstType, QualType SrcType,
17270 Expr *SrcExpr, AssignmentAction Action,
17271 bool *Complained) {
17272 if (Complained)
17273 *Complained = false;
17274
17275 // Decode the result (notice that AST's are still created for extensions).
17276 bool CheckInferredResultType = false;
17277 bool isInvalid = false;
17278 unsigned DiagKind = 0;
17279 ConversionFixItGenerator ConvHints;
17280 bool MayHaveConvFixit = false;
17281 bool MayHaveFunctionDiff = false;
17282 const ObjCInterfaceDecl *IFace = nullptr;
17283 const ObjCProtocolDecl *PDecl = nullptr;
17284
17285 switch (ConvTy) {
17286 case AssignConvertType::Compatible:
17287 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17288 return false;
17289 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17290 // Still a valid conversion, but we may want to diagnose for C++
17291 // compatibility reasons.
17292 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17293 break;
17294 case AssignConvertType::PointerToInt:
17295 if (getLangOpts().CPlusPlus) {
17296 DiagKind = diag::err_typecheck_convert_pointer_int;
17297 isInvalid = true;
17298 } else {
17299 DiagKind = diag::ext_typecheck_convert_pointer_int;
17300 }
17301 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17302 MayHaveConvFixit = true;
17303 break;
17304 case AssignConvertType::IntToPointer:
17305 if (getLangOpts().CPlusPlus) {
17306 DiagKind = diag::err_typecheck_convert_int_pointer;
17307 isInvalid = true;
17308 } else {
17309 DiagKind = diag::ext_typecheck_convert_int_pointer;
17310 }
17311 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17312 MayHaveConvFixit = true;
17313 break;
17314 case AssignConvertType::IncompatibleFunctionPointerStrict:
17315 DiagKind =
17316 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17317 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17318 MayHaveConvFixit = true;
17319 break;
17320 case AssignConvertType::IncompatibleFunctionPointer:
17321 if (getLangOpts().CPlusPlus) {
17322 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17323 isInvalid = true;
17324 } else {
17325 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17326 }
17327 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17328 MayHaveConvFixit = true;
17329 break;
17330 case AssignConvertType::IncompatiblePointer:
17331 if (Action == AssignmentAction::Passing_CFAudited) {
17332 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17333 } else if (getLangOpts().CPlusPlus) {
17334 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17335 isInvalid = true;
17336 } else {
17337 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17338 }
17339 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17340 SrcType->isObjCObjectPointerType();
17341 if (CheckInferredResultType) {
17342 SrcType = SrcType.getUnqualifiedType();
17343 DstType = DstType.getUnqualifiedType();
17344 } else {
17345 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17346 }
17347 MayHaveConvFixit = true;
17348 break;
17349 case AssignConvertType::IncompatiblePointerSign:
17350 if (getLangOpts().CPlusPlus) {
17351 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17352 isInvalid = true;
17353 } else {
17354 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17355 }
17356 break;
17357 case AssignConvertType::FunctionVoidPointer:
17358 if (getLangOpts().CPlusPlus) {
17359 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17360 isInvalid = true;
17361 } else {
17362 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17363 }
17364 break;
17365 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17366 // Perform array-to-pointer decay if necessary.
17367 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType);
17368
17369 isInvalid = true;
17370
17371 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17372 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17373 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17374 DiagKind = diag::err_typecheck_incompatible_address_space;
17375 break;
17376 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17377 DiagKind = diag::err_typecheck_incompatible_ownership;
17378 break;
17379 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17380 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17381 break;
17382 }
17383
17384 llvm_unreachable("unknown error case for discarding qualifiers!");
17385 // fallthrough
17386 }
17387 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17388 // If the qualifiers lost were because we were applying the
17389 // (deprecated) C++ conversion from a string literal to a char*
17390 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17391 // Ideally, this check would be performed in
17392 // checkPointerTypesForAssignment. However, that would require a
17393 // bit of refactoring (so that the second argument is an
17394 // expression, rather than a type), which should be done as part
17395 // of a larger effort to fix checkPointerTypesForAssignment for
17396 // C++ semantics.
17397 if (getLangOpts().CPlusPlus &&
17398 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17399 return false;
17400 if (getLangOpts().CPlusPlus) {
17401 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17402 isInvalid = true;
17403 } else {
17404 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17405 }
17406
17407 break;
17408 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17409 if (getLangOpts().CPlusPlus) {
17410 isInvalid = true;
17411 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17412 } else {
17413 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17414 }
17415 break;
17416 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17417 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17418 isInvalid = true;
17419 break;
17420 case AssignConvertType::IntToBlockPointer:
17421 DiagKind = diag::err_int_to_block_pointer;
17422 isInvalid = true;
17423 break;
17424 case AssignConvertType::IncompatibleBlockPointer:
17425 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17426 isInvalid = true;
17427 break;
17428 case AssignConvertType::IncompatibleObjCQualifiedId: {
17429 if (SrcType->isObjCQualifiedIdType()) {
17430 const ObjCObjectPointerType *srcOPT =
17431 SrcType->castAs<ObjCObjectPointerType>();
17432 for (auto *srcProto : srcOPT->quals()) {
17433 PDecl = srcProto;
17434 break;
17435 }
17436 if (const ObjCInterfaceType *IFaceT =
17437 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17438 IFace = IFaceT->getDecl();
17439 }
17440 else if (DstType->isObjCQualifiedIdType()) {
17441 const ObjCObjectPointerType *dstOPT =
17442 DstType->castAs<ObjCObjectPointerType>();
17443 for (auto *dstProto : dstOPT->quals()) {
17444 PDecl = dstProto;
17445 break;
17446 }
17447 if (const ObjCInterfaceType *IFaceT =
17448 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17449 IFace = IFaceT->getDecl();
17450 }
17451 if (getLangOpts().CPlusPlus) {
17452 DiagKind = diag::err_incompatible_qualified_id;
17453 isInvalid = true;
17454 } else {
17455 DiagKind = diag::warn_incompatible_qualified_id;
17456 }
17457 break;
17458 }
17459 case AssignConvertType::IncompatibleVectors:
17460 if (getLangOpts().CPlusPlus) {
17461 DiagKind = diag::err_incompatible_vectors;
17462 isInvalid = true;
17463 } else {
17464 DiagKind = diag::warn_incompatible_vectors;
17465 }
17466 break;
17467 case AssignConvertType::IncompatibleObjCWeakRef:
17468 DiagKind = diag::err_arc_weak_unavailable_assign;
17469 isInvalid = true;
17470 break;
17471 case AssignConvertType::Incompatible:
17472 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17473 if (Complained)
17474 *Complained = true;
17475 return true;
17476 }
17477
17478 DiagKind = diag::err_typecheck_convert_incompatible;
17479 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17480 MayHaveConvFixit = true;
17481 isInvalid = true;
17482 MayHaveFunctionDiff = true;
17483 break;
17484 }
17485
17486 QualType FirstType, SecondType;
17487 switch (Action) {
17488 case AssignmentAction::Assigning:
17489 case AssignmentAction::Initializing:
17490 // The destination type comes first.
17491 FirstType = DstType;
17492 SecondType = SrcType;
17493 break;
17494
17495 case AssignmentAction::Returning:
17496 case AssignmentAction::Passing:
17497 case AssignmentAction::Passing_CFAudited:
17498 case AssignmentAction::Converting:
17499 case AssignmentAction::Sending:
17500 case AssignmentAction::Casting:
17501 // The source type comes first.
17502 FirstType = SrcType;
17503 SecondType = DstType;
17504 break;
17505 }
17506
17507 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17508 AssignmentAction ActionForDiag = Action;
17509 if (Action == AssignmentAction::Passing_CFAudited)
17510 ActionForDiag = AssignmentAction::Passing;
17511
17512 FDiag << FirstType << SecondType << ActionForDiag
17513 << SrcExpr->getSourceRange();
17514
17515 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17516 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17517 auto isPlainChar = [](const clang::Type *Type) {
17518 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17519 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17520 };
17521 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17522 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17523 }
17524
17525 // If we can fix the conversion, suggest the FixIts.
17526 if (!ConvHints.isNull()) {
17527 for (FixItHint &H : ConvHints.Hints)
17528 FDiag << H;
17529 }
17530
17531 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17532
17533 if (MayHaveFunctionDiff)
17534 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17535
17536 Diag(Loc, PD: FDiag);
17537 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17538 DiagKind == diag::err_incompatible_qualified_id) &&
17539 PDecl && IFace && !IFace->hasDefinition())
17540 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17541 << IFace << PDecl;
17542
17543 if (SecondType == Context.OverloadTy)
17544 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17545 DestType: FirstType, /*TakingAddress=*/true);
17546
17547 if (CheckInferredResultType)
17548 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17549
17550 if (Action == AssignmentAction::Returning &&
17551 ConvTy == AssignConvertType::IncompatiblePointer)
17552 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17553
17554 if (Complained)
17555 *Complained = true;
17556 return isInvalid;
17557}
17558
17559ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17560 llvm::APSInt *Result,
17561 AllowFoldKind CanFold) {
17562 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17563 public:
17564 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17565 QualType T) override {
17566 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17567 << T << S.LangOpts.CPlusPlus;
17568 }
17569 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17570 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17571 }
17572 } Diagnoser;
17573
17574 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17575}
17576
17577ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17578 llvm::APSInt *Result,
17579 unsigned DiagID,
17580 AllowFoldKind CanFold) {
17581 class IDDiagnoser : public VerifyICEDiagnoser {
17582 unsigned DiagID;
17583
17584 public:
17585 IDDiagnoser(unsigned DiagID)
17586 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17587
17588 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17589 return S.Diag(Loc, DiagID);
17590 }
17591 } Diagnoser(DiagID);
17592
17593 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17594}
17595
17596Sema::SemaDiagnosticBuilder
17597Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17598 QualType T) {
17599 return diagnoseNotICE(S, Loc);
17600}
17601
17602Sema::SemaDiagnosticBuilder
17603Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17604 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17605}
17606
17607ExprResult
17608Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17609 VerifyICEDiagnoser &Diagnoser,
17610 AllowFoldKind CanFold) {
17611 SourceLocation DiagLoc = E->getBeginLoc();
17612
17613 if (getLangOpts().CPlusPlus11) {
17614 // C++11 [expr.const]p5:
17615 // If an expression of literal class type is used in a context where an
17616 // integral constant expression is required, then that class type shall
17617 // have a single non-explicit conversion function to an integral or
17618 // unscoped enumeration type
17619 ExprResult Converted;
17620 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17621 VerifyICEDiagnoser &BaseDiagnoser;
17622 public:
17623 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17624 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17625 BaseDiagnoser.Suppress, true),
17626 BaseDiagnoser(BaseDiagnoser) {}
17627
17628 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17629 QualType T) override {
17630 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17631 }
17632
17633 SemaDiagnosticBuilder diagnoseIncomplete(
17634 Sema &S, SourceLocation Loc, QualType T) override {
17635 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
17636 }
17637
17638 SemaDiagnosticBuilder diagnoseExplicitConv(
17639 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17640 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
17641 }
17642
17643 SemaDiagnosticBuilder noteExplicitConv(
17644 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17645 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17646 << ConvTy->isEnumeralType() << ConvTy;
17647 }
17648
17649 SemaDiagnosticBuilder diagnoseAmbiguous(
17650 Sema &S, SourceLocation Loc, QualType T) override {
17651 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
17652 }
17653
17654 SemaDiagnosticBuilder noteAmbiguous(
17655 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17656 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17657 << ConvTy->isEnumeralType() << ConvTy;
17658 }
17659
17660 SemaDiagnosticBuilder diagnoseConversion(
17661 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17662 llvm_unreachable("conversion functions are permitted");
17663 }
17664 } ConvertDiagnoser(Diagnoser);
17665
17666 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
17667 Converter&: ConvertDiagnoser);
17668 if (Converted.isInvalid())
17669 return Converted;
17670 E = Converted.get();
17671 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17672 // don't try to evaluate it later. We also don't want to return the
17673 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17674 // this function will attempt to use 'Value'.
17675 if (isa<RecoveryExpr>(Val: E))
17676 return ExprError();
17677 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17678 return ExprError();
17679 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17680 // An ICE must be of integral or unscoped enumeration type.
17681 if (!Diagnoser.Suppress)
17682 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
17683 << E->getSourceRange();
17684 return ExprError();
17685 }
17686
17687 ExprResult RValueExpr = DefaultLvalueConversion(E);
17688 if (RValueExpr.isInvalid())
17689 return ExprError();
17690
17691 E = RValueExpr.get();
17692
17693 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17694 // in the non-ICE case.
17695 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
17696 SmallVector<PartialDiagnosticAt, 8> Notes;
17697 if (Result)
17698 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
17699 if (!isa<ConstantExpr>(Val: E))
17700 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
17701 : ConstantExpr::Create(Context, E);
17702
17703 if (Notes.empty())
17704 return E;
17705
17706 // If our only note is the usual "invalid subexpression" note, just point
17707 // the caret at its location rather than producing an essentially
17708 // redundant note.
17709 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17710 diag::note_invalid_subexpr_in_const_expr) {
17711 DiagLoc = Notes[0].first;
17712 Notes.clear();
17713 }
17714
17715 if (getLangOpts().CPlusPlus) {
17716 if (!Diagnoser.Suppress) {
17717 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17718 for (const PartialDiagnosticAt &Note : Notes)
17719 Diag(Loc: Note.first, PD: Note.second);
17720 }
17721 return ExprError();
17722 }
17723
17724 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17725 for (const PartialDiagnosticAt &Note : Notes)
17726 Diag(Loc: Note.first, PD: Note.second);
17727
17728 return E;
17729 }
17730
17731 Expr::EvalResult EvalResult;
17732 SmallVector<PartialDiagnosticAt, 8> Notes;
17733 EvalResult.Diag = &Notes;
17734
17735 // Try to evaluate the expression, and produce diagnostics explaining why it's
17736 // not a constant expression as a side-effect.
17737 bool Folded =
17738 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
17739 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17740 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17741
17742 if (!isa<ConstantExpr>(Val: E))
17743 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
17744
17745 // In C++11, we can rely on diagnostics being produced for any expression
17746 // which is not a constant expression. If no diagnostics were produced, then
17747 // this is a constant expression.
17748 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17749 if (Result)
17750 *Result = EvalResult.Val.getInt();
17751 return E;
17752 }
17753
17754 // If our only note is the usual "invalid subexpression" note, just point
17755 // the caret at its location rather than producing an essentially
17756 // redundant note.
17757 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17758 diag::note_invalid_subexpr_in_const_expr) {
17759 DiagLoc = Notes[0].first;
17760 Notes.clear();
17761 }
17762
17763 if (!Folded || CanFold == AllowFoldKind::No) {
17764 if (!Diagnoser.Suppress) {
17765 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17766 for (const PartialDiagnosticAt &Note : Notes)
17767 Diag(Loc: Note.first, PD: Note.second);
17768 }
17769
17770 return ExprError();
17771 }
17772
17773 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17774 for (const PartialDiagnosticAt &Note : Notes)
17775 Diag(Loc: Note.first, PD: Note.second);
17776
17777 if (Result)
17778 *Result = EvalResult.Val.getInt();
17779 return E;
17780}
17781
17782namespace {
17783 // Handle the case where we conclude a expression which we speculatively
17784 // considered to be unevaluated is actually evaluated.
17785 class TransformToPE : public TreeTransform<TransformToPE> {
17786 typedef TreeTransform<TransformToPE> BaseTransform;
17787
17788 public:
17789 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17790
17791 // Make sure we redo semantic analysis
17792 bool AlwaysRebuild() { return true; }
17793 bool ReplacingOriginal() { return true; }
17794
17795 // We need to special-case DeclRefExprs referring to FieldDecls which
17796 // are not part of a member pointer formation; normal TreeTransforming
17797 // doesn't catch this case because of the way we represent them in the AST.
17798 // FIXME: This is a bit ugly; is it really the best way to handle this
17799 // case?
17800 //
17801 // Error on DeclRefExprs referring to FieldDecls.
17802 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17803 if (isa<FieldDecl>(Val: E->getDecl()) &&
17804 !SemaRef.isUnevaluatedContext())
17805 return SemaRef.Diag(Loc: E->getLocation(),
17806 DiagID: diag::err_invalid_non_static_member_use)
17807 << E->getDecl() << E->getSourceRange();
17808
17809 return BaseTransform::TransformDeclRefExpr(E);
17810 }
17811
17812 // Exception: filter out member pointer formation
17813 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17814 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17815 return E;
17816
17817 return BaseTransform::TransformUnaryOperator(E);
17818 }
17819
17820 // The body of a lambda-expression is in a separate expression evaluation
17821 // context so never needs to be transformed.
17822 // FIXME: Ideally we wouldn't transform the closure type either, and would
17823 // just recreate the capture expressions and lambda expression.
17824 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17825 return SkipLambdaBody(E, S: Body);
17826 }
17827 };
17828}
17829
17830ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17831 assert(isUnevaluatedContext() &&
17832 "Should only transform unevaluated expressions");
17833 ExprEvalContexts.back().Context =
17834 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17835 if (isUnevaluatedContext())
17836 return E;
17837 return TransformToPE(*this).TransformExpr(E);
17838}
17839
17840TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17841 assert(isUnevaluatedContext() &&
17842 "Should only transform unevaluated expressions");
17843 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
17844 if (isUnevaluatedContext())
17845 return TInfo;
17846 return TransformToPE(*this).TransformType(TSI: TInfo);
17847}
17848
17849void
17850Sema::PushExpressionEvaluationContext(
17851 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17852 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17853 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
17854 Args&: LambdaContextDecl, Args&: ExprContext);
17855
17856 // Discarded statements and immediate contexts nested in other
17857 // discarded statements or immediate context are themselves
17858 // a discarded statement or an immediate context, respectively.
17859 ExprEvalContexts.back().InDiscardedStatement =
17860 parentEvaluationContext().isDiscardedStatementContext();
17861
17862 // C++23 [expr.const]/p15
17863 // An expression or conversion is in an immediate function context if [...]
17864 // it is a subexpression of a manifestly constant-evaluated expression or
17865 // conversion.
17866 const auto &Prev = parentEvaluationContext();
17867 ExprEvalContexts.back().InImmediateFunctionContext =
17868 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17869
17870 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17871 Prev.InImmediateEscalatingFunctionContext;
17872
17873 Cleanup.reset();
17874 if (!MaybeODRUseExprs.empty())
17875 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
17876}
17877
17878void
17879Sema::PushExpressionEvaluationContext(
17880 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17881 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17882 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17883 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
17884}
17885
17886void Sema::PushExpressionEvaluationContextForFunction(
17887 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
17888 // [expr.const]/p14.1
17889 // An expression or conversion is in an immediate function context if it is
17890 // potentially evaluated and either: its innermost enclosing non-block scope
17891 // is a function parameter scope of an immediate function.
17892 PushExpressionEvaluationContext(
17893 NewContext: FD && FD->isConsteval()
17894 ? ExpressionEvaluationContext::ImmediateFunctionContext
17895 : NewContext);
17896 const Sema::ExpressionEvaluationContextRecord &Parent =
17897 parentEvaluationContext();
17898 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
17899
17900 Current.InDiscardedStatement = false;
17901
17902 if (FD) {
17903
17904 // Each ExpressionEvaluationContextRecord also keeps track of whether the
17905 // context is nested in an immediate function context, so smaller contexts
17906 // that appear inside immediate functions (like variable initializers) are
17907 // considered to be inside an immediate function context even though by
17908 // themselves they are not immediate function contexts. But when a new
17909 // function is entered, we need to reset this tracking, since the entered
17910 // function might be not an immediate function.
17911
17912 Current.InImmediateEscalatingFunctionContext =
17913 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
17914
17915 if (isLambdaMethod(DC: FD))
17916 Current.InImmediateFunctionContext =
17917 FD->isConsteval() ||
17918 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
17919 Parent.isImmediateFunctionContext()));
17920 else
17921 Current.InImmediateFunctionContext = FD->isConsteval();
17922 }
17923}
17924
17925namespace {
17926
17927const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17928 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17929 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
17930 if (E->getOpcode() == UO_Deref)
17931 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
17932 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
17933 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
17934 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
17935 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
17936 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
17937 QualType Inner;
17938 QualType Ty = E->getType();
17939 if (const auto *Ptr = Ty->getAs<PointerType>())
17940 Inner = Ptr->getPointeeType();
17941 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
17942 Inner = Arr->getElementType();
17943 else
17944 return nullptr;
17945
17946 if (Inner->hasAttr(AK: attr::NoDeref))
17947 return E;
17948 }
17949 return nullptr;
17950}
17951
17952} // namespace
17953
17954void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17955 for (const Expr *E : Rec.PossibleDerefs) {
17956 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
17957 if (DeclRef) {
17958 const ValueDecl *Decl = DeclRef->getDecl();
17959 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
17960 << Decl->getName() << E->getSourceRange();
17961 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
17962 } else {
17963 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
17964 << E->getSourceRange();
17965 }
17966 }
17967 Rec.PossibleDerefs.clear();
17968}
17969
17970void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17971 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17972 return;
17973
17974 // Note: ignoring parens here is not justified by the standard rules, but
17975 // ignoring parentheses seems like a more reasonable approach, and this only
17976 // drives a deprecation warning so doesn't affect conformance.
17977 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
17978 if (BO->getOpcode() == BO_Assign) {
17979 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17980 llvm::erase(C&: LHSs, V: BO->getLHS());
17981 }
17982 }
17983}
17984
17985void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
17986 assert(getLangOpts().CPlusPlus20 &&
17987 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17988 "Cannot mark an immediate escalating expression outside of an "
17989 "immediate escalating context");
17990 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
17991 Call && Call->getCallee()) {
17992 if (auto *DeclRef =
17993 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
17994 DeclRef->setIsImmediateEscalating(true);
17995 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
17996 Ctr->setIsImmediateEscalating(true);
17997 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
17998 DeclRef->setIsImmediateEscalating(true);
17999 } else {
18000 assert(false && "expected an immediately escalating expression");
18001 }
18002 if (FunctionScopeInfo *FI = getCurFunction())
18003 FI->FoundImmediateEscalatingExpression = true;
18004}
18005
18006ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18007 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18008 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18009 isCheckingDefaultArgumentOrInitializer() ||
18010 RebuildingImmediateInvocation || isImmediateFunctionContext())
18011 return E;
18012
18013 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18014 /// It's OK if this fails; we'll also remove this in
18015 /// HandleImmediateInvocations, but catching it here allows us to avoid
18016 /// walking the AST looking for it in simple cases.
18017 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18018 if (auto *DeclRef =
18019 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18020 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18021
18022 // C++23 [expr.const]/p16
18023 // An expression or conversion is immediate-escalating if it is not initially
18024 // in an immediate function context and it is [...] an immediate invocation
18025 // that is not a constant expression and is not a subexpression of an
18026 // immediate invocation.
18027 APValue Cached;
18028 auto CheckConstantExpressionAndKeepResult = [&]() {
18029 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18030 Expr::EvalResult Eval;
18031 Eval.Diag = &Notes;
18032 bool Res = E.get()->EvaluateAsConstantExpr(
18033 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18034 if (Res && Notes.empty()) {
18035 Cached = std::move(Eval.Val);
18036 return true;
18037 }
18038 return false;
18039 };
18040
18041 if (!E.get()->isValueDependent() &&
18042 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18043 !CheckConstantExpressionAndKeepResult()) {
18044 MarkExpressionAsImmediateEscalating(E: E.get());
18045 return E;
18046 }
18047
18048 if (Cleanup.exprNeedsCleanups()) {
18049 // Since an immediate invocation is a full expression itself - it requires
18050 // an additional ExprWithCleanups node, but it can participate to a bigger
18051 // full expression which actually requires cleanups to be run after so
18052 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18053 // may discard cleanups for outer expression too early.
18054
18055 // Note that ExprWithCleanups created here must always have empty cleanup
18056 // objects:
18057 // - compound literals do not create cleanup objects in C++ and immediate
18058 // invocations are C++-only.
18059 // - blocks are not allowed inside constant expressions and compiler will
18060 // issue an error if they appear there.
18061 //
18062 // Hence, in correct code any cleanup objects created inside current
18063 // evaluation context must be outside the immediate invocation.
18064 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18065 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18066 }
18067
18068 ConstantExpr *Res = ConstantExpr::Create(
18069 Context: getASTContext(), E: E.get(),
18070 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18071 Context: getASTContext()),
18072 /*IsImmediateInvocation*/ true);
18073 if (Cached.hasValue())
18074 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18075 /// Value-dependent constant expressions should not be immediately
18076 /// evaluated until they are instantiated.
18077 if (!Res->isValueDependent())
18078 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18079 return Res;
18080}
18081
18082static void EvaluateAndDiagnoseImmediateInvocation(
18083 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18084 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18085 Expr::EvalResult Eval;
18086 Eval.Diag = &Notes;
18087 ConstantExpr *CE = Candidate.getPointer();
18088 bool Result = CE->EvaluateAsConstantExpr(
18089 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18090 if (!Result || !Notes.empty()) {
18091 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18092 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18093 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18094 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18095 FunctionDecl *FD = nullptr;
18096 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18097 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18098 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18099 FD = Call->getConstructor();
18100 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18101 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18102
18103 assert(FD && FD->isImmediateFunction() &&
18104 "could not find an immediate function in this expression");
18105 if (FD->isInvalidDecl())
18106 return;
18107 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18108 << FD << FD->isConsteval();
18109 if (auto Context =
18110 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18111 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18112 << Context->Decl;
18113 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18114 }
18115 if (!FD->isConsteval())
18116 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18117 for (auto &Note : Notes)
18118 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18119 return;
18120 }
18121 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18122}
18123
18124static void RemoveNestedImmediateInvocation(
18125 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18126 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18127 struct ComplexRemove : TreeTransform<ComplexRemove> {
18128 using Base = TreeTransform<ComplexRemove>;
18129 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18130 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18131 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18132 CurrentII;
18133 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18134 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18135 SmallVector<Sema::ImmediateInvocationCandidate,
18136 4>::reverse_iterator Current)
18137 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18138 void RemoveImmediateInvocation(ConstantExpr* E) {
18139 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18140 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18141 return Elem.getPointer() == E;
18142 });
18143 // It is possible that some subexpression of the current immediate
18144 // invocation was handled from another expression evaluation context. Do
18145 // not handle the current immediate invocation if some of its
18146 // subexpressions failed before.
18147 if (It == IISet.rend()) {
18148 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18149 CurrentII->setInt(1);
18150 } else {
18151 It->setInt(1); // Mark as deleted
18152 }
18153 }
18154 ExprResult TransformConstantExpr(ConstantExpr *E) {
18155 if (!E->isImmediateInvocation())
18156 return Base::TransformConstantExpr(E);
18157 RemoveImmediateInvocation(E);
18158 return Base::TransformExpr(E: E->getSubExpr());
18159 }
18160 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18161 /// we need to remove its DeclRefExpr from the DRSet.
18162 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18163 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18164 return Base::TransformCXXOperatorCallExpr(E);
18165 }
18166 /// Base::TransformUserDefinedLiteral doesn't preserve the
18167 /// UserDefinedLiteral node.
18168 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18169 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18170 /// here.
18171 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18172 if (!Init)
18173 return Init;
18174
18175 // We cannot use IgnoreImpCasts because we need to preserve
18176 // full expressions.
18177 while (true) {
18178 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18179 Init = ICE->getSubExpr();
18180 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18181 Init = ICE->getSubExpr();
18182 else
18183 break;
18184 }
18185 /// ConstantExprs are the first layer of implicit node to be removed so if
18186 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18187 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18188 CE && CE->isImmediateInvocation())
18189 RemoveImmediateInvocation(E: CE);
18190 return Base::TransformInitializer(Init, NotCopyInit);
18191 }
18192 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18193 DRSet.erase(Ptr: E);
18194 return E;
18195 }
18196 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18197 // Do not rebuild lambdas to avoid creating a new type.
18198 // Lambdas have already been processed inside their eval contexts.
18199 return E;
18200 }
18201 bool AlwaysRebuild() { return false; }
18202 bool ReplacingOriginal() { return true; }
18203 bool AllowSkippingCXXConstructExpr() {
18204 bool Res = AllowSkippingFirstCXXConstructExpr;
18205 AllowSkippingFirstCXXConstructExpr = true;
18206 return Res;
18207 }
18208 bool AllowSkippingFirstCXXConstructExpr = true;
18209 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18210 Rec.ImmediateInvocationCandidates, It);
18211
18212 /// CXXConstructExpr with a single argument are getting skipped by
18213 /// TreeTransform in some situtation because they could be implicit. This
18214 /// can only occur for the top-level CXXConstructExpr because it is used
18215 /// nowhere in the expression being transformed therefore will not be rebuilt.
18216 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18217 /// skipping the first CXXConstructExpr.
18218 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18219 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18220
18221 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18222 // The result may not be usable in case of previous compilation errors.
18223 // In this case evaluation of the expression may result in crash so just
18224 // don't do anything further with the result.
18225 if (Res.isUsable()) {
18226 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18227 It->getPointer()->setSubExpr(Res.get());
18228 }
18229}
18230
18231static void
18232HandleImmediateInvocations(Sema &SemaRef,
18233 Sema::ExpressionEvaluationContextRecord &Rec) {
18234 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18235 Rec.ReferenceToConsteval.size() == 0) ||
18236 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18237 return;
18238
18239 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18240 // [...]
18241 // - the initializer of a variable that is usable in constant expressions or
18242 // has constant initialization.
18243 if (SemaRef.getLangOpts().CPlusPlus23 &&
18244 Rec.ExprContext ==
18245 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18246 auto *VD = cast<VarDecl>(Val: Rec.ManglingContextDecl);
18247 if (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18248 VD->hasConstantInitialization()) {
18249 // An expression or conversion is in an 'immediate function context' if it
18250 // is potentially evaluated and either:
18251 // [...]
18252 // - it is a subexpression of a manifestly constant-evaluated expression
18253 // or conversion.
18254 return;
18255 }
18256 }
18257
18258 /// When we have more than 1 ImmediateInvocationCandidates or previously
18259 /// failed immediate invocations, we need to check for nested
18260 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18261 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18262 /// invocation.
18263 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18264 !SemaRef.FailedImmediateInvocations.empty()) {
18265
18266 /// Prevent sema calls during the tree transform from adding pointers that
18267 /// are already in the sets.
18268 llvm::SaveAndRestore DisableIITracking(
18269 SemaRef.RebuildingImmediateInvocation, true);
18270
18271 /// Prevent diagnostic during tree transfrom as they are duplicates
18272 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18273
18274 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18275 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18276 if (!It->getInt())
18277 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18278 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18279 Rec.ReferenceToConsteval.size()) {
18280 struct SimpleRemove : DynamicRecursiveASTVisitor {
18281 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18282 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18283 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18284 DRSet.erase(Ptr: E);
18285 return DRSet.size();
18286 }
18287 } Visitor(Rec.ReferenceToConsteval);
18288 Visitor.TraverseStmt(
18289 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18290 }
18291 for (auto CE : Rec.ImmediateInvocationCandidates)
18292 if (!CE.getInt())
18293 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18294 for (auto *DR : Rec.ReferenceToConsteval) {
18295 // If the expression is immediate escalating, it is not an error;
18296 // The outer context itself becomes immediate and further errors,
18297 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18298 if (DR->isImmediateEscalating())
18299 continue;
18300 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18301 const NamedDecl *ND = FD;
18302 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18303 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18304 ND = MD->getParent();
18305
18306 // C++23 [expr.const]/p16
18307 // An expression or conversion is immediate-escalating if it is not
18308 // initially in an immediate function context and it is [...] a
18309 // potentially-evaluated id-expression that denotes an immediate function
18310 // that is not a subexpression of an immediate invocation.
18311 bool ImmediateEscalating = false;
18312 bool IsPotentiallyEvaluated =
18313 Rec.Context ==
18314 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18315 Rec.Context ==
18316 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18317 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18318 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18319
18320 if (!Rec.InImmediateEscalatingFunctionContext ||
18321 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18322 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18323 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18324 if (!FD->getBuiltinID())
18325 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18326 if (auto Context =
18327 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18328 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18329 << Context->Decl;
18330 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18331 }
18332 if (FD->isImmediateEscalating() && !FD->isConsteval())
18333 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18334
18335 } else {
18336 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18337 }
18338 }
18339}
18340
18341void Sema::PopExpressionEvaluationContext() {
18342 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18343 if (!Rec.Lambdas.empty()) {
18344 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18345 if (!getLangOpts().CPlusPlus20 &&
18346 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18347 Rec.isUnevaluated() ||
18348 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18349 unsigned D;
18350 if (Rec.isUnevaluated()) {
18351 // C++11 [expr.prim.lambda]p2:
18352 // A lambda-expression shall not appear in an unevaluated operand
18353 // (Clause 5).
18354 D = diag::err_lambda_unevaluated_operand;
18355 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18356 // C++1y [expr.const]p2:
18357 // A conditional-expression e is a core constant expression unless the
18358 // evaluation of e, following the rules of the abstract machine, would
18359 // evaluate [...] a lambda-expression.
18360 D = diag::err_lambda_in_constant_expression;
18361 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18362 // C++17 [expr.prim.lamda]p2:
18363 // A lambda-expression shall not appear [...] in a template-argument.
18364 D = diag::err_lambda_in_invalid_context;
18365 } else
18366 llvm_unreachable("Couldn't infer lambda error message.");
18367
18368 for (const auto *L : Rec.Lambdas)
18369 Diag(Loc: L->getBeginLoc(), DiagID: D);
18370 }
18371 }
18372
18373 // Append the collected materialized temporaries into previous context before
18374 // exit if the previous also is a lifetime extending context.
18375 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18376 parentEvaluationContext().InLifetimeExtendingContext &&
18377 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18378 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18379 RHS: Rec.ForRangeLifetimeExtendTemps);
18380 }
18381
18382 WarnOnPendingNoDerefs(Rec);
18383 HandleImmediateInvocations(SemaRef&: *this, Rec);
18384
18385 // Warn on any volatile-qualified simple-assignments that are not discarded-
18386 // value expressions nor unevaluated operands (those cases get removed from
18387 // this list by CheckUnusedVolatileAssignment).
18388 for (auto *BO : Rec.VolatileAssignmentLHSs)
18389 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18390 << BO->getType();
18391
18392 // When are coming out of an unevaluated context, clear out any
18393 // temporaries that we may have created as part of the evaluation of
18394 // the expression in that context: they aren't relevant because they
18395 // will never be constructed.
18396 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18397 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18398 CE: ExprCleanupObjects.end());
18399 Cleanup = Rec.ParentCleanup;
18400 CleanupVarDeclMarking();
18401 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18402 // Otherwise, merge the contexts together.
18403 } else {
18404 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18405 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18406 }
18407
18408 DiagnoseMisalignedMembers();
18409
18410 // Pop the current expression evaluation context off the stack.
18411 ExprEvalContexts.pop_back();
18412}
18413
18414void Sema::DiscardCleanupsInEvaluationContext() {
18415 ExprCleanupObjects.erase(
18416 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18417 CE: ExprCleanupObjects.end());
18418 Cleanup.reset();
18419 MaybeODRUseExprs.clear();
18420}
18421
18422ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18423 ExprResult Result = CheckPlaceholderExpr(E);
18424 if (Result.isInvalid())
18425 return ExprError();
18426 E = Result.get();
18427 if (!E->getType()->isVariablyModifiedType())
18428 return E;
18429 return TransformToPotentiallyEvaluated(E);
18430}
18431
18432/// Are we in a context that is potentially constant evaluated per C++20
18433/// [expr.const]p12?
18434static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18435 /// C++2a [expr.const]p12:
18436 // An expression or conversion is potentially constant evaluated if it is
18437 switch (SemaRef.ExprEvalContexts.back().Context) {
18438 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18439 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18440
18441 // -- a manifestly constant-evaluated expression,
18442 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18443 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18444 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18445 // -- a potentially-evaluated expression,
18446 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18447 // -- an immediate subexpression of a braced-init-list,
18448
18449 // -- [FIXME] an expression of the form & cast-expression that occurs
18450 // within a templated entity
18451 // -- a subexpression of one of the above that is not a subexpression of
18452 // a nested unevaluated operand.
18453 return true;
18454
18455 case Sema::ExpressionEvaluationContext::Unevaluated:
18456 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18457 // Expressions in this context are never evaluated.
18458 return false;
18459 }
18460 llvm_unreachable("Invalid context");
18461}
18462
18463/// Return true if this function has a calling convention that requires mangling
18464/// in the size of the parameter pack.
18465static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18466 // These manglings are only applicable for targets whcih use Microsoft
18467 // mangling scheme for C.
18468 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18469 return false;
18470
18471 // If this is C++ and this isn't an extern "C" function, parameters do not
18472 // need to be complete. In this case, C++ mangling will apply, which doesn't
18473 // use the size of the parameters.
18474 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18475 return false;
18476
18477 // Stdcall, fastcall, and vectorcall need this special treatment.
18478 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18479 switch (CC) {
18480 case CC_X86StdCall:
18481 case CC_X86FastCall:
18482 case CC_X86VectorCall:
18483 return true;
18484 default:
18485 break;
18486 }
18487 return false;
18488}
18489
18490/// Require that all of the parameter types of function be complete. Normally,
18491/// parameter types are only required to be complete when a function is called
18492/// or defined, but to mangle functions with certain calling conventions, the
18493/// mangler needs to know the size of the parameter list. In this situation,
18494/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18495/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18496/// result in a linker error. Clang doesn't implement this behavior, and instead
18497/// attempts to error at compile time.
18498static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18499 SourceLocation Loc) {
18500 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18501 FunctionDecl *FD;
18502 ParmVarDecl *Param;
18503
18504 public:
18505 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18506 : FD(FD), Param(Param) {}
18507
18508 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18509 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18510 StringRef CCName;
18511 switch (CC) {
18512 case CC_X86StdCall:
18513 CCName = "stdcall";
18514 break;
18515 case CC_X86FastCall:
18516 CCName = "fastcall";
18517 break;
18518 case CC_X86VectorCall:
18519 CCName = "vectorcall";
18520 break;
18521 default:
18522 llvm_unreachable("CC does not need mangling");
18523 }
18524
18525 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18526 << Param->getDeclName() << FD->getDeclName() << CCName;
18527 }
18528 };
18529
18530 for (ParmVarDecl *Param : FD->parameters()) {
18531 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18532 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18533 }
18534}
18535
18536namespace {
18537enum class OdrUseContext {
18538 /// Declarations in this context are not odr-used.
18539 None,
18540 /// Declarations in this context are formally odr-used, but this is a
18541 /// dependent context.
18542 Dependent,
18543 /// Declarations in this context are odr-used but not actually used (yet).
18544 FormallyOdrUsed,
18545 /// Declarations in this context are used.
18546 Used
18547};
18548}
18549
18550/// Are we within a context in which references to resolved functions or to
18551/// variables result in odr-use?
18552static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18553 const Sema::ExpressionEvaluationContextRecord &Context =
18554 SemaRef.currentEvaluationContext();
18555
18556 if (Context.isUnevaluated())
18557 return OdrUseContext::None;
18558
18559 if (SemaRef.CurContext->isDependentContext())
18560 return OdrUseContext::Dependent;
18561
18562 if (Context.isDiscardedStatementContext())
18563 return OdrUseContext::FormallyOdrUsed;
18564
18565 else if (Context.Context ==
18566 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18567 return OdrUseContext::FormallyOdrUsed;
18568
18569 return OdrUseContext::Used;
18570}
18571
18572static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18573 if (!Func->isConstexpr())
18574 return false;
18575
18576 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18577 return true;
18578
18579 // Lambda conversion operators are never user provided.
18580 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
18581 return isLambdaConversionOperator(C: Conv);
18582
18583 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18584 return CCD && CCD->getInheritedConstructor();
18585}
18586
18587void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18588 bool MightBeOdrUse) {
18589 assert(Func && "No function?");
18590
18591 Func->setReferenced();
18592
18593 // Recursive functions aren't really used until they're used from some other
18594 // context.
18595 bool IsRecursiveCall = CurContext == Func;
18596
18597 // C++11 [basic.def.odr]p3:
18598 // A function whose name appears as a potentially-evaluated expression is
18599 // odr-used if it is the unique lookup result or the selected member of a
18600 // set of overloaded functions [...].
18601 //
18602 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18603 // can just check that here.
18604 OdrUseContext OdrUse =
18605 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18606 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18607 OdrUse = OdrUseContext::FormallyOdrUsed;
18608
18609 // Trivial default constructors and destructors are never actually used.
18610 // FIXME: What about other special members?
18611 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18612 OdrUse == OdrUseContext::Used) {
18613 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
18614 if (Constructor->isDefaultConstructor())
18615 OdrUse = OdrUseContext::FormallyOdrUsed;
18616 if (isa<CXXDestructorDecl>(Val: Func))
18617 OdrUse = OdrUseContext::FormallyOdrUsed;
18618 }
18619
18620 // C++20 [expr.const]p12:
18621 // A function [...] is needed for constant evaluation if it is [...] a
18622 // constexpr function that is named by an expression that is potentially
18623 // constant evaluated
18624 bool NeededForConstantEvaluation =
18625 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18626 isImplicitlyDefinableConstexprFunction(Func);
18627
18628 // Determine whether we require a function definition to exist, per
18629 // C++11 [temp.inst]p3:
18630 // Unless a function template specialization has been explicitly
18631 // instantiated or explicitly specialized, the function template
18632 // specialization is implicitly instantiated when the specialization is
18633 // referenced in a context that requires a function definition to exist.
18634 // C++20 [temp.inst]p7:
18635 // The existence of a definition of a [...] function is considered to
18636 // affect the semantics of the program if the [...] function is needed for
18637 // constant evaluation by an expression
18638 // C++20 [basic.def.odr]p10:
18639 // Every program shall contain exactly one definition of every non-inline
18640 // function or variable that is odr-used in that program outside of a
18641 // discarded statement
18642 // C++20 [special]p1:
18643 // The implementation will implicitly define [defaulted special members]
18644 // if they are odr-used or needed for constant evaluation.
18645 //
18646 // Note that we skip the implicit instantiation of templates that are only
18647 // used in unused default arguments or by recursive calls to themselves.
18648 // This is formally non-conforming, but seems reasonable in practice.
18649 bool NeedDefinition =
18650 !IsRecursiveCall &&
18651 (OdrUse == OdrUseContext::Used ||
18652 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18653
18654 // C++14 [temp.expl.spec]p6:
18655 // If a template [...] is explicitly specialized then that specialization
18656 // shall be declared before the first use of that specialization that would
18657 // cause an implicit instantiation to take place, in every translation unit
18658 // in which such a use occurs
18659 if (NeedDefinition &&
18660 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18661 Func->getMemberSpecializationInfo()))
18662 checkSpecializationReachability(Loc, Spec: Func);
18663
18664 if (getLangOpts().CUDA)
18665 CUDA().CheckCall(Loc, Callee: Func);
18666
18667 // If we need a definition, try to create one.
18668 if (NeedDefinition && !Func->getBody()) {
18669 runWithSufficientStackSpace(Loc, Fn: [&] {
18670 if (CXXConstructorDecl *Constructor =
18671 dyn_cast<CXXConstructorDecl>(Val: Func)) {
18672 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
18673 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18674 if (Constructor->isDefaultConstructor()) {
18675 if (Constructor->isTrivial() &&
18676 !Constructor->hasAttr<DLLExportAttr>())
18677 return;
18678 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
18679 } else if (Constructor->isCopyConstructor()) {
18680 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
18681 } else if (Constructor->isMoveConstructor()) {
18682 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
18683 }
18684 } else if (Constructor->getInheritedConstructor()) {
18685 DefineInheritingConstructor(UseLoc: Loc, Constructor);
18686 }
18687 } else if (CXXDestructorDecl *Destructor =
18688 dyn_cast<CXXDestructorDecl>(Val: Func)) {
18689 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
18690 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18691 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18692 return;
18693 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
18694 }
18695 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18696 MarkVTableUsed(Loc, Class: Destructor->getParent());
18697 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
18698 if (MethodDecl->isOverloadedOperator() &&
18699 MethodDecl->getOverloadedOperator() == OO_Equal) {
18700 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
18701 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18702 if (MethodDecl->isCopyAssignmentOperator())
18703 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
18704 else if (MethodDecl->isMoveAssignmentOperator())
18705 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
18706 }
18707 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
18708 MethodDecl->getParent()->isLambda()) {
18709 CXXConversionDecl *Conversion =
18710 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
18711 if (Conversion->isLambdaToBlockPointerConversion())
18712 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18713 else
18714 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18715 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18716 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
18717 }
18718
18719 if (Func->isDefaulted() && !Func->isDeleted()) {
18720 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
18721 if (DCK != DefaultedComparisonKind::None)
18722 DefineDefaultedComparison(Loc, FD: Func, DCK);
18723 }
18724
18725 // Implicit instantiation of function templates and member functions of
18726 // class templates.
18727 if (Func->isImplicitlyInstantiable()) {
18728 TemplateSpecializationKind TSK =
18729 Func->getTemplateSpecializationKindForInstantiation();
18730 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18731 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18732 if (FirstInstantiation) {
18733 PointOfInstantiation = Loc;
18734 if (auto *MSI = Func->getMemberSpecializationInfo())
18735 MSI->setPointOfInstantiation(Loc);
18736 // FIXME: Notify listener.
18737 else
18738 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18739 } else if (TSK != TSK_ImplicitInstantiation) {
18740 // Use the point of use as the point of instantiation, instead of the
18741 // point of explicit instantiation (which we track as the actual point
18742 // of instantiation). This gives better backtraces in diagnostics.
18743 PointOfInstantiation = Loc;
18744 }
18745
18746 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18747 Func->isConstexpr()) {
18748 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
18749 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
18750 CodeSynthesisContexts.size())
18751 PendingLocalImplicitInstantiations.push_back(
18752 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
18753 else if (Func->isConstexpr())
18754 // Do not defer instantiations of constexpr functions, to avoid the
18755 // expression evaluator needing to call back into Sema if it sees a
18756 // call to such a function.
18757 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
18758 else {
18759 Func->setInstantiationIsPending(true);
18760 PendingInstantiations.push_back(
18761 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
18762 if (llvm::isTimeTraceVerbose()) {
18763 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
18764 std::string Name;
18765 llvm::raw_string_ostream OS(Name);
18766 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
18767 /*Qualified=*/true);
18768 return Name;
18769 });
18770 }
18771 // Notify the consumer that a function was implicitly instantiated.
18772 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
18773 }
18774 }
18775 } else {
18776 // Walk redefinitions, as some of them may be instantiable.
18777 for (auto *i : Func->redecls()) {
18778 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
18779 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
18780 }
18781 }
18782 });
18783 }
18784
18785 // If a constructor was defined in the context of a default parameter
18786 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18787 // context), its initializers may not be referenced yet.
18788 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
18789 EnterExpressionEvaluationContext EvalContext(
18790 *this,
18791 Constructor->isImmediateFunction()
18792 ? ExpressionEvaluationContext::ImmediateFunctionContext
18793 : ExpressionEvaluationContext::PotentiallyEvaluated,
18794 Constructor);
18795 for (CXXCtorInitializer *Init : Constructor->inits()) {
18796 if (Init->isInClassMemberInitializer())
18797 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
18798 MarkDeclarationsReferencedInExpr(E: Init->getInit());
18799 });
18800 }
18801 }
18802
18803 // C++14 [except.spec]p17:
18804 // An exception-specification is considered to be needed when:
18805 // - the function is odr-used or, if it appears in an unevaluated operand,
18806 // would be odr-used if the expression were potentially-evaluated;
18807 //
18808 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18809 // function is a pure virtual function we're calling, and in that case the
18810 // function was selected by overload resolution and we need to resolve its
18811 // exception specification for a different reason.
18812 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18813 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
18814 ResolveExceptionSpec(Loc, FPT);
18815
18816 // A callee could be called by a host function then by a device function.
18817 // If we only try recording once, we will miss recording the use on device
18818 // side. Therefore keep trying until it is recorded.
18819 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18820 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
18821 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
18822
18823 // If this is the first "real" use, act on that.
18824 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18825 // Keep track of used but undefined functions.
18826 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
18827 if (mightHaveNonExternalLinkage(FD: Func))
18828 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
18829 else if (Func->getMostRecentDecl()->isInlined() &&
18830 !LangOpts.GNUInline &&
18831 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18832 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
18833 else if (isExternalWithNoLinkageType(VD: Func))
18834 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
18835 }
18836
18837 // Some x86 Windows calling conventions mangle the size of the parameter
18838 // pack into the name. Computing the size of the parameters requires the
18839 // parameter types to be complete. Check that now.
18840 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
18841 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
18842
18843 // In the MS C++ ABI, the compiler emits destructor variants where they are
18844 // used. If the destructor is used here but defined elsewhere, mark the
18845 // virtual base destructors referenced. If those virtual base destructors
18846 // are inline, this will ensure they are defined when emitting the complete
18847 // destructor variant. This checking may be redundant if the destructor is
18848 // provided later in this TU.
18849 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18850 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
18851 CXXRecordDecl *Parent = Dtor->getParent();
18852 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18853 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
18854 }
18855 }
18856
18857 Func->markUsed(C&: Context);
18858 }
18859}
18860
18861/// Directly mark a variable odr-used. Given a choice, prefer to use
18862/// MarkVariableReferenced since it does additional checks and then
18863/// calls MarkVarDeclODRUsed.
18864/// If the variable must be captured:
18865/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18866/// - else capture it in the DeclContext that maps to the
18867/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18868static void
18869MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18870 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18871 // Keep track of used but undefined variables.
18872 // FIXME: We shouldn't suppress this warning for static data members.
18873 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18874 assert(Var && "expected a capturable variable");
18875
18876 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18877 (!Var->isExternallyVisible() || Var->isInline() ||
18878 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
18879 !(Var->isStaticDataMember() && Var->hasInit())) {
18880 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18881 if (old.isInvalid())
18882 old = Loc;
18883 }
18884 QualType CaptureType, DeclRefType;
18885 if (SemaRef.LangOpts.OpenMP)
18886 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
18887 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
18888 /*EllipsisLoc*/ SourceLocation(),
18889 /*BuildAndDiagnose*/ true, CaptureType,
18890 DeclRefType, FunctionScopeIndexToStopAt);
18891
18892 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18893 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
18894 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
18895 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
18896 if (VarTarget == SemaCUDA::CVT_Host &&
18897 (UserTarget == CUDAFunctionTarget::Device ||
18898 UserTarget == CUDAFunctionTarget::HostDevice ||
18899 UserTarget == CUDAFunctionTarget::Global)) {
18900 // Diagnose ODR-use of host global variables in device functions.
18901 // Reference of device global variables in host functions is allowed
18902 // through shadow variables therefore it is not diagnosed.
18903 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18904 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
18905 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18906 SemaRef.targetDiag(Loc: Var->getLocation(),
18907 DiagID: Var->getType().isConstQualified()
18908 ? diag::note_cuda_const_var_unpromoted
18909 : diag::note_cuda_host_var);
18910 }
18911 } else if (VarTarget == SemaCUDA::CVT_Device &&
18912 !Var->hasAttr<CUDASharedAttr>() &&
18913 (UserTarget == CUDAFunctionTarget::Host ||
18914 UserTarget == CUDAFunctionTarget::HostDevice)) {
18915 // Record a CUDA/HIP device side variable if it is ODR-used
18916 // by host code. This is done conservatively, when the variable is
18917 // referenced in any of the following contexts:
18918 // - a non-function context
18919 // - a host function
18920 // - a host device function
18921 // This makes the ODR-use of the device side variable by host code to
18922 // be visible in the device compilation for the compiler to be able to
18923 // emit template variables instantiated by host code only and to
18924 // externalize the static device side variable ODR-used by host code.
18925 if (!Var->hasExternalStorage())
18926 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var);
18927 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18928 (!FD || (!FD->getDescribedFunctionTemplate() &&
18929 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
18930 GVA_StrongExternal)))
18931 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
18932 }
18933 }
18934
18935 V->markUsed(C&: SemaRef.Context);
18936}
18937
18938void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18939 SourceLocation Loc,
18940 unsigned CapturingScopeIndex) {
18941 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
18942}
18943
18944static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
18945 SourceLocation loc,
18946 ValueDecl *var) {
18947 DeclContext *VarDC = var->getDeclContext();
18948
18949 // If the parameter still belongs to the translation unit, then
18950 // we're actually just using one parameter in the declaration of
18951 // the next.
18952 if (isa<ParmVarDecl>(Val: var) &&
18953 isa<TranslationUnitDecl>(Val: VarDC))
18954 return;
18955
18956 // For C code, don't diagnose about capture if we're not actually in code
18957 // right now; it's impossible to write a non-constant expression outside of
18958 // function context, so we'll get other (more useful) diagnostics later.
18959 //
18960 // For C++, things get a bit more nasty... it would be nice to suppress this
18961 // diagnostic for certain cases like using a local variable in an array bound
18962 // for a member of a local class, but the correct predicate is not obvious.
18963 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18964 return;
18965
18966 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
18967 unsigned ContextKind = 3; // unknown
18968 if (isa<CXXMethodDecl>(Val: VarDC) &&
18969 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
18970 ContextKind = 2;
18971 } else if (isa<FunctionDecl>(Val: VarDC)) {
18972 ContextKind = 0;
18973 } else if (isa<BlockDecl>(Val: VarDC)) {
18974 ContextKind = 1;
18975 }
18976
18977 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
18978 << var << ValueKind << ContextKind << VarDC;
18979 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
18980 << var;
18981
18982 // FIXME: Add additional diagnostic info about class etc. which prevents
18983 // capture.
18984}
18985
18986static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18987 ValueDecl *Var,
18988 bool &SubCapturesAreNested,
18989 QualType &CaptureType,
18990 QualType &DeclRefType) {
18991 // Check whether we've already captured it.
18992 if (CSI->CaptureMap.count(Val: Var)) {
18993 // If we found a capture, any subcaptures are nested.
18994 SubCapturesAreNested = true;
18995
18996 // Retrieve the capture type for this variable.
18997 CaptureType = CSI->getCapture(Var).getCaptureType();
18998
18999 // Compute the type of an expression that refers to this variable.
19000 DeclRefType = CaptureType.getNonReferenceType();
19001
19002 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19003 // are mutable in the sense that user can change their value - they are
19004 // private instances of the captured declarations.
19005 const Capture &Cap = CSI->getCapture(Var);
19006 // C++ [expr.prim.lambda]p10:
19007 // The type of such a data member is [...] an lvalue reference to the
19008 // referenced function type if the entity is a reference to a function.
19009 // [...]
19010 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19011 !(isa<LambdaScopeInfo>(Val: CSI) &&
19012 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19013 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19014 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19015 DeclRefType.addConst();
19016 return true;
19017 }
19018 return false;
19019}
19020
19021// Only block literals, captured statements, and lambda expressions can
19022// capture; other scopes don't work.
19023static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19024 ValueDecl *Var,
19025 SourceLocation Loc,
19026 const bool Diagnose,
19027 Sema &S) {
19028 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19029 return getLambdaAwareParentOfDeclContext(DC);
19030
19031 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19032 if (Underlying) {
19033 if (Underlying->hasLocalStorage() && Diagnose)
19034 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19035 }
19036 return nullptr;
19037}
19038
19039// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19040// certain types of variables (unnamed, variably modified types etc.)
19041// so check for eligibility.
19042static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19043 SourceLocation Loc, const bool Diagnose,
19044 Sema &S) {
19045
19046 assert((isa<VarDecl, BindingDecl>(Var)) &&
19047 "Only variables and structured bindings can be captured");
19048
19049 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19050 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19051
19052 // Lambdas are not allowed to capture unnamed variables
19053 // (e.g. anonymous unions).
19054 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19055 // assuming that's the intent.
19056 if (IsLambda && !Var->getDeclName()) {
19057 if (Diagnose) {
19058 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19059 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19060 }
19061 return false;
19062 }
19063
19064 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19065 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19066 if (Diagnose) {
19067 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19068 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19069 }
19070 return false;
19071 }
19072 // Prohibit structs with flexible array members too.
19073 // We cannot capture what is in the tail end of the struct.
19074 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19075 VTD && VTD->hasFlexibleArrayMember()) {
19076 if (Diagnose) {
19077 if (IsBlock)
19078 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19079 else
19080 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19081 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19082 }
19083 return false;
19084 }
19085 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19086 // Lambdas and captured statements are not allowed to capture __block
19087 // variables; they don't support the expected semantics.
19088 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19089 if (Diagnose) {
19090 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19091 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19092 }
19093 return false;
19094 }
19095 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19096 if (S.getLangOpts().OpenCL && IsBlock &&
19097 Var->getType()->isBlockPointerType()) {
19098 if (Diagnose)
19099 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19100 return false;
19101 }
19102
19103 if (isa<BindingDecl>(Val: Var)) {
19104 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19105 if (Diagnose)
19106 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19107 return false;
19108 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19109 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19110 ? diag::warn_cxx17_compat_capture_binding
19111 : diag::ext_capture_binding)
19112 << Var;
19113 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19114 }
19115 }
19116
19117 return true;
19118}
19119
19120// Returns true if the capture by block was successful.
19121static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19122 SourceLocation Loc, const bool BuildAndDiagnose,
19123 QualType &CaptureType, QualType &DeclRefType,
19124 const bool Nested, Sema &S, bool Invalid) {
19125 bool ByRef = false;
19126
19127 // Blocks are not allowed to capture arrays, excepting OpenCL.
19128 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19129 // (decayed to pointers).
19130 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19131 if (BuildAndDiagnose) {
19132 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19133 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19134 Invalid = true;
19135 } else {
19136 return false;
19137 }
19138 }
19139
19140 // Forbid the block-capture of autoreleasing variables.
19141 if (!Invalid &&
19142 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19143 if (BuildAndDiagnose) {
19144 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19145 << /*block*/ 0;
19146 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19147 Invalid = true;
19148 } else {
19149 return false;
19150 }
19151 }
19152
19153 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19154 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19155 QualType PointeeTy = PT->getPointeeType();
19156
19157 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19158 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19159 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19160 if (BuildAndDiagnose) {
19161 SourceLocation VarLoc = Var->getLocation();
19162 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19163 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19164 }
19165 }
19166 }
19167
19168 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19169 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19170 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19171 // Block capture by reference does not change the capture or
19172 // declaration reference types.
19173 ByRef = true;
19174 } else {
19175 // Block capture by copy introduces 'const'.
19176 CaptureType = CaptureType.getNonReferenceType().withConst();
19177 DeclRefType = CaptureType;
19178 }
19179
19180 // Actually capture the variable.
19181 if (BuildAndDiagnose)
19182 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19183 CaptureType, Invalid);
19184
19185 return !Invalid;
19186}
19187
19188/// Capture the given variable in the captured region.
19189static bool captureInCapturedRegion(
19190 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19191 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19192 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19193 Sema &S, bool Invalid) {
19194 // By default, capture variables by reference.
19195 bool ByRef = true;
19196 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19197 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19198 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19199 // Using an LValue reference type is consistent with Lambdas (see below).
19200 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19201 bool HasConst = DeclRefType.isConstQualified();
19202 DeclRefType = DeclRefType.getUnqualifiedType();
19203 // Don't lose diagnostics about assignments to const.
19204 if (HasConst)
19205 DeclRefType.addConst();
19206 }
19207 // Do not capture firstprivates in tasks.
19208 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19209 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19210 return true;
19211 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19212 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19213 }
19214
19215 if (ByRef)
19216 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19217 else
19218 CaptureType = DeclRefType;
19219
19220 // Actually capture the variable.
19221 if (BuildAndDiagnose)
19222 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19223 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19224
19225 return !Invalid;
19226}
19227
19228/// Capture the given variable in the lambda.
19229static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19230 SourceLocation Loc, const bool BuildAndDiagnose,
19231 QualType &CaptureType, QualType &DeclRefType,
19232 const bool RefersToCapturedVariable,
19233 const TryCaptureKind Kind,
19234 SourceLocation EllipsisLoc, const bool IsTopScope,
19235 Sema &S, bool Invalid) {
19236 // Determine whether we are capturing by reference or by value.
19237 bool ByRef = false;
19238 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19239 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19240 } else {
19241 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19242 }
19243
19244 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19245 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19246 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19247 Invalid = true;
19248 }
19249
19250 // Compute the type of the field that will capture this variable.
19251 if (ByRef) {
19252 // C++11 [expr.prim.lambda]p15:
19253 // An entity is captured by reference if it is implicitly or
19254 // explicitly captured but not captured by copy. It is
19255 // unspecified whether additional unnamed non-static data
19256 // members are declared in the closure type for entities
19257 // captured by reference.
19258 //
19259 // FIXME: It is not clear whether we want to build an lvalue reference
19260 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19261 // to do the former, while EDG does the latter. Core issue 1249 will
19262 // clarify, but for now we follow GCC because it's a more permissive and
19263 // easily defensible position.
19264 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19265 } else {
19266 // C++11 [expr.prim.lambda]p14:
19267 // For each entity captured by copy, an unnamed non-static
19268 // data member is declared in the closure type. The
19269 // declaration order of these members is unspecified. The type
19270 // of such a data member is the type of the corresponding
19271 // captured entity if the entity is not a reference to an
19272 // object, or the referenced type otherwise. [Note: If the
19273 // captured entity is a reference to a function, the
19274 // corresponding data member is also a reference to a
19275 // function. - end note ]
19276 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19277 if (!RefType->getPointeeType()->isFunctionType())
19278 CaptureType = RefType->getPointeeType();
19279 }
19280
19281 // Forbid the lambda copy-capture of autoreleasing variables.
19282 if (!Invalid &&
19283 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19284 if (BuildAndDiagnose) {
19285 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19286 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19287 << Var->getDeclName();
19288 Invalid = true;
19289 } else {
19290 return false;
19291 }
19292 }
19293
19294 // Make sure that by-copy captures are of a complete and non-abstract type.
19295 if (!Invalid && BuildAndDiagnose) {
19296 if (!CaptureType->isDependentType() &&
19297 S.RequireCompleteSizedType(
19298 Loc, T: CaptureType,
19299 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19300 Args: Var->getDeclName()))
19301 Invalid = true;
19302 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19303 DiagID: diag::err_capture_of_abstract_type))
19304 Invalid = true;
19305 }
19306 }
19307
19308 // Compute the type of a reference to this captured variable.
19309 if (ByRef)
19310 DeclRefType = CaptureType.getNonReferenceType();
19311 else {
19312 // C++ [expr.prim.lambda]p5:
19313 // The closure type for a lambda-expression has a public inline
19314 // function call operator [...]. This function call operator is
19315 // declared const (9.3.1) if and only if the lambda-expression's
19316 // parameter-declaration-clause is not followed by mutable.
19317 DeclRefType = CaptureType.getNonReferenceType();
19318 bool Const = LSI->lambdaCaptureShouldBeConst();
19319 // C++ [expr.prim.lambda]p10:
19320 // The type of such a data member is [...] an lvalue reference to the
19321 // referenced function type if the entity is a reference to a function.
19322 // [...]
19323 if (Const && !CaptureType->isReferenceType() &&
19324 !DeclRefType->isFunctionType())
19325 DeclRefType.addConst();
19326 }
19327
19328 // Add the capture.
19329 if (BuildAndDiagnose)
19330 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19331 Loc, EllipsisLoc, CaptureType, Invalid);
19332
19333 return !Invalid;
19334}
19335
19336static bool canCaptureVariableByCopy(ValueDecl *Var,
19337 const ASTContext &Context) {
19338 // Offer a Copy fix even if the type is dependent.
19339 if (Var->getType()->isDependentType())
19340 return true;
19341 QualType T = Var->getType().getNonReferenceType();
19342 if (T.isTriviallyCopyableType(Context))
19343 return true;
19344 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19345
19346 if (!(RD = RD->getDefinition()))
19347 return false;
19348 if (RD->hasSimpleCopyConstructor())
19349 return true;
19350 if (RD->hasUserDeclaredCopyConstructor())
19351 for (CXXConstructorDecl *Ctor : RD->ctors())
19352 if (Ctor->isCopyConstructor())
19353 return !Ctor->isDeleted();
19354 }
19355 return false;
19356}
19357
19358/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19359/// default capture. Fixes may be omitted if they aren't allowed by the
19360/// standard, for example we can't emit a default copy capture fix-it if we
19361/// already explicitly copy capture capture another variable.
19362static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19363 ValueDecl *Var) {
19364 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19365 // Don't offer Capture by copy of default capture by copy fixes if Var is
19366 // known not to be copy constructible.
19367 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19368
19369 SmallString<32> FixBuffer;
19370 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19371 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19372 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19373 if (ShouldOfferCopyFix) {
19374 // Offer fixes to insert an explicit capture for the variable.
19375 // [] -> [VarName]
19376 // [OtherCapture] -> [OtherCapture, VarName]
19377 FixBuffer.assign(Refs: {Separator, Var->getName()});
19378 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19379 << Var << /*value*/ 0
19380 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19381 }
19382 // As above but capture by reference.
19383 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19384 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19385 << Var << /*reference*/ 1
19386 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19387 }
19388
19389 // Only try to offer default capture if there are no captures excluding this
19390 // and init captures.
19391 // [this]: OK.
19392 // [X = Y]: OK.
19393 // [&A, &B]: Don't offer.
19394 // [A, B]: Don't offer.
19395 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19396 return !C.isThisCapture() && !C.isInitCapture();
19397 }))
19398 return;
19399
19400 // The default capture specifiers, '=' or '&', must appear first in the
19401 // capture body.
19402 SourceLocation DefaultInsertLoc =
19403 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19404
19405 if (ShouldOfferCopyFix) {
19406 bool CanDefaultCopyCapture = true;
19407 // [=, *this] OK since c++17
19408 // [=, this] OK since c++20
19409 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19410 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19411 ? LSI->getCXXThisCapture().isCopyCapture()
19412 : false;
19413 // We can't use default capture by copy if any captures already specified
19414 // capture by copy.
19415 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19416 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19417 })) {
19418 FixBuffer.assign(Refs: {"=", Separator});
19419 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19420 << /*value*/ 0
19421 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19422 }
19423 }
19424
19425 // We can't use default capture by reference if any captures already specified
19426 // capture by reference.
19427 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19428 return !C.isInitCapture() && C.isReferenceCapture() &&
19429 !C.isThisCapture();
19430 })) {
19431 FixBuffer.assign(Refs: {"&", Separator});
19432 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19433 << /*reference*/ 1
19434 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19435 }
19436}
19437
19438bool Sema::tryCaptureVariable(
19439 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19440 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19441 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19442 // An init-capture is notionally from the context surrounding its
19443 // declaration, but its parent DC is the lambda class.
19444 DeclContext *VarDC = Var->getDeclContext();
19445 DeclContext *DC = CurContext;
19446
19447 // Skip past RequiresExprBodys because they don't constitute function scopes.
19448 while (DC->isRequiresExprBody())
19449 DC = DC->getParent();
19450
19451 // tryCaptureVariable is called every time a DeclRef is formed,
19452 // it can therefore have non-negigible impact on performances.
19453 // For local variables and when there is no capturing scope,
19454 // we can bailout early.
19455 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19456 return true;
19457
19458 // Exception: Function parameters are not tied to the function's DeclContext
19459 // until we enter the function definition. Capturing them anyway would result
19460 // in an out-of-bounds error while traversing DC and its parents.
19461 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19462 return true;
19463
19464 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19465 if (VD) {
19466 if (VD->isInitCapture())
19467 VarDC = VarDC->getParent();
19468 } else {
19469 VD = Var->getPotentiallyDecomposedVarDecl();
19470 }
19471 assert(VD && "Cannot capture a null variable");
19472
19473 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19474 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19475 // We need to sync up the Declaration Context with the
19476 // FunctionScopeIndexToStopAt
19477 if (FunctionScopeIndexToStopAt) {
19478 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19479 unsigned FSIndex = FunctionScopes.size() - 1;
19480 // When we're parsing the lambda parameter list, the current DeclContext is
19481 // NOT the lambda but its parent. So move away the current LSI before
19482 // aligning DC and FunctionScopeIndexToStopAt.
19483 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19484 FSIndex && LSI && !LSI->AfterParameterList)
19485 --FSIndex;
19486 assert(MaxFunctionScopesIndex <= FSIndex &&
19487 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19488 "FunctionScopes.");
19489 while (FSIndex != MaxFunctionScopesIndex) {
19490 DC = getLambdaAwareParentOfDeclContext(DC);
19491 --FSIndex;
19492 }
19493 }
19494
19495 // Capture global variables if it is required to use private copy of this
19496 // variable.
19497 bool IsGlobal = !VD->hasLocalStorage();
19498 if (IsGlobal && !(LangOpts.OpenMP &&
19499 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19500 StopAt: MaxFunctionScopesIndex)))
19501 return true;
19502
19503 if (isa<VarDecl>(Val: Var))
19504 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19505
19506 // Walk up the stack to determine whether we can capture the variable,
19507 // performing the "simple" checks that don't depend on type. We stop when
19508 // we've either hit the declared scope of the variable or find an existing
19509 // capture of that variable. We start from the innermost capturing-entity
19510 // (the DC) and ensure that all intervening capturing-entities
19511 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19512 // declcontext can either capture the variable or have already captured
19513 // the variable.
19514 CaptureType = Var->getType();
19515 DeclRefType = CaptureType.getNonReferenceType();
19516 bool Nested = false;
19517 bool Explicit = (Kind != TryCaptureKind::Implicit);
19518 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19519 do {
19520
19521 LambdaScopeInfo *LSI = nullptr;
19522 if (!FunctionScopes.empty())
19523 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19524 Val: FunctionScopes[FunctionScopesIndex]);
19525
19526 bool IsInScopeDeclarationContext =
19527 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19528
19529 if (LSI && !LSI->AfterParameterList) {
19530 // This allows capturing parameters from a default value which does not
19531 // seems correct
19532 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19533 return true;
19534 }
19535 // If the variable is declared in the current context, there is no need to
19536 // capture it.
19537 if (IsInScopeDeclarationContext &&
19538 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19539 return true;
19540
19541 // Only block literals, captured statements, and lambda expressions can
19542 // capture; other scopes don't work.
19543 DeclContext *ParentDC =
19544 !IsInScopeDeclarationContext
19545 ? DC->getParent()
19546 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19547 Diagnose: BuildAndDiagnose, S&: *this);
19548 // We need to check for the parent *first* because, if we *have*
19549 // private-captured a global variable, we need to recursively capture it in
19550 // intermediate blocks, lambdas, etc.
19551 if (!ParentDC) {
19552 if (IsGlobal) {
19553 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19554 break;
19555 }
19556 return true;
19557 }
19558
19559 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19560 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19561
19562 // Check whether we've already captured it.
19563 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19564 DeclRefType)) {
19565 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19566 break;
19567 }
19568
19569 // When evaluating some attributes (like enable_if) we might refer to a
19570 // function parameter appertaining to the same declaration as that
19571 // attribute.
19572 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19573 Parm && Parm->getDeclContext() == DC)
19574 return true;
19575
19576 // If we are instantiating a generic lambda call operator body,
19577 // we do not want to capture new variables. What was captured
19578 // during either a lambdas transformation or initial parsing
19579 // should be used.
19580 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19581 if (BuildAndDiagnose) {
19582 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19583 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19584 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19585 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19586 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19587 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19588 } else
19589 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19590 }
19591 return true;
19592 }
19593
19594 // Try to capture variable-length arrays types.
19595 if (Var->getType()->isVariablyModifiedType()) {
19596 // We're going to walk down into the type and look for VLA
19597 // expressions.
19598 QualType QTy = Var->getType();
19599 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19600 QTy = PVD->getOriginalType();
19601 captureVariablyModifiedType(Context, T: QTy, CSI);
19602 }
19603
19604 if (getLangOpts().OpenMP) {
19605 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19606 // OpenMP private variables should not be captured in outer scope, so
19607 // just break here. Similarly, global variables that are captured in a
19608 // target region should not be captured outside the scope of the region.
19609 if (RSI->CapRegionKind == CR_OpenMP) {
19610 // FIXME: We should support capturing structured bindings in OpenMP.
19611 if (isa<BindingDecl>(Val: Var)) {
19612 if (BuildAndDiagnose) {
19613 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
19614 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19615 }
19616 return true;
19617 }
19618 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19619 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
19620 // If the variable is private (i.e. not captured) and has variably
19621 // modified type, we still need to capture the type for correct
19622 // codegen in all regions, associated with the construct. Currently,
19623 // it is captured in the innermost captured region only.
19624 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19625 Var->getType()->isVariablyModifiedType()) {
19626 QualType QTy = Var->getType();
19627 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19628 QTy = PVD->getOriginalType();
19629 for (int I = 1,
19630 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19631 I < E; ++I) {
19632 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19633 Val: FunctionScopes[FunctionScopesIndex - I]);
19634 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19635 "Wrong number of captured regions associated with the "
19636 "OpenMP construct.");
19637 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
19638 }
19639 }
19640 bool IsTargetCap =
19641 IsOpenMPPrivateDecl != OMPC_private &&
19642 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
19643 CaptureLevel: RSI->OpenMPCaptureLevel);
19644 // Do not capture global if it is not privatized in outer regions.
19645 bool IsGlobalCap =
19646 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19647 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
19648
19649 // When we detect target captures we are looking from inside the
19650 // target region, therefore we need to propagate the capture from the
19651 // enclosing region. Therefore, the capture is not initially nested.
19652 if (IsTargetCap)
19653 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19654 Level: RSI->OpenMPLevel);
19655
19656 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19657 (IsGlobal && !IsGlobalCap)) {
19658 Nested = !IsTargetCap;
19659 bool HasConst = DeclRefType.isConstQualified();
19660 DeclRefType = DeclRefType.getUnqualifiedType();
19661 // Don't lose diagnostics about assignments to const.
19662 if (HasConst)
19663 DeclRefType.addConst();
19664 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
19665 break;
19666 }
19667 }
19668 }
19669 }
19670 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19671 // No capture-default, and this is not an explicit capture
19672 // so cannot capture this variable.
19673 if (BuildAndDiagnose) {
19674 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19675 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19676 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
19677 if (LSI->Lambda) {
19678 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19679 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19680 }
19681 // FIXME: If we error out because an outer lambda can not implicitly
19682 // capture a variable that an inner lambda explicitly captures, we
19683 // should have the inner lambda do the explicit capture - because
19684 // it makes for cleaner diagnostics later. This would purely be done
19685 // so that the diagnostic does not misleadingly claim that a variable
19686 // can not be captured by a lambda implicitly even though it is captured
19687 // explicitly. Suggestion:
19688 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19689 // at the function head
19690 // - cache the StartingDeclContext - this must be a lambda
19691 // - captureInLambda in the innermost lambda the variable.
19692 }
19693 return true;
19694 }
19695 Explicit = false;
19696 FunctionScopesIndex--;
19697 if (IsInScopeDeclarationContext)
19698 DC = ParentDC;
19699 } while (!VarDC->Equals(DC));
19700
19701 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19702 // computing the type of the capture at each step, checking type-specific
19703 // requirements, and adding captures if requested.
19704 // If the variable had already been captured previously, we start capturing
19705 // at the lambda nested within that one.
19706 bool Invalid = false;
19707 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19708 ++I) {
19709 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
19710
19711 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19712 // certain types of variables (unnamed, variably modified types etc.)
19713 // so check for eligibility.
19714 if (!Invalid)
19715 Invalid =
19716 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
19717
19718 // After encountering an error, if we're actually supposed to capture, keep
19719 // capturing in nested contexts to suppress any follow-on diagnostics.
19720 if (Invalid && !BuildAndDiagnose)
19721 return true;
19722
19723 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
19724 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19725 DeclRefType, Nested, S&: *this, Invalid);
19726 Nested = true;
19727 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19728 Invalid = !captureInCapturedRegion(
19729 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
19730 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19731 Nested = true;
19732 } else {
19733 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19734 Invalid =
19735 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19736 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
19737 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19738 Nested = true;
19739 }
19740
19741 if (Invalid && !BuildAndDiagnose)
19742 return true;
19743 }
19744 return Invalid;
19745}
19746
19747bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19748 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19749 QualType CaptureType;
19750 QualType DeclRefType;
19751 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
19752 /*BuildAndDiagnose=*/true, CaptureType,
19753 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19754}
19755
19756bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19757 QualType CaptureType;
19758 QualType DeclRefType;
19759 return !tryCaptureVariable(
19760 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
19761 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19762}
19763
19764QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19765 assert(Var && "Null value cannot be captured");
19766
19767 QualType CaptureType;
19768 QualType DeclRefType;
19769
19770 // Determine whether we can capture this variable.
19771 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
19772 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19773 FunctionScopeIndexToStopAt: nullptr))
19774 return QualType();
19775
19776 return DeclRefType;
19777}
19778
19779namespace {
19780// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19781// The produced TemplateArgumentListInfo* points to data stored within this
19782// object, so should only be used in contexts where the pointer will not be
19783// used after the CopiedTemplateArgs object is destroyed.
19784class CopiedTemplateArgs {
19785 bool HasArgs;
19786 TemplateArgumentListInfo TemplateArgStorage;
19787public:
19788 template<typename RefExpr>
19789 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19790 if (HasArgs)
19791 E->copyTemplateArgumentsInto(TemplateArgStorage);
19792 }
19793 operator TemplateArgumentListInfo*()
19794#ifdef __has_cpp_attribute
19795#if __has_cpp_attribute(clang::lifetimebound)
19796 [[clang::lifetimebound]]
19797#endif
19798#endif
19799 {
19800 return HasArgs ? &TemplateArgStorage : nullptr;
19801 }
19802};
19803}
19804
19805/// Walk the set of potential results of an expression and mark them all as
19806/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19807///
19808/// \return A new expression if we found any potential results, ExprEmpty() if
19809/// not, and ExprError() if we diagnosed an error.
19810static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19811 NonOdrUseReason NOUR) {
19812 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19813 // an object that satisfies the requirements for appearing in a
19814 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19815 // is immediately applied." This function handles the lvalue-to-rvalue
19816 // conversion part.
19817 //
19818 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19819 // transform it into the relevant kind of non-odr-use node and rebuild the
19820 // tree of nodes leading to it.
19821 //
19822 // This is a mini-TreeTransform that only transforms a restricted subset of
19823 // nodes (and only certain operands of them).
19824
19825 // Rebuild a subexpression.
19826 auto Rebuild = [&](Expr *Sub) {
19827 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
19828 };
19829
19830 // Check whether a potential result satisfies the requirements of NOUR.
19831 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19832 // Any entity other than a VarDecl is always odr-used whenever it's named
19833 // in a potentially-evaluated expression.
19834 auto *VD = dyn_cast<VarDecl>(Val: D);
19835 if (!VD)
19836 return true;
19837
19838 // C++2a [basic.def.odr]p4:
19839 // A variable x whose name appears as a potentially-evalauted expression
19840 // e is odr-used by e unless
19841 // -- x is a reference that is usable in constant expressions, or
19842 // -- x is a variable of non-reference type that is usable in constant
19843 // expressions and has no mutable subobjects, and e is an element of
19844 // the set of potential results of an expression of
19845 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19846 // conversion is applied, or
19847 // -- x is a variable of non-reference type, and e is an element of the
19848 // set of potential results of a discarded-value expression to which
19849 // the lvalue-to-rvalue conversion is not applied
19850 //
19851 // We check the first bullet and the "potentially-evaluated" condition in
19852 // BuildDeclRefExpr. We check the type requirements in the second bullet
19853 // in CheckLValueToRValueConversionOperand below.
19854 switch (NOUR) {
19855 case NOUR_None:
19856 case NOUR_Unevaluated:
19857 llvm_unreachable("unexpected non-odr-use-reason");
19858
19859 case NOUR_Constant:
19860 // Constant references were handled when they were built.
19861 if (VD->getType()->isReferenceType())
19862 return true;
19863 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19864 if (RD->hasDefinition() && RD->hasMutableFields())
19865 return true;
19866 if (!VD->isUsableInConstantExpressions(C: S.Context))
19867 return true;
19868 break;
19869
19870 case NOUR_Discarded:
19871 if (VD->getType()->isReferenceType())
19872 return true;
19873 break;
19874 }
19875 return false;
19876 };
19877
19878 // Check whether this expression may be odr-used in CUDA/HIP.
19879 auto MaybeCUDAODRUsed = [&]() -> bool {
19880 if (!S.LangOpts.CUDA)
19881 return false;
19882 LambdaScopeInfo *LSI = S.getCurLambda();
19883 if (!LSI)
19884 return false;
19885 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
19886 if (!DRE)
19887 return false;
19888 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
19889 if (!VD)
19890 return false;
19891 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
19892 };
19893
19894 // Mark that this expression does not constitute an odr-use.
19895 auto MarkNotOdrUsed = [&] {
19896 if (!MaybeCUDAODRUsed()) {
19897 S.MaybeODRUseExprs.remove(X: E);
19898 if (LambdaScopeInfo *LSI = S.getCurLambda())
19899 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
19900 }
19901 };
19902
19903 // C++2a [basic.def.odr]p2:
19904 // The set of potential results of an expression e is defined as follows:
19905 switch (E->getStmtClass()) {
19906 // -- If e is an id-expression, ...
19907 case Expr::DeclRefExprClass: {
19908 auto *DRE = cast<DeclRefExpr>(Val: E);
19909 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19910 break;
19911
19912 // Rebuild as a non-odr-use DeclRefExpr.
19913 MarkNotOdrUsed();
19914 return DeclRefExpr::Create(
19915 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
19916 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
19917 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
19918 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
19919 }
19920
19921 case Expr::FunctionParmPackExprClass: {
19922 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
19923 // If any of the declarations in the pack is odr-used, then the expression
19924 // as a whole constitutes an odr-use.
19925 for (ValueDecl *D : *FPPE)
19926 if (IsPotentialResultOdrUsed(D))
19927 return ExprEmpty();
19928
19929 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19930 // nothing cares about whether we marked this as an odr-use, but it might
19931 // be useful for non-compiler tools.
19932 MarkNotOdrUsed();
19933 break;
19934 }
19935
19936 // -- If e is a subscripting operation with an array operand...
19937 case Expr::ArraySubscriptExprClass: {
19938 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
19939 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19940 if (!OldBase->getType()->isArrayType())
19941 break;
19942 ExprResult Base = Rebuild(OldBase);
19943 if (!Base.isUsable())
19944 return Base;
19945 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19946 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19947 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19948 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
19949 rbLoc: ASE->getRBracketLoc());
19950 }
19951
19952 case Expr::MemberExprClass: {
19953 auto *ME = cast<MemberExpr>(Val: E);
19954 // -- If e is a class member access expression [...] naming a non-static
19955 // data member...
19956 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
19957 ExprResult Base = Rebuild(ME->getBase());
19958 if (!Base.isUsable())
19959 return Base;
19960 return MemberExpr::Create(
19961 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
19962 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
19963 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
19964 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
19965 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
19966 }
19967
19968 if (ME->getMemberDecl()->isCXXInstanceMember())
19969 break;
19970
19971 // -- If e is a class member access expression naming a static data member,
19972 // ...
19973 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19974 break;
19975
19976 // Rebuild as a non-odr-use MemberExpr.
19977 MarkNotOdrUsed();
19978 return MemberExpr::Create(
19979 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
19980 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
19981 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
19982 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
19983 }
19984
19985 case Expr::BinaryOperatorClass: {
19986 auto *BO = cast<BinaryOperator>(Val: E);
19987 Expr *LHS = BO->getLHS();
19988 Expr *RHS = BO->getRHS();
19989 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19990 if (BO->getOpcode() == BO_PtrMemD) {
19991 ExprResult Sub = Rebuild(LHS);
19992 if (!Sub.isUsable())
19993 return Sub;
19994 BO->setLHS(Sub.get());
19995 // -- If e is a comma expression, ...
19996 } else if (BO->getOpcode() == BO_Comma) {
19997 ExprResult Sub = Rebuild(RHS);
19998 if (!Sub.isUsable())
19999 return Sub;
20000 BO->setRHS(Sub.get());
20001 } else {
20002 break;
20003 }
20004 return ExprResult(BO);
20005 }
20006
20007 // -- If e has the form (e1)...
20008 case Expr::ParenExprClass: {
20009 auto *PE = cast<ParenExpr>(Val: E);
20010 ExprResult Sub = Rebuild(PE->getSubExpr());
20011 if (!Sub.isUsable())
20012 return Sub;
20013 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20014 }
20015
20016 // -- If e is a glvalue conditional expression, ...
20017 // We don't apply this to a binary conditional operator. FIXME: Should we?
20018 case Expr::ConditionalOperatorClass: {
20019 auto *CO = cast<ConditionalOperator>(Val: E);
20020 ExprResult LHS = Rebuild(CO->getLHS());
20021 if (LHS.isInvalid())
20022 return ExprError();
20023 ExprResult RHS = Rebuild(CO->getRHS());
20024 if (RHS.isInvalid())
20025 return ExprError();
20026 if (!LHS.isUsable() && !RHS.isUsable())
20027 return ExprEmpty();
20028 if (!LHS.isUsable())
20029 LHS = CO->getLHS();
20030 if (!RHS.isUsable())
20031 RHS = CO->getRHS();
20032 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20033 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20034 }
20035
20036 // [Clang extension]
20037 // -- If e has the form __extension__ e1...
20038 case Expr::UnaryOperatorClass: {
20039 auto *UO = cast<UnaryOperator>(Val: E);
20040 if (UO->getOpcode() != UO_Extension)
20041 break;
20042 ExprResult Sub = Rebuild(UO->getSubExpr());
20043 if (!Sub.isUsable())
20044 return Sub;
20045 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20046 Input: Sub.get());
20047 }
20048
20049 // [Clang extension]
20050 // -- If e has the form _Generic(...), the set of potential results is the
20051 // union of the sets of potential results of the associated expressions.
20052 case Expr::GenericSelectionExprClass: {
20053 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20054
20055 SmallVector<Expr *, 4> AssocExprs;
20056 bool AnyChanged = false;
20057 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20058 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20059 if (AssocExpr.isInvalid())
20060 return ExprError();
20061 if (AssocExpr.isUsable()) {
20062 AssocExprs.push_back(Elt: AssocExpr.get());
20063 AnyChanged = true;
20064 } else {
20065 AssocExprs.push_back(Elt: OrigAssocExpr);
20066 }
20067 }
20068
20069 void *ExOrTy = nullptr;
20070 bool IsExpr = GSE->isExprPredicate();
20071 if (IsExpr)
20072 ExOrTy = GSE->getControllingExpr();
20073 else
20074 ExOrTy = GSE->getControllingType();
20075 return AnyChanged ? S.CreateGenericSelectionExpr(
20076 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20077 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20078 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20079 : ExprEmpty();
20080 }
20081
20082 // [Clang extension]
20083 // -- If e has the form __builtin_choose_expr(...), the set of potential
20084 // results is the union of the sets of potential results of the
20085 // second and third subexpressions.
20086 case Expr::ChooseExprClass: {
20087 auto *CE = cast<ChooseExpr>(Val: E);
20088
20089 ExprResult LHS = Rebuild(CE->getLHS());
20090 if (LHS.isInvalid())
20091 return ExprError();
20092
20093 ExprResult RHS = Rebuild(CE->getLHS());
20094 if (RHS.isInvalid())
20095 return ExprError();
20096
20097 if (!LHS.get() && !RHS.get())
20098 return ExprEmpty();
20099 if (!LHS.isUsable())
20100 LHS = CE->getLHS();
20101 if (!RHS.isUsable())
20102 RHS = CE->getRHS();
20103
20104 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20105 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20106 }
20107
20108 // Step through non-syntactic nodes.
20109 case Expr::ConstantExprClass: {
20110 auto *CE = cast<ConstantExpr>(Val: E);
20111 ExprResult Sub = Rebuild(CE->getSubExpr());
20112 if (!Sub.isUsable())
20113 return Sub;
20114 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20115 }
20116
20117 // We could mostly rely on the recursive rebuilding to rebuild implicit
20118 // casts, but not at the top level, so rebuild them here.
20119 case Expr::ImplicitCastExprClass: {
20120 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20121 // Only step through the narrow set of cast kinds we expect to encounter.
20122 // Anything else suggests we've left the region in which potential results
20123 // can be found.
20124 switch (ICE->getCastKind()) {
20125 case CK_NoOp:
20126 case CK_DerivedToBase:
20127 case CK_UncheckedDerivedToBase: {
20128 ExprResult Sub = Rebuild(ICE->getSubExpr());
20129 if (!Sub.isUsable())
20130 return Sub;
20131 CXXCastPath Path(ICE->path());
20132 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20133 VK: ICE->getValueKind(), BasePath: &Path);
20134 }
20135
20136 default:
20137 break;
20138 }
20139 break;
20140 }
20141
20142 default:
20143 break;
20144 }
20145
20146 // Can't traverse through this node. Nothing to do.
20147 return ExprEmpty();
20148}
20149
20150ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20151 // Check whether the operand is or contains an object of non-trivial C union
20152 // type.
20153 if (E->getType().isVolatileQualified() &&
20154 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20155 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20156 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20157 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20158 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20159
20160 // C++2a [basic.def.odr]p4:
20161 // [...] an expression of non-volatile-qualified non-class type to which
20162 // the lvalue-to-rvalue conversion is applied [...]
20163 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20164 return E;
20165
20166 ExprResult Result =
20167 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20168 if (Result.isInvalid())
20169 return ExprError();
20170 return Result.get() ? Result : E;
20171}
20172
20173ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20174 if (!Res.isUsable())
20175 return Res;
20176
20177 // If a constant-expression is a reference to a variable where we delay
20178 // deciding whether it is an odr-use, just assume we will apply the
20179 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20180 // (a non-type template argument), we have special handling anyway.
20181 return CheckLValueToRValueConversionOperand(E: Res.get());
20182}
20183
20184void Sema::CleanupVarDeclMarking() {
20185 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20186 // call.
20187 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20188 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20189
20190 for (Expr *E : LocalMaybeODRUseExprs) {
20191 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20192 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20193 Loc: DRE->getLocation(), SemaRef&: *this);
20194 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20195 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20196 SemaRef&: *this);
20197 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20198 for (ValueDecl *VD : *FP)
20199 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20200 } else {
20201 llvm_unreachable("Unexpected expression");
20202 }
20203 }
20204
20205 assert(MaybeODRUseExprs.empty() &&
20206 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20207}
20208
20209static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20210 ValueDecl *Var, Expr *E) {
20211 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20212 if (!VD)
20213 return;
20214
20215 const bool RefersToEnclosingScope =
20216 (SemaRef.CurContext != VD->getDeclContext() &&
20217 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20218 if (RefersToEnclosingScope) {
20219 LambdaScopeInfo *const LSI =
20220 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20221 if (LSI && (!LSI->CallOperator ||
20222 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20223 // If a variable could potentially be odr-used, defer marking it so
20224 // until we finish analyzing the full expression for any
20225 // lvalue-to-rvalue
20226 // or discarded value conversions that would obviate odr-use.
20227 // Add it to the list of potential captures that will be analyzed
20228 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20229 // unless the variable is a reference that was initialized by a constant
20230 // expression (this will never need to be captured or odr-used).
20231 //
20232 // FIXME: We can simplify this a lot after implementing P0588R1.
20233 assert(E && "Capture variable should be used in an expression.");
20234 if (!Var->getType()->isReferenceType() ||
20235 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20236 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20237 }
20238 }
20239}
20240
20241static void DoMarkVarDeclReferenced(
20242 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20243 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20244 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20245 isa<FunctionParmPackExpr>(E)) &&
20246 "Invalid Expr argument to DoMarkVarDeclReferenced");
20247 Var->setReferenced();
20248
20249 if (Var->isInvalidDecl())
20250 return;
20251
20252 auto *MSI = Var->getMemberSpecializationInfo();
20253 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20254 : Var->getTemplateSpecializationKind();
20255
20256 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20257 bool UsableInConstantExpr =
20258 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20259
20260 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20261 RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++;
20262 }
20263
20264 // C++20 [expr.const]p12:
20265 // A variable [...] is needed for constant evaluation if it is [...] a
20266 // variable whose name appears as a potentially constant evaluated
20267 // expression that is either a contexpr variable or is of non-volatile
20268 // const-qualified integral type or of reference type
20269 bool NeededForConstantEvaluation =
20270 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20271
20272 bool NeedDefinition =
20273 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20274 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20275 Var->getType()->isUndeducedType());
20276
20277 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20278 "Can't instantiate a partial template specialization.");
20279
20280 // If this might be a member specialization of a static data member, check
20281 // the specialization is visible. We already did the checks for variable
20282 // template specializations when we created them.
20283 if (NeedDefinition && TSK != TSK_Undeclared &&
20284 !isa<VarTemplateSpecializationDecl>(Val: Var))
20285 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20286
20287 // Perform implicit instantiation of static data members, static data member
20288 // templates of class templates, and variable template specializations. Delay
20289 // instantiations of variable templates, except for those that could be used
20290 // in a constant expression.
20291 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20292 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20293 // instantiation declaration if a variable is usable in a constant
20294 // expression (among other cases).
20295 bool TryInstantiating =
20296 TSK == TSK_ImplicitInstantiation ||
20297 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20298
20299 if (TryInstantiating) {
20300 SourceLocation PointOfInstantiation =
20301 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20302 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20303 if (FirstInstantiation) {
20304 PointOfInstantiation = Loc;
20305 if (MSI)
20306 MSI->setPointOfInstantiation(PointOfInstantiation);
20307 // FIXME: Notify listener.
20308 else
20309 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20310 }
20311
20312 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20313 // Do not defer instantiations of variables that could be used in a
20314 // constant expression.
20315 // The type deduction also needs a complete initializer.
20316 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20317 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20318 });
20319
20320 // The size of an incomplete array type can be updated by
20321 // instantiating the initializer. The DeclRefExpr's type should be
20322 // updated accordingly too, or users of it would be confused!
20323 if (E)
20324 SemaRef.getCompletedType(E);
20325
20326 // Re-set the member to trigger a recomputation of the dependence bits
20327 // for the expression.
20328 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20329 DRE->setDecl(DRE->getDecl());
20330 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20331 ME->setMemberDecl(ME->getMemberDecl());
20332 } else if (FirstInstantiation) {
20333 SemaRef.PendingInstantiations
20334 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20335 } else {
20336 bool Inserted = false;
20337 for (auto &I : SemaRef.SavedPendingInstantiations) {
20338 auto Iter = llvm::find_if(
20339 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20340 return P.first == Var;
20341 });
20342 if (Iter != I.end()) {
20343 SemaRef.PendingInstantiations.push_back(x: *Iter);
20344 I.erase(position: Iter);
20345 Inserted = true;
20346 break;
20347 }
20348 }
20349
20350 // FIXME: For a specialization of a variable template, we don't
20351 // distinguish between "declaration and type implicitly instantiated"
20352 // and "implicit instantiation of definition requested", so we have
20353 // no direct way to avoid enqueueing the pending instantiation
20354 // multiple times.
20355 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20356 SemaRef.PendingInstantiations
20357 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20358 }
20359 }
20360 }
20361
20362 // C++2a [basic.def.odr]p4:
20363 // A variable x whose name appears as a potentially-evaluated expression e
20364 // is odr-used by e unless
20365 // -- x is a reference that is usable in constant expressions
20366 // -- x is a variable of non-reference type that is usable in constant
20367 // expressions and has no mutable subobjects [FIXME], and e is an
20368 // element of the set of potential results of an expression of
20369 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20370 // conversion is applied
20371 // -- x is a variable of non-reference type, and e is an element of the set
20372 // of potential results of a discarded-value expression to which the
20373 // lvalue-to-rvalue conversion is not applied [FIXME]
20374 //
20375 // We check the first part of the second bullet here, and
20376 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20377 // FIXME: To get the third bullet right, we need to delay this even for
20378 // variables that are not usable in constant expressions.
20379
20380 // If we already know this isn't an odr-use, there's nothing more to do.
20381 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20382 if (DRE->isNonOdrUse())
20383 return;
20384 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20385 if (ME->isNonOdrUse())
20386 return;
20387
20388 switch (OdrUse) {
20389 case OdrUseContext::None:
20390 // In some cases, a variable may not have been marked unevaluated, if it
20391 // appears in a defaukt initializer.
20392 assert((!E || isa<FunctionParmPackExpr>(E) ||
20393 SemaRef.isUnevaluatedContext()) &&
20394 "missing non-odr-use marking for unevaluated decl ref");
20395 break;
20396
20397 case OdrUseContext::FormallyOdrUsed:
20398 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20399 // behavior.
20400 break;
20401
20402 case OdrUseContext::Used:
20403 // If we might later find that this expression isn't actually an odr-use,
20404 // delay the marking.
20405 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20406 SemaRef.MaybeODRUseExprs.insert(X: E);
20407 else
20408 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20409 break;
20410
20411 case OdrUseContext::Dependent:
20412 // If this is a dependent context, we don't need to mark variables as
20413 // odr-used, but we may still need to track them for lambda capture.
20414 // FIXME: Do we also need to do this inside dependent typeid expressions
20415 // (which are modeled as unevaluated at this point)?
20416 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20417 break;
20418 }
20419}
20420
20421static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20422 BindingDecl *BD, Expr *E) {
20423 BD->setReferenced();
20424
20425 if (BD->isInvalidDecl())
20426 return;
20427
20428 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20429 if (OdrUse == OdrUseContext::Used) {
20430 QualType CaptureType, DeclRefType;
20431 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20432 /*EllipsisLoc*/ SourceLocation(),
20433 /*BuildAndDiagnose*/ true, CaptureType,
20434 DeclRefType,
20435 /*FunctionScopeIndexToStopAt*/ nullptr);
20436 } else if (OdrUse == OdrUseContext::Dependent) {
20437 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20438 }
20439}
20440
20441void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20442 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20443}
20444
20445// C++ [temp.dep.expr]p3:
20446// An id-expression is type-dependent if it contains:
20447// - an identifier associated by name lookup with an entity captured by copy
20448// in a lambda-expression that has an explicit object parameter whose type
20449// is dependent ([dcl.fct]),
20450static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20451 Sema &SemaRef, ValueDecl *D, Expr *E) {
20452 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20453 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20454 return;
20455
20456 // If any enclosing lambda with a dependent explicit object parameter either
20457 // explicitly captures the variable by value, or has a capture default of '='
20458 // and does not capture the variable by reference, then the type of the DRE
20459 // is dependent on the type of that lambda's explicit object parameter.
20460 auto IsDependent = [&]() {
20461 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20462 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20463 if (!LSI)
20464 continue;
20465
20466 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20467 LSI->AfterParameterList)
20468 return false;
20469
20470 const auto *MD = LSI->CallOperator;
20471 if (MD->getType().isNull())
20472 continue;
20473
20474 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20475 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20476 !Ty->getParamType(i: 0)->isDependentType())
20477 continue;
20478
20479 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20480 if (C->isCopyCapture())
20481 return true;
20482 continue;
20483 }
20484
20485 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20486 return true;
20487 }
20488 return false;
20489 }();
20490
20491 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20492 Set: IsDependent, Context: SemaRef.getASTContext());
20493}
20494
20495static void
20496MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20497 bool MightBeOdrUse,
20498 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20499 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20500 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20501
20502 if (SemaRef.getLangOpts().OpenACC)
20503 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20504
20505 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20506 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20507 if (SemaRef.getLangOpts().CPlusPlus)
20508 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20509 D: Var, E);
20510 return;
20511 }
20512
20513 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20514 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20515 if (SemaRef.getLangOpts().CPlusPlus)
20516 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20517 D: Decl, E);
20518 return;
20519 }
20520 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20521
20522 // If this is a call to a method via a cast, also mark the method in the
20523 // derived class used in case codegen can devirtualize the call.
20524 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20525 if (!ME)
20526 return;
20527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20528 if (!MD)
20529 return;
20530 // Only attempt to devirtualize if this is truly a virtual call.
20531 bool IsVirtualCall = MD->isVirtual() &&
20532 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20533 if (!IsVirtualCall)
20534 return;
20535
20536 // If it's possible to devirtualize the call, mark the called function
20537 // referenced.
20538 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20539 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20540 if (DM)
20541 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20542}
20543
20544void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20545 // [basic.def.odr] (CWG 1614)
20546 // A function is named by an expression or conversion [...]
20547 // unless it is a pure virtual function and either the expression is not an
20548 // id-expression naming the function with an explicitly qualified name or
20549 // the expression forms a pointer to member
20550 bool OdrUse = true;
20551 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20552 if (Method->isVirtual() &&
20553 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20554 OdrUse = false;
20555
20556 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20557 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20558 !isImmediateFunctionContext() &&
20559 !isCheckingDefaultArgumentOrInitializer() &&
20560 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20561 !FD->isDependentContext())
20562 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20563 }
20564 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
20565 RefsMinusAssignments);
20566}
20567
20568void Sema::MarkMemberReferenced(MemberExpr *E) {
20569 // C++11 [basic.def.odr]p2:
20570 // A non-overloaded function whose name appears as a potentially-evaluated
20571 // expression or a member of a set of candidate functions, if selected by
20572 // overload resolution when referred to from a potentially-evaluated
20573 // expression, is odr-used, unless it is a pure virtual function and its
20574 // name is not explicitly qualified.
20575 bool MightBeOdrUse = true;
20576 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20578 if (Method->isPureVirtual())
20579 MightBeOdrUse = false;
20580 }
20581 SourceLocation Loc =
20582 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20583 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
20584 RefsMinusAssignments);
20585}
20586
20587void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20588 for (ValueDecl *VD : *E)
20589 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
20590 RefsMinusAssignments);
20591}
20592
20593/// Perform marking for a reference to an arbitrary declaration. It
20594/// marks the declaration referenced, and performs odr-use checking for
20595/// functions and variables. This method should not be used when building a
20596/// normal expression which refers to a variable.
20597void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20598 bool MightBeOdrUse) {
20599 if (MightBeOdrUse) {
20600 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20601 MarkVariableReferenced(Loc, Var: VD);
20602 return;
20603 }
20604 }
20605 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20606 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
20607 return;
20608 }
20609 D->setReferenced();
20610}
20611
20612namespace {
20613 // Mark all of the declarations used by a type as referenced.
20614 // FIXME: Not fully implemented yet! We need to have a better understanding
20615 // of when we're entering a context we should not recurse into.
20616 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20617 // TreeTransforms rebuilding the type in a new context. Rather than
20618 // duplicating the TreeTransform logic, we should consider reusing it here.
20619 // Currently that causes problems when rebuilding LambdaExprs.
20620class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20621 Sema &S;
20622 SourceLocation Loc;
20623
20624public:
20625 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20626
20627 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20628};
20629}
20630
20631bool MarkReferencedDecls::TraverseTemplateArgument(
20632 const TemplateArgument &Arg) {
20633 {
20634 // A non-type template argument is a constant-evaluated context.
20635 EnterExpressionEvaluationContext Evaluated(
20636 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20637 if (Arg.getKind() == TemplateArgument::Declaration) {
20638 if (Decl *D = Arg.getAsDecl())
20639 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20640 } else if (Arg.getKind() == TemplateArgument::Expression) {
20641 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20642 }
20643 }
20644
20645 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
20646}
20647
20648void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20649 MarkReferencedDecls Marker(*this, Loc);
20650 Marker.TraverseType(T);
20651}
20652
20653namespace {
20654/// Helper class that marks all of the declarations referenced by
20655/// potentially-evaluated subexpressions as "referenced".
20656class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20657public:
20658 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20659 bool SkipLocalVariables;
20660 ArrayRef<const Expr *> StopAt;
20661
20662 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20663 ArrayRef<const Expr *> StopAt)
20664 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20665
20666 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20667 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
20668 }
20669
20670 void Visit(Expr *E) {
20671 if (llvm::is_contained(Range&: StopAt, Element: E))
20672 return;
20673 Inherited::Visit(S: E);
20674 }
20675
20676 void VisitConstantExpr(ConstantExpr *E) {
20677 // Don't mark declarations within a ConstantExpression, as this expression
20678 // will be evaluated and folded to a value.
20679 }
20680
20681 void VisitDeclRefExpr(DeclRefExpr *E) {
20682 // If we were asked not to visit local variables, don't.
20683 if (SkipLocalVariables) {
20684 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
20685 if (VD->hasLocalStorage())
20686 return;
20687 }
20688
20689 // FIXME: This can trigger the instantiation of the initializer of a
20690 // variable, which can cause the expression to become value-dependent
20691 // or error-dependent. Do we need to propagate the new dependence bits?
20692 S.MarkDeclRefReferenced(E);
20693 }
20694
20695 void VisitMemberExpr(MemberExpr *E) {
20696 S.MarkMemberReferenced(E);
20697 Visit(E: E->getBase());
20698 }
20699};
20700} // namespace
20701
20702void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20703 bool SkipLocalVariables,
20704 ArrayRef<const Expr*> StopAt) {
20705 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20706}
20707
20708/// Emit a diagnostic when statements are reachable.
20709bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20710 const PartialDiagnostic &PD) {
20711 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20712 // The initializer of a constexpr variable or of the first declaration of a
20713 // static data member is not syntactically a constant evaluated constant,
20714 // but nonetheless is always required to be a constant expression, so we
20715 // can skip diagnosing.
20716 if (Decl &&
20717 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20718 Decl->isFirstDecl() && !Decl->isInline())))
20719 return false;
20720
20721 if (Stmts.empty()) {
20722 Diag(Loc, PD);
20723 return true;
20724 }
20725
20726 if (getCurFunction()) {
20727 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20728 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20729 return true;
20730 }
20731
20732 // For non-constexpr file-scope variables with reachability context (non-empty
20733 // Stmts), build a CFG for the initializer and check whether the context in
20734 // question is reachable.
20735 if (Decl && Decl->isFileVarDecl()) {
20736 AnalysisWarnings.registerVarDeclWarning(
20737 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20738 return true;
20739 }
20740
20741 Diag(Loc, PD);
20742 return true;
20743}
20744
20745/// Emit a diagnostic that describes an effect on the run-time behavior
20746/// of the program being compiled.
20747///
20748/// This routine emits the given diagnostic when the code currently being
20749/// type-checked is "potentially evaluated", meaning that there is a
20750/// possibility that the code will actually be executable. Code in sizeof()
20751/// expressions, code used only during overload resolution, etc., are not
20752/// potentially evaluated. This routine will suppress such diagnostics or,
20753/// in the absolutely nutty case of potentially potentially evaluated
20754/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20755/// later.
20756///
20757/// This routine should be used for all diagnostics that describe the run-time
20758/// behavior of a program, such as passing a non-POD value through an ellipsis.
20759/// Failure to do so will likely result in spurious diagnostics or failures
20760/// during overload resolution or within sizeof/alignof/typeof/typeid.
20761bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20762 const PartialDiagnostic &PD) {
20763
20764 if (ExprEvalContexts.back().isDiscardedStatementContext())
20765 return false;
20766
20767 switch (ExprEvalContexts.back().Context) {
20768 case ExpressionEvaluationContext::Unevaluated:
20769 case ExpressionEvaluationContext::UnevaluatedList:
20770 case ExpressionEvaluationContext::UnevaluatedAbstract:
20771 case ExpressionEvaluationContext::DiscardedStatement:
20772 // The argument will never be evaluated, so don't complain.
20773 break;
20774
20775 case ExpressionEvaluationContext::ConstantEvaluated:
20776 case ExpressionEvaluationContext::ImmediateFunctionContext:
20777 // Relevant diagnostics should be produced by constant evaluation.
20778 break;
20779
20780 case ExpressionEvaluationContext::PotentiallyEvaluated:
20781 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20782 return DiagIfReachable(Loc, Stmts, PD);
20783 }
20784
20785 return false;
20786}
20787
20788bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20789 const PartialDiagnostic &PD) {
20790 return DiagRuntimeBehavior(
20791 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20792 PD);
20793}
20794
20795bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20796 CallExpr *CE, FunctionDecl *FD) {
20797 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20798 return false;
20799
20800 // If we're inside a decltype's expression, don't check for a valid return
20801 // type or construct temporaries until we know whether this is the last call.
20802 if (ExprEvalContexts.back().ExprContext ==
20803 ExpressionEvaluationContextRecord::EK_Decltype) {
20804 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
20805 return false;
20806 }
20807
20808 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20809 FunctionDecl *FD;
20810 CallExpr *CE;
20811
20812 public:
20813 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20814 : FD(FD), CE(CE) { }
20815
20816 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20817 if (!FD) {
20818 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
20819 << T << CE->getSourceRange();
20820 return;
20821 }
20822
20823 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
20824 << CE->getSourceRange() << FD << T;
20825 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
20826 << FD->getDeclName();
20827 }
20828 } Diagnoser(FD, CE);
20829
20830 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
20831 return true;
20832
20833 return false;
20834}
20835
20836// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20837// will prevent this condition from triggering, which is what we want.
20838void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20839 SourceLocation Loc;
20840
20841 unsigned diagnostic = diag::warn_condition_is_assignment;
20842 bool IsOrAssign = false;
20843
20844 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
20845 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20846 return;
20847
20848 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20849
20850 // Greylist some idioms by putting them into a warning subcategory.
20851 if (ObjCMessageExpr *ME
20852 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
20853 Selector Sel = ME->getSelector();
20854
20855 // self = [<foo> init...]
20856 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20857 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20858
20859 // <foo> = [<bar> nextObject]
20860 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
20861 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20862 }
20863
20864 Loc = Op->getOperatorLoc();
20865 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
20866 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20867 return;
20868
20869 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20870 Loc = Op->getOperatorLoc();
20871 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
20872 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
20873 else {
20874 // Not an assignment.
20875 return;
20876 }
20877
20878 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
20879
20880 SourceLocation Open = E->getBeginLoc();
20881 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
20882 Diag(Loc, DiagID: diag::note_condition_assign_silence)
20883 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
20884 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
20885
20886 if (IsOrAssign)
20887 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
20888 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
20889 else
20890 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
20891 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
20892}
20893
20894void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20895 // Don't warn if the parens came from a macro.
20896 SourceLocation parenLoc = ParenE->getBeginLoc();
20897 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20898 return;
20899 // Don't warn for dependent expressions.
20900 if (ParenE->isTypeDependent())
20901 return;
20902
20903 Expr *E = ParenE->IgnoreParens();
20904 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20905 return;
20906
20907 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
20908 if (opE->getOpcode() == BO_EQ &&
20909 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
20910 == Expr::MLV_Valid) {
20911 SourceLocation Loc = opE->getOperatorLoc();
20912
20913 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
20914 SourceRange ParenERange = ParenE->getSourceRange();
20915 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
20916 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
20917 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
20918 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
20919 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
20920 }
20921}
20922
20923ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20924 bool IsConstexpr) {
20925 DiagnoseAssignmentAsCondition(E);
20926 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
20927 DiagnoseEqualityWithExtraParens(ParenE: parenE);
20928
20929 ExprResult result = CheckPlaceholderExpr(E);
20930 if (result.isInvalid()) return ExprError();
20931 E = result.get();
20932
20933 if (!E->isTypeDependent()) {
20934 if (getLangOpts().CPlusPlus)
20935 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
20936
20937 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20938 if (ERes.isInvalid())
20939 return ExprError();
20940 E = ERes.get();
20941
20942 QualType T = E->getType();
20943 if (!T->isScalarType()) { // C99 6.8.4.1p1
20944 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
20945 << T << E->getSourceRange();
20946 return ExprError();
20947 }
20948 CheckBoolLikeConversion(E, CC: Loc);
20949 }
20950
20951 return E;
20952}
20953
20954Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20955 Expr *SubExpr, ConditionKind CK,
20956 bool MissingOK) {
20957 // MissingOK indicates whether having no condition expression is valid
20958 // (for loop) or invalid (e.g. while loop).
20959 if (!SubExpr)
20960 return MissingOK ? ConditionResult() : ConditionError();
20961
20962 ExprResult Cond;
20963 switch (CK) {
20964 case ConditionKind::Boolean:
20965 Cond = CheckBooleanCondition(Loc, E: SubExpr);
20966 break;
20967
20968 case ConditionKind::ConstexprIf:
20969 // Note: this might produce a FullExpr
20970 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
20971 break;
20972
20973 case ConditionKind::Switch:
20974 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
20975 break;
20976 }
20977 if (Cond.isInvalid()) {
20978 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
20979 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
20980 if (!Cond.get())
20981 return ConditionError();
20982 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
20983 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
20984
20985 if (!Cond.isUsable())
20986 return ConditionError();
20987
20988 return ConditionResult(*this, nullptr, Cond,
20989 CK == ConditionKind::ConstexprIf);
20990}
20991
20992namespace {
20993 /// A visitor for rebuilding a call to an __unknown_any expression
20994 /// to have an appropriate type.
20995 struct RebuildUnknownAnyFunction
20996 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20997
20998 Sema &S;
20999
21000 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21001
21002 ExprResult VisitStmt(Stmt *S) {
21003 llvm_unreachable("unexpected statement!");
21004 }
21005
21006 ExprResult VisitExpr(Expr *E) {
21007 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21008 << E->getSourceRange();
21009 return ExprError();
21010 }
21011
21012 /// Rebuild an expression which simply semantically wraps another
21013 /// expression which it shares the type and value kind of.
21014 template <class T> ExprResult rebuildSugarExpr(T *E) {
21015 ExprResult SubResult = Visit(S: E->getSubExpr());
21016 if (SubResult.isInvalid()) return ExprError();
21017
21018 Expr *SubExpr = SubResult.get();
21019 E->setSubExpr(SubExpr);
21020 E->setType(SubExpr->getType());
21021 E->setValueKind(SubExpr->getValueKind());
21022 assert(E->getObjectKind() == OK_Ordinary);
21023 return E;
21024 }
21025
21026 ExprResult VisitParenExpr(ParenExpr *E) {
21027 return rebuildSugarExpr(E);
21028 }
21029
21030 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21031 return rebuildSugarExpr(E);
21032 }
21033
21034 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21035 ExprResult SubResult = Visit(S: E->getSubExpr());
21036 if (SubResult.isInvalid()) return ExprError();
21037
21038 Expr *SubExpr = SubResult.get();
21039 E->setSubExpr(SubExpr);
21040 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21041 assert(E->isPRValue());
21042 assert(E->getObjectKind() == OK_Ordinary);
21043 return E;
21044 }
21045
21046 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21047 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21048
21049 E->setType(VD->getType());
21050
21051 assert(E->isPRValue());
21052 if (S.getLangOpts().CPlusPlus &&
21053 !(isa<CXXMethodDecl>(Val: VD) &&
21054 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21055 E->setValueKind(VK_LValue);
21056
21057 return E;
21058 }
21059
21060 ExprResult VisitMemberExpr(MemberExpr *E) {
21061 return resolveDecl(E, VD: E->getMemberDecl());
21062 }
21063
21064 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21065 return resolveDecl(E, VD: E->getDecl());
21066 }
21067 };
21068}
21069
21070/// Given a function expression of unknown-any type, try to rebuild it
21071/// to have a function type.
21072static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21073 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21074 if (Result.isInvalid()) return ExprError();
21075 return S.DefaultFunctionArrayConversion(E: Result.get());
21076}
21077
21078namespace {
21079 /// A visitor for rebuilding an expression of type __unknown_anytype
21080 /// into one which resolves the type directly on the referring
21081 /// expression. Strict preservation of the original source
21082 /// structure is not a goal.
21083 struct RebuildUnknownAnyExpr
21084 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21085
21086 Sema &S;
21087
21088 /// The current destination type.
21089 QualType DestType;
21090
21091 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21092 : S(S), DestType(CastType) {}
21093
21094 ExprResult VisitStmt(Stmt *S) {
21095 llvm_unreachable("unexpected statement!");
21096 }
21097
21098 ExprResult VisitExpr(Expr *E) {
21099 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21100 << E->getSourceRange();
21101 return ExprError();
21102 }
21103
21104 ExprResult VisitCallExpr(CallExpr *E);
21105 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21106
21107 /// Rebuild an expression which simply semantically wraps another
21108 /// expression which it shares the type and value kind of.
21109 template <class T> ExprResult rebuildSugarExpr(T *E) {
21110 ExprResult SubResult = Visit(S: E->getSubExpr());
21111 if (SubResult.isInvalid()) return ExprError();
21112 Expr *SubExpr = SubResult.get();
21113 E->setSubExpr(SubExpr);
21114 E->setType(SubExpr->getType());
21115 E->setValueKind(SubExpr->getValueKind());
21116 assert(E->getObjectKind() == OK_Ordinary);
21117 return E;
21118 }
21119
21120 ExprResult VisitParenExpr(ParenExpr *E) {
21121 return rebuildSugarExpr(E);
21122 }
21123
21124 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21125 return rebuildSugarExpr(E);
21126 }
21127
21128 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21129 const PointerType *Ptr = DestType->getAs<PointerType>();
21130 if (!Ptr) {
21131 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21132 << E->getSourceRange();
21133 return ExprError();
21134 }
21135
21136 if (isa<CallExpr>(Val: E->getSubExpr())) {
21137 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21138 << E->getSourceRange();
21139 return ExprError();
21140 }
21141
21142 assert(E->isPRValue());
21143 assert(E->getObjectKind() == OK_Ordinary);
21144 E->setType(DestType);
21145
21146 // Build the sub-expression as if it were an object of the pointee type.
21147 DestType = Ptr->getPointeeType();
21148 ExprResult SubResult = Visit(S: E->getSubExpr());
21149 if (SubResult.isInvalid()) return ExprError();
21150 E->setSubExpr(SubResult.get());
21151 return E;
21152 }
21153
21154 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21155
21156 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21157
21158 ExprResult VisitMemberExpr(MemberExpr *E) {
21159 return resolveDecl(E, VD: E->getMemberDecl());
21160 }
21161
21162 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21163 return resolveDecl(E, VD: E->getDecl());
21164 }
21165 };
21166}
21167
21168/// Rebuilds a call expression which yielded __unknown_anytype.
21169ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21170 Expr *CalleeExpr = E->getCallee();
21171
21172 enum FnKind {
21173 FK_MemberFunction,
21174 FK_FunctionPointer,
21175 FK_BlockPointer
21176 };
21177
21178 FnKind Kind;
21179 QualType CalleeType = CalleeExpr->getType();
21180 if (CalleeType == S.Context.BoundMemberTy) {
21181 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21182 Kind = FK_MemberFunction;
21183 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21184 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21185 CalleeType = Ptr->getPointeeType();
21186 Kind = FK_FunctionPointer;
21187 } else {
21188 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21189 Kind = FK_BlockPointer;
21190 }
21191 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21192
21193 // Verify that this is a legal result type of a function.
21194 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21195 DestType->isFunctionType()) {
21196 unsigned diagID = diag::err_func_returning_array_function;
21197 if (Kind == FK_BlockPointer)
21198 diagID = diag::err_block_returning_array_function;
21199
21200 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21201 << DestType->isFunctionType() << DestType;
21202 return ExprError();
21203 }
21204
21205 // Otherwise, go ahead and set DestType as the call's result.
21206 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21207 E->setValueKind(Expr::getValueKindForType(T: DestType));
21208 assert(E->getObjectKind() == OK_Ordinary);
21209
21210 // Rebuild the function type, replacing the result type with DestType.
21211 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21212 if (Proto) {
21213 // __unknown_anytype(...) is a special case used by the debugger when
21214 // it has no idea what a function's signature is.
21215 //
21216 // We want to build this call essentially under the K&R
21217 // unprototyped rules, but making a FunctionNoProtoType in C++
21218 // would foul up all sorts of assumptions. However, we cannot
21219 // simply pass all arguments as variadic arguments, nor can we
21220 // portably just call the function under a non-variadic type; see
21221 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21222 // However, it turns out that in practice it is generally safe to
21223 // call a function declared as "A foo(B,C,D);" under the prototype
21224 // "A foo(B,C,D,...);". The only known exception is with the
21225 // Windows ABI, where any variadic function is implicitly cdecl
21226 // regardless of its normal CC. Therefore we change the parameter
21227 // types to match the types of the arguments.
21228 //
21229 // This is a hack, but it is far superior to moving the
21230 // corresponding target-specific code from IR-gen to Sema/AST.
21231
21232 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21233 SmallVector<QualType, 8> ArgTypes;
21234 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21235 ArgTypes.reserve(N: E->getNumArgs());
21236 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21237 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21238 }
21239 ParamTypes = ArgTypes;
21240 }
21241 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21242 EPI: Proto->getExtProtoInfo());
21243 } else {
21244 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21245 Info: FnType->getExtInfo());
21246 }
21247
21248 // Rebuild the appropriate pointer-to-function type.
21249 switch (Kind) {
21250 case FK_MemberFunction:
21251 // Nothing to do.
21252 break;
21253
21254 case FK_FunctionPointer:
21255 DestType = S.Context.getPointerType(T: DestType);
21256 break;
21257
21258 case FK_BlockPointer:
21259 DestType = S.Context.getBlockPointerType(T: DestType);
21260 break;
21261 }
21262
21263 // Finally, we can recurse.
21264 ExprResult CalleeResult = Visit(S: CalleeExpr);
21265 if (!CalleeResult.isUsable()) return ExprError();
21266 E->setCallee(CalleeResult.get());
21267
21268 // Bind a temporary if necessary.
21269 return S.MaybeBindToTemporary(E);
21270}
21271
21272ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21273 // Verify that this is a legal result type of a call.
21274 if (DestType->isArrayType() || DestType->isFunctionType()) {
21275 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21276 << DestType->isFunctionType() << DestType;
21277 return ExprError();
21278 }
21279
21280 // Rewrite the method result type if available.
21281 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21282 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21283 Method->setReturnType(DestType);
21284 }
21285
21286 // Change the type of the message.
21287 E->setType(DestType.getNonReferenceType());
21288 E->setValueKind(Expr::getValueKindForType(T: DestType));
21289
21290 return S.MaybeBindToTemporary(E);
21291}
21292
21293ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21294 // The only case we should ever see here is a function-to-pointer decay.
21295 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21296 assert(E->isPRValue());
21297 assert(E->getObjectKind() == OK_Ordinary);
21298
21299 E->setType(DestType);
21300
21301 // Rebuild the sub-expression as the pointee (function) type.
21302 DestType = DestType->castAs<PointerType>()->getPointeeType();
21303
21304 ExprResult Result = Visit(S: E->getSubExpr());
21305 if (!Result.isUsable()) return ExprError();
21306
21307 E->setSubExpr(Result.get());
21308 return E;
21309 } else if (E->getCastKind() == CK_LValueToRValue) {
21310 assert(E->isPRValue());
21311 assert(E->getObjectKind() == OK_Ordinary);
21312
21313 assert(isa<BlockPointerType>(E->getType()));
21314
21315 E->setType(DestType);
21316
21317 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21318 DestType = S.Context.getLValueReferenceType(T: DestType);
21319
21320 ExprResult Result = Visit(S: E->getSubExpr());
21321 if (!Result.isUsable()) return ExprError();
21322
21323 E->setSubExpr(Result.get());
21324 return E;
21325 } else {
21326 llvm_unreachable("Unhandled cast type!");
21327 }
21328}
21329
21330ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21331 ExprValueKind ValueKind = VK_LValue;
21332 QualType Type = DestType;
21333
21334 // We know how to make this work for certain kinds of decls:
21335
21336 // - functions
21337 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21338 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21339 DestType = Ptr->getPointeeType();
21340 ExprResult Result = resolveDecl(E, VD);
21341 if (Result.isInvalid()) return ExprError();
21342 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21343 VK: VK_PRValue);
21344 }
21345
21346 if (!Type->isFunctionType()) {
21347 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21348 << VD << E->getSourceRange();
21349 return ExprError();
21350 }
21351 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21352 // We must match the FunctionDecl's type to the hack introduced in
21353 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21354 // type. See the lengthy commentary in that routine.
21355 QualType FDT = FD->getType();
21356 const FunctionType *FnType = FDT->castAs<FunctionType>();
21357 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21358 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21359 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21360 SourceLocation Loc = FD->getLocation();
21361 FunctionDecl *NewFD = FunctionDecl::Create(
21362 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21363 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21364 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21365 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21366 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21367
21368 if (FD->getQualifier())
21369 NewFD->setQualifierInfo(FD->getQualifierLoc());
21370
21371 SmallVector<ParmVarDecl*, 16> Params;
21372 for (const auto &AI : FT->param_types()) {
21373 ParmVarDecl *Param =
21374 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21375 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21376 Params.push_back(Elt: Param);
21377 }
21378 NewFD->setParams(Params);
21379 DRE->setDecl(NewFD);
21380 VD = DRE->getDecl();
21381 }
21382 }
21383
21384 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21385 if (MD->isInstance()) {
21386 ValueKind = VK_PRValue;
21387 Type = S.Context.BoundMemberTy;
21388 }
21389
21390 // Function references aren't l-values in C.
21391 if (!S.getLangOpts().CPlusPlus)
21392 ValueKind = VK_PRValue;
21393
21394 // - variables
21395 } else if (isa<VarDecl>(Val: VD)) {
21396 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21397 Type = RefTy->getPointeeType();
21398 } else if (Type->isFunctionType()) {
21399 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21400 << VD << E->getSourceRange();
21401 return ExprError();
21402 }
21403
21404 // - nothing else
21405 } else {
21406 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21407 << VD << E->getSourceRange();
21408 return ExprError();
21409 }
21410
21411 // Modifying the declaration like this is friendly to IR-gen but
21412 // also really dangerous.
21413 VD->setType(DestType);
21414 E->setType(Type);
21415 E->setValueKind(ValueKind);
21416 return E;
21417}
21418
21419ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21420 Expr *CastExpr, CastKind &CastKind,
21421 ExprValueKind &VK, CXXCastPath &Path) {
21422 // The type we're casting to must be either void or complete.
21423 if (!CastType->isVoidType() &&
21424 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21425 DiagID: diag::err_typecheck_cast_to_incomplete))
21426 return ExprError();
21427
21428 // Rewrite the casted expression from scratch.
21429 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21430 if (!result.isUsable()) return ExprError();
21431
21432 CastExpr = result.get();
21433 VK = CastExpr->getValueKind();
21434 CastKind = CK_NoOp;
21435
21436 return CastExpr;
21437}
21438
21439ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21440 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21441}
21442
21443ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21444 Expr *arg, QualType &paramType) {
21445 // If the syntactic form of the argument is not an explicit cast of
21446 // any sort, just do default argument promotion.
21447 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21448 if (!castArg) {
21449 ExprResult result = DefaultArgumentPromotion(E: arg);
21450 if (result.isInvalid()) return ExprError();
21451 paramType = result.get()->getType();
21452 return result;
21453 }
21454
21455 // Otherwise, use the type that was written in the explicit cast.
21456 assert(!arg->hasPlaceholderType());
21457 paramType = castArg->getTypeAsWritten();
21458
21459 // Copy-initialize a parameter of that type.
21460 InitializedEntity entity =
21461 InitializedEntity::InitializeParameter(Context, Type: paramType,
21462 /*consumed*/ Consumed: false);
21463 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21464}
21465
21466static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21467 Expr *orig = E;
21468 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21469 while (true) {
21470 E = E->IgnoreParenImpCasts();
21471 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21472 E = call->getCallee();
21473 diagID = diag::err_uncasted_call_of_unknown_any;
21474 } else {
21475 break;
21476 }
21477 }
21478
21479 SourceLocation loc;
21480 NamedDecl *d;
21481 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21482 loc = ref->getLocation();
21483 d = ref->getDecl();
21484 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21485 loc = mem->getMemberLoc();
21486 d = mem->getMemberDecl();
21487 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21488 diagID = diag::err_uncasted_call_of_unknown_any;
21489 loc = msg->getSelectorStartLoc();
21490 d = msg->getMethodDecl();
21491 if (!d) {
21492 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21493 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21494 << orig->getSourceRange();
21495 return ExprError();
21496 }
21497 } else {
21498 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21499 << E->getSourceRange();
21500 return ExprError();
21501 }
21502
21503 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21504
21505 // Never recoverable.
21506 return ExprError();
21507}
21508
21509ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21510 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21511 if (!placeholderType) return E;
21512
21513 switch (placeholderType->getKind()) {
21514 case BuiltinType::UnresolvedTemplate: {
21515 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
21516 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21517 // There's only one FoundDecl for UnresolvedTemplate type. See
21518 // BuildTemplateIdExpr.
21519 NamedDecl *Temp = *ULE->decls_begin();
21520 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21521
21522 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21523 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21524 // as it models only the unqualified-id case, where this case can clearly be
21525 // qualified. Thus we can't just qualify an assumed template.
21526 TemplateName TN;
21527 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21528 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21529 Template: TemplateName(TD));
21530 else
21531 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21532
21533 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21534 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21535 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
21536 << IsTypeAliasTemplateDecl;
21537
21538 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21539 bool HasAnyDependentTA = false;
21540 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21541 HasAnyDependentTA |= Arg.getArgument().isDependent();
21542 TAL.addArgument(Loc: Arg);
21543 }
21544
21545 QualType TST;
21546 {
21547 SFINAETrap Trap(*this);
21548 TST = CheckTemplateIdType(
21549 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
21550 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21551 }
21552 if (TST.isNull())
21553 TST = Context.getTemplateSpecializationType(
21554 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
21555 /*CanonicalArgs=*/{},
21556 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21557 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
21558 T: TST);
21559 }
21560
21561 // Overloaded expressions.
21562 case BuiltinType::Overload: {
21563 // Try to resolve a single function template specialization.
21564 // This is obligatory.
21565 ExprResult Result = E;
21566 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21567 return Result;
21568
21569 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21570 // leaves Result unchanged on failure.
21571 Result = E;
21572 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21573 return Result;
21574
21575 // If that failed, try to recover with a call.
21576 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
21577 /*complain*/ ForceComplain: true);
21578 return Result;
21579 }
21580
21581 // Bound member functions.
21582 case BuiltinType::BoundMember: {
21583 ExprResult result = E;
21584 const Expr *BME = E->IgnoreParens();
21585 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
21586 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21587 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
21588 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21589 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21590 if (ME->getMemberNameInfo().getName().getNameKind() ==
21591 DeclarationName::CXXDestructorName)
21592 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21593 }
21594 tryToRecoverWithCall(E&: result, PD,
21595 /*complain*/ ForceComplain: true);
21596 return result;
21597 }
21598
21599 // ARC unbridged casts.
21600 case BuiltinType::ARCUnbridgedCast: {
21601 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
21602 ObjC().diagnoseARCUnbridgedCast(e: realCast);
21603 return realCast;
21604 }
21605
21606 // Expressions of unknown type.
21607 case BuiltinType::UnknownAny:
21608 return diagnoseUnknownAnyExpr(S&: *this, E);
21609
21610 // Pseudo-objects.
21611 case BuiltinType::PseudoObject:
21612 return PseudoObject().checkRValue(E);
21613
21614 case BuiltinType::BuiltinFn: {
21615 // Accept __noop without parens by implicitly converting it to a call expr.
21616 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
21617 if (DRE) {
21618 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21619 unsigned BuiltinID = FD->getBuiltinID();
21620 if (BuiltinID == Builtin::BI__noop) {
21621 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
21622 CK: CK_BuiltinFnToFnPtr)
21623 .get();
21624 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21625 VK: VK_PRValue, RParenLoc: SourceLocation(),
21626 FPFeatures: FPOptionsOverride());
21627 }
21628
21629 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
21630 // Any use of these other than a direct call is ill-formed as of C++20,
21631 // because they are not addressable functions. In earlier language
21632 // modes, warn and force an instantiation of the real body.
21633 Diag(Loc: E->getBeginLoc(),
21634 DiagID: getLangOpts().CPlusPlus20
21635 ? diag::err_use_of_unaddressable_function
21636 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21637 if (FD->isImplicitlyInstantiable()) {
21638 // Require a definition here because a normal attempt at
21639 // instantiation for a builtin will be ignored, and we won't try
21640 // again later. We assume that the definition of the template
21641 // precedes this use.
21642 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
21643 /*Recursive=*/false,
21644 /*DefinitionRequired=*/true,
21645 /*AtEndOfTU=*/false);
21646 }
21647 // Produce a properly-typed reference to the function.
21648 CXXScopeSpec SS;
21649 SS.Adopt(Other: DRE->getQualifierLoc());
21650 TemplateArgumentListInfo TemplateArgs;
21651 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
21652 return BuildDeclRefExpr(
21653 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
21654 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
21655 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
21656 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21657 }
21658 }
21659
21660 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
21661 return ExprError();
21662 }
21663
21664 case BuiltinType::IncompleteMatrixIdx: {
21665 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
21666 // At this point, we know there was no second [] to complete the operator.
21667 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21668 if (getLangOpts().HLSL) {
21669 return CreateBuiltinMatrixSingleSubscriptExpr(
21670 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
21671 }
21672 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
21673 return ExprError();
21674 }
21675
21676 // Expressions of unknown type.
21677 case BuiltinType::ArraySection:
21678 // If we've already diagnosed something on the array section type, we
21679 // shouldn't need to do any further diagnostic here.
21680 if (!E->containsErrors())
21681 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
21682 << cast<ArraySectionExpr>(Val: E)->isOMPArraySection();
21683 return ExprError();
21684
21685 // Expressions of unknown type.
21686 case BuiltinType::OMPArrayShaping:
21687 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
21688
21689 case BuiltinType::OMPIterator:
21690 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
21691
21692 // Everything else should be impossible.
21693#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21694 case BuiltinType::Id:
21695#include "clang/Basic/OpenCLImageTypes.def"
21696#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21697 case BuiltinType::Id:
21698#include "clang/Basic/OpenCLExtensionTypes.def"
21699#define SVE_TYPE(Name, Id, SingletonId) \
21700 case BuiltinType::Id:
21701#include "clang/Basic/AArch64ACLETypes.def"
21702#define PPC_VECTOR_TYPE(Name, Id, Size) \
21703 case BuiltinType::Id:
21704#include "clang/Basic/PPCTypes.def"
21705#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21706#include "clang/Basic/RISCVVTypes.def"
21707#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21708#include "clang/Basic/WebAssemblyReferenceTypes.def"
21709#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21710#include "clang/Basic/AMDGPUTypes.def"
21711#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21712#include "clang/Basic/HLSLIntangibleTypes.def"
21713#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21714#define PLACEHOLDER_TYPE(Id, SingletonId)
21715#include "clang/AST/BuiltinTypes.def"
21716 break;
21717 }
21718
21719 llvm_unreachable("invalid placeholder type!");
21720}
21721
21722bool Sema::CheckCaseExpression(Expr *E) {
21723 if (E->isTypeDependent())
21724 return true;
21725 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
21726 return E->getType()->isIntegralOrEnumerationType();
21727 return false;
21728}
21729
21730ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21731 ArrayRef<Expr *> SubExprs, QualType T) {
21732 if (!Context.getLangOpts().RecoveryAST)
21733 return ExprError();
21734
21735 if (isSFINAEContext())
21736 return ExprError();
21737
21738 if (T.isNull() || T->isUndeducedType() ||
21739 !Context.getLangOpts().RecoveryASTType)
21740 // We don't know the concrete type, fallback to dependent type.
21741 T = Context.DependentTy;
21742
21743 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
21744}
21745