clang 18.0.0git
SemaExpr.cpp
Go to the documentation of this file.
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 "TreeTransform.h"
14#include "UsedDeclVisitor.h"
17#include "clang/AST/ASTLambda.h"
20#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
42#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Overload.h"
50#include "clang/Sema/Scope.h"
54#include "clang/Sema/Template.h"
55#include "llvm/ADT/STLExtras.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/ConvertUTF.h"
59#include "llvm/Support/SaveAndRestore.h"
60#include "llvm/Support/TypeSize.h"
61#include <optional>
62
63using namespace clang;
64using namespace sema;
65
66/// Determine whether the use of this declaration is valid, without
67/// emitting diagnostics.
68bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
69 // See if this is an auto-typed variable whose initializer we are parsing.
70 if (ParsingInitForAutoVars.count(D))
71 return false;
72
73 // See if this is a deleted function.
74 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75 if (FD->isDeleted())
76 return false;
77
78 // If the function has a deduced return type, and we can't deduce it,
79 // then we can't use it either.
80 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
81 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
82 return false;
83
84 // See if this is an aligned allocation/deallocation function that is
85 // unavailable.
86 if (TreatUnavailableAsInvalid &&
88 return false;
89 }
90
91 // See if this function is unavailable.
92 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
93 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
94 return false;
95
96 if (isa<UnresolvedUsingIfExistsDecl>(D))
97 return false;
98
99 return true;
100}
101
103 // Warn if this is used but marked unused.
104 if (const auto *A = D->getAttr<UnusedAttr>()) {
105 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
106 // should diagnose them.
107 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
108 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
109 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
110 if (DC && !DC->hasAttr<UnusedAttr>())
111 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
112 }
113 }
114}
115
116/// Emit a note explaining that this function is deleted.
118 assert(Decl && Decl->isDeleted());
119
120 if (Decl->isDefaulted()) {
121 // If the method was explicitly defaulted, point at that declaration.
122 if (!Decl->isImplicit())
123 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
124
125 // Try to diagnose why this special member function was implicitly
126 // deleted. This might fail, if that reason no longer applies.
128 return;
129 }
130
131 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
132 if (Ctor && Ctor->isInheritingConstructor())
134
135 Diag(Decl->getLocation(), diag::note_availability_specified_here)
136 << Decl << 1;
137}
138
139/// Determine whether a FunctionDecl was ever declared with an
140/// explicit storage class.
142 for (auto *I : D->redecls()) {
143 if (I->getStorageClass() != SC_None)
144 return true;
145 }
146 return false;
147}
148
149/// Check whether we're in an extern inline function and referring to a
150/// variable or function with internal linkage (C11 6.7.4p3).
151///
152/// This is only a warning because we used to silently accept this code, but
153/// in many cases it will not behave correctly. This is not enabled in C++ mode
154/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
155/// and so while there may still be user mistakes, most of the time we can't
156/// prove that there are errors.
158 const NamedDecl *D,
159 SourceLocation Loc) {
160 // This is disabled under C++; there are too many ways for this to fire in
161 // contexts where the warning is a false positive, or where it is technically
162 // correct but benign.
163 if (S.getLangOpts().CPlusPlus)
164 return;
165
166 // Check if this is an inlined function or method.
167 FunctionDecl *Current = S.getCurFunctionDecl();
168 if (!Current)
169 return;
170 if (!Current->isInlined())
171 return;
172 if (!Current->isExternallyVisible())
173 return;
174
175 // Check if the decl has internal linkage.
177 return;
178
179 // Downgrade from ExtWarn to Extension if
180 // (1) the supposedly external inline function is in the main file,
181 // and probably won't be included anywhere else.
182 // (2) the thing we're referencing is a pure function.
183 // (3) the thing we're referencing is another inline function.
184 // This last can give us false negatives, but it's better than warning on
185 // wrappers for simple C library functions.
186 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
187 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
188 if (!DowngradeWarning && UsedFn)
189 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
190
191 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
192 : diag::ext_internal_in_extern_inline)
193 << /*IsVar=*/!UsedFn << D;
194
196
197 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
198 << D;
199}
200
202 const FunctionDecl *First = Cur->getFirstDecl();
203
204 // Suggest "static" on the function, if possible.
206 SourceLocation DeclBegin = First->getSourceRange().getBegin();
207 Diag(DeclBegin, diag::note_convert_inline_to_static)
208 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
209 }
210}
211
212/// Determine whether the use of this declaration is valid, and
213/// emit any corresponding diagnostics.
214///
215/// This routine diagnoses various problems with referencing
216/// declarations that can occur when using a declaration. For example,
217/// it might warn if a deprecated or unavailable declaration is being
218/// used, or produce an error (and return true) if a C++0x deleted
219/// function is being used.
220///
221/// \returns true if there was an error (this declaration cannot be
222/// referenced), false otherwise.
223///
225 const ObjCInterfaceDecl *UnknownObjCClass,
226 bool ObjCPropertyAccess,
227 bool AvoidPartialAvailabilityChecks,
228 ObjCInterfaceDecl *ClassReceiver,
229 bool SkipTrailingRequiresClause) {
230 SourceLocation Loc = Locs.front();
231 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
232 // If there were any diagnostics suppressed by template argument deduction,
233 // emit them now.
234 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235 if (Pos != SuppressedDiagnostics.end()) {
236 for (const PartialDiagnosticAt &Suppressed : Pos->second)
237 Diag(Suppressed.first, Suppressed.second);
238
239 // Clear out the list of suppressed diagnostics, so that we don't emit
240 // them again for this specialization. However, we don't obsolete this
241 // entry from the table, because we want to avoid ever emitting these
242 // diagnostics again.
243 Pos->second.clear();
244 }
245
246 // C++ [basic.start.main]p3:
247 // The function 'main' shall not be used within a program.
248 if (cast<FunctionDecl>(D)->isMain())
249 Diag(Loc, diag::ext_main_used);
250
251 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
252 }
253
254 // See if this is an auto-typed variable whose initializer we are parsing.
255 if (ParsingInitForAutoVars.count(D)) {
256 if (isa<BindingDecl>(D)) {
257 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
258 << D->getDeclName();
259 } else {
260 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
261 << D->getDeclName() << cast<VarDecl>(D)->getType();
262 }
263 return true;
264 }
265
266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
267 // See if this is a deleted function.
268 if (FD->isDeleted()) {
269 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
270 if (Ctor && Ctor->isInheritingConstructor())
271 Diag(Loc, diag::err_deleted_inherited_ctor_use)
272 << Ctor->getParent()
273 << Ctor->getInheritedConstructor().getConstructor()->getParent();
274 else
275 Diag(Loc, diag::err_deleted_function_use);
277 return true;
278 }
279
280 // [expr.prim.id]p4
281 // A program that refers explicitly or implicitly to a function with a
282 // trailing requires-clause whose constraint-expression is not satisfied,
283 // other than to declare it, is ill-formed. [...]
284 //
285 // See if this is a function with constraints that need to be satisfied.
286 // Check this before deducing the return type, as it might instantiate the
287 // definition.
288 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
289 ConstraintSatisfaction Satisfaction;
290 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
291 /*ForOverloadResolution*/ true))
292 // A diagnostic will have already been generated (non-constant
293 // constraint expression, for example)
294 return true;
295 if (!Satisfaction.IsSatisfied) {
296 Diag(Loc,
297 diag::err_reference_to_function_with_unsatisfied_constraints)
298 << D;
299 DiagnoseUnsatisfiedConstraint(Satisfaction);
300 return true;
301 }
302 }
303
304 // If the function has a deduced return type, and we can't deduce it,
305 // then we can't use it either.
306 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307 DeduceReturnType(FD, Loc))
308 return true;
309
310 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
311 return true;
312
313 }
314
315 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
316 // Lambdas are only default-constructible or assignable in C++2a onwards.
317 if (MD->getParent()->isLambda() &&
318 ((isa<CXXConstructorDecl>(MD) &&
319 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
320 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322 << !isa<CXXConstructorDecl>(MD);
323 }
324 }
325
326 auto getReferencedObjCProp = [](const NamedDecl *D) ->
327 const ObjCPropertyDecl * {
328 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
329 return MD->findPropertyDecl();
330 return nullptr;
331 };
332 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334 return true;
335 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
336 return true;
337 }
338
339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340 // Only the variables omp_in and omp_out are allowed in the combiner.
341 // Only the variables omp_priv and omp_orig are allowed in the
342 // initializer-clause.
343 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
344 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345 isa<VarDecl>(D)) {
346 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
348 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349 return true;
350 }
351
352 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353 // List-items in map clauses on this construct may only refer to the declared
354 // variable var and entities that could be referenced by a procedure defined
355 // at the same location.
356 // [OpenMP 5.2] Also allow iterator declared variables.
357 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
358 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
359 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
361 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
366 Diag(Loc, diag::err_use_of_empty_using_if_exists);
367 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368 return true;
369 }
370
371 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372 AvoidPartialAvailabilityChecks, ClassReceiver);
373
374 DiagnoseUnusedOfDecl(*this, D, Loc);
375
377
378 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
379 if (getLangOpts().getFPEvalMethod() !=
382 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
383 Diag(D->getLocation(),
384 diag::err_type_available_only_in_default_eval_method)
385 << D->getName();
386 }
387
388 if (auto *VD = dyn_cast<ValueDecl>(D))
389 checkTypeSupport(VD->getType(), Loc, VD);
390
391 if (LangOpts.SYCLIsDevice ||
392 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
394 if (const auto *VD = dyn_cast<VarDecl>(D))
395 if (VD->getTLSKind() != VarDecl::TLS_None)
396 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
397 }
398
399 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
401 // C++ [expr.prim.req.nested] p3
402 // A local parameter shall only appear as an unevaluated operand
403 // (Clause 8) within the constraint-expression.
404 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
405 << D;
406 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
407 return true;
408 }
409
410 return false;
411}
412
413/// DiagnoseSentinelCalls - This routine checks whether a call or
414/// message-send is to a declaration with the sentinel attribute, and
415/// if so, it checks that the requirements of the sentinel are
416/// satisfied.
418 ArrayRef<Expr *> Args) {
419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420 if (!Attr)
421 return;
422
423 // The number of formal parameters of the declaration.
424 unsigned NumFormalParams;
425
426 // The kind of declaration. This is also an index into a %select in
427 // the diagnostic.
428 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
429
430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
431 NumFormalParams = MD->param_size();
432 CalleeKind = CK_Method;
433 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
434 NumFormalParams = FD->param_size();
435 CalleeKind = CK_Function;
436 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
437 QualType Ty = VD->getType();
438 const FunctionType *Fn = nullptr;
439 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
440 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
441 if (!Fn)
442 return;
443 CalleeKind = CK_Function;
444 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
445 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
446 CalleeKind = CK_Block;
447 } else {
448 return;
449 }
450
451 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
452 NumFormalParams = proto->getNumParams();
453 else
454 NumFormalParams = 0;
455 } else {
456 return;
457 }
458
459 // "NullPos" is the number of formal parameters at the end which
460 // effectively count as part of the variadic arguments. This is
461 // useful if you would prefer to not have *any* formal parameters,
462 // but the language forces you to have at least one.
463 unsigned NullPos = Attr->getNullPos();
464 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
465 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
466
467 // The number of arguments which should follow the sentinel.
468 unsigned NumArgsAfterSentinel = Attr->getSentinel();
469
470 // If there aren't enough arguments for all the formal parameters,
471 // the sentinel, and the args after the sentinel, complain.
472 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
473 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
475 return;
476 }
477
478 // Otherwise, find the sentinel expression.
479 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
480 if (!SentinelExpr)
481 return;
482 if (SentinelExpr->isValueDependent())
483 return;
484 if (Context.isSentinelNullExpr(SentinelExpr))
485 return;
486
487 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
488 // or 'NULL' if those are actually defined in the context. Only use
489 // 'nil' for ObjC methods, where it's much more likely that the
490 // variadic arguments form a list of object pointers.
491 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
492 std::string NullValue;
493 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
494 NullValue = "nil";
495 else if (getLangOpts().CPlusPlus11)
496 NullValue = "nullptr";
497 else if (PP.isMacroDefined("NULL"))
498 NullValue = "NULL";
499 else
500 NullValue = "(void*) 0";
501
502 if (MissingNilLoc.isInvalid())
503 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
504 else
505 Diag(MissingNilLoc, diag::warn_missing_sentinel)
506 << int(CalleeKind)
507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
508 Diag(D->getLocation(), diag::note_sentinel_here)
509 << int(CalleeKind) << Attr->getRange();
510}
511
513 return E ? E->getSourceRange() : SourceRange();
514}
515
516//===----------------------------------------------------------------------===//
517// Standard Promotions and Conversions
518//===----------------------------------------------------------------------===//
519
520/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
522 // Handle any placeholder expressions which made it here.
523 if (E->hasPlaceholderType()) {
525 if (result.isInvalid()) return ExprError();
526 E = result.get();
527 }
528
529 QualType Ty = E->getType();
530 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
531
532 if (Ty->isFunctionType()) {
533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
536 return ExprError();
537
539 CK_FunctionToPointerDecay).get();
540 } else if (Ty->isArrayType()) {
541 // In C90 mode, arrays only promote to pointers if the array expression is
542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543 // type 'array of type' is converted to an expression that has type 'pointer
544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
545 // that has type 'array of type' ...". The relevant change is "an lvalue"
546 // (C90) to "an expression" (C99).
547 //
548 // C++ 4.2p1:
549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550 // T" can be converted to an rvalue of type "pointer to T".
551 //
552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
554 CK_ArrayToPointerDecay);
555 if (Res.isInvalid())
556 return ExprError();
557 E = Res.get();
558 }
559 }
560 return E;
561}
562
564 // Check to see if we are dereferencing a null pointer. If so,
565 // and if not volatile-qualified, this is undefined behavior that the
566 // optimizer will delete, so warn about it. People sometimes try to use this
567 // to get a deterministic trap and are surprised by clang's behavior. This
568 // only handles the pattern "*null", which is a very syntactic check.
569 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
570 if (UO && UO->getOpcode() == UO_Deref &&
571 UO->getSubExpr()->getType()->isPointerType()) {
572 const LangAS AS =
573 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
574 if ((!isTargetAddressSpace(AS) ||
575 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
576 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
578 !UO->getType().isVolatileQualified()) {
579 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
580 S.PDiag(diag::warn_indirection_through_null)
581 << UO->getSubExpr()->getSourceRange());
582 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
583 S.PDiag(diag::note_indirection_through_null));
584 }
585 }
586}
587
588static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589 SourceLocation AssignLoc,
590 const Expr* RHS) {
591 const ObjCIvarDecl *IV = OIRE->getDecl();
592 if (!IV)
593 return;
594
595 DeclarationName MemberName = IV->getDeclName();
597 if (!Member || !Member->isStr("isa"))
598 return;
599
600 const Expr *Base = OIRE->getBase();
601 QualType BaseType = Base->getType();
602 if (OIRE->isArrow())
603 BaseType = BaseType->getPointeeType();
604 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606 ObjCInterfaceDecl *ClassDeclared = nullptr;
607 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
608 if (!ClassDeclared->getSuperClass()
609 && (*ClassDeclared->ivar_begin()) == IV) {
610 if (RHS) {
611 NamedDecl *ObjectSetClass =
613 &S.Context.Idents.get("object_setClass"),
615 if (ObjectSetClass) {
616 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
619 "object_setClass(")
621 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
622 << FixItHint::CreateInsertion(RHSLocEnd, ")");
623 }
624 else
625 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
626 } else {
627 NamedDecl *ObjectGetClass =
629 &S.Context.Idents.get("object_getClass"),
631 if (ObjectGetClass)
632 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
634 "object_getClass(")
636 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
637 else
638 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
639 }
640 S.Diag(IV->getLocation(), diag::note_ivar_decl);
641 }
642 }
643}
644
646 // Handle any placeholder expressions which made it here.
647 if (E->hasPlaceholderType()) {
649 if (result.isInvalid()) return ExprError();
650 E = result.get();
651 }
652
653 // C++ [conv.lval]p1:
654 // A glvalue of a non-function, non-array type T can be
655 // converted to a prvalue.
656 if (!E->isGLValue()) return E;
657
658 QualType T = E->getType();
659 assert(!T.isNull() && "r-value conversion on typeless expression?");
660
661 // lvalue-to-rvalue conversion cannot be applied to function or array types.
662 if (T->isFunctionType() || T->isArrayType())
663 return E;
664
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 if (getLangOpts().CPlusPlus &&
668 (E->getType() == Context.OverloadTy ||
669 T->isDependentType() ||
670 T->isRecordType()))
671 return E;
672
673 // The C standard is actually really unclear on this point, and
674 // DR106 tells us what the result should be but not why. It's
675 // generally best to say that void types just doesn't undergo
676 // lvalue-to-rvalue at all. Note that expressions of unqualified
677 // 'void' type are never l-values, but qualified void can be.
678 if (T->isVoidType())
679 return E;
680
681 // OpenCL usually rejects direct accesses to values of 'half' type.
682 if (getLangOpts().OpenCL &&
683 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
684 T->isHalfType()) {
685 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
686 << 0 << T;
687 return ExprError();
688 }
689
691 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
692 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
693 &Context.Idents.get("object_getClass"),
695 if (ObjectGetClass)
696 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
697 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
699 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
700 else
701 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
702 }
703 else if (const ObjCIvarRefExpr *OIRE =
704 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
705 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
706
707 // C++ [conv.lval]p1:
708 // [...] If T is a non-class type, the type of the prvalue is the
709 // cv-unqualified version of T. Otherwise, the type of the
710 // rvalue is T.
711 //
712 // C99 6.3.2.1p2:
713 // If the lvalue has qualified type, the value has the unqualified
714 // version of the type of the lvalue; otherwise, the value has the
715 // type of the lvalue.
716 if (T.hasQualifiers())
717 T = T.getUnqualifiedType();
718
719 // Under the MS ABI, lock down the inheritance model now.
720 if (T->isMemberPointerType() &&
722 (void)isCompleteType(E->getExprLoc(), T);
723
725 if (Res.isInvalid())
726 return Res;
727 E = Res.get();
728
729 // Loading a __weak object implicitly retains the value, so we need a cleanup to
730 // balance that.
733
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, CK, E, nullptr, VK_PRValue,
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, CK_AtomicToNonAtomic, Res.get(),
749 nullptr, VK_PRValue, FPOptionsOverride());
750 }
751
752 return Res;
753}
754
757 if (Res.isInvalid())
758 return ExprError();
759 Res = DefaultLvalueConversion(Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res;
763}
764
765/// CallExprUnaryConversions - a special case of an unary conversion
766/// performed on a function designator of a call expression.
768 QualType Ty = E->getType();
769 ExprResult Res = E;
770 // Only do implicit cast for a function type, but not for a pointer
771 // to function type.
772 if (Ty->isFunctionType()) {
774 CK_FunctionToPointerDecay);
775 if (Res.isInvalid())
776 return ExprError();
777 }
778 Res = DefaultLvalueConversion(Res.get());
779 if (Res.isInvalid())
780 return ExprError();
781 return Res.get();
782}
783
784/// UsualUnaryConversions - Performs various conversions that are common to most
785/// operators (C99 6.3). The conversions of array and function types are
786/// sometimes suppressed. For example, the array->pointer conversion doesn't
787/// apply if the array is an argument to the sizeof or address (&) operators.
788/// In these instances, this routine should *not* be called.
790 // First, convert to an r-value.
792 if (Res.isInvalid())
793 return ExprError();
794 E = Res.get();
795
796 QualType Ty = E->getType();
797 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
798
799 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
800 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
801 (getLangOpts().getFPEvalMethod() !=
804 switch (EvalMethod) {
805 default:
806 llvm_unreachable("Unrecognized float evaluation method");
807 break;
809 llvm_unreachable("Float evaluation method should be set by now");
810 break;
813 // Widen the expression to double.
814 return Ty->isComplexType()
817 CK_FloatingComplexCast)
818 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
819 break;
822 // Widen the expression to long double.
823 return Ty->isComplexType()
826 CK_FloatingComplexCast)
828 CK_FloatingCast);
829 break;
830 }
831 }
832
833 // Half FP have to be promoted to float unless it is natively supported
834 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
835 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
836
837 // Try to perform integral promotions if the object has a theoretically
838 // promotable type.
840 // C99 6.3.1.1p2:
841 //
842 // The following may be used in an expression wherever an int or
843 // unsigned int may be used:
844 // - an object or expression with an integer type whose integer
845 // conversion rank is less than or equal to the rank of int
846 // and unsigned int.
847 // - A bit-field of type _Bool, int, signed int, or unsigned int.
848 //
849 // If an int can represent all values of the original type, the
850 // value is converted to an int; otherwise, it is converted to an
851 // unsigned int. These are called the integer promotions. All
852 // other types are unchanged by the integer promotions.
853
855 if (!PTy.isNull()) {
856 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
857 return E;
858 }
861 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
862 return E;
863 }
864 }
865 return E;
866}
867
868/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
869/// do not have a prototype. Arguments that have type float or __fp16
870/// are promoted to double. All other argument types are converted by
871/// UsualUnaryConversions().
873 QualType Ty = E->getType();
874 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
875
877 if (Res.isInvalid())
878 return ExprError();
879 E = Res.get();
880
881 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
882 // promote to double.
883 // Note that default argument promotion applies only to float (and
884 // half/fp16); it does not apply to _Float16.
885 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
886 if (BTy && (BTy->getKind() == BuiltinType::Half ||
887 BTy->getKind() == BuiltinType::Float)) {
888 if (getLangOpts().OpenCL &&
889 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
890 if (BTy->getKind() == BuiltinType::Half) {
891 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
892 }
893 } else {
894 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
895 }
896 }
897 if (BTy &&
898 getLangOpts().getExtendIntArgs() ==
903 E = (Ty->isUnsignedIntegerType())
904 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
905 .get()
906 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
908 "Unexpected typesize for LongLongTy");
909 }
910
911 // C++ performs lvalue-to-rvalue conversion as a default argument
912 // promotion, even on class types, but note:
913 // C++11 [conv.lval]p2:
914 // When an lvalue-to-rvalue conversion occurs in an unevaluated
915 // operand or a subexpression thereof the value contained in the
916 // referenced object is not accessed. Otherwise, if the glvalue
917 // has a class type, the conversion copy-initializes a temporary
918 // of type T from the glvalue and the result of the conversion
919 // is a prvalue for the temporary.
920 // FIXME: add some way to gate this entire thing for correctness in
921 // potentially potentially evaluated contexts.
925 E->getExprLoc(), E);
926 if (Temp.isInvalid())
927 return ExprError();
928 E = Temp.get();
929 }
930
931 return E;
932}
933
934/// Determine the degree of POD-ness for an expression.
935/// Incomplete types are considered POD, since this check can be performed
936/// when we're in an unevaluated context.
938 if (Ty->isIncompleteType()) {
939 // C++11 [expr.call]p7:
940 // After these conversions, if the argument does not have arithmetic,
941 // enumeration, pointer, pointer to member, or class type, the program
942 // is ill-formed.
943 //
944 // Since we've already performed array-to-pointer and function-to-pointer
945 // decay, the only such type in C++ is cv void. This also handles
946 // initializer lists as variadic arguments.
947 if (Ty->isVoidType())
948 return VAK_Invalid;
949
950 if (Ty->isObjCObjectType())
951 return VAK_Invalid;
952 return VAK_Valid;
953 }
954
956 return VAK_Invalid;
957
958 if (Context.getTargetInfo().getTriple().isWasm() &&
960 return VAK_Invalid;
961 }
962
963 if (Ty.isCXX98PODType(Context))
964 return VAK_Valid;
965
966 // C++11 [expr.call]p7:
967 // Passing a potentially-evaluated argument of class type (Clause 9)
968 // having a non-trivial copy constructor, a non-trivial move constructor,
969 // or a non-trivial destructor, with no corresponding parameter,
970 // is conditionally-supported with implementation-defined semantics.
972 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
973 if (!Record->hasNonTrivialCopyConstructor() &&
974 !Record->hasNonTrivialMoveConstructor() &&
975 !Record->hasNonTrivialDestructor())
976 return VAK_ValidInCXX11;
977
978 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
979 return VAK_Valid;
980
981 if (Ty->isObjCObjectType())
982 return VAK_Invalid;
983
984 if (getLangOpts().MSVCCompat)
985 return VAK_MSVCUndefined;
986
987 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
988 // permitted to reject them. We should consider doing so.
989 return VAK_Undefined;
990}
991
993 // Don't allow one to pass an Objective-C interface to a vararg.
994 const QualType &Ty = E->getType();
996
997 // Complain about passing non-POD types through varargs.
998 switch (VAK) {
999 case VAK_ValidInCXX11:
1001 E->getBeginLoc(), nullptr,
1002 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1003 [[fallthrough]];
1004 case VAK_Valid:
1005 if (Ty->isRecordType()) {
1006 // This is unlikely to be what the user intended. If the class has a
1007 // 'c_str' member function, the user probably meant to call that.
1008 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1009 PDiag(diag::warn_pass_class_arg_to_vararg)
1010 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1011 }
1012 break;
1013
1014 case VAK_Undefined:
1015 case VAK_MSVCUndefined:
1016 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1017 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1018 << getLangOpts().CPlusPlus11 << Ty << CT);
1019 break;
1020
1021 case VAK_Invalid:
1023 Diag(E->getBeginLoc(),
1024 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1025 << Ty << CT;
1026 else if (Ty->isObjCObjectType())
1027 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1028 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1029 << Ty << CT);
1030 else
1031 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1032 << isa<InitListExpr>(E) << Ty << CT;
1033 break;
1034 }
1035}
1036
1037/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1038/// will create a trap if the resulting type is not a POD type.
1040 FunctionDecl *FDecl) {
1041 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1042 // Strip the unbridged-cast placeholder expression off, if applicable.
1043 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1044 (CT == VariadicMethod ||
1045 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1046 E = stripARCUnbridgedCast(E);
1047
1048 // Otherwise, do normal placeholder checking.
1049 } else {
1050 ExprResult ExprRes = CheckPlaceholderExpr(E);
1051 if (ExprRes.isInvalid())
1052 return ExprError();
1053 E = ExprRes.get();
1054 }
1055 }
1056
1058 if (ExprRes.isInvalid())
1059 return ExprError();
1060
1061 // Copy blocks to the heap.
1062 if (ExprRes.get()->getType()->isBlockPointerType())
1063 maybeExtendBlockObject(ExprRes);
1064
1065 E = ExprRes.get();
1066
1067 // Diagnostics regarding non-POD argument types are
1068 // emitted along with format string checking in Sema::CheckFunctionCall().
1070 // Turn this into a trap.
1071 CXXScopeSpec SS;
1072 SourceLocation TemplateKWLoc;
1073 UnqualifiedId Name;
1074 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1075 E->getBeginLoc());
1076 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1077 /*HasTrailingLParen=*/true,
1078 /*IsAddressOfOperand=*/false);
1079 if (TrapFn.isInvalid())
1080 return ExprError();
1081
1083 std::nullopt, E->getEndLoc());
1084 if (Call.isInvalid())
1085 return ExprError();
1086
1087 ExprResult Comma =
1088 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1089 if (Comma.isInvalid())
1090 return ExprError();
1091 return Comma.get();
1092 }
1093
1094 if (!getLangOpts().CPlusPlus &&
1096 diag::err_call_incomplete_argument))
1097 return ExprError();
1098
1099 return E;
1100}
1101
1102/// Converts an integer to complex float type. Helper function of
1103/// UsualArithmeticConversions()
1104///
1105/// \return false if the integer expression is an integer type and is
1106/// successfully converted to the complex type.
1108 ExprResult &ComplexExpr,
1109 QualType IntTy,
1110 QualType ComplexTy,
1111 bool SkipCast) {
1112 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1113 if (SkipCast) return false;
1114 if (IntTy->isIntegerType()) {
1115 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1116 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1118 CK_FloatingRealToComplex);
1119 } else {
1120 assert(IntTy->isComplexIntegerType());
1121 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1122 CK_IntegralComplexToFloatingComplex);
1123 }
1124 return false;
1125}
1126
1127// This handles complex/complex, complex/float, or float/complex.
1128// When both operands are complex, the shorter operand is converted to the
1129// type of the longer, and that is the type of the result. This corresponds
1130// to what is done when combining two real floating-point operands.
1131// The fun begins when size promotion occur across type domains.
1132// From H&S 6.3.4: When one operand is complex and the other is a real
1133// floating-point type, the less precise type is converted, within it's
1134// real or complex domain, to the precision of the other type. For example,
1135// when combining a "long double" with a "double _Complex", the
1136// "double _Complex" is promoted to "long double _Complex".
1138 QualType ShorterType,
1139 QualType LongerType,
1140 bool PromotePrecision) {
1141 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1143 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1144
1145 if (PromotePrecision) {
1146 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1147 Shorter =
1148 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1149 } else {
1150 if (LongerIsComplex)
1151 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1152 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1153 }
1154 }
1155 return Result;
1156}
1157
1158/// Handle arithmetic conversion with complex types. Helper function of
1159/// UsualArithmeticConversions()
1161 ExprResult &RHS, QualType LHSType,
1162 QualType RHSType, bool IsCompAssign) {
1163 // if we have an integer operand, the result is the complex type.
1164 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1165 /*SkipCast=*/false))
1166 return LHSType;
1167 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1168 /*SkipCast=*/IsCompAssign))
1169 return RHSType;
1170
1171 // Compute the rank of the two types, regardless of whether they are complex.
1172 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1173 if (Order < 0)
1174 // Promote the precision of the LHS if not an assignment.
1175 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1176 /*PromotePrecision=*/!IsCompAssign);
1177 // Promote the precision of the RHS unless it is already the same as the LHS.
1178 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1179 /*PromotePrecision=*/Order > 0);
1180}
1181
1182/// Handle arithmetic conversion from integer to float. Helper function
1183/// of UsualArithmeticConversions()
1185 ExprResult &IntExpr,
1186 QualType FloatTy, QualType IntTy,
1187 bool ConvertFloat, bool ConvertInt) {
1188 if (IntTy->isIntegerType()) {
1189 if (ConvertInt)
1190 // Convert intExpr to the lhs floating point type.
1191 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1192 CK_IntegralToFloating);
1193 return FloatTy;
1194 }
1195
1196 // Convert both sides to the appropriate complex float.
1197 assert(IntTy->isComplexIntegerType());
1198 QualType result = S.Context.getComplexType(FloatTy);
1199
1200 // _Complex int -> _Complex float
1201 if (ConvertInt)
1202 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1203 CK_IntegralComplexToFloatingComplex);
1204
1205 // float -> _Complex float
1206 if (ConvertFloat)
1207 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1208 CK_FloatingRealToComplex);
1209
1210 return result;
1211}
1212
1213/// Handle arithmethic conversion with floating point types. Helper
1214/// function of UsualArithmeticConversions()
1216 ExprResult &RHS, QualType LHSType,
1217 QualType RHSType, bool IsCompAssign) {
1218 bool LHSFloat = LHSType->isRealFloatingType();
1219 bool RHSFloat = RHSType->isRealFloatingType();
1220
1221 // N1169 4.1.4: If one of the operands has a floating type and the other
1222 // operand has a fixed-point type, the fixed-point operand
1223 // is converted to the floating type [...]
1224 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1225 if (LHSFloat)
1226 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1227 else if (!IsCompAssign)
1228 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1229 return LHSFloat ? LHSType : RHSType;
1230 }
1231
1232 // If we have two real floating types, convert the smaller operand
1233 // to the bigger result.
1234 if (LHSFloat && RHSFloat) {
1235 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1236 if (order > 0) {
1237 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1238 return LHSType;
1239 }
1240
1241 assert(order < 0 && "illegal float comparison");
1242 if (!IsCompAssign)
1243 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1244 return RHSType;
1245 }
1246
1247 if (LHSFloat) {
1248 // Half FP has to be promoted to float unless it is natively supported
1249 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1250 LHSType = S.Context.FloatTy;
1251
1252 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1253 /*ConvertFloat=*/!IsCompAssign,
1254 /*ConvertInt=*/ true);
1255 }
1256 assert(RHSFloat);
1257 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1258 /*ConvertFloat=*/ true,
1259 /*ConvertInt=*/!IsCompAssign);
1260}
1261
1262/// Diagnose attempts to convert between __float128, __ibm128 and
1263/// long double if there is no support for such conversion.
1264/// Helper function of UsualArithmeticConversions().
1265static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1266 QualType RHSType) {
1267 // No issue if either is not a floating point type.
1268 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1269 return false;
1270
1271 // No issue if both have the same 128-bit float semantics.
1272 auto *LHSComplex = LHSType->getAs<ComplexType>();
1273 auto *RHSComplex = RHSType->getAs<ComplexType>();
1274
1275 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1276 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1277
1278 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1279 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1280
1281 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1282 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1283 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1284 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1285 return false;
1286
1287 return true;
1288}
1289
1290typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1291
1292namespace {
1293/// These helper callbacks are placed in an anonymous namespace to
1294/// permit their use as function template parameters.
1295ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1296 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1297}
1298
1299ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1300 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1301 CK_IntegralComplexCast);
1302}
1303}
1304
1305/// Handle integer arithmetic conversions. Helper function of
1306/// UsualArithmeticConversions()
1307template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1309 ExprResult &RHS, QualType LHSType,
1310 QualType RHSType, bool IsCompAssign) {
1311 // The rules for this case are in C99 6.3.1.8
1312 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1313 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1314 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1315 if (LHSSigned == RHSSigned) {
1316 // Same signedness; use the higher-ranked type
1317 if (order >= 0) {
1318 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1319 return LHSType;
1320 } else if (!IsCompAssign)
1321 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1322 return RHSType;
1323 } else if (order != (LHSSigned ? 1 : -1)) {
1324 // The unsigned type has greater than or equal rank to the
1325 // signed type, so use the unsigned type
1326 if (RHSSigned) {
1327 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1328 return LHSType;
1329 } else if (!IsCompAssign)
1330 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1331 return RHSType;
1332 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1333 // The two types are different widths; if we are here, that
1334 // means the signed type is larger than the unsigned type, so
1335 // use the signed type.
1336 if (LHSSigned) {
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 {
1343 // The signed type is higher-ranked than the unsigned type,
1344 // but isn't actually any bigger (like unsigned int and long
1345 // on most 32-bit systems). Use the unsigned type corresponding
1346 // to the signed type.
1347 QualType result =
1348 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1349 RHS = (*doRHSCast)(S, RHS.get(), result);
1350 if (!IsCompAssign)
1351 LHS = (*doLHSCast)(S, LHS.get(), result);
1352 return result;
1353 }
1354}
1355
1356/// Handle conversions with GCC complex int extension. Helper function
1357/// of UsualArithmeticConversions()
1359 ExprResult &RHS, QualType LHSType,
1360 QualType RHSType,
1361 bool IsCompAssign) {
1362 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1363 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1364
1365 if (LHSComplexInt && RHSComplexInt) {
1366 QualType LHSEltType = LHSComplexInt->getElementType();
1367 QualType RHSEltType = RHSComplexInt->getElementType();
1368 QualType ScalarType =
1369 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1370 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1371
1372 return S.Context.getComplexType(ScalarType);
1373 }
1374
1375 if (LHSComplexInt) {
1376 QualType LHSEltType = LHSComplexInt->getElementType();
1377 QualType ScalarType =
1378 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1379 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1381 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1382 CK_IntegralRealToComplex);
1383
1384 return ComplexType;
1385 }
1386
1387 assert(RHSComplexInt);
1388
1389 QualType RHSEltType = RHSComplexInt->getElementType();
1390 QualType ScalarType =
1391 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1392 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1394
1395 if (!IsCompAssign)
1396 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1397 CK_IntegralRealToComplex);
1398 return ComplexType;
1399}
1400
1401/// Return the rank of a given fixed point or integer type. The value itself
1402/// doesn't matter, but the values must be increasing with proper increasing
1403/// rank as described in N1169 4.1.1.
1404static unsigned GetFixedPointRank(QualType Ty) {
1405 const auto *BTy = Ty->getAs<BuiltinType>();
1406 assert(BTy && "Expected a builtin type.");
1407
1408 switch (BTy->getKind()) {
1409 case BuiltinType::ShortFract:
1410 case BuiltinType::UShortFract:
1411 case BuiltinType::SatShortFract:
1412 case BuiltinType::SatUShortFract:
1413 return 1;
1414 case BuiltinType::Fract:
1415 case BuiltinType::UFract:
1416 case BuiltinType::SatFract:
1417 case BuiltinType::SatUFract:
1418 return 2;
1419 case BuiltinType::LongFract:
1420 case BuiltinType::ULongFract:
1421 case BuiltinType::SatLongFract:
1422 case BuiltinType::SatULongFract:
1423 return 3;
1424 case BuiltinType::ShortAccum:
1425 case BuiltinType::UShortAccum:
1426 case BuiltinType::SatShortAccum:
1427 case BuiltinType::SatUShortAccum:
1428 return 4;
1429 case BuiltinType::Accum:
1430 case BuiltinType::UAccum:
1431 case BuiltinType::SatAccum:
1432 case BuiltinType::SatUAccum:
1433 return 5;
1434 case BuiltinType::LongAccum:
1435 case BuiltinType::ULongAccum:
1436 case BuiltinType::SatLongAccum:
1437 case BuiltinType::SatULongAccum:
1438 return 6;
1439 default:
1440 if (BTy->isInteger())
1441 return 0;
1442 llvm_unreachable("Unexpected fixed point or integer type");
1443 }
1444}
1445
1446/// handleFixedPointConversion - Fixed point operations between fixed
1447/// point types and integers or other fixed point types do not fall under
1448/// usual arithmetic conversion since these conversions could result in loss
1449/// of precsision (N1169 4.1.4). These operations should be calculated with
1450/// the full precision of their result type (N1169 4.1.6.2.1).
1452 QualType RHSTy) {
1453 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1454 "Expected at least one of the operands to be a fixed point type");
1455 assert((LHSTy->isFixedPointOrIntegerType() ||
1456 RHSTy->isFixedPointOrIntegerType()) &&
1457 "Special fixed point arithmetic operation conversions are only "
1458 "applied to ints or other fixed point types");
1459
1460 // If one operand has signed fixed-point type and the other operand has
1461 // unsigned fixed-point type, then the unsigned fixed-point operand is
1462 // converted to its corresponding signed fixed-point type and the resulting
1463 // type is the type of the converted operand.
1464 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1466 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1468
1469 // The result type is the type with the highest rank, whereby a fixed-point
1470 // conversion rank is always greater than an integer conversion rank; if the
1471 // type of either of the operands is a saturating fixedpoint type, the result
1472 // type shall be the saturating fixed-point type corresponding to the type
1473 // with the highest rank; the resulting value is converted (taking into
1474 // account rounding and overflow) to the precision of the resulting type.
1475 // Same ranks between signed and unsigned types are resolved earlier, so both
1476 // types are either signed or both unsigned at this point.
1477 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1478 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1479
1480 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1481
1483 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1484
1485 return ResultTy;
1486}
1487
1488/// Check that the usual arithmetic conversions can be performed on this pair of
1489/// expressions that might be of enumeration type.
1491 SourceLocation Loc,
1492 Sema::ArithConvKind ACK) {
1493 // C++2a [expr.arith.conv]p1:
1494 // If one operand is of enumeration type and the other operand is of a
1495 // different enumeration type or a floating-point type, this behavior is
1496 // deprecated ([depr.arith.conv.enum]).
1497 //
1498 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1499 // Eventually we will presumably reject these cases (in C++23 onwards?).
1500 QualType L = LHS->getType(), R = RHS->getType();
1501 bool LEnum = L->isUnscopedEnumerationType(),
1502 REnum = R->isUnscopedEnumerationType();
1503 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1504 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1505 (REnum && L->isFloatingType())) {
1506 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1507 ? diag::err_arith_conv_enum_float_cxx26
1508 : S.getLangOpts().CPlusPlus20
1509 ? diag::warn_arith_conv_enum_float_cxx20
1510 : diag::warn_arith_conv_enum_float)
1511 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1512 << L << R;
1513 } else if (!IsCompAssign && LEnum && REnum &&
1515 unsigned DiagID;
1516 // In C++ 26, usual arithmetic conversions between 2 different enum types
1517 // are ill-formed.
1518 if (S.getLangOpts().CPlusPlus26)
1519 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1520 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1521 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1522 // If either enumeration type is unnamed, it's less likely that the
1523 // user cares about this, but this situation is still deprecated in
1524 // C++2a. Use a different warning group.
1525 DiagID = S.getLangOpts().CPlusPlus20
1526 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1527 : diag::warn_arith_conv_mixed_anon_enum_types;
1528 } else if (ACK == Sema::ACK_Conditional) {
1529 // Conditional expressions are separated out because they have
1530 // historically had a different warning flag.
1531 DiagID = S.getLangOpts().CPlusPlus20
1532 ? diag::warn_conditional_mixed_enum_types_cxx20
1533 : diag::warn_conditional_mixed_enum_types;
1534 } else if (ACK == Sema::ACK_Comparison) {
1535 // Comparison expressions are separated out because they have
1536 // historically had a different warning flag.
1537 DiagID = S.getLangOpts().CPlusPlus20
1538 ? diag::warn_comparison_mixed_enum_types_cxx20
1539 : diag::warn_comparison_mixed_enum_types;
1540 } else {
1541 DiagID = S.getLangOpts().CPlusPlus20
1542 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1543 : diag::warn_arith_conv_mixed_enum_types;
1544 }
1545 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1546 << (int)ACK << L << R;
1547 }
1548}
1549
1550/// UsualArithmeticConversions - Performs various conversions that are common to
1551/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1552/// routine returns the first non-arithmetic type found. The client is
1553/// responsible for emitting appropriate error diagnostics.
1555 SourceLocation Loc,
1556 ArithConvKind ACK) {
1557 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1558
1559 if (ACK != ACK_CompAssign) {
1560 LHS = UsualUnaryConversions(LHS.get());
1561 if (LHS.isInvalid())
1562 return QualType();
1563 }
1564
1565 RHS = UsualUnaryConversions(RHS.get());
1566 if (RHS.isInvalid())
1567 return QualType();
1568
1569 // For conversion purposes, we ignore any qualifiers.
1570 // For example, "const float" and "float" are equivalent.
1571 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1572 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1573
1574 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1575 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1576 LHSType = AtomicLHS->getValueType();
1577
1578 // If both types are identical, no conversion is needed.
1579 if (Context.hasSameType(LHSType, RHSType))
1580 return Context.getCommonSugaredType(LHSType, RHSType);
1581
1582 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1583 // The caller can deal with this (e.g. pointer + int).
1584 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1585 return QualType();
1586
1587 // Apply unary and bitfield promotions to the LHS's type.
1588 QualType LHSUnpromotedType = LHSType;
1589 if (Context.isPromotableIntegerType(LHSType))
1590 LHSType = Context.getPromotedIntegerType(LHSType);
1591 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1592 if (!LHSBitfieldPromoteTy.isNull())
1593 LHSType = LHSBitfieldPromoteTy;
1594 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1595 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1596
1597 // If both types are identical, no conversion is needed.
1598 if (Context.hasSameType(LHSType, RHSType))
1599 return Context.getCommonSugaredType(LHSType, RHSType);
1600
1601 // At this point, we have two different arithmetic types.
1602
1603 // Diagnose attempts to convert between __ibm128, __float128 and long double
1604 // where such conversions currently can't be handled.
1605 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1606 return QualType();
1607
1608 // Handle complex types first (C99 6.3.1.8p1).
1609 if (LHSType->isComplexType() || RHSType->isComplexType())
1610 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1611 ACK == ACK_CompAssign);
1612
1613 // Now handle "real" floating types (i.e. float, double, long double).
1614 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1615 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1616 ACK == ACK_CompAssign);
1617
1618 // Handle GCC complex int extension.
1619 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1620 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1621 ACK == ACK_CompAssign);
1622
1623 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1624 return handleFixedPointConversion(*this, LHSType, RHSType);
1625
1626 // Finally, we have two differing integer types.
1627 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1628 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1629}
1630
1631//===----------------------------------------------------------------------===//
1632// Semantic Analysis for various Expression Types
1633//===----------------------------------------------------------------------===//
1634
1635
1637 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1638 bool PredicateIsExpr, void *ControllingExprOrType,
1639 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1640 unsigned NumAssocs = ArgTypes.size();
1641 assert(NumAssocs == ArgExprs.size());
1642
1643 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1644 for (unsigned i = 0; i < NumAssocs; ++i) {
1645 if (ArgTypes[i])
1646 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1647 else
1648 Types[i] = nullptr;
1649 }
1650
1651 // If we have a controlling type, we need to convert it from a parsed type
1652 // into a semantic type and then pass that along.
1653 if (!PredicateIsExpr) {
1654 TypeSourceInfo *ControllingType;
1655 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1656 &ControllingType);
1657 assert(ControllingType && "couldn't get the type out of the parser");
1658 ControllingExprOrType = ControllingType;
1659 }
1660
1662 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1663 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1664 delete [] Types;
1665 return ER;
1666}
1667
1669 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1670 bool PredicateIsExpr, void *ControllingExprOrType,
1672 unsigned NumAssocs = Types.size();
1673 assert(NumAssocs == Exprs.size());
1674 assert(ControllingExprOrType &&
1675 "Must have either a controlling expression or a controlling type");
1676
1677 Expr *ControllingExpr = nullptr;
1678 TypeSourceInfo *ControllingType = nullptr;
1679 if (PredicateIsExpr) {
1680 // Decay and strip qualifiers for the controlling expression type, and
1681 // handle placeholder type replacement. See committee discussion from WG14
1682 // DR423.
1686 reinterpret_cast<Expr *>(ControllingExprOrType));
1687 if (R.isInvalid())
1688 return ExprError();
1689 ControllingExpr = R.get();
1690 } else {
1691 // The extension form uses the type directly rather than converting it.
1692 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1693 if (!ControllingType)
1694 return ExprError();
1695 }
1696
1697 bool TypeErrorFound = false,
1698 IsResultDependent = ControllingExpr
1699 ? ControllingExpr->isTypeDependent()
1700 : ControllingType->getType()->isDependentType(),
1701 ContainsUnexpandedParameterPack =
1702 ControllingExpr
1703 ? ControllingExpr->containsUnexpandedParameterPack()
1704 : ControllingType->getType()->containsUnexpandedParameterPack();
1705
1706 // The controlling expression is an unevaluated operand, so side effects are
1707 // likely unintended.
1708 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1709 ControllingExpr->HasSideEffects(Context, false))
1710 Diag(ControllingExpr->getExprLoc(),
1711 diag::warn_side_effects_unevaluated_context);
1712
1713 for (unsigned i = 0; i < NumAssocs; ++i) {
1714 if (Exprs[i]->containsUnexpandedParameterPack())
1715 ContainsUnexpandedParameterPack = true;
1716
1717 if (Types[i]) {
1718 if (Types[i]->getType()->containsUnexpandedParameterPack())
1719 ContainsUnexpandedParameterPack = true;
1720
1721 if (Types[i]->getType()->isDependentType()) {
1722 IsResultDependent = true;
1723 } else {
1724 // We relax the restriction on use of incomplete types and non-object
1725 // types with the type-based extension of _Generic. Allowing incomplete
1726 // objects means those can be used as "tags" for a type-safe way to map
1727 // to a value. Similarly, matching on function types rather than
1728 // function pointer types can be useful. However, the restriction on VM
1729 // types makes sense to retain as there are open questions about how
1730 // the selection can be made at compile time.
1731 //
1732 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1733 // complete object type other than a variably modified type."
1734 unsigned D = 0;
1735 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1736 D = diag::err_assoc_type_incomplete;
1737 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1738 D = diag::err_assoc_type_nonobject;
1739 else if (Types[i]->getType()->isVariablyModifiedType())
1740 D = diag::err_assoc_type_variably_modified;
1741 else if (ControllingExpr) {
1742 // Because the controlling expression undergoes lvalue conversion,
1743 // array conversion, and function conversion, an association which is
1744 // of array type, function type, or is qualified can never be
1745 // reached. We will warn about this so users are less surprised by
1746 // the unreachable association. However, we don't have to handle
1747 // function types; that's not an object type, so it's handled above.
1748 //
1749 // The logic is somewhat different for C++ because C++ has different
1750 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1751 // If T is a non-class type, the type of the prvalue is the cv-
1752 // unqualified version of T. Otherwise, the type of the prvalue is T.
1753 // The result of these rules is that all qualified types in an
1754 // association in C are unreachable, and in C++, only qualified non-
1755 // class types are unreachable.
1756 //
1757 // NB: this does not apply when the first operand is a type rather
1758 // than an expression, because the type form does not undergo
1759 // conversion.
1760 unsigned Reason = 0;
1761 QualType QT = Types[i]->getType();
1762 if (QT->isArrayType())
1763 Reason = 1;
1764 else if (QT.hasQualifiers() &&
1765 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1766 Reason = 2;
1767
1768 if (Reason)
1769 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1770 diag::warn_unreachable_association)
1771 << QT << (Reason - 1);
1772 }
1773
1774 if (D != 0) {
1775 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1776 << Types[i]->getTypeLoc().getSourceRange()
1777 << Types[i]->getType();
1778 TypeErrorFound = true;
1779 }
1780
1781 // C11 6.5.1.1p2 "No two generic associations in the same generic
1782 // selection shall specify compatible types."
1783 for (unsigned j = i+1; j < NumAssocs; ++j)
1784 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1785 Context.typesAreCompatible(Types[i]->getType(),
1786 Types[j]->getType())) {
1787 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1788 diag::err_assoc_compatible_types)
1789 << Types[j]->getTypeLoc().getSourceRange()
1790 << Types[j]->getType()
1791 << Types[i]->getType();
1792 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1793 diag::note_compat_assoc)
1794 << Types[i]->getTypeLoc().getSourceRange()
1795 << Types[i]->getType();
1796 TypeErrorFound = true;
1797 }
1798 }
1799 }
1800 }
1801 if (TypeErrorFound)
1802 return ExprError();
1803
1804 // If we determined that the generic selection is result-dependent, don't
1805 // try to compute the result expression.
1806 if (IsResultDependent) {
1807 if (ControllingExpr)
1808 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1809 Types, Exprs, DefaultLoc, RParenLoc,
1810 ContainsUnexpandedParameterPack);
1811 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1812 Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack);
1814 }
1815
1816 SmallVector<unsigned, 1> CompatIndices;
1817 unsigned DefaultIndex = -1U;
1818 // Look at the canonical type of the controlling expression in case it was a
1819 // deduced type like __auto_type. However, when issuing diagnostics, use the
1820 // type the user wrote in source rather than the canonical one.
1821 for (unsigned i = 0; i < NumAssocs; ++i) {
1822 if (!Types[i])
1823 DefaultIndex = i;
1824 else if (ControllingExpr &&
1826 ControllingExpr->getType().getCanonicalType(),
1827 Types[i]->getType()))
1828 CompatIndices.push_back(i);
1829 else if (ControllingType &&
1831 ControllingType->getType().getCanonicalType(),
1832 Types[i]->getType()))
1833 CompatIndices.push_back(i);
1834 }
1835
1836 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1837 TypeSourceInfo *ControllingType) {
1838 // We strip parens here because the controlling expression is typically
1839 // parenthesized in macro definitions.
1840 if (ControllingExpr)
1841 ControllingExpr = ControllingExpr->IgnoreParens();
1842
1843 SourceRange SR = ControllingExpr
1844 ? ControllingExpr->getSourceRange()
1845 : ControllingType->getTypeLoc().getSourceRange();
1846 QualType QT = ControllingExpr ? ControllingExpr->getType()
1847 : ControllingType->getType();
1848
1849 return std::make_pair(SR, QT);
1850 };
1851
1852 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1853 // type compatible with at most one of the types named in its generic
1854 // association list."
1855 if (CompatIndices.size() > 1) {
1856 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1857 SourceRange SR = P.first;
1858 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1859 << SR << P.second << (unsigned)CompatIndices.size();
1860 for (unsigned I : CompatIndices) {
1861 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1862 diag::note_compat_assoc)
1863 << Types[I]->getTypeLoc().getSourceRange()
1864 << Types[I]->getType();
1865 }
1866 return ExprError();
1867 }
1868
1869 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1870 // its controlling expression shall have type compatible with exactly one of
1871 // the types named in its generic association list."
1872 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1873 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1874 SourceRange SR = P.first;
1875 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1876 return ExprError();
1877 }
1878
1879 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1880 // type name that is compatible with the type of the controlling expression,
1881 // then the result expression of the generic selection is the expression
1882 // in that generic association. Otherwise, the result expression of the
1883 // generic selection is the expression in the default generic association."
1884 unsigned ResultIndex =
1885 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1886
1887 if (ControllingExpr) {
1889 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1890 ContainsUnexpandedParameterPack, ResultIndex);
1891 }
1893 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1894 ContainsUnexpandedParameterPack, ResultIndex);
1895}
1896
1898 switch (Kind) {
1899 default:
1900 llvm_unreachable("unexpected TokenKind");
1901 case tok::kw___func__:
1902 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1903 case tok::kw___FUNCTION__:
1905 case tok::kw___FUNCDNAME__:
1906 return PredefinedIdentKind::FuncDName; // [MS]
1907 case tok::kw___FUNCSIG__:
1908 return PredefinedIdentKind::FuncSig; // [MS]
1909 case tok::kw_L__FUNCTION__:
1910 return PredefinedIdentKind::LFunction; // [MS]
1911 case tok::kw_L__FUNCSIG__:
1912 return PredefinedIdentKind::LFuncSig; // [MS]
1913 case tok::kw___PRETTY_FUNCTION__:
1915 }
1916}
1917
1918/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1919/// to determine the value of a PredefinedExpr. This can be either a
1920/// block, lambda, captured statement, function, otherwise a nullptr.
1922 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1923 DC = DC->getParent();
1924 return cast_or_null<Decl>(DC);
1925}
1926
1927/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1928/// location of the token and the offset of the ud-suffix within it.
1930 unsigned Offset) {
1931 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1932 S.getLangOpts());
1933}
1934
1935/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1936/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1938 IdentifierInfo *UDSuffix,
1939 SourceLocation UDSuffixLoc,
1940 ArrayRef<Expr*> Args,
1941 SourceLocation LitEndLoc) {
1942 assert(Args.size() <= 2 && "too many arguments for literal operator");
1943
1944 QualType ArgTy[2];
1945 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1946 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1947 if (ArgTy[ArgIdx]->isArrayType())
1948 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1949 }
1950
1951 DeclarationName OpName =
1953 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1954 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1955
1956 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1957 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1958 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1959 /*AllowStringTemplatePack*/ false,
1960 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1961 return ExprError();
1962
1963 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1964}
1965
1967 // StringToks needs backing storage as it doesn't hold array elements itself
1968 std::vector<Token> ExpandedToks;
1969 if (getLangOpts().MicrosoftExt)
1970 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1971
1972 StringLiteralParser Literal(StringToks, PP,
1974 if (Literal.hadError)
1975 return ExprError();
1976
1977 SmallVector<SourceLocation, 4> StringTokLocs;
1978 for (const Token &Tok : StringToks)
1979 StringTokLocs.push_back(Tok.getLocation());
1980
1982 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1983 &StringTokLocs[0], StringTokLocs.size());
1984
1985 if (!Literal.getUDSuffix().empty()) {
1986 SourceLocation UDSuffixLoc =
1987 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1988 Literal.getUDSuffixOffset());
1989 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1990 }
1991
1992 return Lit;
1993}
1994
1995std::vector<Token>
1997 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1998 // local macros that expand to string literals that may be concatenated.
1999 // These macros are expanded here (in Sema), because StringLiteralParser
2000 // (in Lex) doesn't know the enclosing function (because it hasn't been
2001 // parsed yet).
2002 assert(getLangOpts().MicrosoftExt);
2003
2004 // Note: Although function local macros are defined only inside functions,
2005 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2006 // expansion of macros into empty string literals without additional checks.
2007 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2008 if (!CurrentDecl)
2009 CurrentDecl = Context.getTranslationUnitDecl();
2010
2011 std::vector<Token> ExpandedToks;
2012 ExpandedToks.reserve(Toks.size());
2013 for (const Token &Tok : Toks) {
2014 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2015 assert(tok::isStringLiteral(Tok.getKind()));
2016 ExpandedToks.emplace_back(Tok);
2017 continue;
2018 }
2019 if (isa<TranslationUnitDecl>(CurrentDecl))
2020 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2021 // Stringify predefined expression
2022 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2023 << Tok.getKind();
2024 SmallString<64> Str;
2025 llvm::raw_svector_ostream OS(Str);
2026 Token &Exp = ExpandedToks.emplace_back();
2027 Exp.startToken();
2028 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2029 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2030 OS << 'L';
2031 Exp.setKind(tok::wide_string_literal);
2032 } else {
2033 Exp.setKind(tok::string_literal);
2034 }
2035 OS << '"'
2037 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2038 << '"';
2039 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2040 }
2041 return ExpandedToks;
2042}
2043
2044/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2045/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2046/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2047/// multiple tokens. However, the common case is that StringToks points to one
2048/// string.
2049///
2052 assert(!StringToks.empty() && "Must have at least one string!");
2053
2054 // StringToks needs backing storage as it doesn't hold array elements itself
2055 std::vector<Token> ExpandedToks;
2056 if (getLangOpts().MicrosoftExt)
2057 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2058
2059 StringLiteralParser Literal(StringToks, PP);
2060 if (Literal.hadError)
2061 return ExprError();
2062
2063 SmallVector<SourceLocation, 4> StringTokLocs;
2064 for (const Token &Tok : StringToks)
2065 StringTokLocs.push_back(Tok.getLocation());
2066
2067 QualType CharTy = Context.CharTy;
2069 if (Literal.isWide()) {
2070 CharTy = Context.getWideCharType();
2072 } else if (Literal.isUTF8()) {
2073 if (getLangOpts().Char8)
2074 CharTy = Context.Char8Ty;
2076 } else if (Literal.isUTF16()) {
2077 CharTy = Context.Char16Ty;
2079 } else if (Literal.isUTF32()) {
2080 CharTy = Context.Char32Ty;
2082 } else if (Literal.isPascal()) {
2083 CharTy = Context.UnsignedCharTy;
2084 }
2085
2086 // Warn on initializing an array of char from a u8 string literal; this
2087 // becomes ill-formed in C++2a.
2089 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2090 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2091
2092 // Create removals for all 'u8' prefixes in the string literal(s). This
2093 // ensures C++2a compatibility (but may change the program behavior when
2094 // built by non-Clang compilers for which the execution character set is
2095 // not always UTF-8).
2096 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2097 SourceLocation RemovalDiagLoc;
2098 for (const Token &Tok : StringToks) {
2099 if (Tok.getKind() == tok::utf8_string_literal) {
2100 if (RemovalDiagLoc.isInvalid())
2101 RemovalDiagLoc = Tok.getLocation();
2103 Tok.getLocation(),
2104 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2106 }
2107 }
2108 Diag(RemovalDiagLoc, RemovalDiag);
2109 }
2110
2111 QualType StrTy =
2112 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2113
2114 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2115 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2116 Kind, Literal.Pascal, StrTy,
2117 &StringTokLocs[0],
2118 StringTokLocs.size());
2119 if (Literal.getUDSuffix().empty())
2120 return Lit;
2121
2122 // We're building a user-defined literal.
2123 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2124 SourceLocation UDSuffixLoc =
2125 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2126 Literal.getUDSuffixOffset());
2127
2128 // Make sure we're allowed user-defined literals here.
2129 if (!UDLScope)
2130 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2131
2132 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2133 // operator "" X (str, len)
2134 QualType SizeType = Context.getSizeType();
2135
2136 DeclarationName OpName =
2138 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2139 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2140
2141 QualType ArgTy[] = {
2142 Context.getArrayDecayedType(StrTy), SizeType
2143 };
2144
2145 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2146 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2147 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2148 /*AllowStringTemplatePack*/ true,
2149 /*DiagnoseMissing*/ true, Lit)) {
2150
2151 case LOLR_Cooked: {
2152 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2153 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2154 StringTokLocs[0]);
2155 Expr *Args[] = { Lit, LenArg };
2156
2157 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2158 }
2159
2160 case LOLR_Template: {
2161 TemplateArgumentListInfo ExplicitArgs;
2162 TemplateArgument Arg(Lit);
2163 TemplateArgumentLocInfo ArgInfo(Lit);
2164 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2165 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2166 StringTokLocs.back(), &ExplicitArgs);
2167 }
2168
2170 TemplateArgumentListInfo ExplicitArgs;
2171
2172 unsigned CharBits = Context.getIntWidth(CharTy);
2173 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2174 llvm::APSInt Value(CharBits, CharIsUnsigned);
2175
2176 TemplateArgument TypeArg(CharTy);
2178 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2179
2180 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2181 Value = Lit->getCodeUnit(I);
2182 TemplateArgument Arg(Context, Value, CharTy);
2184 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2185 }
2186 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2187 StringTokLocs.back(), &ExplicitArgs);
2188 }
2189 case LOLR_Raw:
2191 llvm_unreachable("unexpected literal operator lookup result");
2192 case LOLR_Error:
2193 return ExprError();
2194 }
2195 llvm_unreachable("unexpected literal operator lookup result");
2196}
2197
2200 SourceLocation Loc,
2201 const CXXScopeSpec *SS) {
2202 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2203 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2204}
2205
2208 const DeclarationNameInfo &NameInfo,
2209 const CXXScopeSpec *SS, NamedDecl *FoundD,
2210 SourceLocation TemplateKWLoc,
2211 const TemplateArgumentListInfo *TemplateArgs) {
2214 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2215 TemplateArgs);
2216}
2217
2218// CUDA/HIP: Check whether a captured reference variable is referencing a
2219// host variable in a device or host device lambda.
2221 VarDecl *VD) {
2222 if (!S.getLangOpts().CUDA || !VD->hasInit())
2223 return false;
2224 assert(VD->getType()->isReferenceType());
2225
2226 // Check whether the reference variable is referencing a host variable.
2227 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2228 if (!DRE)
2229 return false;
2230 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2231 if (!Referee || !Referee->hasGlobalStorage() ||
2232 Referee->hasAttr<CUDADeviceAttr>())
2233 return false;
2234
2235 // Check whether the current function is a device or host device lambda.
2236 // Check whether the reference variable is a capture by getDeclContext()
2237 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2238 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2239 if (MD && MD->getParent()->isLambda() &&
2240 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2241 VD->getDeclContext() != MD)
2242 return true;
2243
2244 return false;
2245}
2246
2248 // A declaration named in an unevaluated operand never constitutes an odr-use.
2250 return NOUR_Unevaluated;
2251
2252 // C++2a [basic.def.odr]p4:
2253 // A variable x whose name appears as a potentially-evaluated expression e
2254 // is odr-used by e unless [...] x is a reference that is usable in
2255 // constant expressions.
2256 // CUDA/HIP:
2257 // If a reference variable referencing a host variable is captured in a
2258 // device or host device lambda, the value of the referee must be copied
2259 // to the capture and the reference variable must be treated as odr-use
2260 // since the value of the referee is not known at compile time and must
2261 // be loaded from the captured.
2262 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2263 if (VD->getType()->isReferenceType() &&
2264 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2266 VD->isUsableInConstantExpressions(Context))
2267 return NOUR_Constant;
2268 }
2269
2270 // All remaining non-variable cases constitute an odr-use. For variables, we
2271 // need to wait and see how the expression is used.
2272 return NOUR_None;
2273}
2274
2275/// BuildDeclRefExpr - Build an expression that references a
2276/// declaration that does not require a closure capture.
2279 const DeclarationNameInfo &NameInfo,
2280 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2281 SourceLocation TemplateKWLoc,
2282 const TemplateArgumentListInfo *TemplateArgs) {
2283 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2284 NeedToCaptureVariable(D, NameInfo.getLoc());
2285
2287 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2288 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2290
2291 // C++ [except.spec]p17:
2292 // An exception-specification is considered to be needed when:
2293 // - in an expression, the function is the unique lookup result or
2294 // the selected member of a set of overloaded functions.
2295 //
2296 // We delay doing this until after we've built the function reference and
2297 // marked it as used so that:
2298 // a) if the function is defaulted, we get errors from defining it before /
2299 // instead of errors from computing its exception specification, and
2300 // b) if the function is a defaulted comparison, we can use the body we
2301 // build when defining it as input to the exception specification
2302 // computation rather than computing a new body.
2303 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2304 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2305 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2307 }
2308 }
2309
2310 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2312 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2314
2315 const auto *FD = dyn_cast<FieldDecl>(D);
2316 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2317 FD = IFD->getAnonField();
2318 if (FD) {
2319 UnusedPrivateFields.remove(FD);
2320 // Just in case we're building an illegal pointer-to-member.
2321 if (FD->isBitField())
2323 }
2324
2325 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2326 // designates a bit-field.
2327 if (const auto *BD = dyn_cast<BindingDecl>(D))
2328 if (const auto *BE = BD->getBinding())
2329 E->setObjectKind(BE->getObjectKind());
2330
2331 return E;
2332}
2333
2334/// Decomposes the given name into a DeclarationNameInfo, its location, and
2335/// possibly a list of template arguments.
2336///
2337/// If this produces template arguments, it is permitted to call
2338/// DecomposeTemplateName.
2339///
2340/// This actually loses a lot of source location information for
2341/// non-standard name kinds; we should consider preserving that in
2342/// some way.
2343void
2346 DeclarationNameInfo &NameInfo,
2347 const TemplateArgumentListInfo *&TemplateArgs) {
2348 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2349 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2350 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2351
2352 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2353 Id.TemplateId->NumArgs);
2354 translateTemplateArguments(TemplateArgsPtr, Buffer);
2355
2356 TemplateName TName = Id.TemplateId->Template.get();
2357 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2358 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2359 TemplateArgs = &Buffer;
2360 } else {
2361 NameInfo = GetNameFromUnqualifiedId(Id);
2362 TemplateArgs = nullptr;
2363 }
2364}
2365
2367 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2369 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2370 DeclContext *Ctx =
2371 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2372 if (!TC) {
2373 // Emit a special diagnostic for failed member lookups.
2374 // FIXME: computing the declaration context might fail here (?)
2375 if (Ctx)
2376 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2377 << SS.getRange();
2378 else
2379 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2380 return;
2381 }
2382
2383 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2384 bool DroppedSpecifier =
2385 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2386 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2387 ? diag::note_implicit_param_decl
2388 : diag::note_previous_decl;
2389 if (!Ctx)
2390 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2391 SemaRef.PDiag(NoteID));
2392 else
2393 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2394 << Typo << Ctx << DroppedSpecifier
2395 << SS.getRange(),
2396 SemaRef.PDiag(NoteID));
2397}
2398
2399/// Diagnose a lookup that found results in an enclosing class during error
2400/// recovery. This usually indicates that the results were found in a dependent
2401/// base class that could not be searched as part of a template definition.
2402/// Always issues a diagnostic (though this may be only a warning in MS
2403/// compatibility mode).
2404///
2405/// Return \c true if the error is unrecoverable, or \c false if the caller
2406/// should attempt to recover using these lookup results.
2408 // During a default argument instantiation the CurContext points
2409 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2410 // function parameter list, hence add an explicit check.
2411 bool isDefaultArgument =
2412 !CodeSynthesisContexts.empty() &&
2413 CodeSynthesisContexts.back().Kind ==
2415 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2416 bool isInstance = CurMethod && CurMethod->isInstance() &&
2417 R.getNamingClass() == CurMethod->getParent() &&
2418 !isDefaultArgument;
2419
2420 // There are two ways we can find a class-scope declaration during template
2421 // instantiation that we did not find in the template definition: if it is a
2422 // member of a dependent base class, or if it is declared after the point of
2423 // use in the same class. Distinguish these by comparing the class in which
2424 // the member was found to the naming class of the lookup.
2425 unsigned DiagID = diag::err_found_in_dependent_base;
2426 unsigned NoteID = diag::note_member_declared_at;
2428 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2429 : diag::err_found_later_in_class;
2430 } else if (getLangOpts().MSVCCompat) {
2431 DiagID = diag::ext_found_in_dependent_base;
2432 NoteID = diag::note_dependent_member_use;
2433 }
2434
2435 if (isInstance) {
2436 // Give a code modification hint to insert 'this->'.
2437 Diag(R.getNameLoc(), DiagID)
2438 << R.getLookupName()
2439 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2441 } else {
2442 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2443 // they're not shadowed).
2444 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2445 }
2446
2447 for (const NamedDecl *D : R)
2448 Diag(D->getLocation(), NoteID);
2449
2450 // Return true if we are inside a default argument instantiation
2451 // and the found name refers to an instance member function, otherwise
2452 // the caller will try to create an implicit member call and this is wrong
2453 // for default arguments.
2454 //
2455 // FIXME: Is this special case necessary? We could allow the caller to
2456 // diagnose this.
2457 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2458 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2459 return true;
2460 }
2461
2462 // Tell the callee to try to recover.
2463 return false;
2464}
2465
2466/// Diagnose an empty lookup.
2467///
2468/// \return false if new lookup candidates were found
2471 TemplateArgumentListInfo *ExplicitTemplateArgs,
2472 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2473 TypoExpr **Out) {
2474 DeclarationName Name = R.getLookupName();
2475
2476 unsigned diagnostic = diag::err_undeclared_var_use;
2477 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2478 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2479 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2480 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2481 diagnostic = diag::err_undeclared_use;
2482 diagnostic_suggest = diag::err_undeclared_use_suggest;
2483 }
2484
2485 // If the original lookup was an unqualified lookup, fake an
2486 // unqualified lookup. This is useful when (for example) the
2487 // original lookup would not have found something because it was a
2488 // dependent name.
2489 DeclContext *DC =
2490 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2491 while (DC) {
2492 if (isa<CXXRecordDecl>(DC)) {
2493 LookupQualifiedName(R, DC);
2494
2495 if (!R.empty()) {
2496 // Don't give errors about ambiguities in this lookup.
2498
2499 // If there's a best viable function among the results, only mention
2500 // that one in the notes.
2501 OverloadCandidateSet Candidates(R.getNameLoc(),
2503 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2505 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2506 OR_Success) {
2507 R.clear();
2508 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2509 R.resolveKind();
2510 }
2511
2513 }
2514
2515 R.clear();
2516 }
2517
2518 DC = DC->getLookupParent();
2519 }
2520
2521 // We didn't find anything, so try to correct for a typo.
2522 TypoCorrection Corrected;
2523 if (S && Out) {
2524 SourceLocation TypoLoc = R.getNameLoc();
2525 assert(!ExplicitTemplateArgs &&
2526 "Diagnosing an empty lookup with explicit template args!");
2527 *Out = CorrectTypoDelayed(
2528 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2529 [=](const TypoCorrection &TC) {
2530 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2531 diagnostic, diagnostic_suggest);
2532 },
2533 nullptr, CTK_ErrorRecovery, LookupCtx);
2534 if (*Out)
2535 return true;
2536 } else if (S && (Corrected =
2538 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2539 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2540 bool DroppedSpecifier =
2541 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2542 R.setLookupName(Corrected.getCorrection());
2543
2544 bool AcceptableWithRecovery = false;
2545 bool AcceptableWithoutRecovery = false;
2546 NamedDecl *ND = Corrected.getFoundDecl();
2547 if (ND) {
2548 if (Corrected.isOverloaded()) {
2552 for (NamedDecl *CD : Corrected) {
2553 if (FunctionTemplateDecl *FTD =
2554 dyn_cast<FunctionTemplateDecl>(CD))
2556 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2557 Args, OCS);
2558 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2559 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2561 Args, OCS);
2562 }
2563 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2564 case OR_Success:
2565 ND = Best->FoundDecl;
2566 Corrected.setCorrectionDecl(ND);
2567 break;
2568 default:
2569 // FIXME: Arbitrarily pick the first declaration for the note.
2570 Corrected.setCorrectionDecl(ND);
2571 break;
2572 }
2573 }
2574 R.addDecl(ND);
2575 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2576 CXXRecordDecl *Record = nullptr;
2577 if (Corrected.getCorrectionSpecifier()) {
2578 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2579 Record = Ty->getAsCXXRecordDecl();
2580 }
2581 if (!Record)
2582 Record = cast<CXXRecordDecl>(
2584 R.setNamingClass(Record);
2585 }
2586
2587 auto *UnderlyingND = ND->getUnderlyingDecl();
2588 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2589 isa<FunctionTemplateDecl>(UnderlyingND);
2590 // FIXME: If we ended up with a typo for a type name or
2591 // Objective-C class name, we're in trouble because the parser
2592 // is in the wrong place to recover. Suggest the typo
2593 // correction, but don't make it a fix-it since we're not going
2594 // to recover well anyway.
2595 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2596 getAsTypeTemplateDecl(UnderlyingND) ||
2597 isa<ObjCInterfaceDecl>(UnderlyingND);
2598 } else {
2599 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2600 // because we aren't able to recover.
2601 AcceptableWithoutRecovery = true;
2602 }
2603
2604 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2605 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2606 ? diag::note_implicit_param_decl
2607 : diag::note_previous_decl;
2608 if (SS.isEmpty())
2609 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2610 PDiag(NoteID), AcceptableWithRecovery);
2611 else
2612 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2613 << Name << computeDeclContext(SS, false)
2614 << DroppedSpecifier << SS.getRange(),
2615 PDiag(NoteID), AcceptableWithRecovery);
2616
2617 // Tell the callee whether to try to recover.
2618 return !AcceptableWithRecovery;
2619 }
2620 }
2621 R.clear();
2622
2623 // Emit a special diagnostic for failed member lookups.
2624 // FIXME: computing the declaration context might fail here (?)
2625 if (!SS.isEmpty()) {
2626 Diag(R.getNameLoc(), diag::err_no_member)
2627 << Name << computeDeclContext(SS, false)
2628 << SS.getRange();
2629 return true;
2630 }
2631
2632 // Give up, we can't recover.
2633 Diag(R.getNameLoc(), diagnostic) << Name;
2634 return true;
2635}
2636
2637/// In Microsoft mode, if we are inside a template class whose parent class has
2638/// dependent base classes, and we can't resolve an unqualified identifier, then
2639/// assume the identifier is a member of a dependent base class. We can only
2640/// recover successfully in static methods, instance methods, and other contexts
2641/// where 'this' is available. This doesn't precisely match MSVC's
2642/// instantiation model, but it's close enough.
2643static Expr *
2645 DeclarationNameInfo &NameInfo,
2646 SourceLocation TemplateKWLoc,
2647 const TemplateArgumentListInfo *TemplateArgs) {
2648 // Only try to recover from lookup into dependent bases in static methods or
2649 // contexts where 'this' is available.
2650 QualType ThisType = S.getCurrentThisType();
2651 const CXXRecordDecl *RD = nullptr;
2652 if (!ThisType.isNull())
2653 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2654 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2655 RD = MD->getParent();
2656 if (!RD || !RD->hasAnyDependentBases())
2657 return nullptr;
2658
2659 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2660 // is available, suggest inserting 'this->' as a fixit.
2661 SourceLocation Loc = NameInfo.getLoc();
2662 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2663 DB << NameInfo.getName() << RD;
2664
2665 if (!ThisType.isNull()) {
2666 DB << FixItHint::CreateInsertion(Loc, "this->");
2668 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2669 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2670 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2671 }
2672
2673 // Synthesize a fake NNS that points to the derived class. This will
2674 // perform name lookup during template instantiation.
2675 CXXScopeSpec SS;
2676 auto *NNS =
2677 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2678 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2680 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2681 TemplateArgs);
2682}
2683
2686 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2687 bool HasTrailingLParen, bool IsAddressOfOperand,
2689 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2690 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2691 "cannot be direct & operand and have a trailing lparen");
2692 if (SS.isInvalid())
2693 return ExprError();
2694
2695 TemplateArgumentListInfo TemplateArgsBuffer;
2696
2697 // Decompose the UnqualifiedId into the following data.
2698 DeclarationNameInfo NameInfo;
2699 const TemplateArgumentListInfo *TemplateArgs;
2700 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2701
2702 DeclarationName Name = NameInfo.getName();
2703 IdentifierInfo *II = Name.getAsIdentifierInfo();
2704 SourceLocation NameLoc = NameInfo.getLoc();
2705
2706 if (II && II->isEditorPlaceholder()) {
2707 // FIXME: When typed placeholders are supported we can create a typed
2708 // placeholder expression node.
2709 return ExprError();
2710 }
2711
2712 // C++ [temp.dep.expr]p3:
2713 // An id-expression is type-dependent if it contains:
2714 // -- an identifier that was declared with a dependent type,
2715 // (note: handled after lookup)
2716 // -- a template-id that is dependent,
2717 // (note: handled in BuildTemplateIdExpr)
2718 // -- a conversion-function-id that specifies a dependent type,
2719 // -- a nested-name-specifier that contains a class-name that
2720 // names a dependent type.
2721 // Determine whether this is a member of an unknown specialization;
2722 // we need to handle these differently.
2723 bool DependentID = false;
2724 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2725 Name.getCXXNameType()->isDependentType()) {
2726 DependentID = true;
2727 } else if (SS.isSet()) {
2728 if (DeclContext *DC = computeDeclContext(SS, false)) {
2729 if (RequireCompleteDeclContext(SS, DC))
2730 return ExprError();
2731 } else {
2732 DependentID = true;
2733 }
2734 }
2735
2736 if (DependentID)
2737 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2738 IsAddressOfOperand, TemplateArgs);
2739
2740 // Perform the required lookup.
2741 LookupResult R(*this, NameInfo,
2745 if (TemplateKWLoc.isValid() || TemplateArgs) {
2746 // Lookup the template name again to correctly establish the context in
2747 // which it was found. This is really unfortunate as we already did the
2748 // lookup to determine that it was a template name in the first place. If
2749 // this becomes a performance hit, we can work harder to preserve those
2750 // results until we get here but it's likely not worth it.
2751 bool MemberOfUnknownSpecialization;
2752 AssumedTemplateKind AssumedTemplate;
2753 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2754 MemberOfUnknownSpecialization, TemplateKWLoc,
2755 &AssumedTemplate))
2756 return ExprError();
2757
2758 if (MemberOfUnknownSpecialization ||
2760 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2761 IsAddressOfOperand, TemplateArgs);
2762 } else {
2763 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2764 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2765
2766 // If the result might be in a dependent base class, this is a dependent
2767 // id-expression.
2769 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2770 IsAddressOfOperand, TemplateArgs);
2771
2772 // If this reference is in an Objective-C method, then we need to do
2773 // some special Objective-C lookup, too.
2774 if (IvarLookupFollowUp) {
2775 ExprResult E(LookupInObjCMethod(R, S, II, true));
2776 if (E.isInvalid())
2777 return ExprError();
2778
2779 if (Expr *Ex = E.getAs<Expr>())
2780 return Ex;
2781 }
2782 }
2783
2784 if (R.isAmbiguous())
2785 return ExprError();
2786
2787 // This could be an implicitly declared function reference if the language
2788 // mode allows it as a feature.
2789 if (R.empty() && HasTrailingLParen && II &&
2790 getLangOpts().implicitFunctionsAllowed()) {
2791 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2792 if (D) R.addDecl(D);
2793 }
2794
2795 // Determine whether this name might be a candidate for
2796 // argument-dependent lookup.
2797 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2798
2799 if (R.empty() && !ADL) {
2800 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2801 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2802 TemplateKWLoc, TemplateArgs))
2803 return E;
2804 }
2805
2806 // Don't diagnose an empty lookup for inline assembly.
2807 if (IsInlineAsmIdentifier)
2808 return ExprError();
2809
2810 // If this name wasn't predeclared and if this is not a function
2811 // call, diagnose the problem.
2812 TypoExpr *TE = nullptr;
2813 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2814 : nullptr);
2815 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2816 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2817 "Typo correction callback misconfigured");
2818 if (CCC) {
2819 // Make sure the callback knows what the typo being diagnosed is.
2820 CCC->setTypoName(II);
2821 if (SS.isValid())
2822 CCC->setTypoNNS(SS.getScopeRep());
2823 }
2824 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2825 // a template name, but we happen to have always already looked up the name
2826 // before we get here if it must be a template name.
2827 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2828 std::nullopt, nullptr, &TE)) {
2829 if (TE && KeywordReplacement) {
2830 auto &State = getTypoExprState(TE);
2831 auto BestTC = State.Consumer->getNextCorrection();
2832 if (BestTC.isKeyword()) {
2833 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2834 if (State.DiagHandler)
2835 State.DiagHandler(BestTC);
2836 KeywordReplacement->startToken();
2837 KeywordReplacement->setKind(II->getTokenID());
2838 KeywordReplacement->setIdentifierInfo(II);
2839 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2840 // Clean up the state associated with the TypoExpr, since it has
2841 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2842 clearDelayedTypo(TE);
2843 // Signal that a correction to a keyword was performed by returning a
2844 // valid-but-null ExprResult.
2845 return (Expr*)nullptr;
2846 }
2847 State.Consumer->resetCorrectionStream();
2848 }
2849 return TE ? TE : ExprError();
2850 }
2851
2852 assert(!R.empty() &&
2853 "DiagnoseEmptyLookup returned false but added no results");
2854
2855 // If we found an Objective-C instance variable, let
2856 // LookupInObjCMethod build the appropriate expression to
2857 // reference the ivar.
2858 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2859 R.clear();
2860 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2861 // In a hopelessly buggy code, Objective-C instance variable
2862 // lookup fails and no expression will be built to reference it.
2863 if (!E.isInvalid() && !E.get())
2864 return ExprError();
2865 return E;
2866 }
2867 }
2868
2869 // This is guaranteed from this point on.
2870 assert(!R.empty() || ADL);
2871
2872 // Check whether this might be a C++ implicit instance member access.
2873 // C++ [class.mfct.non-static]p3:
2874 // When an id-expression that is not part of a class member access
2875 // syntax and not used to form a pointer to member is used in the
2876 // body of a non-static member function of class X, if name lookup
2877 // resolves the name in the id-expression to a non-static non-type
2878 // member of some class C, the id-expression is transformed into a
2879 // class member access expression using (*this) as the
2880 // postfix-expression to the left of the . operator.
2881 //
2882 // But we don't actually need to do this for '&' operands if R
2883 // resolved to a function or overloaded function set, because the
2884 // expression is ill-formed if it actually works out to be a
2885 // non-static member function:
2886 //
2887 // C++ [expr.ref]p4:
2888 // Otherwise, if E1.E2 refers to a non-static member function. . .
2889 // [t]he expression can be used only as the left-hand operand of a
2890 // member function call.
2891 //
2892 // There are other safeguards against such uses, but it's important
2893 // to get this right here so that we don't end up making a
2894 // spuriously dependent expression if we're inside a dependent
2895 // instance method.
2896 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2897 bool MightBeImplicitMember;
2898 if (!IsAddressOfOperand)
2899 MightBeImplicitMember = true;
2900 else if (!SS.isEmpty())
2901 MightBeImplicitMember = false;
2902 else if (R.isOverloadedResult())
2903 MightBeImplicitMember = false;
2904 else if (R.isUnresolvableResult())
2905 MightBeImplicitMember = true;
2906 else
2907 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2908 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2909 isa<MSPropertyDecl>(R.getFoundDecl());
2910
2911 if (MightBeImplicitMember)
2912 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2913 R, TemplateArgs, S);
2914 }
2915
2916 if (TemplateArgs || TemplateKWLoc.isValid()) {
2917
2918 // In C++1y, if this is a variable template id, then check it
2919 // in BuildTemplateIdExpr().
2920 // The single lookup result must be a variable template declaration.
2921 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2922 Id.TemplateId->Kind == TNK_Var_template) {
2923 assert(R.getAsSingle<VarTemplateDecl>() &&
2924 "There should only be one declaration found.");
2925 }
2926
2927 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2928 }
2929
2930 return BuildDeclarationNameExpr(SS, R, ADL);
2931}
2932
2933/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2934/// declaration name, generally during template instantiation.
2935/// There's a large number of things which don't need to be done along
2936/// this path.
2938 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2939 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2940 if (NameInfo.getName().isDependentName())
2941 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2942 NameInfo, /*TemplateArgs=*/nullptr);
2943
2944 DeclContext *DC = computeDeclContext(SS, false);
2945 if (!DC)
2946 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2947 NameInfo, /*TemplateArgs=*/nullptr);
2948
2949 if (RequireCompleteDeclContext(SS, DC))
2950 return ExprError();
2951
2952 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2953 LookupQualifiedName(R, DC);
2954
2955 if (R.isAmbiguous())
2956 return ExprError();
2957
2959 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2960 NameInfo, /*TemplateArgs=*/nullptr);
2961
2962 if (R.empty()) {
2963 // Don't diagnose problems with invalid record decl, the secondary no_member
2964 // diagnostic during template instantiation is likely bogus, e.g. if a class
2965 // is invalid because it's derived from an invalid base class, then missing
2966 // members were likely supposed to be inherited.
2967 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2968 if (CD->isInvalidDecl())
2969 return ExprError();
2970 Diag(NameInfo.getLoc(), diag::err_no_member)
2971 << NameInfo.getName() << DC << SS.getRange();
2972 return ExprError();
2973 }
2974
2975 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2976 // Diagnose a missing typename if this resolved unambiguously to a type in
2977 // a dependent context. If we can recover with a type, downgrade this to
2978 // a warning in Microsoft compatibility mode.
2979 unsigned DiagID = diag::err_typename_missing;
2980 if (RecoveryTSI && getLangOpts().MSVCCompat)
2981 DiagID = diag::ext_typename_missing;
2982 SourceLocation Loc = SS.getBeginLoc();
2983 auto D = Diag(Loc, DiagID);
2984 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2985 << SourceRange(Loc, NameInfo.getEndLoc());
2986
2987 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2988 // context.
2989 if (!RecoveryTSI)
2990 return ExprError();
2991
2992 // Only issue the fixit if we're prepared to recover.
2993 D << FixItHint::CreateInsertion(Loc, "typename ");
2994
2995 // Recover by pretending this was an elaborated type.
2997 TypeLocBuilder TLB;
2998 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2999
3004
3005 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3006
3007 return ExprEmpty();
3008 }
3009
3010 // Defend against this resolving to an implicit member access. We usually
3011 // won't get here if this might be a legitimate a class member (we end up in
3012 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3013 // a pointer-to-member or in an unevaluated context in C++11.
3014 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3016 /*TemplateKWLoc=*/SourceLocation(),
3017 R, /*TemplateArgs=*/nullptr, S);
3018
3019 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3020}
3021
3022/// The parser has read a name in, and Sema has detected that we're currently
3023/// inside an ObjC method. Perform some additional checks and determine if we
3024/// should form a reference to an ivar.
3025///
3026/// Ideally, most of this would be done by lookup, but there's
3027/// actually quite a lot of extra work involved.
3029 IdentifierInfo *II) {
3030 SourceLocation Loc = Lookup.getNameLoc();
3031 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3032
3033 // Check for error condition which is already reported.
3034 if (!CurMethod)
3035 return DeclResult(true);
3036
3037 // There are two cases to handle here. 1) scoped lookup could have failed,
3038 // in which case we should look for an ivar. 2) scoped lookup could have
3039 // found a decl, but that decl is outside the current instance method (i.e.
3040 // a global variable). In these two cases, we do a lookup for an ivar with
3041 // this name, if the lookup sucedes, we replace it our current decl.
3042
3043 // If we're in a class method, we don't normally want to look for
3044 // ivars. But if we don't find anything else, and there's an
3045 // ivar, that's an error.
3046 bool IsClassMethod = CurMethod->isClassMethod();
3047
3048 bool LookForIvars;
3049 if (Lookup.empty())
3050 LookForIvars = true;
3051 else if (IsClassMethod)
3052 LookForIvars = false;
3053 else
3054 LookForIvars = (Lookup.isSingleResult() &&
3056 ObjCInterfaceDecl *IFace = nullptr;
3057 if (LookForIvars) {
3058 IFace = CurMethod->getClassInterface();
3059 ObjCInterfaceDecl *ClassDeclared;
3060 ObjCIvarDecl *IV = nullptr;
3061 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3062 // Diagnose using an ivar in a class method.
3063 if (IsClassMethod) {
3064 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3065 return DeclResult(true);
3066 }
3067
3068 // Diagnose the use of an ivar outside of the declaring class.
3070 !declaresSameEntity(ClassDeclared, IFace) &&
3071 !getLangOpts().DebuggerSupport)
3072 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3073
3074 // Success.
3075 return IV;
3076 }
3077 } else if (CurMethod->isInstanceMethod()) {
3078 // We should warn if a local variable hides an ivar.
3079 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3080 ObjCInterfaceDecl *ClassDeclared;
3081 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3082 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3083 declaresSameEntity(IFace, ClassDeclared))
3084 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3085 }
3086 }
3087 } else if (Lookup.isSingleResult() &&
3089 // If accessing a stand-alone ivar in a class method, this is an error.
3090 if (const ObjCIvarDecl *IV =
3091 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3092 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3093 return DeclResult(true);
3094 }
3095 }
3096
3097 // Didn't encounter an error, didn't find an ivar.
3098 return DeclResult(false);
3099}
3100
3102 ObjCIvarDecl *IV) {
3103 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3104 assert(CurMethod && CurMethod->isInstanceMethod() &&
3105 "should not reference ivar from this context");
3106
3107 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3108 assert(IFace && "should not reference ivar from this context");
3109
3110 // If we're referencing an invalid decl, just return this as a silent
3111 // error node. The error diagnostic was already emitted on the decl.
3112 if (IV->isInvalidDecl())
3113 return ExprError();
3114
3115 // Check if referencing a field with __attribute__((deprecated)).
3116 if (DiagnoseUseOfDecl(IV, Loc))
3117 return ExprError();
3118
3119 // FIXME: This should use a new expr for a direct reference, don't
3120 // turn this into Self->ivar, just return a BareIVarExpr or something.
3121 IdentifierInfo &II = Context.Idents.get("self");
3122 UnqualifiedId SelfName;
3123 SelfName.setImplicitSelfParam(&II);
3124 CXXScopeSpec SelfScopeSpec;
3125 SourceLocation TemplateKWLoc;
3126 ExprResult SelfExpr =
3127 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3128 /*HasTrailingLParen=*/false,
3129 /*IsAddressOfOperand=*/false);
3130 if (SelfExpr.isInvalid())
3131 return ExprError();
3132
3133 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3134 if (SelfExpr.isInvalid())
3135 return ExprError();
3136
3137 MarkAnyDeclReferenced(Loc, IV, true);
3138
3139 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3140 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3141 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3142 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3143
3145 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3146 IV->getLocation(), SelfExpr.get(), true, true);
3147
3149 if (!isUnevaluatedContext() &&
3150 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3152 }
3153 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3154 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3155 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3156
3157 return Result;
3158}
3159
3160/// The parser has read a name in, and Sema has detected that we're currently
3161/// inside an ObjC method. Perform some additional checks and determine if we
3162/// should form a reference to an ivar. If so, build an expression referencing
3163/// that ivar.
3166 IdentifierInfo *II, bool AllowBuiltinCreation) {
3167 // FIXME: Integrate this lookup step into LookupParsedName.
3168 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3169 if (Ivar.isInvalid())
3170 return ExprError();
3171 if (Ivar.isUsable())
3172 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3173 cast<ObjCIvarDecl>(Ivar.get()));
3174
3175 if (Lookup.empty() && II && AllowBuiltinCreation)
3176 LookupBuiltin(Lookup);
3177
3178 // Sentinel value saying that we didn't do anything special.
3179 return ExprResult(false);
3180}
3181
3182/// Cast a base object to a member's actual type.
3183///
3184/// There are two relevant checks:
3185///
3186/// C++ [class.access.base]p7:
3187///
3188/// If a class member access operator [...] is used to access a non-static
3189/// data member or non-static member function, the reference is ill-formed if
3190/// the left operand [...] cannot be implicitly converted to a pointer to the
3191/// naming class of the right operand.
3192///
3193/// C++ [expr.ref]p7:
3194///
3195/// If E2 is a non-static data member or a non-static member function, the
3196/// program is ill-formed if the class of which E2 is directly a member is an
3197/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3198///
3199/// Note that the latter check does not consider access; the access of the
3200/// "real" base class is checked as appropriate when checking the access of the
3201/// member name.
3204 NestedNameSpecifier *Qualifier,
3205 NamedDecl *FoundDecl,
3206 NamedDecl *Member) {
3207 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3208 if (!RD)
3209 return From;
3210
3211 QualType DestRecordType;
3212 QualType DestType;
3213 QualType FromRecordType;
3214 QualType FromType = From->getType();
3215 bool PointerConversions = false;
3216 if (isa<FieldDecl>(Member)) {
3217 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3218 auto FromPtrType = FromType->getAs<PointerType>();
3219 DestRecordType = Context.getAddrSpaceQualType(
3220 DestRecordType, FromPtrType
3221 ? FromType->getPointeeType().getAddressSpace()
3222 : FromType.getAddressSpace());
3223
3224 if (FromPtrType) {
3225 DestType = Context.getPointerType(DestRecordType);
3226 FromRecordType = FromPtrType->getPointeeType();
3227 PointerConversions = true;
3228 } else {
3229 DestType = DestRecordType;
3230 FromRecordType = FromType;
3231 }
3232 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3233 if (!Method->isImplicitObjectMemberFunction())
3234 return From;
3235
3236 DestType = Method->getThisType().getNonReferenceType();
3237 DestRecordType = Method->getFunctionObjectParameterType();
3238
3239 if (FromType->getAs<PointerType>()) {
3240 FromRecordType = FromType->getPointeeType();
3241 PointerConversions = true;
3242 } else {
3243 FromRecordType = FromType;
3244 DestType = DestRecordType;
3245 }
3246
3247 LangAS FromAS = FromRecordType.getAddressSpace();
3248 LangAS DestAS = DestRecordType.getAddressSpace();
3249 if (FromAS != DestAS) {
3250 QualType FromRecordTypeWithoutAS =
3251 Context.removeAddrSpaceQualType(FromRecordType);
3252 QualType FromTypeWithDestAS =
3253 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3254 if (PointerConversions)
3255 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3256 From = ImpCastExprToType(From, FromTypeWithDestAS,
3257 CK_AddressSpaceConversion, From->getValueKind())
3258 .get();
3259 }
3260 } else {
3261 // No conversion necessary.
3262 return From;
3263 }
3264
3265 if (DestType->isDependentType() || FromType->isDependentType())
3266 return From;
3267
3268 // If the unqualified types are the same, no conversion is necessary.
3269 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3270 return From;
3271
3272 SourceRange FromRange = From->getSourceRange();
3273 SourceLocation FromLoc = FromRange.getBegin();
3274
3275 ExprValueKind VK = From->getValueKind();
3276
3277 // C++ [class.member.lookup]p8:
3278 // [...] Ambiguities can often be resolved by qualifying a name with its
3279 // class name.
3280 //
3281 // If the member was a qualified name and the qualified referred to a
3282 // specific base subobject type, we'll cast to that intermediate type
3283 // first and then to the object in which the member is declared. That allows
3284 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3285 //
3286 // class Base { public: int x; };
3287 // class Derived1 : public Base { };
3288 // class Derived2 : public Base { };
3289 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3290 //
3291 // void VeryDerived::f() {
3292 // x = 17; // error: ambiguous base subobjects
3293 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3294 // }
3295 if (Qualifier && Qualifier->getAsType()) {
3296 QualType QType = QualType(Qualifier->getAsType(), 0);
3297 assert(QType->isRecordType() && "lookup done with non-record type");
3298
3299 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3300
3301 // In C++98, the qualifier type doesn't actually have to be a base
3302 // type of the object type, in which case we just ignore it.
3303 // Otherwise build the appropriate casts.
3304 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3305 CXXCastPath BasePath;
3306 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3307 FromLoc, FromRange, &BasePath))
3308 return ExprError();
3309
3310 if (PointerConversions)
3311 QType = Context.getPointerType(QType);
3312 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3313 VK, &BasePath).get();
3314
3315 FromType = QType;
3316 FromRecordType = QRecordType;
3317
3318 // If the qualifier type was the same as the destination type,
3319 // we're done.
3320 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3321 return From;
3322 }
3323 }
3324
3325 CXXCastPath BasePath;
3326 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3327 FromLoc, FromRange, &BasePath,
3328 /*IgnoreAccess=*/true))
3329 return ExprError();
3330
3331 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3332 VK, &BasePath);
3333}
3334
3336 const LookupResult &R,
3337 bool HasTrailingLParen) {
3338 // Only when used directly as the postfix-expression of a call.
3339 if (!HasTrailingLParen)
3340 return false;
3341
3342 // Never if a scope specifier was provided.
3343 if (SS.isSet())
3344 return false;
3345
3346 // Only in C++ or ObjC++.
3347 if (!getLangOpts().CPlusPlus)
3348 return false;
3349
3350 // Turn off ADL when we find certain kinds of declarations during
3351 // normal lookup:
3352 for (const NamedDecl *D : R) {
3353 // C++0x [basic.lookup.argdep]p3:
3354 // -- a declaration of a class member
3355 // Since using decls preserve this property, we check this on the
3356 // original decl.
3357 if (D->isCXXClassMember())
3358 return false;
3359
3360 // C++0x [basic.lookup.argdep]p3:
3361 // -- a block-scope function declaration that is not a
3362 // using-declaration
3363 // NOTE: we also trigger this for function templates (in fact, we
3364 // don't check the decl type at all, since all other decl types
3365 // turn off ADL anyway).
3366 if (isa<UsingShadowDecl>(D))
3367 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3368 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3369 return false;
3370
3371 // C++0x [basic.lookup.argdep]p3:
3372 // -- a declaration that is neither a function or a function
3373 // template
3374 // And also for builtin functions.
3375 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3376 // But also builtin functions.
3377 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3378 return false;
3379 } else if (!isa<FunctionTemplateDecl>(D))
3380 return false;
3381 }
3382
3383 return true;
3384}
3385
3386
3387/// Diagnoses obvious problems with the use of the given declaration
3388/// as an expression. This is only actually called for lookups that
3389/// were not overloaded, and it doesn't promise that the declaration
3390/// will in fact be used.
3392 bool AcceptInvalid) {
3393 if (D->isInvalidDecl() && !AcceptInvalid)
3394 return true;
3395
3396 if (isa<TypedefNameDecl>(D)) {
3397 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3398 return true;
3399 }
3400
3401 if (isa<ObjCInterfaceDecl>(D)) {
3402 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3403 return true;
3404 }
3405
3406 if (isa<NamespaceDecl>(D)) {
3407 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3408 return true;
3409 }
3410
3411 return false;
3412}
3413
3414// Certain multiversion types should be treated as overloaded even when there is
3415// only one result.
3417 assert(R.isSingleResult() && "Expected only a single result");
3418 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3419 return FD &&
3420 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3421}
3422
3424 LookupResult &R, bool NeedsADL,
3425 bool AcceptInvalidDecl) {
3426 // If this is a single, fully-resolved result and we don't need ADL,
3427 // just build an ordinary singleton decl ref.
3428 if (!NeedsADL && R.isSingleResult() &&
3432 R.getRepresentativeDecl(), nullptr,
3433 AcceptInvalidDecl);
3434
3435 // We only need to check the declaration if there's exactly one
3436 // result, because in the overloaded case the results can only be
3437 // functions and function templates.
3439 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3440 AcceptInvalidDecl))
3441 return ExprError();
3442
3443 // Otherwise, just build an unresolved lookup expression. Suppress
3444 // any lookup-related diagnostics; we'll hash these out later, when
3445 // we've picked a target.
3447
3452 NeedsADL, R.isOverloadedResult(),
3453 R.begin(), R.end());
3454
3455 return ULE;
3456}
3457
3459 SourceLocation loc,
3460 ValueDecl *var);
3461
3462/// Complete semantic analysis for a reference to the given declaration.
3464 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3465 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3466 bool AcceptInvalidDecl) {
3467 assert(D && "Cannot refer to a NULL declaration");
3468 assert(!isa<FunctionTemplateDecl>(D) &&
3469 "Cannot refer unambiguously to a function template");
3470
3471 SourceLocation Loc = NameInfo.getLoc();
3472 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3473 // Recovery from invalid cases (e.g. D is an invalid Decl).
3474 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3475 // diagnostics, as invalid decls use int as a fallback type.
3476 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3477 }
3478
3479 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3480 // Specifically diagnose references to class templates that are missing
3481 // a template argument list.
3483 return ExprError();
3484 }
3485
3486 // Make sure that we're referring to a value.
3487 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3488 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3489 Diag(D->getLocation(), diag::note_declared_at);
3490 return ExprError();
3491 }
3492
3493 // Check whether this declaration can be used. Note that we suppress
3494 // this check when we're going to perform argument-dependent lookup
3495 // on this function name, because this might not be the function
3496 // that overload resolution actually selects.
3497 if (DiagnoseUseOfDecl(D, Loc))
3498 return ExprError();
3499
3500 auto *VD = cast<ValueDecl>(D);
3501
3502 // Only create DeclRefExpr's for valid Decl's.
3503 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3504 return ExprError();
3505
3506 // Handle members of anonymous structs and unions. If we got here,
3507 // and the reference is to a class member indirect field, then this
3508 // must be the subject of a pointer-to-member expression.
3509 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3510 IndirectField && !IndirectField->isCXXClassMember())
3512 IndirectField);
3513
3514 QualType type = VD->getType();
3515 if (type.isNull())
3516 return ExprError();
3517 ExprValueKind valueKind = VK_PRValue;
3518
3519 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3520 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3521 // is expanded by some outer '...' in the context of the use.
3522 type = type.getNonPackExpansionType();
3523
3524 switch (D->getKind()) {
3525 // Ignore all the non-ValueDecl kinds.
3526#define ABSTRACT_DECL(kind)
3527#define VALUE(type, base)
3528#define DECL(type, base) case Decl::type:
3529#include "clang/AST/DeclNodes.inc"
3530 llvm_unreachable("invalid value decl kind");
3531
3532 // These shouldn't make it here.
3533 case Decl::ObjCAtDefsField:
3534 llvm_unreachable("forming non-member reference to ivar?");
3535
3536 // Enum constants are always r-values and never references.
3537 // Unresolved using declarations are dependent.
3538 case Decl::EnumConstant:
3539 case Decl::UnresolvedUsingValue:
3540 case Decl::OMPDeclareReduction:
3541 case Decl::OMPDeclareMapper:
3542 valueKind = VK_PRValue;
3543 break;
3544
3545 // Fields and indirect fields that got here must be for
3546 // pointer-to-member expressions; we just call them l-values for
3547 // internal consistency, because this subexpression doesn't really
3548 // exist in the high-level semantics.
3549 case Decl::Field:
3550 case Decl::IndirectField:
3551 case Decl::ObjCIvar:
3552 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3553
3554 // These can't have reference type in well-formed programs, but
3555 // for internal consistency we do this anyway.
3556 type = type.getNonReferenceType();
3557 valueKind = VK_LValue;
3558 break;
3559
3560 // Non-type template parameters are either l-values or r-values
3561 // depending on the type.
3562 case Decl::NonTypeTemplateParm: {
3563 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3564 type = reftype->getPointeeType();
3565 valueKind = VK_LValue; // even if the parameter is an r-value reference
3566 break;
3567 }
3568
3569 // [expr.prim.id.unqual]p2:
3570 // If the entity is a template parameter object for a template
3571 // parameter of type T, the type of the expression is const T.
3572 // [...] The expression is an lvalue if the entity is a [...] template
3573 // parameter object.
3574 if (type->isRecordType()) {
3575 type = type.getUnqualifiedType().withConst();
3576 valueKind = VK_LValue;
3577 break;
3578 }
3579
3580 // For non-references, we need to strip qualifiers just in case
3581 // the template parameter was declared as 'const int' or whatever.
3582 valueKind = VK_PRValue;
3583 type = type.getUnqualifiedType();
3584 break;
3585 }
3586
3587 case Decl::Var:
3588 case Decl::VarTemplateSpecialization:
3589 case Decl::VarTemplatePartialSpecialization:
3590 case Decl::Decomposition:
3591 case Decl::OMPCapturedExpr:
3592 // In C, "extern void blah;" is valid and is an r-value.
3593 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3594 type->isVoidType()) {
3595 valueKind = VK_PRValue;
3596 break;
3597 }
3598 [[fallthrough]];
3599
3600 case Decl::ImplicitParam:
3601 case Decl::ParmVar: {
3602 // These are always l-values.
3603 valueKind = VK_LValue;
3604 type = type.getNonReferenceType();
3605
3606 // FIXME: Does the addition of const really only apply in
3607 // potentially-evaluated contexts? Since the variable isn't actually
3608 // captured in an unevaluated context, it seems that the answer is no.
3609 if (!isUnevaluatedContext()) {
3610 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3611 if (!CapturedType.isNull())
3612 type = CapturedType;
3613 }
3614
3615 break;
3616 }
3617
3618 case Decl::Binding:
3619 // These are always lvalues.
3620 valueKind = VK_LValue;
3621 type = type.getNonReferenceType();
3622 break;
3623
3624 case Decl::Function: {
3625 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3628 valueKind = VK_PRValue;
3629 break;
3630 }
3631 }
3632
3633 const FunctionType *fty = type->castAs<FunctionType>();
3634
3635 // If we're referring to a function with an __unknown_anytype
3636 // result type, make the entire expression __unknown_anytype.
3637 if (fty->getReturnType() == Context.UnknownAnyTy) {
3639 valueKind = VK_PRValue;
3640 break;
3641 }
3642
3643 // Functions are l-values in C++.
3644 if (getLangOpts().CPlusPlus) {
3645 valueKind = VK_LValue;
3646 break;
3647 }
3648
3649 // C99 DR 316 says that, if a function type comes from a
3650 // function definition (without a prototype), that type is only
3651 // used for checking compatibility. Therefore, when referencing
3652 // the function, we pretend that we don't have the full function
3653 // type.
3654 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3656 fty->getExtInfo());
3657
3658 // Functions are r-values in C.
3659 valueKind = VK_PRValue;
3660 break;
3661 }
3662
3663 case Decl::CXXDeductionGuide:
3664 llvm_unreachable("building reference to deduction guide");
3665
3666 case Decl::MSProperty:
3667 case Decl::MSGuid:
3668 case Decl::TemplateParamObject:
3669 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3670 // capture in OpenMP, or duplicated between host and device?
3671 valueKind = VK_LValue;
3672 break;
3673
3674 case Decl::UnnamedGlobalConstant:
3675 valueKind = VK_LValue;
3676 break;
3677
3678 case Decl::CXXMethod:
3679 // If we're referring to a method with an __unknown_anytype
3680 // result type, make the entire expression __unknown_anytype.
3681 // This should only be possible with a type written directly.
3682 if (const FunctionProtoType *proto =
3683 dyn_cast<FunctionProtoType>(VD->getType()))
3684 if (proto->getReturnType() == Context.UnknownAnyTy) {
3686 valueKind = VK_PRValue;
3687 break;
3688 }
3689
3690 // C++ methods are l-values if static, r-values if non-static.
3691 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3692 valueKind = VK_LValue;
3693 break;
3694 }
3695 [[fallthrough]];
3696
3697 case Decl::CXXConversion:
3698 case Decl::CXXDestructor:
3699 case Decl::CXXConstructor:
3700 valueKind = VK_PRValue;
3701 break;
3702 }
3703
3704 auto *E =
3705 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3706 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3707 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3708 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3709 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3710 // diagnostics).
3711 if (VD->isInvalidDecl() && E)
3712 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3713 return E;
3714}
3715
3716static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3718 Target.resize(CharByteWidth * (Source.size() + 1));
3719 char *ResultPtr = &Target[0];
3720 const llvm::UTF8 *ErrorPtr;
3721 bool success =
3722 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3723 (void)success;
3724 assert(success);
3725 Target.resize(ResultPtr - &Target[0]);
3726}
3727
3730 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3731 if (!currentDecl) {
3732 Diag(Loc, diag::ext_predef_outside_function);
3733 currentDecl = Context.getTranslationUnitDecl();
3734 }
3735
3736 QualType ResTy;
3737 StringLiteral *SL = nullptr;
3738 if (cast<DeclContext>(currentDecl)->isDependentContext())
3739 ResTy = Context.DependentTy;
3740 else {
3741 // Pre-defined identifiers are of type char[x], where x is the length of
3742 // the string.
3743 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3744 unsigned Length = Str.length();
3745
3746 llvm::APInt LengthI(32, Length + 1);
3749 ResTy =
3751 SmallString<32> RawChars;
3753 Str, RawChars);
3754 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3756 /*IndexTypeQuals*/ 0);
3758 /*Pascal*/ false, ResTy, Loc);
3759 } else {
3761 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3763 /*IndexTypeQuals*/ 0);
3765 /*Pascal*/ false, ResTy, Loc);
3766 }
3767 }
3768
3769 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3770 SL);
3771}
3772
3774 SourceLocation LParen,
3775 SourceLocation RParen,
3776 TypeSourceInfo *TSI) {
3777 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3778}
3779
3781 SourceLocation LParen,
3782 SourceLocation RParen,
3783 ParsedType ParsedTy) {
3784 TypeSourceInfo *TSI = nullptr;
3785 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3786
3787 if (Ty.isNull())
3788 return ExprError();
3789 if (!TSI)
3790 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3791
3792 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3793}
3794
3796 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3797}
3798
3800 SmallString<16> CharBuffer;
3801 bool Invalid = false;
3802 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3803 if (Invalid)
3804 return ExprError();
3805
3806 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3807 PP, Tok.getKind());
3808 if (Literal.hadError())
3809 return ExprError();
3810
3811 QualType Ty;
3812 if (Literal.isWide())
3813 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3814 else if (Literal.isUTF8() && getLangOpts().C23)
3815 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3816 else if (Literal.isUTF8() && getLangOpts().Char8)
3817 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3818 else if (Literal.isUTF16())
3819 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3820 else if (Literal.isUTF32())
3821 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3822 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3823 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3824 else
3825 Ty = Context.CharTy; // 'x' -> char in C++;
3826 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3827
3829 if (Literal.isWide())
3831 else if (Literal.isUTF16())
3833 else if (Literal.isUTF32())
3835 else if (Literal.isUTF8())
3837
3838 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3839 Tok.getLocation());
3840
3841 if (Literal.getUDSuffix().empty())
3842 return Lit;
3843
3844 // We're building a user-defined literal.
3845 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3846 SourceLocation UDSuffixLoc =
3847 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3848
3849 // Make sure we're allowed user-defined literals here.
3850 if (!UDLScope)
3851 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3852
3853 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3854 // operator "" X (ch)
3855 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3856 Lit, Tok.getLocation());
3857}
3858
3860 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3861 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3862 Context.IntTy, Loc);
3863}
3864
3866 QualType Ty, SourceLocation Loc) {
3867 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3868
3869 using llvm::APFloat;
3870 APFloat Val(Format);
3871
3872 APFloat::opStatus result = Literal.GetFloatValue(Val);
3873
3874 // Overflow is always an error, but underflow is only an error if
3875 // we underflowed to zero (APFloat reports denormals as underflow).
3876 if ((result & APFloat::opOverflow) ||
3877 ((result & APFloat::opUnderflow) && Val.isZero())) {
3878 unsigned diagnostic;
3879 SmallString<20> buffer;
3880 if (result & APFloat::opOverflow) {
3881 diagnostic = diag::warn_float_overflow;
3882 APFloat::getLargest(Format).toString(buffer);
3883 } else {
3884 diagnostic = diag::warn_float_underflow;
3885 APFloat::getSmallest(Format).toString(buffer);
3886 }
3887
3888 S.Diag(Loc, diagnostic)
3889 << Ty
3890 << StringRef(buffer.data(), buffer.size());
3891 }
3892
3893 bool isExact = (result == APFloat::opOK);
3894 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3895}
3896
3898 assert(E && "Invalid expression");
3899
3900 if (E->isValueDependent())
3901 return false;
3902
3903 QualType QT = E->getType();
3904 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3905 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3906 return true;
3907 }
3908
3909 llvm::APSInt ValueAPS;
3911
3912 if (R.isInvalid())
3913 return true;
3914
3915 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3916 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3917 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3918 << toString(ValueAPS, 10) << ValueIsPositive;
3919 return true;
3920 }
3921
3922 return false;
3923}
3924
3926 // Fast path for a single digit (which is quite common). A single digit
3927 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3928 if (Tok.getLength() == 1) {
3929 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3930 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3931 }
3932
3933 SmallString<128> SpellingBuffer;
3934 // NumericLiteralParser wants to overread by one character. Add padding to
3935 // the buffer in case the token is copied to the buffer. If getSpelling()
3936 // returns a StringRef to the memory buffer, it should have a null char at
3937 // the EOF, so it is also safe.
3938 SpellingBuffer.resize(Tok.getLength() + 1);
3939
3940 // Get the spelling of the token, which eliminates trigraphs, etc.
3941 bool Invalid = false;
3942 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3943 if (Invalid)
3944 return ExprError();
3945
3946 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3949 if (Literal.hadError)
3950 return ExprError();
3951
3952 if (Literal.hasUDSuffix()) {
3953 // We're building a user-defined literal.
3954 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3955 SourceLocation UDSuffixLoc =
3956 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3957
3958 // Make sure we're allowed user-defined literals here.
3959 if (!UDLScope)
3960 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3961
3962 QualType CookedTy;
3963 if (Literal.isFloatingLiteral()) {
3964 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3965 // long double, the literal is treated as a call of the form
3966 // operator "" X (f L)
3967 CookedTy = Context.LongDoubleTy;
3968 } else {
3969 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3970 // unsigned long long, the literal is treated as a call of the form
3971 // operator "" X (n ULL)
3972 CookedTy = Context.UnsignedLongLongTy;
3973 }
3974
3975 DeclarationName OpName =
3977 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3978 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3979
3980 SourceLocation TokLoc = Tok.getLocation();
3981
3982 // Perform literal operator lookup to determine if we're building a raw
3983 // literal or a cooked one.
3984 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3985 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3986 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3987 /*AllowStringTemplatePack*/ false,
3988 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3990 // Lookup failure for imaginary constants isn't fatal, there's still the
3991 // GNU extension producing _Complex types.
3992 break;
3993 case LOLR_Error:
3994 return ExprError();
3995 case LOLR_Cooked: {
3996 Expr *Lit;
3997 if (Literal.isFloatingLiteral()) {
3998 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3999 } else {
4000 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
4001 if (Literal.GetIntegerValue(ResultVal))
4002 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4003 << /* Unsigned */ 1;
4004 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
4005 Tok.getLocation());
4006 }
4007 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4008 }
4009
4010 case LOLR_Raw: {
4011 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4012 // literal is treated as a call of the form
4013 // operator "" X ("n")
4014 unsigned Length = Literal.getUDSuffixOffset();
4017 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
4018 Expr *Lit =
4019 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4021 /*Pascal*/ false, StrTy, &TokLoc, 1);
4022 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4023 }
4024
4025 case LOLR_Template: {
4026 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4027 // template), L is treated as a call fo the form
4028 // operator "" X <'c1', 'c2', ... 'ck'>()
4029 // where n is the source character sequence c1 c2 ... ck.
4030 TemplateArgumentListInfo ExplicitArgs;
4031 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4032 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4033 llvm::APSInt Value(CharBits, CharIsUnsigned);
4034 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4035 Value = TokSpelling[I];
4038 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4039 }
4040 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4041 &ExplicitArgs);
4042 }
4044 llvm_unreachable("unexpected literal operator lookup result");
4045 }
4046 }
4047
4048 Expr *Res;
4049
4050 if (Literal.isFixedPointLiteral()) {
4051 QualType Ty;
4052
4053 if (Literal.isAccum) {
4054 if (Literal.isHalf) {
4055 Ty = Context.ShortAccumTy;
4056 } else if (Literal.isLong) {
4057 Ty = Context.LongAccumTy;
4058 } else {
4059 Ty = Context.AccumTy;
4060 }
4061 } else if (Literal.isFract) {
4062 if (Literal.isHalf) {
4063 Ty = Context.ShortFractTy;
4064 } else if (Literal.isLong) {
4065 Ty = Context.LongFractTy;
4066 } else {
4067 Ty = Context.FractTy;
4068 }
4069 }
4070
4071 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4072
4073 bool isSigned = !Literal.isUnsigned;
4074 unsigned scale = Context.getFixedPointScale(Ty);
4075 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4076
4077 llvm::APInt Val(bit_width, 0, isSigned);
4078 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4079 bool ValIsZero = Val.isZero() && !Overflowed;
4080
4081 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4082 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4083 // Clause 6.4.4 - The value of a constant shall be in the range of
4084 // representable values for its type, with exception for constants of a
4085 // fract type with a value of exactly 1; such a constant shall denote
4086 // the maximal value for the type.
4087 --Val;
4088 else if (Val.ugt(MaxVal) || Overflowed)
4089 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4090
4092 Tok.getLocation(), scale);
4093 } else if (Literal.isFloatingLiteral()) {
4094 QualType Ty;
4095 if (Literal.isHalf){
4096 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4097 Ty = Context.HalfTy;
4098 else {
4099 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4100 return ExprError();
4101 }
4102 } else if (Literal.isFloat)
4103 Ty = Context.FloatTy;
4104 else if (Literal.isLong)
4105 Ty = Context.LongDoubleTy;
4106 else if (Literal.isFloat16)
4107 Ty = Context.Float16Ty;
4108 else if (Literal.isFloat128)
4109 Ty = Context.Float128Ty;
4110 else
4111 Ty = Context.DoubleTy;
4112
4113 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4114
4115 if (Ty == Context.DoubleTy) {
4116 if (getLangOpts().SinglePrecisionConstants) {
4117 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4118 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4119 }
4120 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4121 "cl_khr_fp64", getLangOpts())) {
4122 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4123 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4125 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4126 }
4127 }
4128 } else if (!Literal.isIntegerLiteral()) {
4129 return ExprError();
4130 } else {
4131 QualType Ty;
4132
4133 // 'z/uz' literals are a C++23 feature.
4134 if (Literal.isSizeT)
4137 ? diag::warn_cxx20_compat_size_t_suffix
4138 : diag::ext_cxx23_size_t_suffix
4139 : diag::err_cxx23_size_t_suffix);
4140
4141 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4142 // but we do not currently support the suffix in C++ mode because it's not
4143 // entirely clear whether WG21 will prefer this suffix to return a library
4144 // type such as std::bit_int instead of returning a _BitInt.
4145 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4147 ? diag::warn_c23_compat_bitint_suffix
4148 : diag::ext_c23_bitint_suffix);
4149
4150 // Get the value in the widest-possible width. What is "widest" depends on
4151 // whether the literal is a bit-precise integer or not. For a bit-precise
4152 // integer type, try to scan the source to determine how many bits are
4153 // needed to represent the value. This may seem a bit expensive, but trying
4154 // to get the integer value from an overly-wide APInt is *extremely*
4155 // expensive, so the naive approach of assuming
4156 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4157 unsigned BitsNeeded =
4158 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4159 Literal.getLiteralDigits(), Literal.getRadix())
4161 llvm::APInt ResultVal(BitsNeeded, 0);
4162
4163 if (Literal.GetIntegerValue(ResultVal)) {
4164 // If this value didn't fit into uintmax_t, error and force to ull.
4165 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4166 << /* Unsigned */ 1;
4168 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4169 "long long is not intmax_t?");
4170 } else {
4171 // If this value fits into a ULL, try to figure out what else it fits into
4172 // according to the rules of C99 6.4.4.1p5.
4173
4174 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4175 // be an unsigned int.
4176 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4177
4178 // Check from smallest to largest, picking the smallest type we can.
4179 unsigned Width = 0;
4180
4181 // Microsoft specific integer suffixes are explicitly sized.
4182 if (Literal.MicrosoftInteger) {
4183 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4184 Width = 8;
4185 Ty = Context.CharTy;
4186 } else {
4187 Width = Literal.MicrosoftInteger;
4188 Ty = Context.getIntTypeForBitwidth(Width,
4189 /*Signed=*/!Literal.isUnsigned);
4190 }
4191 }
4192
4193 // Bit-precise integer literals are automagically-sized based on the
4194 // width required by the literal.
4195 if (Literal.isBitInt) {
4196 // The signed version has one more bit for the sign value. There are no
4197 // zero-width bit-precise integers, even if the literal value is 0.
4198 Width = std::max(ResultVal.getActiveBits(), 1u) +
4199 (Literal.isUnsigned ? 0u : 1u);
4200
4201 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4202 // and reset the type to the largest supported width.
4203 unsigned int MaxBitIntWidth =
4205 if (Width > MaxBitIntWidth) {
4206 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4207 << Literal.isUnsigned;
4208 Width = MaxBitIntWidth;
4209 }
4210
4211 // Reset the result value to the smaller APInt and select the correct
4212 // type to be used. Note, we zext even for signed values because the
4213 // literal itself is always an unsigned value (a preceeding - is a
4214 // unary operator, not part of the literal).
4215 ResultVal = ResultVal.zextOrTrunc(Width);
4216 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4217 }
4218
4219 // Check C++23 size_t literals.
4220 if (Literal.isSizeT) {
4221 assert(!Literal.MicrosoftInteger &&
4222 "size_t literals can't be Microsoft literals");
4223 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4225
4226 // Does it fit in size_t?
4227 if (ResultVal.isIntN(SizeTSize)) {
4228 // Does it fit in ssize_t?
4229 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4231 else if (AllowUnsigned)
4232 Ty = Context.getSizeType();
4233 Width = SizeTSize;
4234 }
4235 }
4236
4237 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4238 !Literal.isSizeT) {
4239 // Are int/unsigned possibilities?
4240 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4241
4242 // Does it fit in a unsigned int?
4243 if (ResultVal.isIntN(IntSize)) {
4244 // Does it fit in a signed int?
4245 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4246 Ty = Context.IntTy;
4247 else if (AllowUnsigned)
4249 Width = IntSize;
4250 }
4251 }
4252
4253 // Are long/unsigned long possibilities?
4254 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4255 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4256
4257 // Does it fit in a unsigned long?
4258 if (ResultVal.isIntN(LongSize)) {
4259 // Does it fit in a signed long?
4260 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4261 Ty = Context.LongTy;
4262 else if (AllowUnsigned)
4264 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4265 // is compatible.
4266 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4267 const unsigned LongLongSize =
4269 Diag(Tok.getLocation(),
4271 ? Literal.isLong
4272 ? diag::warn_old_implicitly_unsigned_long_cxx
4273 : /*C++98 UB*/ diag::
4274 ext_old_implicitly_unsigned_long_cxx
4275 : diag::warn_old_implicitly_unsigned_long)
4276 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4277 : /*will be ill-formed*/ 1);
4279 }
4280 Width = LongSize;
4281 }
4282 }
4283
4284 // Check long long if needed.
4285 if (Ty.isNull() && !Literal.isSizeT) {
4286 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4287
4288 // Does it fit in a unsigned long long?
4289 if (ResultVal.isIntN(LongLongSize)) {
4290 // Does it fit in a signed long long?
4291 // To be compatible with MSVC, hex integer literals ending with the
4292 // LL or i64 suffix are always signed in Microsoft mode.
4293 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4294 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4295 Ty = Context.LongLongTy;
4296 else if (AllowUnsigned)
4298 Width = LongLongSize;
4299
4300 // 'long long' is a C99 or C++11 feature, whether the literal
4301 // explicitly specified 'long long' or we needed the extra width.
4302 if (getLangOpts().CPlusPlus)
4303 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4304 ? diag::warn_cxx98_compat_longlong
4305 : diag::ext_cxx11_longlong);
4306 else if (!getLangOpts().C99)
4307 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4308 }
4309 }
4310
4311 // If we still couldn't decide a type, we either have 'size_t' literal
4312 // that is out of range, or a decimal literal that does not fit in a
4313 // signed long long and has no U suffix.
4314 if (Ty.isNull()) {
4315 if (Literal.isSizeT)
4316 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4317 << Literal.isUnsigned;
4318 else
4319 Diag(Tok.getLocation(),
4320 diag::ext_integer_literal_too_large_for_signed);
4323 }
4324
4325 if (ResultVal.getBitWidth() != Width)
4326 ResultVal = ResultVal.trunc(Width);
4327 }
4328 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4329 }
4330
4331 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4332 if (Literal.isImaginary) {
4333 Res = new (Context) ImaginaryLiteral(Res,
4335
4336 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4337 }
4338 return Res;
4339}
4340
4342 assert(E && "ActOnParenExpr() missing expr");
4343 QualType ExprTy = E->getType();
4344 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4345 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4346 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4347 return new (Context) ParenExpr(L, R, E);
4348}
4349
4351 SourceLocation Loc,
4352 SourceRange ArgRange) {
4353 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4354 // scalar or vector data type argument..."
4355 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4356 // type (C99 6.2.5p18) or void.
4357 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4358 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4359 << T << ArgRange;
4360 return true;
4361 }
4362
4363 assert((T->isVoidType() || !T->isIncompleteType()) &&
4364 "Scalar types should always be complete");
4365 return false;
4366}
4367
4369 SourceLocation Loc,
4370 SourceRange ArgRange) {
4371 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4372 if (!T->isVectorType() && !T->isSizelessVectorType())
4373 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4374 << ""
4375 << "__builtin_vectorelements" << T << ArgRange;
4376
4377 return false;
4378}
4379
4381 SourceLocation Loc,
4382 SourceRange ArgRange,
4383 UnaryExprOrTypeTrait TraitKind) {
4384 // Invalid types must be hard errors for SFINAE in C++.
4385 if (S.LangOpts.CPlusPlus)
4386 return true;
4387
4388 // C99 6.5.3.4p1:
4389 if (T->isFunctionType() &&
4390 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4391 TraitKind == UETT_PreferredAlignOf)) {
4392 // sizeof(function)/alignof(function) is allowed as an extension.
4393 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4394 << getTraitSpelling(TraitKind) << ArgRange;
4395 return false;
4396 }
4397
4398 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4399 // this is an error (OpenCL v1.1 s6.3.k)
4400 if (T->isVoidType()) {
4401 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4402 : diag::ext_sizeof_alignof_void_type;
4403 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4404 return false;
4405 }
4406
4407 return true;
4408}
4409
4411 SourceLocation Loc,
4412 SourceRange ArgRange,
4413 UnaryExprOrTypeTrait TraitKind) {
4414 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4415 // runtime doesn't allow it.
4417 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4418 << T << (TraitKind == UETT_SizeOf)
4419 << ArgRange;
4420 return true;
4421 }
4422
4423 return false;
4424}
4425
4426/// Check whether E is a pointer from a decayed array type (the decayed
4427/// pointer type is equal to T) and emit a warning if it is.
4429 const Expr *E) {
4430 // Don't warn if the operation changed the type.
4431 if (T != E->getType())
4432 return;
4433
4434 // Now look for array decays.
4435 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4436 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4437 return;
4438
4439 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4440 << ICE->getType()
4441 << ICE->getSubExpr()->getType();
4442}
4443
4444/// Check the constraints on expression operands to unary type expression
4445/// and type traits.
4446///
4447/// Completes any types necessary and validates the constraints on the operand
4448/// expression. The logic mostly mirrors the type-based overload, but may modify
4449/// the expression as it completes the type for that expression through template
4450/// instantiation, etc.
4452 UnaryExprOrTypeTrait ExprKind) {
4453 QualType ExprTy = E->getType();
4454 assert(!ExprTy->isReferenceType());
4455
4456 bool IsUnevaluatedOperand =
4457 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4458 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4459 ExprKind == UETT_VecStep);
4460 if (IsUnevaluatedOperand) {
4462 if (Result.isInvalid())
4463 return true;
4464 E = Result.get();
4465 }
4466
4467 // The operand for sizeof and alignof is in an unevaluated expression context,
4468 // so side effects could result in unintended consequences.
4469 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4470 // used to build SFINAE gadgets.
4471 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4472 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4474 !E->getType()->isVariableArrayType() &&
4475 E->HasSideEffects(Context, false))
4476 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4477
4478 if (ExprKind == UETT_VecStep)
4479 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4480 E->getSourceRange());
4481
4482 if (ExprKind == UETT_VectorElements)
4483 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4484 E->getSourceRange());
4485
4486 // Explicitly list some types as extensions.
4487 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4488 E->getSourceRange(), ExprKind))
4489 return false;
4490
4491 // WebAssembly tables are always illegal operands to unary expressions and
4492 // type traits.
4493 if (Context.getTargetInfo().getTriple().isWasm() &&
4495 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4496 << getTraitSpelling(ExprKind);
4497 return true;
4498 }
4499
4500 // 'alignof' applied to an expression only requires the base element type of
4501 // the expression to be complete. 'sizeof' requires the expression's type to
4502 // be complete (and will attempt to complete it if it's an array of unknown
4503 // bound).
4504 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4507 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4508 getTraitSpelling(ExprKind), E->getSourceRange()))
4509 return true;
4510 } else {
4512 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4513 getTraitSpelling(ExprKind), E->getSourceRange()))
4514 return true;
4515 }
4516
4517 // Completing the expression's type may have changed it.
4518 ExprTy = E->getType();
4519 assert(!ExprTy->isReferenceType());
4520
4521 if (ExprTy->isFunctionType()) {
4522 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4523 << getTraitSpelling(ExprKind) << E->getSourceRange();
4524 return true;
4525 }
4526
4527 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4528 E->getSourceRange(), ExprKind))
4529 return true;
4530
4531 if (ExprKind == UETT_SizeOf) {
4532 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4533 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4534 QualType OType = PVD->getOriginalType();
4535 QualType Type = PVD->getType();
4536 if (Type->isPointerType() && OType->isArrayType()) {
4537 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4538 << Type << OType;
4539 Diag(PVD->getLocation(), diag::note_declared_at);
4540 }
4541 }
4542 }
4543
4544 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4545 // decays into a pointer and returns an unintended result. This is most
4546 // likely a typo for "sizeof(array) op x".
4547 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4548 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4549 BO->getLHS());
4550 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4551 BO->getRHS());
4552 }
4553 }
4554
4555 return false;
4556}
4557
4558static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4559 // Cannot know anything else if the expression is dependent.
4560 if (E->isTypeDependent())
4561 return false;
4562
4563 if (E->getObjectKind() == OK_BitField) {
4564 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4565 << 1 << E->getSourceRange();
4566 return true;
4567 }
4568
4569 ValueDecl *D = nullptr;
4570 Expr *Inner = E->IgnoreParens();
4571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4572 D = DRE->getDecl();
4573 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4574 D = ME->getMemberDecl();
4575 }
4576
4577 // If it's a field, require the containing struct to have a
4578 // complete definition so that we can compute the layout.
4579 //
4580 // This can happen in C++11 onwards, either by naming the member
4581 // in a way that is not transformed into a member access expression
4582 // (in an unevaluated operand, for instance), or by naming the member
4583 // in a trailing-return-type.
4584 //
4585 // For the record, since __alignof__ on expressions is a GCC
4586 // extension, GCC seems to permit this but always gives the
4587 // nonsensical answer 0.
4588 //
4589 // We don't really need the layout here --- we could instead just
4590 // directly check for all the appropriate alignment-lowing
4591 // attributes --- but that would require duplicating a lot of
4592 // logic that just isn't worth duplicating for such a marginal
4593 // use-case.
4594 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4595 // Fast path this check, since we at least know the record has a
4596 // definition if we can find a member of it.
4597 if (!FD->getParent()->isCompleteDefinition()) {
4598 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4599 << E->getSourceRange();
4600 return true;
4601 }
4602
4603 // Otherwise, if it's a field, and the field doesn't have
4604 // reference type, then it must have a complete type (or be a
4605 // flexible array member, which we explicitly want to
4606 // white-list anyway), which makes the following checks trivial.
4607 if (!FD->getType()->isReferenceType())
4608 return false;
4609 }
4610
4611 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4612}
4613
4615 E = E->IgnoreParens();
4616
4617 // Cannot know anything else if the expression is dependent.
4618 if (E->isTypeDependent())
4619 return false;
4620
4621 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4622}
4623
4625 CapturingScopeInfo *CSI) {
4626 assert(T->isVariablyModifiedType());
4627 assert(CSI != nullptr);
4628
4629 // We're going to walk down into the type and look for VLA expressions.
4630 do {
4631 const Type *Ty = T.getTypePtr();
4632 switch (Ty->getTypeClass()) {
4633#define TYPE(Class, Base)
4634#define ABSTRACT_TYPE(Class, Base)
4635#define NON_CANONICAL_TYPE(Class, Base)
4636#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4637#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4638#include "clang/AST/TypeNodes.inc"
4639 T = QualType();
4640 break;
4641 // These types are never variably-modified.
4642 case Type::Builtin:
4643 case Type::Complex:
4644 case Type::Vector:
4645 case Type::ExtVector:
4646 case Type::ConstantMatrix:
4647 case Type::Record:
4648 case Type::Enum:
4649 case Type::TemplateSpecialization:
4650 case Type::ObjCObject:
4651 case Type::ObjCInterface:
4652 case Type::ObjCObjectPointer:
4653 case Type::ObjCTypeParam:
4654 case Type::Pipe:
4655 case Type::BitInt:
4656 llvm_unreachable("type class is never variably-modified!");
4657 case Type::Elaborated:
4658 T = cast<ElaboratedType>(Ty)->getNamedType();
4659 break;
4660 case Type::Adjusted:
4661 T = cast<AdjustedType>(Ty)->getOriginalType();
4662 break;
4663 case Type::Decayed:
4664 T = cast<DecayedType>(Ty)->getPointeeType();
4665 break;
4666 case Type::Pointer:
4667 T = cast<PointerType>(Ty)->getPointeeType();
4668 break;
4669 case Type::BlockPointer:
4670 T = cast<BlockPointerType>(Ty)->getPointeeType();
4671 break;
4672 case Type::LValueReference:
4673 case Type::RValueReference:
4674 T = cast<ReferenceType>(Ty)->getPointeeType();
4675 break;
4676 case Type::MemberPointer:
4677 T = cast<MemberPointerType>(Ty)->getPointeeType();
4678 break;
4679 case Type::ConstantArray:
4680 case Type::IncompleteArray:
4681 // Losing element qualification here is fine.
4682 T = cast<ArrayType>(Ty)->getElementType();
4683 break;
4684 case Type::VariableArray: {
4685 // Losing element qualification here is fine.
4686 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4687
4688 // Unknown size indication requires no size computation.
4689 // Otherwise, evaluate and record it.
4690 auto Size = VAT->getSizeExpr();
4691 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4692 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4693 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4694
4695 T = VAT->getElementType();
4696 break;
4697 }
4698 case Type::FunctionProto:
4699 case Type::FunctionNoProto:
4700 T = cast<FunctionType>(Ty)->getReturnType();
4701 break;
4702 case Type::Paren:
4703 case Type::TypeOf:
4704 case Type::UnaryTransform:
4705 case Type::Attributed:
4706 case Type::BTFTagAttributed:
4707 case Type::SubstTemplateTypeParm:
4708 case Type::MacroQualified:
4709 // Keep walking after single level desugaring.
4710 T = T.getSingleStepDesugaredType(Context);
4711 break;
4712 case Type::Typedef:
4713 T = cast<TypedefType>(Ty)->desugar();
4714 break;
4715 case Type::Decltype:
4716 T = cast<DecltypeType>(Ty)->desugar();
4717 break;
4718 case Type::Using:
4719 T = cast<UsingType>(Ty)->desugar();
4720 break;
4721 case Type::Auto:
4722 case Type::DeducedTemplateSpecialization:
4723 T = cast<DeducedType>(Ty)->getDeducedType();
4724 break;
4725 case Type::TypeOfExpr:
4726 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4727 break;
4728 case Type::Atomic:
4729 T = cast<AtomicType>(Ty)->getValueType();
4730 break;
4731 }
4732 } while (!T.isNull() && T->isVariablyModifiedType());
4733}
4734
4735/// Check the constraints on operands to unary expression and type
4736/// traits.
4737///
4738/// This will complete any types necessary, and validate the various constraints
4739/// on those operands.
4740///
4741/// The UsualUnaryConversions() function is *not* called by this routine.
4742/// C99 6.3.2.1p[2-4] all state:
4743/// Except when it is the operand of the sizeof operator ...
4744///
4745/// C++ [expr.sizeof]p4
4746/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4747/// standard conversions are not applied to the operand of sizeof.
4748///
4749/// This policy is followed for all of the unary trait expressions.
4751 SourceLocation OpLoc,
4752 SourceRange ExprRange,
4753 UnaryExprOrTypeTrait ExprKind,
4754 StringRef KWName) {
4755 if (ExprType->isDependentType())
4756 return false;
4757
4758 // C++ [expr.sizeof]p2:
4759 // When applied to a reference or a reference type, the result
4760 // is the size of the referenced type.
4761 // C++11 [expr.alignof]p3:
4762 // When alignof is applied to a reference type, the result
4763 // shall be the alignment of the referenced type.
4764 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4765 ExprType = Ref->getPointeeType();
4766
4767 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4768 // When alignof or _Alignof is applied to an array type, the result
4769 // is the alignment of the element type.
4770 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4771 ExprKind == UETT_OpenMPRequiredSimdAlign)
4772 ExprType = Context.getBaseElementType(ExprType);
4773
4774 if (ExprKind == UETT_VecStep)
4775 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4776
4777 if (ExprKind == UETT_VectorElements)
4778 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4779 ExprRange);
4780
4781 // Explicitly list some types as extensions.
4782 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4783 ExprKind))
4784 return false;
4785
4787 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4788 KWName, ExprRange))
4789 return true;
4790
4791 if (ExprType->isFunctionType()) {
4792 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4793 return true;
4794 }
4795
4796 // WebAssembly tables are always illegal operands to unary expressions and
4797 // type traits.
4798 if (Context.getTargetInfo().getTriple().isWasm() &&
4799 ExprType->isWebAssemblyTableType()) {
4800 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4801 << getTraitSpelling(ExprKind);
4802 return true;
4803 }
4804
4805 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4806 ExprKind))
4807 return true;
4808
4809 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4810 if (auto *TT = ExprType->getAs<TypedefType>()) {
4811 for (auto I = FunctionScopes.rbegin(),
4812 E = std::prev(FunctionScopes.rend());
4813 I != E; ++I) {
4814 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4815 if (CSI == nullptr)
4816 break;
4817 DeclContext *DC = nullptr;
4818 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4819 DC = LSI->CallOperator;
4820 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4821 DC = CRSI->TheCapturedDecl;
4822 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4823 DC = BSI->TheDecl;
4824 if (DC) {
4825 if (DC->containsDecl(TT->getDecl()))
4826 break;
4827 captureVariablyModifiedType(Context, ExprType, CSI);
4828 }
4829 }
4830 }
4831 }
4832
4833 return false;
4834}
4835
4836/// Build a sizeof or alignof expression given a type operand.
4838 SourceLocation OpLoc,
4839 UnaryExprOrTypeTrait ExprKind,
4840 SourceRange R) {
4841 if (!TInfo)
4842 return ExprError();
4843
4844 QualType T = TInfo->getType();
4845
4846 if (!T->isDependentType() &&
4847 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4848 getTraitSpelling(ExprKind)))
4849 return ExprError();
4850
4851 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4852 // properly deal with VLAs in nested calls of sizeof and typeof.
4853 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4854 TInfo->getType()->isVariablyModifiedType())
4855 TInfo = TransformToPotentiallyEvaluated(TInfo);
4856
4857 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4858 return new (Context) UnaryExprOrTypeTraitExpr(
4859 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4860}
4861
4862/// Build a sizeof or alignof expression given an expression
4863/// operand.
4866 UnaryExprOrTypeTrait ExprKind) {
4868 if (PE.isInvalid())
4869 return ExprError();
4870
4871 E = PE.get();
4872
4873 // Verify that the operand is valid.
4874 bool isInvalid = false;
4875 if (E->isTypeDependent()) {
4876 // Delay type-checking for type-dependent expressions.
4877 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4878 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4879 } else if (ExprKind == UETT_VecStep) {
4881 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4882 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4883 isInvalid = true;
4884 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4885 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4886 isInvalid = true;
4887 } else if (ExprKind == UETT_VectorElements) {
4888 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4889 } else {
4891 }
4892
4893 if (isInvalid)
4894 return ExprError();
4895
4896 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4898 if (PE.isInvalid()) return ExprError();
4899 E = PE.get();
4900 }
4901
4902 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4903 return new (Context) UnaryExprOrTypeTraitExpr(
4904 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4905}
4906
4907/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4908/// expr and the same for @c alignof and @c __alignof
4909/// Note that the ArgRange is invalid if isType is false.
4912 UnaryExprOrTypeTrait ExprKind, bool IsType,
4913 void *TyOrEx, SourceRange ArgRange) {
4914 // If error parsing type, ignore.
4915 if (!TyOrEx) return ExprError();
4916
4917 if (IsType) {
4918 TypeSourceInfo *TInfo;
4919 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4920 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4921 }
4922
4923 Expr *ArgEx = (Expr *)TyOrEx;
4924 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4925 return Result;
4926}
4927
4929 SourceLocation OpLoc, SourceRange R) {
4930 if (!TInfo)
4931 return true;
4932 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4933 UETT_AlignOf, KWName);
4934}
4935
4936/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4937/// _Alignas(type-name) .
4938/// [dcl.align] An alignment-specifier of the form
4939/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4940///
4941/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4942/// _Alignas(_Alignof(type-name)).