clang 22.0.0git
SemaExprCXX.cpp
Go to the documentation of this file.
1//===--- SemaExprCXX.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/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/TypeLoc.h"
34#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Scope.h"
41#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/SemaHLSL.h"
44#include "clang/Sema/SemaObjC.h"
45#include "clang/Sema/SemaPPC.h"
46#include "clang/Sema/Template.h"
48#include "llvm/ADT/APInt.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TypeSize.h"
53#include <optional>
54using namespace clang;
55using namespace sema;
56
58 SourceLocation NameLoc,
59 const IdentifierInfo &Name) {
61 QualType Type(NNS.getAsType(), 0);
62 if ([[maybe_unused]] const auto *DNT = dyn_cast<DependentNameType>(Type))
63 assert(DNT->getIdentifier() == &Name && "not a constructor name");
64
65 // This reference to the type is located entirely at the location of the
66 // final identifier in the qualified-id.
69}
70
72 SourceLocation NameLoc, Scope *S,
73 CXXScopeSpec &SS, bool EnteringContext) {
74 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
75 assert(CurClass && &II == CurClass->getIdentifier() &&
76 "not a constructor name");
77
78 // When naming a constructor as a member of a dependent context (eg, in a
79 // friend declaration or an inherited constructor declaration), form an
80 // unresolved "typename" type.
81 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
83 SS.getScopeRep(), &II);
84 return ParsedType::make(T);
85 }
86
87 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
88 return ParsedType();
89
90 // Find the injected-class-name declaration. Note that we make no attempt to
91 // diagnose cases where the injected-class-name is shadowed: the only
92 // declaration that can validly shadow the injected-class-name is a
93 // non-static data member, and if the class contains both a non-static data
94 // member and a constructor then it is ill-formed (we check that in
95 // CheckCompletedCXXClass).
96 CXXRecordDecl *InjectedClassName = nullptr;
97 for (NamedDecl *ND : CurClass->lookup(&II)) {
98 auto *RD = dyn_cast<CXXRecordDecl>(ND);
99 if (RD && RD->isInjectedClassName()) {
100 InjectedClassName = RD;
101 break;
102 }
103 }
104 if (!InjectedClassName) {
105 if (!CurClass->isInvalidDecl()) {
106 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
107 // properly. Work around it here for now.
109 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
110 }
111 return ParsedType();
112 }
113
115 InjectedClassName, /*OwnsTag=*/false);
116 return ParsedType::make(T);
117}
118
120 SourceLocation NameLoc, Scope *S,
121 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
122 bool EnteringContext) {
123 // Determine where to perform name lookup.
124
125 // FIXME: This area of the standard is very messy, and the current
126 // wording is rather unclear about which scopes we search for the
127 // destructor name; see core issues 399 and 555. Issue 399 in
128 // particular shows where the current description of destructor name
129 // lookup is completely out of line with existing practice, e.g.,
130 // this appears to be ill-formed:
131 //
132 // namespace N {
133 // template <typename T> struct S {
134 // ~S();
135 // };
136 // }
137 //
138 // void f(N::S<int>* s) {
139 // s->N::S<int>::~S();
140 // }
141 //
142 // See also PR6358 and PR6359.
143 //
144 // For now, we accept all the cases in which the name given could plausibly
145 // be interpreted as a correct destructor name, issuing off-by-default
146 // extension diagnostics on the cases that don't strictly conform to the
147 // C++20 rules. This basically means we always consider looking in the
148 // nested-name-specifier prefix, the complete nested-name-specifier, and
149 // the scope, and accept if we find the expected type in any of the three
150 // places.
151
152 if (SS.isInvalid())
153 return nullptr;
154
155 // Whether we've failed with a diagnostic already.
156 bool Failed = false;
157
160
161 // If we have an object type, it's because we are in a
162 // pseudo-destructor-expression or a member access expression, and
163 // we know what type we're looking for.
164 QualType SearchType =
165 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
166
167 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
168 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
169 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
170 if (!Type)
171 return false;
172
173 if (SearchType.isNull() || SearchType->isDependentType())
174 return true;
175
177 return Context.hasSameUnqualifiedType(T, SearchType);
178 };
179
180 unsigned NumAcceptableResults = 0;
181 for (NamedDecl *D : Found) {
182 if (IsAcceptableResult(D))
183 ++NumAcceptableResults;
184
185 // Don't list a class twice in the lookup failure diagnostic if it's
186 // found by both its injected-class-name and by the name in the enclosing
187 // scope.
188 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
189 if (RD->isInjectedClassName())
190 D = cast<NamedDecl>(RD->getParent());
191
192 if (FoundDeclSet.insert(D).second)
193 FoundDecls.push_back(D);
194 }
195
196 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
197 // results, and all non-matching results if we have a search type. It's not
198 // clear what the right behavior is if destructor lookup hits an ambiguity,
199 // but other compilers do generally accept at least some kinds of
200 // ambiguity.
201 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
202 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
203 LookupResult::Filter F = Found.makeFilter();
204 while (F.hasNext()) {
205 NamedDecl *D = F.next();
206 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
207 Diag(D->getLocation(), diag::note_destructor_type_here)
209 /*Qualifier=*/std::nullopt, TD);
210 else
211 Diag(D->getLocation(), diag::note_destructor_nontype_here);
212
213 if (!IsAcceptableResult(D))
214 F.erase();
215 }
216 F.done();
217 }
218
219 if (Found.isAmbiguous())
220 Failed = true;
221
222 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
223 if (IsAcceptableResult(Type)) {
225 /*Qualifier=*/std::nullopt, Type);
226 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
227 return CreateParsedType(T,
229 }
230 }
231
232 return nullptr;
233 };
234
235 bool IsDependent = false;
236
237 auto LookupInObjectType = [&]() -> ParsedType {
238 if (Failed || SearchType.isNull())
239 return nullptr;
240
241 IsDependent |= SearchType->isDependentType();
242
243 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
244 DeclContext *LookupCtx = computeDeclContext(SearchType);
245 if (!LookupCtx)
246 return nullptr;
247 LookupQualifiedName(Found, LookupCtx);
248 return CheckLookupResult(Found);
249 };
250
251 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
252 if (Failed)
253 return nullptr;
254
255 IsDependent |= isDependentScopeSpecifier(LookupSS);
256 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
257 if (!LookupCtx)
258 return nullptr;
259
260 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
261 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
262 Failed = true;
263 return nullptr;
264 }
265 LookupQualifiedName(Found, LookupCtx);
266 return CheckLookupResult(Found);
267 };
268
269 auto LookupInScope = [&]() -> ParsedType {
270 if (Failed || !S)
271 return nullptr;
272
273 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
274 LookupName(Found, S);
275 return CheckLookupResult(Found);
276 };
277
278 // C++2a [basic.lookup.qual]p6:
279 // In a qualified-id of the form
280 //
281 // nested-name-specifier[opt] type-name :: ~ type-name
282 //
283 // the second type-name is looked up in the same scope as the first.
284 //
285 // We interpret this as meaning that if you do a dual-scope lookup for the
286 // first name, you also do a dual-scope lookup for the second name, per
287 // C++ [basic.lookup.classref]p4:
288 //
289 // If the id-expression in a class member access is a qualified-id of the
290 // form
291 //
292 // class-name-or-namespace-name :: ...
293 //
294 // the class-name-or-namespace-name following the . or -> is first looked
295 // up in the class of the object expression and the name, if found, is used.
296 // Otherwise, it is looked up in the context of the entire
297 // postfix-expression.
298 //
299 // This looks in the same scopes as for an unqualified destructor name:
300 //
301 // C++ [basic.lookup.classref]p3:
302 // If the unqualified-id is ~ type-name, the type-name is looked up
303 // in the context of the entire postfix-expression. If the type T
304 // of the object expression is of a class type C, the type-name is
305 // also looked up in the scope of class C. At least one of the
306 // lookups shall find a name that refers to cv T.
307 //
308 // FIXME: The intent is unclear here. Should type-name::~type-name look in
309 // the scope anyway if it finds a non-matching name declared in the class?
310 // If both lookups succeed and find a dependent result, which result should
311 // we retain? (Same question for p->~type-name().)
312
313 auto Prefix = [&]() -> NestedNameSpecifierLoc {
315 if (!NNS)
316 return NestedNameSpecifierLoc();
317 if (auto TL = NNS.getAsTypeLoc())
318 return TL.getPrefix();
319 return NNS.getAsNamespaceAndPrefix().Prefix;
320 }();
321
322 if (Prefix) {
323 // This is
324 //
325 // nested-name-specifier type-name :: ~ type-name
326 //
327 // Look for the second type-name in the nested-name-specifier.
328 CXXScopeSpec PrefixSS;
329 PrefixSS.Adopt(Prefix);
330 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
331 return T;
332 } else {
333 // This is one of
334 //
335 // type-name :: ~ type-name
336 // ~ type-name
337 //
338 // Look in the scope and (if any) the object type.
339 if (ParsedType T = LookupInScope())
340 return T;
341 if (ParsedType T = LookupInObjectType())
342 return T;
343 }
344
345 if (Failed)
346 return nullptr;
347
348 if (IsDependent) {
349 // We didn't find our type, but that's OK: it's dependent anyway.
350
351 // FIXME: What if we have no nested-name-specifier?
352 TypeSourceInfo *TSI = nullptr;
353 QualType T =
355 SS.getWithLocInContext(Context), II, NameLoc, &TSI,
356 /*DeducedTSTContext=*/true);
357 return CreateParsedType(T, TSI);
358 }
359
360 // The remaining cases are all non-standard extensions imitating the behavior
361 // of various other compilers.
362 unsigned NumNonExtensionDecls = FoundDecls.size();
363
364 if (SS.isSet()) {
365 // For compatibility with older broken C++ rules and existing code,
366 //
367 // nested-name-specifier :: ~ type-name
368 //
369 // also looks for type-name within the nested-name-specifier.
370 if (ParsedType T = LookupInNestedNameSpec(SS)) {
371 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
372 << SS.getRange()
374 ("::" + II.getName()).str());
375 return T;
376 }
377
378 // For compatibility with other compilers and older versions of Clang,
379 //
380 // nested-name-specifier type-name :: ~ type-name
381 //
382 // also looks for type-name in the scope. Unfortunately, we can't
383 // reasonably apply this fallback for dependent nested-name-specifiers.
384 if (Prefix) {
385 if (ParsedType T = LookupInScope()) {
386 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
388 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
390 return T;
391 }
392 }
393 }
394
395 // We didn't find anything matching; tell the user what we did find (if
396 // anything).
397
398 // Don't tell the user about declarations we shouldn't have found.
399 FoundDecls.resize(NumNonExtensionDecls);
400
401 // List types before non-types.
402 llvm::stable_sort(FoundDecls, [](NamedDecl *A, NamedDecl *B) {
403 return isa<TypeDecl>(A->getUnderlyingDecl()) >
404 isa<TypeDecl>(B->getUnderlyingDecl());
405 });
406
407 // Suggest a fixit to properly name the destroyed type.
408 auto MakeFixItHint = [&]{
409 const CXXRecordDecl *Destroyed = nullptr;
410 // FIXME: If we have a scope specifier, suggest its last component?
411 if (!SearchType.isNull())
412 Destroyed = SearchType->getAsCXXRecordDecl();
413 else if (S)
414 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
415 if (Destroyed)
417 Destroyed->getNameAsString());
418 return FixItHint();
419 };
420
421 if (FoundDecls.empty()) {
422 // FIXME: Attempt typo-correction?
423 Diag(NameLoc, diag::err_undeclared_destructor_name)
424 << &II << MakeFixItHint();
425 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
426 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
427 assert(!SearchType.isNull() &&
428 "should only reject a type result if we have a search type");
429 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
431 /*Qualifier=*/std::nullopt, TD)
432 << SearchType << MakeFixItHint();
433 } else {
434 Diag(NameLoc, diag::err_destructor_expr_nontype)
435 << &II << MakeFixItHint();
436 }
437 } else {
438 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
439 : diag::err_destructor_expr_mismatch)
440 << &II << SearchType << MakeFixItHint();
441 }
442
443 for (NamedDecl *FoundD : FoundDecls) {
444 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
445 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
447 /*Qualifier=*/std::nullopt, TD);
448 else
449 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
450 << FoundD;
451 }
452
453 return nullptr;
454}
455
457 ParsedType ObjectType) {
459 return nullptr;
460
462 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
463 return nullptr;
464 }
465
467 "unexpected type in getDestructorType");
469
470 // If we know the type of the object, check that the correct destructor
471 // type was named now; we can give better diagnostics this way.
472 QualType SearchType = GetTypeFromParser(ObjectType);
473 if (!SearchType.isNull() && !SearchType->isDependentType() &&
474 !Context.hasSameUnqualifiedType(T, SearchType)) {
475 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
476 << T << SearchType;
477 return nullptr;
478 }
479
480 return ParsedType::make(T);
481}
482
484 const UnqualifiedId &Name, bool IsUDSuffix) {
485 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
486 if (!IsUDSuffix) {
487 // [over.literal] p8
488 //
489 // double operator""_Bq(long double); // OK: not a reserved identifier
490 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
491 const IdentifierInfo *II = Name.Identifier;
493 SourceLocation Loc = Name.getEndLoc();
494
496 Name.getSourceRange(),
497 (StringRef("operator\"\"") + II->getName()).str());
498
499 // Only emit this diagnostic if we start with an underscore, else the
500 // diagnostic for C++11 requiring a space between the quotes and the
501 // identifier conflicts with this and gets confusing. The diagnostic stating
502 // this is a reserved name should force the underscore, which gets this
503 // back.
504 if (II->isReservedLiteralSuffixId() !=
506 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
507
508 if (isReservedInAllContexts(Status))
509 Diag(Loc, diag::warn_reserved_extern_symbol)
510 << II << static_cast<int>(Status) << Hint;
511 }
512
513 switch (SS.getScopeRep().getKind()) {
515 // Per C++11 [over.literal]p2, literal operators can only be declared at
516 // namespace scope. Therefore, this unqualified-id cannot name anything.
517 // Reject it early, because we have no AST representation for this in the
518 // case where the scope is dependent.
519 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
520 << SS.getScopeRep();
521 return true;
522
527 return false;
528 }
529
530 llvm_unreachable("unknown nested name specifier kind");
531}
532
534 SourceLocation TypeidLoc,
535 TypeSourceInfo *Operand,
536 SourceLocation RParenLoc) {
537 // C++ [expr.typeid]p4:
538 // The top-level cv-qualifiers of the lvalue expression or the type-id
539 // that is the operand of typeid are always ignored.
540 // If the type of the type-id is a class type or a reference to a class
541 // type, the class shall be completely-defined.
542 Qualifiers Quals;
543 QualType T
544 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
545 Quals);
546 if (T->isRecordType() &&
547 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
548 return ExprError();
549
551 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
552
553 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
554 return ExprError();
555
556 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
557 SourceRange(TypeidLoc, RParenLoc));
558}
559
561 SourceLocation TypeidLoc,
562 Expr *E,
563 SourceLocation RParenLoc) {
564 bool WasEvaluated = false;
565 if (E && !E->isTypeDependent()) {
566 if (E->hasPlaceholderType()) {
568 if (result.isInvalid()) return ExprError();
569 E = result.get();
570 }
571
572 QualType T = E->getType();
573 if (auto *RecordD = T->getAsCXXRecordDecl()) {
574 // C++ [expr.typeid]p3:
575 // [...] If the type of the expression is a class type, the class
576 // shall be completely-defined.
577 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
578 return ExprError();
579
580 // C++ [expr.typeid]p3:
581 // When typeid is applied to an expression other than an glvalue of a
582 // polymorphic class type [...] [the] expression is an unevaluated
583 // operand. [...]
584 if (RecordD->isPolymorphic() && E->isGLValue()) {
585 if (isUnevaluatedContext()) {
586 // The operand was processed in unevaluated context, switch the
587 // context and recheck the subexpression.
589 if (Result.isInvalid())
590 return ExprError();
591 E = Result.get();
592 }
593
594 // We require a vtable to query the type at run time.
595 MarkVTableUsed(TypeidLoc, RecordD);
596 WasEvaluated = true;
597 }
598 }
599
601 if (Result.isInvalid())
602 return ExprError();
603 E = Result.get();
604
605 // C++ [expr.typeid]p4:
606 // [...] If the type of the type-id is a reference to a possibly
607 // cv-qualified type, the result of the typeid expression refers to a
608 // std::type_info object representing the cv-unqualified referenced
609 // type.
610 Qualifiers Quals;
611 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
612 if (!Context.hasSameType(T, UnqualT)) {
613 T = UnqualT;
614 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
615 }
616 }
617
619 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
620 << E->getType());
621 else if (!inTemplateInstantiation() &&
622 E->HasSideEffects(Context, WasEvaluated)) {
623 // The expression operand for typeid is in an unevaluated expression
624 // context, so side effects could result in unintended consequences.
625 Diag(E->getExprLoc(), WasEvaluated
626 ? diag::warn_side_effects_typeid
627 : diag::warn_side_effects_unevaluated_context);
628 }
629
630 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
631 SourceRange(TypeidLoc, RParenLoc));
632}
633
634/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
637 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
638 // typeid is not supported in OpenCL.
639 if (getLangOpts().OpenCLCPlusPlus) {
640 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
641 << "typeid");
642 }
643
644 // Find the std::type_info type.
645 if (!getStdNamespace())
646 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
647
648 if (!CXXTypeInfoDecl) {
649 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
650 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
653 // Microsoft's typeinfo doesn't have type_info in std but in the global
654 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
655 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
658 }
659 if (!CXXTypeInfoDecl)
660 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
661 }
662
663 if (!getLangOpts().RTTI) {
664 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
665 }
666
668
669 if (isType) {
670 // The operand is a type; handle it as such.
671 TypeSourceInfo *TInfo = nullptr;
673 &TInfo);
674 if (T.isNull())
675 return ExprError();
676
677 if (!TInfo)
678 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
679
680 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
681 }
682
683 // The operand is an expression.
685 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
686
687 if (!getLangOpts().RTTIData && !Result.isInvalid())
688 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
689 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
690 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
691 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
693 return Result;
694}
695
696/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
697/// a single GUID.
698static void
701 // Optionally remove one level of pointer, reference or array indirection.
702 const Type *Ty = QT.getTypePtr();
703 if (QT->isPointerOrReferenceType())
704 Ty = QT->getPointeeType().getTypePtr();
705 else if (QT->isArrayType())
706 Ty = Ty->getBaseElementTypeUnsafe();
707
708 const auto *TD = Ty->getAsTagDecl();
709 if (!TD)
710 return;
711
712 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
713 UuidAttrs.insert(Uuid);
714 return;
715 }
716
717 // __uuidof can grab UUIDs from template arguments.
718 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
719 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
720 for (const TemplateArgument &TA : TAL.asArray()) {
721 const UuidAttr *UuidForTA = nullptr;
722 if (TA.getKind() == TemplateArgument::Type)
723 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
724 else if (TA.getKind() == TemplateArgument::Declaration)
725 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
726
727 if (UuidForTA)
728 UuidAttrs.insert(UuidForTA);
729 }
730 }
731}
732
734 SourceLocation TypeidLoc,
735 TypeSourceInfo *Operand,
736 SourceLocation RParenLoc) {
737 MSGuidDecl *Guid = nullptr;
738 if (!Operand->getType()->isDependentType()) {
740 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
741 if (UuidAttrs.empty())
742 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
743 if (UuidAttrs.size() > 1)
744 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
745 Guid = UuidAttrs.back()->getGuidDecl();
746 }
747
748 return new (Context)
749 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
750}
751
753 Expr *E, SourceLocation RParenLoc) {
754 MSGuidDecl *Guid = nullptr;
755 if (!E->getType()->isDependentType()) {
757 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
759 } else {
761 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
762 if (UuidAttrs.empty())
763 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
764 if (UuidAttrs.size() > 1)
765 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
766 Guid = UuidAttrs.back()->getGuidDecl();
767 }
768 }
769
770 return new (Context)
771 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
772}
773
774/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
777 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
778 QualType GuidType = Context.getMSGuidType();
779 GuidType.addConst();
780
781 if (isType) {
782 // The operand is a type; handle it as such.
783 TypeSourceInfo *TInfo = nullptr;
785 &TInfo);
786 if (T.isNull())
787 return ExprError();
788
789 if (!TInfo)
790 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
791
792 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
793 }
794
795 // The operand is an expression.
796 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
797}
798
801 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
802 "Unknown C++ Boolean value!");
803 return new (Context)
804 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
805}
806
810}
811
814 bool IsThrownVarInScope = false;
815 if (Ex) {
816 // C++0x [class.copymove]p31:
817 // When certain criteria are met, an implementation is allowed to omit the
818 // copy/move construction of a class object [...]
819 //
820 // - in a throw-expression, when the operand is the name of a
821 // non-volatile automatic object (other than a function or catch-
822 // clause parameter) whose scope does not extend beyond the end of the
823 // innermost enclosing try-block (if there is one), the copy/move
824 // operation from the operand to the exception object (15.1) can be
825 // omitted by constructing the automatic object directly into the
826 // exception object
827 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
828 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
829 Var && Var->hasLocalStorage() &&
830 !Var->getType().isVolatileQualified()) {
831 for (; S; S = S->getParent()) {
832 if (S->isDeclScope(Var)) {
833 IsThrownVarInScope = true;
834 break;
835 }
836
837 // FIXME: Many of the scope checks here seem incorrect.
838 if (S->getFlags() &
841 break;
842 }
843 }
844 }
845
846 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
847}
848
850 bool IsThrownVarInScope) {
851 const llvm::Triple &T = Context.getTargetInfo().getTriple();
852 const bool IsOpenMPGPUTarget =
853 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
854
855 DiagnoseExceptionUse(OpLoc, /* IsTry= */ false);
856
857 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
858 if (IsOpenMPGPUTarget)
859 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
860
861 // Exceptions aren't allowed in CUDA device code.
862 if (getLangOpts().CUDA)
863 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
864 << "throw" << CUDA().CurrentTarget();
865
866 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
867 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
868
869 // Exceptions that escape a compute construct are ill-formed.
870 if (getLangOpts().OpenACC && getCurScope() &&
871 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
872 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
873 << /*throw*/ 2 << /*out of*/ 0;
874
875 if (Ex && !Ex->isTypeDependent()) {
876 // Initialize the exception result. This implicitly weeds out
877 // abstract types or types with inaccessible copy constructors.
878
879 // C++0x [class.copymove]p31:
880 // When certain criteria are met, an implementation is allowed to omit the
881 // copy/move construction of a class object [...]
882 //
883 // - in a throw-expression, when the operand is the name of a
884 // non-volatile automatic object (other than a function or
885 // catch-clause
886 // parameter) whose scope does not extend beyond the end of the
887 // innermost enclosing try-block (if there is one), the copy/move
888 // operation from the operand to the exception object (15.1) can be
889 // omitted by constructing the automatic object directly into the
890 // exception object
891 NamedReturnInfo NRInfo =
892 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
893
894 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
895 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
896 return ExprError();
897
898 InitializedEntity Entity =
899 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
900 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
901 if (Res.isInvalid())
902 return ExprError();
903 Ex = Res.get();
904 }
905
906 // PPC MMA non-pointer types are not allowed as throw expr types.
907 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
908 PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
909
910 return new (Context)
911 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
912}
913
914static void
916 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
917 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
918 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
919 bool ParentIsPublic) {
920 for (const CXXBaseSpecifier &BS : RD->bases()) {
921 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
922 bool NewSubobject;
923 // Virtual bases constitute the same subobject. Non-virtual bases are
924 // always distinct subobjects.
925 if (BS.isVirtual())
926 NewSubobject = VBases.insert(BaseDecl).second;
927 else
928 NewSubobject = true;
929
930 if (NewSubobject)
931 ++SubobjectsSeen[BaseDecl];
932
933 // Only add subobjects which have public access throughout the entire chain.
934 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
935 if (PublicPath)
936 PublicSubobjectsSeen.insert(BaseDecl);
937
938 // Recurse on to each base subobject.
939 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
940 PublicPath);
941 }
942}
943
946 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
948 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
949 SubobjectsSeen[RD] = 1;
950 PublicSubobjectsSeen.insert(RD);
951 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
952 /*ParentIsPublic=*/true);
953
954 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
955 // Skip ambiguous objects.
956 if (SubobjectsSeen[PublicSubobject] > 1)
957 continue;
958
959 Objects.push_back(PublicSubobject);
960 }
961}
962
964 QualType ExceptionObjectTy, Expr *E) {
965 // If the type of the exception would be an incomplete type or a pointer
966 // to an incomplete type other than (cv) void the program is ill-formed.
967 QualType Ty = ExceptionObjectTy;
968 bool isPointer = false;
969 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
970 Ty = Ptr->getPointeeType();
971 isPointer = true;
972 }
973
974 // Cannot throw WebAssembly reference type.
976 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
977 return true;
978 }
979
980 // Cannot throw WebAssembly table.
981 if (isPointer && Ty.isWebAssemblyReferenceType()) {
982 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
983 return true;
984 }
985
986 if (!isPointer || !Ty->isVoidType()) {
987 if (RequireCompleteType(ThrowLoc, Ty,
988 isPointer ? diag::err_throw_incomplete_ptr
989 : diag::err_throw_incomplete,
990 E->getSourceRange()))
991 return true;
992
993 if (!isPointer && Ty->isSizelessType()) {
994 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
995 return true;
996 }
997
998 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
999 diag::err_throw_abstract_type, E))
1000 return true;
1001 }
1002
1003 // If the exception has class type, we need additional handling.
1005 if (!RD)
1006 return false;
1007
1008 // If we are throwing a polymorphic class type or pointer thereof,
1009 // exception handling will make use of the vtable.
1010 MarkVTableUsed(ThrowLoc, RD);
1011
1012 // If a pointer is thrown, the referenced object will not be destroyed.
1013 if (isPointer)
1014 return false;
1015
1016 // If the class has a destructor, we must be able to call it.
1017 if (!RD->hasIrrelevantDestructor()) {
1021 PDiag(diag::err_access_dtor_exception) << Ty);
1023 return true;
1024 }
1025 }
1026
1027 // The MSVC ABI creates a list of all types which can catch the exception
1028 // object. This list also references the appropriate copy constructor to call
1029 // if the object is caught by value and has a non-trivial copy constructor.
1031 // We are only interested in the public, unambiguous bases contained within
1032 // the exception object. Bases which are ambiguous or otherwise
1033 // inaccessible are not catchable types.
1034 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1035 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1036
1037 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1038 // Attempt to lookup the copy constructor. Various pieces of machinery
1039 // will spring into action, like template instantiation, which means this
1040 // cannot be a simple walk of the class's decls. Instead, we must perform
1041 // lookup and overload resolution.
1042 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1043 if (!CD || CD->isDeleted())
1044 continue;
1045
1046 // Mark the constructor referenced as it is used by this throw expression.
1048
1049 // Skip this copy constructor if it is trivial, we don't need to record it
1050 // in the catchable type data.
1051 if (CD->isTrivial())
1052 continue;
1053
1054 // The copy constructor is non-trivial, create a mapping from this class
1055 // type to this constructor.
1056 // N.B. The selection of copy constructor is not sensitive to this
1057 // particular throw-site. Lookup will be performed at the catch-site to
1058 // ensure that the copy constructor is, in fact, accessible (via
1059 // friendship or any other means).
1061
1062 // We don't keep the instantiated default argument expressions around so
1063 // we must rebuild them here.
1064 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1065 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1066 return true;
1067 }
1068 }
1069 }
1070
1071 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1072 // the runtime with no ability for the compiler to request additional
1073 // alignment. Warn if the exception type requires alignment beyond the minimum
1074 // guaranteed by the target C++ runtime.
1076 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1077 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1078 if (ExnObjAlign < TypeAlign) {
1079 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1080 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1081 << Ty << (unsigned)TypeAlign.getQuantity()
1082 << (unsigned)ExnObjAlign.getQuantity();
1083 }
1084 }
1085 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1086 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1087 auto Ty = Dtor->getType();
1088 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1089 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1090 !FT->isNothrow())
1091 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1092 }
1093 }
1094 }
1095
1096 return false;
1097}
1098
1100 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1101 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1102
1103 QualType ClassType = ThisTy->getPointeeType();
1104 LambdaScopeInfo *CurLSI = nullptr;
1105 DeclContext *CurDC = CurSemaContext;
1106
1107 // Iterate through the stack of lambdas starting from the innermost lambda to
1108 // the outermost lambda, checking if '*this' is ever captured by copy - since
1109 // that could change the cv-qualifiers of the '*this' object.
1110 // The object referred to by '*this' starts out with the cv-qualifiers of its
1111 // member function. We then start with the innermost lambda and iterate
1112 // outward checking to see if any lambda performs a by-copy capture of '*this'
1113 // - and if so, any nested lambda must respect the 'constness' of that
1114 // capturing lamdbda's call operator.
1115 //
1116
1117 // Since the FunctionScopeInfo stack is representative of the lexical
1118 // nesting of the lambda expressions during initial parsing (and is the best
1119 // place for querying information about captures about lambdas that are
1120 // partially processed) and perhaps during instantiation of function templates
1121 // that contain lambda expressions that need to be transformed BUT not
1122 // necessarily during instantiation of a nested generic lambda's function call
1123 // operator (which might even be instantiated at the end of the TU) - at which
1124 // time the DeclContext tree is mature enough to query capture information
1125 // reliably - we use a two pronged approach to walk through all the lexically
1126 // enclosing lambda expressions:
1127 //
1128 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1129 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1130 // enclosed by the call-operator of the LSI below it on the stack (while
1131 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1132 // the stack represents the innermost lambda.
1133 //
1134 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1135 // represents a lambda's call operator. If it does, we must be instantiating
1136 // a generic lambda's call operator (represented by the Current LSI, and
1137 // should be the only scenario where an inconsistency between the LSI and the
1138 // DeclContext should occur), so climb out the DeclContexts if they
1139 // represent lambdas, while querying the corresponding closure types
1140 // regarding capture information.
1141
1142 // 1) Climb down the function scope info stack.
1143 for (int I = FunctionScopes.size();
1144 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1145 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1146 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1147 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1148 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1149
1150 if (!CurLSI->isCXXThisCaptured())
1151 continue;
1152
1153 auto C = CurLSI->getCXXThisCapture();
1154
1155 if (C.isCopyCapture()) {
1156 if (CurLSI->lambdaCaptureShouldBeConst())
1157 ClassType.addConst();
1158 return ASTCtx.getPointerType(ClassType);
1159 }
1160 }
1161
1162 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1163 // can happen during instantiation of its nested generic lambda call
1164 // operator); 2. if we're in a lambda scope (lambda body).
1165 if (CurLSI && isLambdaCallOperator(CurDC)) {
1167 "While computing 'this' capture-type for a generic lambda, when we "
1168 "run out of enclosing LSI's, yet the enclosing DC is a "
1169 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1170 "lambda call oeprator");
1171 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1172
1173 auto IsThisCaptured =
1174 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1175 IsConst = false;
1176 IsByCopy = false;
1177 for (auto &&C : Closure->captures()) {
1178 if (C.capturesThis()) {
1179 if (C.getCaptureKind() == LCK_StarThis)
1180 IsByCopy = true;
1181 if (Closure->getLambdaCallOperator()->isConst())
1182 IsConst = true;
1183 return true;
1184 }
1185 }
1186 return false;
1187 };
1188
1189 bool IsByCopyCapture = false;
1190 bool IsConstCapture = false;
1191 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1192 while (Closure &&
1193 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1194 if (IsByCopyCapture) {
1195 if (IsConstCapture)
1196 ClassType.addConst();
1197 return ASTCtx.getPointerType(ClassType);
1198 }
1199 Closure = isLambdaCallOperator(Closure->getParent())
1200 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1201 : nullptr;
1202 }
1203 }
1204 return ThisTy;
1205}
1206
1210
1211 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1212 if (method && method->isImplicitObjectMemberFunction())
1213 ThisTy = method->getThisType().getNonReferenceType();
1214 }
1215
1217 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1218
1219 // This is a lambda call operator that is being instantiated as a default
1220 // initializer. DC must point to the enclosing class type, so we can recover
1221 // the 'this' type from it.
1222 CanQualType ClassTy = Context.getCanonicalTagType(cast<CXXRecordDecl>(DC));
1223 // There are no cv-qualifiers for 'this' within default initializers,
1224 // per [expr.prim.general]p4.
1225 ThisTy = Context.getPointerType(ClassTy);
1226 }
1227
1228 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1229 // might need to be adjusted if the lambda or any of its enclosing lambda's
1230 // captures '*this' by copy.
1231 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1234 return ThisTy;
1235}
1236
1238 Decl *ContextDecl,
1239 Qualifiers CXXThisTypeQuals,
1240 bool Enabled)
1241 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1242{
1243 if (!Enabled || !ContextDecl)
1244 return;
1245
1246 CXXRecordDecl *Record = nullptr;
1247 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1248 Record = Template->getTemplatedDecl();
1249 else
1250 Record = cast<CXXRecordDecl>(ContextDecl);
1251
1253 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1254
1256 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1257
1258 this->Enabled = true;
1259}
1260
1261
1263 if (Enabled) {
1264 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1265 }
1266}
1267
1269 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1270 assert(!LSI->isCXXThisCaptured());
1271 // [=, this] {}; // until C++20: Error: this when = is the default
1273 !Sema.getLangOpts().CPlusPlus20)
1274 return;
1275 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1277 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1278}
1279
1281 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1282 const bool ByCopy) {
1283 // We don't need to capture this in an unevaluated context.
1285 return true;
1286
1287 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1288
1289 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1290 ? *FunctionScopeIndexToStopAt
1291 : FunctionScopes.size() - 1;
1292
1293 // Check that we can capture the *enclosing object* (referred to by '*this')
1294 // by the capturing-entity/closure (lambda/block/etc) at
1295 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1296
1297 // Note: The *enclosing object* can only be captured by-value by a
1298 // closure that is a lambda, using the explicit notation:
1299 // [*this] { ... }.
1300 // Every other capture of the *enclosing object* results in its by-reference
1301 // capture.
1302
1303 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1304 // stack), we can capture the *enclosing object* only if:
1305 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1306 // - or, 'L' has an implicit capture.
1307 // AND
1308 // -- there is no enclosing closure
1309 // -- or, there is some enclosing closure 'E' that has already captured the
1310 // *enclosing object*, and every intervening closure (if any) between 'E'
1311 // and 'L' can implicitly capture the *enclosing object*.
1312 // -- or, every enclosing closure can implicitly capture the
1313 // *enclosing object*
1314
1315
1316 unsigned NumCapturingClosures = 0;
1317 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1318 if (CapturingScopeInfo *CSI =
1319 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1320 if (CSI->CXXThisCaptureIndex != 0) {
1321 // 'this' is already being captured; there isn't anything more to do.
1322 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1323 break;
1324 }
1325 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1327 // This context can't implicitly capture 'this'; fail out.
1328 if (BuildAndDiagnose) {
1330 Diag(Loc, diag::err_this_capture)
1331 << (Explicit && idx == MaxFunctionScopesIndex);
1332 if (!Explicit)
1333 buildLambdaThisCaptureFixit(*this, LSI);
1334 }
1335 return true;
1336 }
1337 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1338 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1339 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1340 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1341 (Explicit && idx == MaxFunctionScopesIndex)) {
1342 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1343 // iteration through can be an explicit capture, all enclosing closures,
1344 // if any, must perform implicit captures.
1345
1346 // This closure can capture 'this'; continue looking upwards.
1347 NumCapturingClosures++;
1348 continue;
1349 }
1350 // This context can't implicitly capture 'this'; fail out.
1351 if (BuildAndDiagnose) {
1353 Diag(Loc, diag::err_this_capture)
1354 << (Explicit && idx == MaxFunctionScopesIndex);
1355 }
1356 if (!Explicit)
1357 buildLambdaThisCaptureFixit(*this, LSI);
1358 return true;
1359 }
1360 break;
1361 }
1362 if (!BuildAndDiagnose) return false;
1363
1364 // If we got here, then the closure at MaxFunctionScopesIndex on the
1365 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1366 // (including implicit by-reference captures in any enclosing closures).
1367
1368 // In the loop below, respect the ByCopy flag only for the closure requesting
1369 // the capture (i.e. first iteration through the loop below). Ignore it for
1370 // all enclosing closure's up to NumCapturingClosures (since they must be
1371 // implicitly capturing the *enclosing object* by reference (see loop
1372 // above)).
1373 assert((!ByCopy ||
1374 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1375 "Only a lambda can capture the enclosing object (referred to by "
1376 "*this) by copy");
1377 QualType ThisTy = getCurrentThisType();
1378 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1379 --idx, --NumCapturingClosures) {
1380 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1381
1382 // The type of the corresponding data member (not a 'this' pointer if 'by
1383 // copy').
1384 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1385
1386 bool isNested = NumCapturingClosures > 1;
1387 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1388 }
1389 return false;
1390}
1391
1393 // C++20 [expr.prim.this]p1:
1394 // The keyword this names a pointer to the object for which an
1395 // implicit object member function is invoked or a non-static
1396 // data member's initializer is evaluated.
1397 QualType ThisTy = getCurrentThisType();
1398
1399 if (CheckCXXThisType(Loc, ThisTy))
1400 return ExprError();
1401
1402 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1403}
1404
1406 if (!Type.isNull())
1407 return false;
1408
1409 // C++20 [expr.prim.this]p3:
1410 // If a declaration declares a member function or member function template
1411 // of a class X, the expression this is a prvalue of type
1412 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1413 // the optional cv-qualifier-seq and the end of the function-definition,
1414 // member-declarator, or declarator. It shall not appear within the
1415 // declaration of either a static member function or an explicit object
1416 // member function of the current class (although its type and value
1417 // category are defined within such member functions as they are within
1418 // an implicit object member function).
1420 const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1421 if (Method && Method->isExplicitObjectMemberFunction()) {
1422 Diag(Loc, diag::err_invalid_this_use) << 1;
1424 Diag(Loc, diag::err_invalid_this_use) << 1;
1425 } else {
1426 Diag(Loc, diag::err_invalid_this_use) << 0;
1427 }
1428 return true;
1429}
1430
1432 bool IsImplicit) {
1433 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1435 return This;
1436}
1437
1439 CheckCXXThisCapture(This->getExprLoc());
1440 if (This->isTypeDependent())
1441 return;
1442
1443 // Check if 'this' is captured by value in a lambda with a dependent explicit
1444 // object parameter, and mark it as type-dependent as well if so.
1445 auto IsDependent = [&]() {
1446 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1447 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1448 if (!LSI)
1449 continue;
1450
1451 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1452 LSI->AfterParameterList)
1453 return false;
1454
1455 // If this lambda captures 'this' by value, then 'this' is dependent iff
1456 // this lambda has a dependent explicit object parameter. If we can't
1457 // determine whether it does (e.g. because the CXXMethodDecl's type is
1458 // null), assume it doesn't.
1459 if (LSI->isCXXThisCaptured()) {
1460 if (!LSI->getCXXThisCapture().isCopyCapture())
1461 continue;
1462
1463 const auto *MD = LSI->CallOperator;
1464 if (MD->getType().isNull())
1465 return false;
1466
1467 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1468 return Ty && MD->isExplicitObjectMemberFunction() &&
1469 Ty->getParamType(0)->isDependentType();
1470 }
1471 }
1472 return false;
1473 }();
1474
1475 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1476}
1477
1479 // If we're outside the body of a member function, then we'll have a specified
1480 // type for 'this'.
1482 return false;
1483
1484 // Determine whether we're looking into a class that's currently being
1485 // defined.
1486 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1487 return Class && Class->isBeingDefined();
1488}
1489
1492 SourceLocation LParenOrBraceLoc,
1493 MultiExprArg exprs,
1494 SourceLocation RParenOrBraceLoc,
1495 bool ListInitialization) {
1496 if (!TypeRep)
1497 return ExprError();
1498
1499 TypeSourceInfo *TInfo;
1500 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1501 if (!TInfo)
1503
1504 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1505 RParenOrBraceLoc, ListInitialization);
1506 if (Result.isInvalid())
1508 RParenOrBraceLoc, exprs, Ty);
1509 return Result;
1510}
1511
1514 SourceLocation LParenOrBraceLoc,
1515 MultiExprArg Exprs,
1516 SourceLocation RParenOrBraceLoc,
1517 bool ListInitialization) {
1518 QualType Ty = TInfo->getType();
1519 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1520 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1521
1522 InitializedEntity Entity =
1524 InitializationKind Kind =
1525 Exprs.size()
1526 ? ListInitialization
1528 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1529 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1530 RParenOrBraceLoc)
1531 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1532 RParenOrBraceLoc);
1533
1534 // C++17 [expr.type.conv]p1:
1535 // If the type is a placeholder for a deduced class type, [...perform class
1536 // template argument deduction...]
1537 // C++23:
1538 // Otherwise, if the type contains a placeholder type, it is replaced by the
1539 // type determined by placeholder type deduction.
1540 DeducedType *Deduced = Ty->getContainedDeducedType();
1541 if (Deduced && !Deduced->isDeduced() &&
1542 isa<DeducedTemplateSpecializationType>(Deduced)) {
1544 Kind, Exprs);
1545 if (Ty.isNull())
1546 return ExprError();
1547 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1548 } else if (Deduced && !Deduced->isDeduced()) {
1549 MultiExprArg Inits = Exprs;
1550 if (ListInitialization) {
1551 auto *ILE = cast<InitListExpr>(Exprs[0]);
1552 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1553 }
1554
1555 if (Inits.empty())
1556 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1557 << Ty << FullRange);
1558 if (Inits.size() > 1) {
1559 Expr *FirstBad = Inits[1];
1560 return ExprError(Diag(FirstBad->getBeginLoc(),
1561 diag::err_auto_expr_init_multiple_expressions)
1562 << Ty << FullRange);
1563 }
1564 if (getLangOpts().CPlusPlus23) {
1565 if (Ty->getAs<AutoType>())
1566 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1567 }
1568 Expr *Deduce = Inits[0];
1569 if (isa<InitListExpr>(Deduce))
1570 return ExprError(
1571 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1572 << ListInitialization << Ty << FullRange);
1574 TemplateDeductionInfo Info(Deduce->getExprLoc());
1576 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1579 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1580 << Ty << Deduce->getType() << FullRange
1581 << Deduce->getSourceRange());
1582 if (DeducedType.isNull()) {
1584 return ExprError();
1585 }
1586
1587 Ty = DeducedType;
1588 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1589 }
1590
1593 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1594 RParenOrBraceLoc, ListInitialization);
1595
1596 // C++ [expr.type.conv]p1:
1597 // If the expression list is a parenthesized single expression, the type
1598 // conversion expression is equivalent (in definedness, and if defined in
1599 // meaning) to the corresponding cast expression.
1600 if (Exprs.size() == 1 && !ListInitialization &&
1601 !isa<InitListExpr>(Exprs[0])) {
1602 Expr *Arg = Exprs[0];
1603 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1604 RParenOrBraceLoc);
1605 }
1606
1607 // For an expression of the form T(), T shall not be an array type.
1608 QualType ElemTy = Ty;
1609 if (Ty->isArrayType()) {
1610 if (!ListInitialization)
1611 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1612 << FullRange);
1613 ElemTy = Context.getBaseElementType(Ty);
1614 }
1615
1616 // Only construct objects with object types.
1617 // The standard doesn't explicitly forbid function types here, but that's an
1618 // obvious oversight, as there's no way to dynamically construct a function
1619 // in general.
1620 if (Ty->isFunctionType())
1621 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1622 << Ty << FullRange);
1623
1624 // C++17 [expr.type.conv]p2, per DR2351:
1625 // If the type is cv void and the initializer is () or {}, the expression is
1626 // a prvalue of the specified type that performs no initialization.
1627 if (Ty->isVoidType()) {
1628 if (Exprs.empty())
1629 return new (Context) CXXScalarValueInitExpr(
1630 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());
1631 if (ListInitialization &&
1632 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) {
1634 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid,
1635 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(),
1636 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc());
1637 }
1638 } else if (RequireCompleteType(TyBeginLoc, ElemTy,
1639 diag::err_invalid_incomplete_type_use,
1640 FullRange))
1641 return ExprError();
1642
1643 // Otherwise, the expression is a prvalue of the specified type whose
1644 // result object is direct-initialized (11.6) with the initializer.
1645 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1646 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1647
1648 if (Result.isInvalid())
1649 return Result;
1650
1651 Expr *Inner = Result.get();
1652 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1653 Inner = BTE->getSubExpr();
1654 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1655 CE && CE->isImmediateInvocation())
1656 Inner = CE->getSubExpr();
1657 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1658 !isa<CXXScalarValueInitExpr>(Inner)) {
1659 // If we created a CXXTemporaryObjectExpr, that node also represents the
1660 // functional cast. Otherwise, create an explicit cast to represent
1661 // the syntactic form of a functional-style cast that was used here.
1662 //
1663 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1664 // would give a more consistent AST representation than using a
1665 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1666 // is sometimes handled by initialization and sometimes not.
1667 QualType ResultType = Result.get()->getType();
1668 SourceRange Locs = ListInitialization
1669 ? SourceRange()
1670 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1672 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1673 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1674 Locs.getBegin(), Locs.getEnd());
1675 }
1676
1677 return Result;
1678}
1679
1681 // [CUDA] Ignore this function, if we can't call it.
1682 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1683 if (getLangOpts().CUDA) {
1684 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1685 // If it's not callable at all, it's not the right function.
1686 if (CallPreference < SemaCUDA::CFP_WrongSide)
1687 return false;
1688 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1689 // Maybe. We have to check if there are better alternatives.
1691 Method->getDeclContext()->lookup(Method->getDeclName());
1692 for (const auto *D : R) {
1693 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1694 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1695 return false;
1696 }
1697 }
1698 // We've found no better variants.
1699 }
1700 }
1701
1703 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1704
1705 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1706 return Result;
1707
1708 // In case of CUDA, return true if none of the 1-argument deallocator
1709 // functions are actually callable.
1710 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1711 assert(FD->getNumParams() == 1 &&
1712 "Only single-operand functions should be in PreventedBy");
1713 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1714 });
1715}
1716
1717/// Determine whether the given function is a non-placement
1718/// deallocation function.
1720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1722
1723 if (!FD->getDeclName().isAnyOperatorDelete())
1724 return false;
1725
1728 FD->getNumParams();
1729
1730 unsigned UsualParams = 1;
1731 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1733 FD->getParamDecl(UsualParams)->getType(),
1734 S.Context.getSizeType()))
1735 ++UsualParams;
1736
1737 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1739 FD->getParamDecl(UsualParams)->getType(),
1741 ++UsualParams;
1742
1743 return UsualParams == FD->getNumParams();
1744}
1745
1746namespace {
1747 struct UsualDeallocFnInfo {
1748 UsualDeallocFnInfo()
1749 : Found(), FD(nullptr),
1751 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType,
1753 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1754 Destroying(false),
1755 IDP({AllocType, TypeAwareAllocationMode::No,
1756 AlignedAllocationMode::No, SizedDeallocationMode::No}),
1757 CUDAPref(SemaCUDA::CFP_Native) {
1758 // A function template declaration is only a usual deallocation function
1759 // if it is a typed delete.
1760 if (!FD) {
1761 if (AllocType.isNull())
1762 return;
1763 auto *FTD = dyn_cast<FunctionTemplateDecl>(Found->getUnderlyingDecl());
1764 if (!FTD)
1765 return;
1766 FunctionDecl *InstantiatedDecl =
1767 S.BuildTypeAwareUsualDelete(FTD, AllocType, Loc);
1768 if (!InstantiatedDecl)
1769 return;
1770 FD = InstantiatedDecl;
1771 }
1772 unsigned NumBaseParams = 1;
1773 if (FD->isTypeAwareOperatorNewOrDelete()) {
1774 // If this is a type aware operator delete we instantiate an appropriate
1775 // specialization of std::type_identity<>. If we do not know the
1776 // type being deallocated, or if the type-identity parameter of the
1777 // deallocation function does not match the constructed type_identity
1778 // specialization we reject the declaration.
1779 if (AllocType.isNull()) {
1780 FD = nullptr;
1781 return;
1782 }
1783 QualType TypeIdentityTag = FD->getParamDecl(0)->getType();
1784 QualType ExpectedTypeIdentityTag =
1785 S.tryBuildStdTypeIdentity(AllocType, Loc);
1786 if (ExpectedTypeIdentityTag.isNull()) {
1787 FD = nullptr;
1788 return;
1789 }
1790 if (!S.Context.hasSameType(TypeIdentityTag, ExpectedTypeIdentityTag)) {
1791 FD = nullptr;
1792 return;
1793 }
1794 IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes;
1795 ++NumBaseParams;
1796 }
1797
1798 if (FD->isDestroyingOperatorDelete()) {
1799 Destroying = true;
1800 ++NumBaseParams;
1801 }
1802
1803 if (NumBaseParams < FD->getNumParams() &&
1805 FD->getParamDecl(NumBaseParams)->getType(),
1806 S.Context.getSizeType())) {
1807 ++NumBaseParams;
1808 IDP.PassSize = SizedDeallocationMode::Yes;
1809 }
1810
1811 if (NumBaseParams < FD->getNumParams() &&
1812 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1813 ++NumBaseParams;
1814 IDP.PassAlignment = AlignedAllocationMode::Yes;
1815 }
1816
1817 // In CUDA, determine how much we'd like / dislike to call this.
1818 if (S.getLangOpts().CUDA)
1819 CUDAPref = S.CUDA().IdentifyPreference(
1820 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1821 }
1822
1823 explicit operator bool() const { return FD; }
1824
1825 int Compare(Sema &S, const UsualDeallocFnInfo &Other,
1826 ImplicitDeallocationParameters TargetIDP) const {
1827 assert(!TargetIDP.Type.isNull() ||
1828 !isTypeAwareAllocation(Other.IDP.PassTypeIdentity));
1829
1830 // C++ P0722:
1831 // A destroying operator delete is preferred over a non-destroying
1832 // operator delete.
1833 if (Destroying != Other.Destroying)
1834 return Destroying ? 1 : -1;
1835
1836 const ImplicitDeallocationParameters &OtherIDP = Other.IDP;
1837 // Selection for type awareness has priority over alignment and size
1838 if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity)
1839 return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1;
1840
1841 // C++17 [expr.delete]p10:
1842 // If the type has new-extended alignment, a function with a parameter
1843 // of type std::align_val_t is preferred; otherwise a function without
1844 // such a parameter is preferred
1845 if (IDP.PassAlignment != OtherIDP.PassAlignment)
1846 return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1;
1847
1848 if (IDP.PassSize != OtherIDP.PassSize)
1849 return IDP.PassSize == TargetIDP.PassSize ? 1 : -1;
1850
1851 if (isTypeAwareAllocation(IDP.PassTypeIdentity)) {
1852 // Type aware allocation involves templates so we need to choose
1853 // the best type
1854 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
1855 FunctionTemplateDecl *OtherPrimaryTemplate =
1856 Other.FD->getPrimaryTemplate();
1857 if ((!PrimaryTemplate) != (!OtherPrimaryTemplate))
1858 return OtherPrimaryTemplate ? 1 : -1;
1859
1860 if (PrimaryTemplate && OtherPrimaryTemplate) {
1861 const auto *DC = dyn_cast<CXXRecordDecl>(Found->getDeclContext());
1862 const auto *OtherDC =
1863 dyn_cast<CXXRecordDecl>(Other.Found->getDeclContext());
1864 unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs();
1866 PrimaryTemplate, OtherPrimaryTemplate, SourceLocation(),
1867 TPOC_Call, ImplicitArgCount,
1868 DC ? S.Context.getCanonicalTagType(DC) : QualType{},
1869 OtherDC ? S.Context.getCanonicalTagType(OtherDC) : QualType{},
1870 false)) {
1871 return Best == PrimaryTemplate ? 1 : -1;
1872 }
1873 }
1874 }
1875
1876 // Use CUDA call preference as a tiebreaker.
1877 if (CUDAPref > Other.CUDAPref)
1878 return 1;
1879 if (CUDAPref == Other.CUDAPref)
1880 return 0;
1881 return -1;
1882 }
1883
1885 FunctionDecl *FD;
1886 bool Destroying;
1889 };
1890}
1891
1892/// Determine whether a type has new-extended alignment. This may be called when
1893/// the type is incomplete (for a delete-expression with an incomplete pointee
1894/// type), in which case it will conservatively return false if the alignment is
1895/// not known.
1896static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1897 return S.getLangOpts().AlignedAllocation &&
1898 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1900}
1901
1902static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc,
1904 CXXRecordDecl *NamingClass, DeclAccessPair Decl,
1905 FunctionDecl *Operator) {
1906 if (Operator->isTypeAwareOperatorNewOrDelete()) {
1907 QualType SelectedTypeIdentityParameter =
1908 Operator->getParamDecl(0)->getType();
1909 if (S.RequireCompleteType(StartLoc, SelectedTypeIdentityParameter,
1910 diag::err_incomplete_type))
1911 return true;
1912 }
1913
1914 // FIXME: DiagnoseUseOfDecl?
1915 if (Operator->isDeleted()) {
1916 if (Diagnose) {
1917 StringLiteral *Msg = Operator->getDeletedMessage();
1918 S.Diag(StartLoc, diag::err_deleted_function_use)
1919 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
1920 S.NoteDeletedFunction(Operator);
1921 }
1922 return true;
1923 }
1924 Sema::AccessResult Accessible =
1925 S.CheckAllocationAccess(StartLoc, Range, NamingClass, Decl, Diagnose);
1926 return Accessible == Sema::AR_inaccessible;
1927}
1928
1929/// Select the correct "usual" deallocation function to use from a selection of
1930/// deallocation functions (either global or class-scope).
1931static UsualDeallocFnInfo resolveDeallocationOverload(
1934 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1935
1936 UsualDeallocFnInfo Best;
1937 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1938 UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc);
1939 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1940 Info.CUDAPref == SemaCUDA::CFP_Never)
1941 continue;
1942
1944 isTypeAwareAllocation(Info.IDP.PassTypeIdentity))
1945 continue;
1946 if (!Best) {
1947 Best = Info;
1948 if (BestFns)
1949 BestFns->push_back(Info);
1950 continue;
1951 }
1952 int ComparisonResult = Best.Compare(S, Info, IDP);
1953 if (ComparisonResult > 0)
1954 continue;
1955
1956 // If more than one preferred function is found, all non-preferred
1957 // functions are eliminated from further consideration.
1958 if (BestFns && ComparisonResult < 0)
1959 BestFns->clear();
1960
1961 Best = Info;
1962 if (BestFns)
1963 BestFns->push_back(Info);
1964 }
1965
1966 return Best;
1967}
1968
1969/// Determine whether a given type is a class for which 'delete[]' would call
1970/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1971/// we need to store the array size (even if the type is
1972/// trivially-destructible).
1974 TypeAwareAllocationMode PassType,
1975 QualType allocType) {
1976 const auto *record =
1978 if (!record) return false;
1979
1980 // Try to find an operator delete[] in class scope.
1981
1982 DeclarationName deleteName =
1983 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1984 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1985 S.LookupQualifiedName(ops, record->getOriginalDecl()->getDefinitionOrSelf());
1986
1987 // We're just doing this for information.
1988 ops.suppressDiagnostics();
1989
1990 // Very likely: there's no operator delete[].
1991 if (ops.empty()) return false;
1992
1993 // If it's ambiguous, it should be illegal to call operator delete[]
1994 // on this thing, so it doesn't matter if we allocate extra space or not.
1995 if (ops.isAmbiguous()) return false;
1996
1997 // C++17 [expr.delete]p10:
1998 // If the deallocation functions have class scope, the one without a
1999 // parameter of type std::size_t is selected.
2001 allocType, PassType,
2004 auto Best = resolveDeallocationOverload(S, ops, IDP, loc);
2005 return Best && isSizedDeallocation(Best.IDP.PassSize);
2006}
2007
2009Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2010 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
2011 SourceLocation PlacementRParen, SourceRange TypeIdParens,
2013 std::optional<Expr *> ArraySize;
2014 // If the specified type is an array, unwrap it and save the expression.
2015 if (D.getNumTypeObjects() > 0 &&
2016 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
2017 DeclaratorChunk &Chunk = D.getTypeObject(0);
2018 if (D.getDeclSpec().hasAutoTypeSpec())
2019 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
2020 << D.getSourceRange());
2021 if (Chunk.Arr.hasStatic)
2022 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
2023 << D.getSourceRange());
2024 if (!Chunk.Arr.NumElts && !Initializer)
2025 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
2026 << D.getSourceRange());
2027
2028 ArraySize = Chunk.Arr.NumElts;
2029 D.DropFirstTypeObject();
2030 }
2031
2032 // Every dimension shall be of constant size.
2033 if (ArraySize) {
2034 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
2035 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
2036 break;
2037
2038 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
2039 if (Expr *NumElts = Array.NumElts) {
2040 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
2041 // FIXME: GCC permits constant folding here. We should either do so consistently
2042 // or not do so at all, rather than changing behavior in C++14 onwards.
2043 if (getLangOpts().CPlusPlus14) {
2044 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
2045 // shall be a converted constant expression (5.19) of type std::size_t
2046 // and shall evaluate to a strictly positive value.
2047 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
2048 Array.NumElts =
2051 .get();
2052 } else {
2053 Array.NumElts = VerifyIntegerConstantExpression(
2054 NumElts, nullptr, diag::err_new_array_nonconst,
2056 .get();
2057 }
2058 if (!Array.NumElts)
2059 return ExprError();
2060 }
2061 }
2062 }
2063 }
2064
2066 QualType AllocType = TInfo->getType();
2067 if (D.isInvalidType())
2068 return ExprError();
2069
2070 SourceRange DirectInitRange;
2071 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
2072 DirectInitRange = List->getSourceRange();
2073
2074 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2075 PlacementLParen, PlacementArgs, PlacementRParen,
2076 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
2077 Initializer);
2078}
2079
2081 Expr *Init, bool IsCPlusPlus20) {
2082 if (!Init)
2083 return true;
2084 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
2085 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2086 if (isa<ImplicitValueInitExpr>(Init))
2087 return true;
2088 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2089 return !CCE->isListInitialization() &&
2090 CCE->getConstructor()->isDefaultConstructor();
2091 else if (Style == CXXNewInitializationStyle::Braces) {
2092 assert(isa<InitListExpr>(Init) &&
2093 "Shouldn't create list CXXConstructExprs for arrays.");
2094 return true;
2095 }
2096 return false;
2097}
2098
2099bool
2101 if (!getLangOpts().AlignedAllocationUnavailable)
2102 return false;
2103 if (FD.isDefined())
2104 return false;
2105 UnsignedOrNone AlignmentParam = std::nullopt;
2106 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2107 AlignmentParam)
2108 return true;
2109 return false;
2110}
2111
2112// Emit a diagnostic if an aligned allocation/deallocation function that is not
2113// implemented in the standard library is selected.
2117 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2118 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2119 getASTContext().getTargetInfo().getPlatformName());
2120 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2121
2122 bool IsDelete = FD.getDeclName().isAnyOperatorDelete();
2123 Diag(Loc, diag::err_aligned_allocation_unavailable)
2124 << IsDelete << FD.getType().getAsString() << OSName
2125 << OSVersion.getAsString() << OSVersion.empty();
2126 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2127 }
2128}
2129
2131 SourceLocation PlacementLParen,
2132 MultiExprArg PlacementArgs,
2133 SourceLocation PlacementRParen,
2134 SourceRange TypeIdParens, QualType AllocType,
2135 TypeSourceInfo *AllocTypeInfo,
2136 std::optional<Expr *> ArraySize,
2137 SourceRange DirectInitRange, Expr *Initializer) {
2138 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2139 SourceLocation StartLoc = Range.getBegin();
2140
2141 CXXNewInitializationStyle InitStyle;
2142 if (DirectInitRange.isValid()) {
2143 assert(Initializer && "Have parens but no initializer.");
2145 } else if (isa_and_nonnull<InitListExpr>(Initializer))
2147 else {
2148 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2149 isa<CXXConstructExpr>(Initializer)) &&
2150 "Initializer expression that cannot have been implicitly created.");
2152 }
2153
2154 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2155 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2156 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2157 "paren init for non-call init");
2158 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2159 } else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Initializer)) {
2160 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2161 "paren init for non-call init");
2162 Exprs = List->getInitExprs();
2163 }
2164
2165 // C++11 [expr.new]p15:
2166 // A new-expression that creates an object of type T initializes that
2167 // object as follows:
2168 InitializationKind Kind = [&] {
2169 switch (InitStyle) {
2170 // - If the new-initializer is omitted, the object is default-
2171 // initialized (8.5); if no initialization is performed,
2172 // the object has indeterminate value
2174 return InitializationKind::CreateDefault(TypeRange.getBegin());
2175 // - Otherwise, the new-initializer is interpreted according to the
2176 // initialization rules of 8.5 for direct-initialization.
2178 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2179 DirectInitRange.getBegin(),
2180 DirectInitRange.getEnd());
2183 Initializer->getBeginLoc(),
2184 Initializer->getEndLoc());
2185 }
2186 llvm_unreachable("Unknown initialization kind");
2187 }();
2188
2189 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2190 auto *Deduced = AllocType->getContainedDeducedType();
2191 if (Deduced && !Deduced->isDeduced() &&
2192 isa<DeducedTemplateSpecializationType>(Deduced)) {
2193 if (ArraySize)
2194 return ExprError(
2195 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2196 diag::err_deduced_class_template_compound_type)
2197 << /*array*/ 2
2198 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2199
2200 InitializedEntity Entity
2201 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2203 AllocTypeInfo, Entity, Kind, Exprs);
2204 if (AllocType.isNull())
2205 return ExprError();
2206 } else if (Deduced && !Deduced->isDeduced()) {
2207 MultiExprArg Inits = Exprs;
2208 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2209 if (Braced) {
2210 auto *ILE = cast<InitListExpr>(Exprs[0]);
2211 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2212 }
2213
2214 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2215 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2216 << AllocType << TypeRange);
2217 if (Inits.size() > 1) {
2218 Expr *FirstBad = Inits[1];
2219 return ExprError(Diag(FirstBad->getBeginLoc(),
2220 diag::err_auto_new_ctor_multiple_expressions)
2221 << AllocType << TypeRange);
2222 }
2223 if (Braced && !getLangOpts().CPlusPlus17)
2224 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2225 << AllocType << TypeRange;
2226 Expr *Deduce = Inits[0];
2227 if (isa<InitListExpr>(Deduce))
2228 return ExprError(
2229 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2230 << Braced << AllocType << TypeRange);
2232 TemplateDeductionInfo Info(Deduce->getExprLoc());
2234 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2237 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2238 << AllocType << Deduce->getType() << TypeRange
2239 << Deduce->getSourceRange());
2240 if (DeducedType.isNull()) {
2242 return ExprError();
2243 }
2244 AllocType = DeducedType;
2245 }
2246
2247 // Per C++0x [expr.new]p5, the type being constructed may be a
2248 // typedef of an array type.
2249 // Dependent case will be handled separately.
2250 if (!ArraySize && !AllocType->isDependentType()) {
2251 if (const ConstantArrayType *Array
2252 = Context.getAsConstantArrayType(AllocType)) {
2253 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2255 TypeRange.getEnd());
2256 AllocType = Array->getElementType();
2257 }
2258 }
2259
2260 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2261 return ExprError();
2262
2263 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2264 return ExprError();
2265
2266 // In ARC, infer 'retaining' for the allocated
2267 if (getLangOpts().ObjCAutoRefCount &&
2268 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2269 AllocType->isObjCLifetimeType()) {
2270 AllocType = Context.getLifetimeQualifiedType(AllocType,
2271 AllocType->getObjCARCImplicitLifetime());
2272 }
2273
2274 QualType ResultType = Context.getPointerType(AllocType);
2275
2276 if (ArraySize && *ArraySize &&
2277 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2278 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2279 if (result.isInvalid()) return ExprError();
2280 ArraySize = result.get();
2281 }
2282 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2283 // integral or enumeration type with a non-negative value."
2284 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2285 // enumeration type, or a class type for which a single non-explicit
2286 // conversion function to integral or unscoped enumeration type exists.
2287 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2288 // std::size_t.
2289 std::optional<uint64_t> KnownArraySize;
2290 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2291 ExprResult ConvertedSize;
2292 if (getLangOpts().CPlusPlus14) {
2293 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2294
2295 ConvertedSize = PerformImplicitConversion(
2297
2298 if (!ConvertedSize.isInvalid() && (*ArraySize)->getType()->isRecordType())
2299 // Diagnose the compatibility of this conversion.
2300 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2301 << (*ArraySize)->getType() << 0 << "'size_t'";
2302 } else {
2303 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2304 protected:
2305 Expr *ArraySize;
2306
2307 public:
2308 SizeConvertDiagnoser(Expr *ArraySize)
2309 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2310 ArraySize(ArraySize) {}
2311
2312 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2313 QualType T) override {
2314 return S.Diag(Loc, diag::err_array_size_not_integral)
2315 << S.getLangOpts().CPlusPlus11 << T;
2316 }
2317
2318 SemaDiagnosticBuilder diagnoseIncomplete(
2319 Sema &S, SourceLocation Loc, QualType T) override {
2320 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2321 << T << ArraySize->getSourceRange();
2322 }
2323
2324 SemaDiagnosticBuilder diagnoseExplicitConv(
2325 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2326 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2327 }
2328
2329 SemaDiagnosticBuilder noteExplicitConv(
2330 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2331 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2332 << ConvTy->isEnumeralType() << ConvTy;
2333 }
2334
2335 SemaDiagnosticBuilder diagnoseAmbiguous(
2336 Sema &S, SourceLocation Loc, QualType T) override {
2337 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2338 }
2339
2340 SemaDiagnosticBuilder noteAmbiguous(
2341 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2342 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2343 << ConvTy->isEnumeralType() << ConvTy;
2344 }
2345
2346 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2347 QualType T,
2348 QualType ConvTy) override {
2349 return S.Diag(Loc,
2350 S.getLangOpts().CPlusPlus11
2351 ? diag::warn_cxx98_compat_array_size_conversion
2352 : diag::ext_array_size_conversion)
2353 << T << ConvTy->isEnumeralType() << ConvTy;
2354 }
2355 } SizeDiagnoser(*ArraySize);
2356
2357 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2358 SizeDiagnoser);
2359 }
2360 if (ConvertedSize.isInvalid())
2361 return ExprError();
2362
2363 ArraySize = ConvertedSize.get();
2364 QualType SizeType = (*ArraySize)->getType();
2365
2366 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2367 return ExprError();
2368
2369 // C++98 [expr.new]p7:
2370 // The expression in a direct-new-declarator shall have integral type
2371 // with a non-negative value.
2372 //
2373 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2374 // per CWG1464. Otherwise, if it's not a constant, we must have an
2375 // unparenthesized array type.
2376
2377 // We've already performed any required implicit conversion to integer or
2378 // unscoped enumeration type.
2379 // FIXME: Per CWG1464, we are required to check the value prior to
2380 // converting to size_t. This will never find a negative array size in
2381 // C++14 onwards, because Value is always unsigned here!
2382 if (std::optional<llvm::APSInt> Value =
2383 (*ArraySize)->getIntegerConstantExpr(Context)) {
2384 if (Value->isSigned() && Value->isNegative()) {
2385 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2386 diag::err_typecheck_negative_array_size)
2387 << (*ArraySize)->getSourceRange());
2388 }
2389
2390 if (!AllocType->isDependentType()) {
2391 unsigned ActiveSizeBits =
2393 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2394 return ExprError(
2395 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2396 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2397 }
2398
2399 KnownArraySize = Value->getZExtValue();
2400 } else if (TypeIdParens.isValid()) {
2401 // Can't have dynamic array size when the type-id is in parentheses.
2402 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2403 << (*ArraySize)->getSourceRange()
2404 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2405 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2406
2407 TypeIdParens = SourceRange();
2408 }
2409
2410 // Note that we do *not* convert the argument in any way. It can
2411 // be signed, larger than size_t, whatever.
2412 }
2413
2414 FunctionDecl *OperatorNew = nullptr;
2415 FunctionDecl *OperatorDelete = nullptr;
2416 unsigned Alignment =
2417 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2418 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2421 alignedAllocationModeFromBool(getLangOpts().AlignedAllocation &&
2422 Alignment > NewAlignment)};
2423
2424 if (CheckArgsForPlaceholders(PlacementArgs))
2425 return ExprError();
2426
2429 SourceRange AllocationParameterRange = Range;
2430 if (PlacementLParen.isValid() && PlacementRParen.isValid())
2431 AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen);
2432 if (!AllocType->isDependentType() &&
2433 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2434 FindAllocationFunctions(StartLoc, AllocationParameterRange, Scope, Scope,
2435 AllocType, ArraySize.has_value(), IAP,
2436 PlacementArgs, OperatorNew, OperatorDelete))
2437 return ExprError();
2438
2439 // If this is an array allocation, compute whether the usual array
2440 // deallocation function for the type has a size_t parameter.
2441 bool UsualArrayDeleteWantsSize = false;
2442 if (ArraySize && !AllocType->isDependentType())
2443 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
2444 *this, StartLoc, IAP.PassTypeIdentity, AllocType);
2445
2446 SmallVector<Expr *, 8> AllPlaceArgs;
2447 if (OperatorNew) {
2448 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2449 VariadicCallType CallType = Proto->isVariadic()
2452
2453 // We've already converted the placement args, just fill in any default
2454 // arguments. Skip the first parameter because we don't have a corresponding
2455 // argument. Skip the second parameter too if we're passing in the
2456 // alignment; we've already filled it in.
2457 unsigned NumImplicitArgs = 1;
2459 assert(OperatorNew->isTypeAwareOperatorNewOrDelete());
2460 NumImplicitArgs++;
2461 }
2463 NumImplicitArgs++;
2464 if (GatherArgumentsForCall(AllocationParameterRange.getBegin(), OperatorNew,
2465 Proto, NumImplicitArgs, PlacementArgs,
2466 AllPlaceArgs, CallType))
2467 return ExprError();
2468
2469 if (!AllPlaceArgs.empty())
2470 PlacementArgs = AllPlaceArgs;
2471
2472 // We would like to perform some checking on the given `operator new` call,
2473 // but the PlacementArgs does not contain the implicit arguments,
2474 // namely allocation size and maybe allocation alignment,
2475 // so we need to conjure them.
2476
2477 QualType SizeTy = Context.getSizeType();
2478 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2479
2480 llvm::APInt SingleEltSize(
2481 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2482
2483 // How many bytes do we want to allocate here?
2484 std::optional<llvm::APInt> AllocationSize;
2485 if (!ArraySize && !AllocType->isDependentType()) {
2486 // For non-array operator new, we only want to allocate one element.
2487 AllocationSize = SingleEltSize;
2488 } else if (KnownArraySize && !AllocType->isDependentType()) {
2489 // For array operator new, only deal with static array size case.
2490 bool Overflow;
2491 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2492 .umul_ov(SingleEltSize, Overflow);
2493 (void)Overflow;
2494 assert(
2495 !Overflow &&
2496 "Expected that all the overflows would have been handled already.");
2497 }
2498
2499 IntegerLiteral AllocationSizeLiteral(
2500 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2501 SizeTy, StartLoc);
2502 // Otherwise, if we failed to constant-fold the allocation size, we'll
2503 // just give up and pass-in something opaque, that isn't a null pointer.
2504 OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue,
2505 OK_Ordinary, /*SourceExpr=*/nullptr);
2506
2507 // Let's synthesize the alignment argument in case we will need it.
2508 // Since we *really* want to allocate these on stack, this is slightly ugly
2509 // because there might not be a `std::align_val_t` type.
2511 QualType AlignValT =
2513 IntegerLiteral AlignmentLiteral(
2514 Context,
2515 llvm::APInt(Context.getTypeSize(SizeTy),
2516 Alignment / Context.getCharWidth()),
2517 SizeTy, StartLoc);
2518 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2519 CK_IntegralCast, &AlignmentLiteral,
2521
2522 // Adjust placement args by prepending conjured size and alignment exprs.
2524 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2525 CallArgs.emplace_back(AllocationSize
2526 ? static_cast<Expr *>(&AllocationSizeLiteral)
2527 : &OpaqueAllocationSize);
2529 CallArgs.emplace_back(&DesiredAlignment);
2530 llvm::append_range(CallArgs, PlacementArgs);
2531
2532 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2533
2534 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2535 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2536
2537 // Warn if the type is over-aligned and is being allocated by (unaligned)
2538 // global operator new.
2539 if (PlacementArgs.empty() && !isAlignedAllocation(IAP.PassAlignment) &&
2540 (OperatorNew->isImplicit() ||
2541 (OperatorNew->getBeginLoc().isValid() &&
2542 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2543 if (Alignment > NewAlignment)
2544 Diag(StartLoc, diag::warn_overaligned_type)
2545 << AllocType
2546 << unsigned(Alignment / Context.getCharWidth())
2547 << unsigned(NewAlignment / Context.getCharWidth());
2548 }
2549 }
2550
2551 // Array 'new' can't have any initializers except empty parentheses.
2552 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2553 // dialect distinction.
2554 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2556 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2557 Exprs.back()->getEndLoc());
2558 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2559 return ExprError();
2560 }
2561
2562 // If we can perform the initialization, and we've not already done so,
2563 // do it now.
2564 if (!AllocType->isDependentType() &&
2566 // The type we initialize is the complete type, including the array bound.
2567 QualType InitType;
2568 if (KnownArraySize)
2569 InitType = Context.getConstantArrayType(
2570 AllocType,
2571 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2572 *KnownArraySize),
2573 *ArraySize, ArraySizeModifier::Normal, 0);
2574 else if (ArraySize)
2575 InitType = Context.getIncompleteArrayType(AllocType,
2577 else
2578 InitType = AllocType;
2579
2580 InitializedEntity Entity
2581 = InitializedEntity::InitializeNew(StartLoc, InitType);
2582 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2583 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2584 if (FullInit.isInvalid())
2585 return ExprError();
2586
2587 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2588 // we don't want the initialized object to be destructed.
2589 // FIXME: We should not create these in the first place.
2590 if (CXXBindTemporaryExpr *Binder =
2591 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2592 FullInit = Binder->getSubExpr();
2593
2594 Initializer = FullInit.get();
2595
2596 // FIXME: If we have a KnownArraySize, check that the array bound of the
2597 // initializer is no greater than that constant value.
2598
2599 if (ArraySize && !*ArraySize) {
2600 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2601 if (CAT) {
2602 // FIXME: Track that the array size was inferred rather than explicitly
2603 // specified.
2604 ArraySize = IntegerLiteral::Create(
2605 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2606 } else {
2607 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2608 << Initializer->getSourceRange();
2609 }
2610 }
2611 }
2612
2613 // Mark the new and delete operators as referenced.
2614 if (OperatorNew) {
2615 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2616 return ExprError();
2617 MarkFunctionReferenced(StartLoc, OperatorNew);
2618 }
2619 if (OperatorDelete) {
2620 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2621 return ExprError();
2622 MarkFunctionReferenced(StartLoc, OperatorDelete);
2623 }
2624
2625 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2626 IAP, UsualArrayDeleteWantsSize, PlacementArgs,
2627 TypeIdParens, ArraySize, InitStyle, Initializer,
2628 ResultType, AllocTypeInfo, Range, DirectInitRange);
2629}
2630
2632 SourceRange R) {
2633 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2634 // abstract class type or array thereof.
2635 if (AllocType->isFunctionType())
2636 return Diag(Loc, diag::err_bad_new_type)
2637 << AllocType << 0 << R;
2638 else if (AllocType->isReferenceType())
2639 return Diag(Loc, diag::err_bad_new_type)
2640 << AllocType << 1 << R;
2641 else if (!AllocType->isDependentType() &&
2643 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2644 return true;
2645 else if (RequireNonAbstractType(Loc, AllocType,
2646 diag::err_allocation_of_abstract_type))
2647 return true;
2648 else if (AllocType->isVariablyModifiedType())
2649 return Diag(Loc, diag::err_variably_modified_new_type)
2650 << AllocType;
2651 else if (AllocType.getAddressSpace() != LangAS::Default &&
2652 !getLangOpts().OpenCLCPlusPlus)
2653 return Diag(Loc, diag::err_address_space_qualified_new)
2654 << AllocType.getUnqualifiedType()
2656 else if (getLangOpts().ObjCAutoRefCount) {
2657 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2658 QualType BaseAllocType = Context.getBaseElementType(AT);
2659 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2660 BaseAllocType->isObjCLifetimeType())
2661 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2662 << BaseAllocType;
2663 }
2664 }
2665
2666 return false;
2667}
2668
2669enum class ResolveMode { Typed, Untyped };
2672 SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment,
2673 FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates,
2674 Expr *AlignArg, bool Diagnose) {
2675 unsigned NonTypeArgumentOffset = 0;
2676 if (Mode == ResolveMode::Typed) {
2677 ++NonTypeArgumentOffset;
2678 }
2679
2680 OverloadCandidateSet Candidates(R.getNameLoc(),
2682 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2683 Alloc != AllocEnd; ++Alloc) {
2684 // Even member operator new/delete are implicitly treated as
2685 // static, so don't use AddMemberCandidate.
2686 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2687 bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete();
2688 if (IsTypeAware == (Mode != ResolveMode::Typed))
2689 continue;
2690
2691 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2692 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2693 /*ExplicitTemplateArgs=*/nullptr, Args,
2694 Candidates,
2695 /*SuppressUserConversions=*/false);
2696 continue;
2697 }
2698
2699 FunctionDecl *Fn = cast<FunctionDecl>(D);
2700 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2701 /*SuppressUserConversions=*/false);
2702 }
2703
2704 // Do the resolution.
2706 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2707 case OR_Success: {
2708 // Got one!
2709 FunctionDecl *FnDecl = Best->Function;
2711 Best->FoundDecl) == Sema::AR_inaccessible)
2712 return true;
2713
2714 Operator = FnDecl;
2715 return false;
2716 }
2717
2719 // C++17 [expr.new]p13:
2720 // If no matching function is found and the allocated object type has
2721 // new-extended alignment, the alignment argument is removed from the
2722 // argument list, and overload resolution is performed again.
2723 if (isAlignedAllocation(PassAlignment)) {
2724 PassAlignment = AlignedAllocationMode::No;
2725 AlignArg = Args[NonTypeArgumentOffset + 1];
2726 Args.erase(Args.begin() + NonTypeArgumentOffset + 1);
2727 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2728 PassAlignment, Operator,
2729 &Candidates, AlignArg, Diagnose);
2730 }
2731
2732 // MSVC will fall back on trying to find a matching global operator new
2733 // if operator new[] cannot be found. Also, MSVC will leak by not
2734 // generating a call to operator delete or operator delete[], but we
2735 // will not replicate that bug.
2736 // FIXME: Find out how this interacts with the std::align_val_t fallback
2737 // once MSVC implements it.
2738 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2739 S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) {
2740 R.clear();
2743 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2744 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2745 PassAlignment, Operator,
2746 /*Candidates=*/nullptr,
2747 /*AlignArg=*/nullptr, Diagnose);
2748 }
2749 if (Mode == ResolveMode::Typed) {
2750 // If we can't find a matching type aware operator we don't consider this
2751 // a failure.
2752 Operator = nullptr;
2753 return false;
2754 }
2755 if (Diagnose) {
2756 // If this is an allocation of the form 'new (p) X' for some object
2757 // pointer p (or an expression that will decay to such a pointer),
2758 // diagnose the reason for the error.
2759 if (!R.isClassLookup() && Args.size() == 2 &&
2760 (Args[1]->getType()->isObjectPointerType() ||
2761 Args[1]->getType()->isArrayType())) {
2762 const QualType Arg1Type = Args[1]->getType();
2763 QualType UnderlyingType = S.Context.getBaseElementType(Arg1Type);
2764 if (UnderlyingType->isPointerType())
2765 UnderlyingType = UnderlyingType->getPointeeType();
2766 if (UnderlyingType.isConstQualified()) {
2767 S.Diag(Args[1]->getExprLoc(),
2768 diag::err_placement_new_into_const_qualified_storage)
2769 << Arg1Type << Args[1]->getSourceRange();
2770 return true;
2771 }
2772 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2773 << R.getLookupName() << Range;
2774 // Listing the candidates is unlikely to be useful; skip it.
2775 return true;
2776 }
2777
2778 // Finish checking all candidates before we note any. This checking can
2779 // produce additional diagnostics so can't be interleaved with our
2780 // emission of notes.
2781 //
2782 // For an aligned allocation, separately check the aligned and unaligned
2783 // candidates with their respective argument lists.
2786 llvm::SmallVector<Expr*, 4> AlignedArgs;
2787 if (AlignedCandidates) {
2788 auto IsAligned = [NonTypeArgumentOffset](OverloadCandidate &C) {
2789 auto AlignArgOffset = NonTypeArgumentOffset + 1;
2790 return C.Function->getNumParams() > AlignArgOffset &&
2791 C.Function->getParamDecl(AlignArgOffset)
2792 ->getType()
2793 ->isAlignValT();
2794 };
2795 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2796
2797 AlignedArgs.reserve(Args.size() + NonTypeArgumentOffset + 1);
2798 for (unsigned Idx = 0; Idx < NonTypeArgumentOffset + 1; ++Idx)
2799 AlignedArgs.push_back(Args[Idx]);
2800 AlignedArgs.push_back(AlignArg);
2801 AlignedArgs.append(Args.begin() + NonTypeArgumentOffset + 1,
2802 Args.end());
2803 AlignedCands = AlignedCandidates->CompleteCandidates(
2804 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2805
2806 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2807 R.getNameLoc(), IsUnaligned);
2808 } else {
2809 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2810 R.getNameLoc());
2811 }
2812
2813 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2814 << R.getLookupName() << Range;
2815 if (AlignedCandidates)
2816 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2817 R.getNameLoc());
2818 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2819 }
2820 return true;
2821
2822 case OR_Ambiguous:
2823 if (Diagnose) {
2824 Candidates.NoteCandidates(
2826 S.PDiag(diag::err_ovl_ambiguous_call)
2827 << R.getLookupName() << Range),
2828 S, OCD_AmbiguousCandidates, Args);
2829 }
2830 return true;
2831
2832 case OR_Deleted: {
2833 if (Diagnose)
2835 Candidates, Best->Function, Args);
2836 return true;
2837 }
2838 }
2839 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2840}
2841
2843
2845 LookupResult &FoundDelete,
2846 DeallocLookupMode Mode,
2847 DeclarationName Name) {
2849 if (Mode != DeallocLookupMode::OptionallyTyped) {
2850 // We're going to remove either the typed or the non-typed
2851 bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped;
2852 LookupResult::Filter Filter = FoundDelete.makeFilter();
2853 while (Filter.hasNext()) {
2854 FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction();
2855 if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl)
2856 Filter.erase();
2857 }
2858 Filter.done();
2859 }
2860}
2861
2865 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2866 Operator = nullptr;
2868 assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2869 // The internal overload resolution work mutates the argument list
2870 // in accordance with the spec. We may want to change that in future,
2871 // but for now we deal with this by making a copy of the non-type-identity
2872 // arguments.
2873 SmallVector<Expr *> UntypedParameters;
2874 UntypedParameters.reserve(Args.size() - 1);
2875 UntypedParameters.push_back(Args[1]);
2876 // Type aware allocation implicitly includes the alignment parameter so
2877 // only include it in the untyped parameter list if alignment was explicitly
2878 // requested
2880 UntypedParameters.push_back(Args[2]);
2881 UntypedParameters.append(Args.begin() + 3, Args.end());
2882
2883 AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment;
2886 S, R, Range, ResolveMode::Typed, Args, IAP.PassAlignment, Operator,
2887 AlignedCandidates, AlignArg, Diagnose))
2888 return true;
2889 if (Operator)
2890 return false;
2891
2892 // If we got to this point we could not find a matching typed operator
2893 // so we update the IAP flags, and revert to our stored copy of the
2894 // type-identity-less argument list.
2896 IAP.PassAlignment = InitialAlignmentMode;
2897 Args = std::move(UntypedParameters);
2898 }
2899 assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2901 S, R, Range, ResolveMode::Untyped, Args, IAP.PassAlignment, Operator,
2902 AlignedCandidates, AlignArg, Diagnose);
2903}
2904
2908 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
2909 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
2910 FunctionDecl *&OperatorDelete, bool Diagnose) {
2911 // --- Choosing an allocation function ---
2912 // C++ 5.3.4p8 - 14 & 18
2913 // 1) If looking in AllocationFunctionScope::Global scope for allocation
2914 // functions, only look in
2915 // the global scope. Else, if AllocationFunctionScope::Class, only look in
2916 // the scope of the allocated class. If AllocationFunctionScope::Both, look
2917 // in both.
2918 // 2) If an array size is given, look for operator new[], else look for
2919 // operator new.
2920 // 3) The first argument is always size_t. Append the arguments from the
2921 // placement form.
2922
2923 SmallVector<Expr*, 8> AllocArgs;
2924 AllocArgs.reserve(IAP.getNumImplicitArgs() + PlaceArgs.size());
2925
2926 // C++ [expr.new]p8:
2927 // If the allocated type is a non-array type, the allocation
2928 // function's name is operator new and the deallocation function's
2929 // name is operator delete. If the allocated type is an array
2930 // type, the allocation function's name is operator new[] and the
2931 // deallocation function's name is operator delete[].
2933 IsArray ? OO_Array_New : OO_New);
2934
2935 QualType AllocElemType = Context.getBaseElementType(AllocType);
2936
2937 // We don't care about the actual value of these arguments.
2938 // FIXME: Should the Sema create the expression and embed it in the syntax
2939 // tree? Or should the consumer just recalculate the value?
2940 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2941
2942 // We use size_t as a stand in so that we can construct the init
2943 // expr on the stack
2944 QualType TypeIdentity = Context.getSizeType();
2946 QualType SpecializedTypeIdentity =
2947 tryBuildStdTypeIdentity(IAP.Type, StartLoc);
2948 if (!SpecializedTypeIdentity.isNull()) {
2949 TypeIdentity = SpecializedTypeIdentity;
2950 if (RequireCompleteType(StartLoc, TypeIdentity,
2951 diag::err_incomplete_type))
2952 return true;
2953 } else
2955 }
2956 TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity;
2957
2958 CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc);
2960 AllocArgs.push_back(&TypeIdentityParam);
2961
2962 QualType SizeTy = Context.getSizeType();
2963 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2964 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2965 SourceLocation());
2966 AllocArgs.push_back(&Size);
2967
2968 QualType AlignValT = Context.VoidTy;
2969 bool IncludeAlignParam = isAlignedAllocation(IAP.PassAlignment) ||
2971 if (IncludeAlignParam) {
2974 }
2975 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2976 if (IncludeAlignParam)
2977 AllocArgs.push_back(&Align);
2978
2979 llvm::append_range(AllocArgs, PlaceArgs);
2980
2981 // Find the allocation function.
2982 {
2983 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2984
2985 // C++1z [expr.new]p9:
2986 // If the new-expression begins with a unary :: operator, the allocation
2987 // function's name is looked up in the global scope. Otherwise, if the
2988 // allocated type is a class type T or array thereof, the allocation
2989 // function's name is looked up in the scope of T.
2990 if (AllocElemType->isRecordType() &&
2992 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2993
2994 // We can see ambiguity here if the allocation function is found in
2995 // multiple base classes.
2996 if (R.isAmbiguous())
2997 return true;
2998
2999 // If this lookup fails to find the name, or if the allocated type is not
3000 // a class type, the allocation function's name is looked up in the
3001 // global scope.
3002 if (R.empty()) {
3003 if (NewScope == AllocationFunctionScope::Class)
3004 return true;
3005
3007 }
3008
3009 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
3010 if (PlaceArgs.empty()) {
3011 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
3012 } else {
3013 Diag(StartLoc, diag::err_openclcxx_placement_new);
3014 }
3015 return true;
3016 }
3017
3018 assert(!R.empty() && "implicitly declared allocation functions not found");
3019 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3020
3021 // We do our own custom access checks below.
3023
3024 if (resolveAllocationOverload(*this, R, Range, AllocArgs, IAP, OperatorNew,
3025 /*Candidates=*/nullptr,
3026 /*AlignArg=*/nullptr, Diagnose))
3027 return true;
3028 }
3029
3030 // We don't need an operator delete if we're running under -fno-exceptions.
3031 if (!getLangOpts().Exceptions) {
3032 OperatorDelete = nullptr;
3033 return false;
3034 }
3035
3036 // Note, the name of OperatorNew might have been changed from array to
3037 // non-array by resolveAllocationOverload.
3039 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
3040 ? OO_Array_Delete
3041 : OO_Delete);
3042
3043 // C++ [expr.new]p19:
3044 //
3045 // If the new-expression begins with a unary :: operator, the
3046 // deallocation function's name is looked up in the global
3047 // scope. Otherwise, if the allocated type is a class type T or an
3048 // array thereof, the deallocation function's name is looked up in
3049 // the scope of T. If this lookup fails to find the name, or if
3050 // the allocated type is not a class type or array thereof, the
3051 // deallocation function's name is looked up in the global scope.
3052 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
3053 if (AllocElemType->isRecordType() &&
3054 DeleteScope != AllocationFunctionScope::Global) {
3055 auto *RD = AllocElemType->castAsCXXRecordDecl();
3056 LookupQualifiedName(FoundDelete, RD);
3057 }
3058 if (FoundDelete.isAmbiguous())
3059 return true; // FIXME: clean up expressions?
3060
3061 // Filter out any destroying operator deletes. We can't possibly call such a
3062 // function in this context, because we're handling the case where the object
3063 // was not successfully constructed.
3064 // FIXME: This is not covered by the language rules yet.
3065 {
3066 LookupResult::Filter Filter = FoundDelete.makeFilter();
3067 while (Filter.hasNext()) {
3068 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
3069 if (FD && FD->isDestroyingOperatorDelete())
3070 Filter.erase();
3071 }
3072 Filter.done();
3073 }
3074
3075 auto GetRedeclContext = [](Decl *D) {
3076 return D->getDeclContext()->getRedeclContext();
3077 };
3078
3079 DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew);
3080
3081 bool FoundGlobalDelete = FoundDelete.empty();
3082 bool IsClassScopedTypeAwareNew =
3084 OperatorNewContext->isRecord();
3085 auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) {
3087 if (Diagnose) {
3088 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)
3089 << OperatorNew->getDeclName() << IsPlacementOperator << DeleteName;
3090 Diag(OperatorNew->getLocation(), diag::note_type_aware_operator_declared)
3091 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3092 << OperatorNew->getDeclName() << OperatorNewContext;
3093 }
3094 };
3095 if (IsClassScopedTypeAwareNew && FoundDelete.empty()) {
3096 DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false);
3097 return true;
3098 }
3099 if (FoundDelete.empty()) {
3100 FoundDelete.clear(LookupOrdinaryName);
3101
3102 if (DeleteScope == AllocationFunctionScope::Class)
3103 return true;
3104
3106 DeallocLookupMode LookupMode = isTypeAwareAllocation(OriginalTypeAwareState)
3107 ? DeallocLookupMode::OptionallyTyped
3108 : DeallocLookupMode::Untyped;
3109 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete, LookupMode,
3110 DeleteName);
3111 }
3112
3113 FoundDelete.suppressDiagnostics();
3114
3116
3117 // Whether we're looking for a placement operator delete is dictated
3118 // by whether we selected a placement operator new, not by whether
3119 // we had explicit placement arguments. This matters for things like
3120 // struct A { void *operator new(size_t, int = 0); ... };
3121 // A *a = new A()
3122 //
3123 // We don't have any definition for what a "placement allocation function"
3124 // is, but we assume it's any allocation function whose
3125 // parameter-declaration-clause is anything other than (size_t).
3126 //
3127 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
3128 // This affects whether an exception from the constructor of an overaligned
3129 // type uses the sized or non-sized form of aligned operator delete.
3130
3131 unsigned NonPlacementNewArgCount = 1; // size parameter
3133 NonPlacementNewArgCount =
3134 /* type-identity */ 1 + /* size */ 1 + /* alignment */ 1;
3135 bool isPlacementNew = !PlaceArgs.empty() ||
3136 OperatorNew->param_size() != NonPlacementNewArgCount ||
3137 OperatorNew->isVariadic();
3138
3139 if (isPlacementNew) {
3140 // C++ [expr.new]p20:
3141 // A declaration of a placement deallocation function matches the
3142 // declaration of a placement allocation function if it has the
3143 // same number of parameters and, after parameter transformations
3144 // (8.3.5), all parameter types except the first are
3145 // identical. [...]
3146 //
3147 // To perform this comparison, we compute the function type that
3148 // the deallocation function should have, and use that type both
3149 // for template argument deduction and for comparison purposes.
3150 QualType ExpectedFunctionType;
3151 {
3152 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
3153
3154 SmallVector<QualType, 6> ArgTypes;
3155 int InitialParamOffset = 0;
3157 ArgTypes.push_back(TypeIdentity);
3158 InitialParamOffset = 1;
3159 }
3160 ArgTypes.push_back(Context.VoidPtrTy);
3161 for (unsigned I = ArgTypes.size() - InitialParamOffset,
3162 N = Proto->getNumParams();
3163 I < N; ++I)
3164 ArgTypes.push_back(Proto->getParamType(I));
3165
3167 // FIXME: This is not part of the standard's rule.
3168 EPI.Variadic = Proto->isVariadic();
3169
3170 ExpectedFunctionType
3171 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
3172 }
3173
3174 for (LookupResult::iterator D = FoundDelete.begin(),
3175 DEnd = FoundDelete.end();
3176 D != DEnd; ++D) {
3177 FunctionDecl *Fn = nullptr;
3178 if (FunctionTemplateDecl *FnTmpl =
3179 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
3180 // Perform template argument deduction to try to match the
3181 // expected function type.
3182 TemplateDeductionInfo Info(StartLoc);
3183 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
3185 continue;
3186 } else
3187 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
3188
3189 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
3190 ExpectedFunctionType,
3191 /*AdjustExcpetionSpec*/true),
3192 ExpectedFunctionType))
3193 Matches.push_back(std::make_pair(D.getPair(), Fn));
3194 }
3195
3196 if (getLangOpts().CUDA)
3197 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
3198 Matches);
3199 if (Matches.empty() && isTypeAwareAllocation(IAP.PassTypeIdentity)) {
3200 DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew);
3201 return true;
3202 }
3203 } else {
3204 // C++1y [expr.new]p22:
3205 // For a non-placement allocation function, the normal deallocation
3206 // function lookup is used
3207 //
3208 // Per [expr.delete]p10, this lookup prefers a member operator delete
3209 // without a size_t argument, but prefers a non-member operator delete
3210 // with a size_t where possible (which it always is in this case).
3213 AllocElemType, OriginalTypeAwareState,
3215 hasNewExtendedAlignment(*this, AllocElemType)),
3216 sizedDeallocationModeFromBool(FoundGlobalDelete)};
3217 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
3218 *this, FoundDelete, IDP, StartLoc, &BestDeallocFns);
3219 if (Selected && BestDeallocFns.empty())
3220 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
3221 else {
3222 // If we failed to select an operator, all remaining functions are viable
3223 // but ambiguous.
3224 for (auto Fn : BestDeallocFns)
3225 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
3226 }
3227 }
3228
3229 // C++ [expr.new]p20:
3230 // [...] If the lookup finds a single matching deallocation
3231 // function, that function will be called; otherwise, no
3232 // deallocation function will be called.
3233 if (Matches.size() == 1) {
3234 OperatorDelete = Matches[0].second;
3235 DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete);
3236 bool FoundTypeAwareOperator =
3237 OperatorDelete->isTypeAwareOperatorNewOrDelete() ||
3238 OperatorNew->isTypeAwareOperatorNewOrDelete();
3239 if (Diagnose && FoundTypeAwareOperator) {
3240 bool MismatchedTypeAwareness =
3241 OperatorDelete->isTypeAwareOperatorNewOrDelete() !=
3242 OperatorNew->isTypeAwareOperatorNewOrDelete();
3243 bool MismatchedContext = OperatorDeleteContext != OperatorNewContext;
3244 if (MismatchedTypeAwareness || MismatchedContext) {
3245 FunctionDecl *Operators[] = {OperatorDelete, OperatorNew};
3246 bool TypeAwareOperatorIndex =
3247 OperatorNew->isTypeAwareOperatorNewOrDelete();
3248 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)
3249 << Operators[TypeAwareOperatorIndex]->getDeclName()
3250 << isPlacementNew
3251 << Operators[!TypeAwareOperatorIndex]->getDeclName()
3252 << GetRedeclContext(Operators[TypeAwareOperatorIndex]);
3253 Diag(OperatorNew->getLocation(),
3254 diag::note_type_aware_operator_declared)
3255 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3256 << OperatorNew->getDeclName() << OperatorNewContext;
3257 Diag(OperatorDelete->getLocation(),
3258 diag::note_type_aware_operator_declared)
3259 << OperatorDelete->isTypeAwareOperatorNewOrDelete()
3260 << OperatorDelete->getDeclName() << OperatorDeleteContext;
3261 }
3262 }
3263
3264 // C++1z [expr.new]p23:
3265 // If the lookup finds a usual deallocation function (3.7.4.2)
3266 // with a parameter of type std::size_t and that function, considered
3267 // as a placement deallocation function, would have been
3268 // selected as a match for the allocation function, the program
3269 // is ill-formed.
3270 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
3271 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
3272 UsualDeallocFnInfo Info(*this,
3273 DeclAccessPair::make(OperatorDelete, AS_public),
3274 AllocElemType, StartLoc);
3275 // Core issue, per mail to core reflector, 2016-10-09:
3276 // If this is a member operator delete, and there is a corresponding
3277 // non-sized member operator delete, this isn't /really/ a sized
3278 // deallocation function, it just happens to have a size_t parameter.
3279 bool IsSizedDelete = isSizedDeallocation(Info.IDP.PassSize);
3280 if (IsSizedDelete && !FoundGlobalDelete) {
3281 ImplicitDeallocationParameters SizeTestingIDP = {
3282 AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment,
3284 auto NonSizedDelete = resolveDeallocationOverload(
3285 *this, FoundDelete, SizeTestingIDP, StartLoc);
3286 if (NonSizedDelete &&
3287 !isSizedDeallocation(NonSizedDelete.IDP.PassSize) &&
3288 NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment)
3289 IsSizedDelete = false;
3290 }
3291
3292 if (IsSizedDelete && !isTypeAwareAllocation(IAP.PassTypeIdentity)) {
3293 SourceRange R = PlaceArgs.empty()
3294 ? SourceRange()
3295 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3296 PlaceArgs.back()->getEndLoc());
3297 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3298 if (!OperatorDelete->isImplicit())
3299 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3300 << DeleteName;
3301 }
3302 }
3303 if (CheckDeleteOperator(*this, StartLoc, Range, Diagnose,
3304 FoundDelete.getNamingClass(), Matches[0].first,
3305 Matches[0].second))
3306 return true;
3307
3308 } else if (!Matches.empty()) {
3309 // We found multiple suitable operators. Per [expr.new]p20, that means we
3310 // call no 'operator delete' function, but we should at least warn the user.
3311 // FIXME: Suppress this warning if the construction cannot throw.
3312 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3313 << DeleteName << AllocElemType;
3314
3315 for (auto &Match : Matches)
3316 Diag(Match.second->getLocation(),
3317 diag::note_member_declared_here) << DeleteName;
3318 }
3319
3320 return false;
3321}
3322
3325 return;
3326
3327 // The implicitly declared new and delete operators
3328 // are not supported in OpenCL.
3329 if (getLangOpts().OpenCLCPlusPlus)
3330 return;
3331
3332 // C++ [basic.stc.dynamic.general]p2:
3333 // The library provides default definitions for the global allocation
3334 // and deallocation functions. Some global allocation and deallocation
3335 // functions are replaceable ([new.delete]); these are attached to the
3336 // global module ([module.unit]).
3337 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3338 PushGlobalModuleFragment(SourceLocation());
3339
3340 // C++ [basic.std.dynamic]p2:
3341 // [...] The following allocation and deallocation functions (18.4) are
3342 // implicitly declared in global scope in each translation unit of a
3343 // program
3344 //
3345 // C++03:
3346 // void* operator new(std::size_t) throw(std::bad_alloc);
3347 // void* operator new[](std::size_t) throw(std::bad_alloc);
3348 // void operator delete(void*) throw();
3349 // void operator delete[](void*) throw();
3350 // C++11:
3351 // void* operator new(std::size_t);
3352 // void* operator new[](std::size_t);
3353 // void operator delete(void*) noexcept;
3354 // void operator delete[](void*) noexcept;
3355 // C++1y:
3356 // void* operator new(std::size_t);
3357 // void* operator new[](std::size_t);
3358 // void operator delete(void*) noexcept;
3359 // void operator delete[](void*) noexcept;
3360 // void operator delete(void*, std::size_t) noexcept;
3361 // void operator delete[](void*, std::size_t) noexcept;
3362 //
3363 // These implicit declarations introduce only the function names operator
3364 // new, operator new[], operator delete, operator delete[].
3365 //
3366 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3367 // "std" or "bad_alloc" as necessary to form the exception specification.
3368 // However, we do not make these implicit declarations visible to name
3369 // lookup.
3370 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3371 // The "std::bad_alloc" class has not yet been declared, so build it
3372 // implicitly.
3376 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3377 getStdBadAlloc()->setImplicit(true);
3378
3379 // The implicitly declared "std::bad_alloc" should live in global module
3380 // fragment.
3381 if (TheGlobalModuleFragment) {
3384 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3385 }
3386 }
3387 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3388 // The "std::align_val_t" enum class has not yet been declared, so build it
3389 // implicitly.
3390 auto *AlignValT = EnumDecl::Create(
3392 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3393
3394 // The implicitly declared "std::align_val_t" should live in global module
3395 // fragment.
3396 if (TheGlobalModuleFragment) {
3397 AlignValT->setModuleOwnershipKind(
3399 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3400 }
3401
3402 AlignValT->setIntegerType(Context.getSizeType());
3403 AlignValT->setPromotionType(Context.getSizeType());
3404 AlignValT->setImplicit(true);
3405
3406 StdAlignValT = AlignValT;
3407 }
3408
3410
3413
3414 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3415 QualType Return, QualType Param) {
3417 Params.push_back(Param);
3418
3419 // Create up to four variants of the function (sized/aligned).
3420 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3421 (Kind == OO_Delete || Kind == OO_Array_Delete);
3422 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3423
3424 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3425 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3426 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3427 if (Sized)
3428 Params.push_back(SizeT);
3429
3430 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3431 if (Aligned)
3432 Params.push_back(Context.getCanonicalTagType(getStdAlignValT()));
3433
3435 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3436
3437 if (Aligned)
3438 Params.pop_back();
3439 }
3440 }
3441 };
3442
3443 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3444 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3445 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3446 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3447
3448 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3449 PopGlobalModuleFragment();
3450}
3451
3452/// DeclareGlobalAllocationFunction - Declares a single implicit global
3453/// allocation function if it doesn't already exist.
3455 QualType Return,
3456 ArrayRef<QualType> Params) {
3458
3459 // Check if this function is already declared.
3460 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3461 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3462 Alloc != AllocEnd; ++Alloc) {
3463 // Only look at non-template functions, as it is the predefined,
3464 // non-templated allocation function we are trying to declare here.
3465 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3466 if (Func->getNumParams() == Params.size()) {
3467 if (std::equal(Func->param_begin(), Func->param_end(), Params.begin(),
3468 Params.end(), [&](ParmVarDecl *D, QualType RT) {
3469 return Context.hasSameUnqualifiedType(D->getType(),
3470 RT);
3471 })) {
3472 // Make the function visible to name lookup, even if we found it in
3473 // an unimported module. It either is an implicitly-declared global
3474 // allocation function, or is suppressing that function.
3475 Func->setVisibleDespiteOwningModule();
3476 return;
3477 }
3478 }
3479 }
3480 }
3481
3484
3485 QualType BadAllocType;
3486 bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew();
3487 if (HasBadAllocExceptionSpec) {
3488 if (!getLangOpts().CPlusPlus11) {
3489 BadAllocType = Context.getCanonicalTagType(getStdBadAlloc());
3490 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3492 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3493 }
3494 if (getLangOpts().NewInfallible) {
3496 }
3497 } else {
3498 EPI.ExceptionSpec =
3500 }
3501
3502 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3503 // The MSVC STL has explicit cdecl on its (host-side) allocation function
3504 // specializations for the allocation, so in order to prevent a CC clash
3505 // we use the host's CC, if available, or CC_C as a fallback, for the
3506 // host-side implicit decls, knowing these do not get emitted when compiling
3507 // for device.
3508 if (getLangOpts().CUDAIsDevice && ExtraAttr &&
3509 isa<CUDAHostAttr>(ExtraAttr) &&
3510 Context.getTargetInfo().getTriple().isSPIRV()) {
3511 if (auto *ATI = Context.getAuxTargetInfo())
3512 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(ATI->getDefaultCallingConv());
3513 else
3515 }
3516 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3518 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3519 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3520 true);
3521 Alloc->setImplicit();
3522 // Global allocation functions should always be visible.
3523 Alloc->setVisibleDespiteOwningModule();
3524
3525 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3526 !getLangOpts().CheckNew)
3527 Alloc->addAttr(
3528 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3529
3530 // C++ [basic.stc.dynamic.general]p2:
3531 // The library provides default definitions for the global allocation
3532 // and deallocation functions. Some global allocation and deallocation
3533 // functions are replaceable ([new.delete]); these are attached to the
3534 // global module ([module.unit]).
3535 //
3536 // In the language wording, these functions are attched to the global
3537 // module all the time. But in the implementation, the global module
3538 // is only meaningful when we're in a module unit. So here we attach
3539 // these allocation functions to global module conditionally.
3540 if (TheGlobalModuleFragment) {
3541 Alloc->setModuleOwnershipKind(
3543 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3544 }
3545
3547 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3549 ? VisibilityAttr::Hidden
3551 ? VisibilityAttr::Protected
3552 : VisibilityAttr::Default));
3553
3555 for (QualType T : Params) {
3556 ParamDecls.push_back(ParmVarDecl::Create(
3557 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3558 /*TInfo=*/nullptr, SC_None, nullptr));
3559 ParamDecls.back()->setImplicit();
3560 }
3561 Alloc->setParams(ParamDecls);
3562 if (ExtraAttr)
3563 Alloc->addAttr(ExtraAttr);
3566 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3567 };
3568
3569 if (!LangOpts.CUDA)
3570 CreateAllocationFunctionDecl(nullptr);
3571 else {
3572 // Host and device get their own declaration so each can be
3573 // defined or re-declared independently.
3574 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3575 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3576 }
3577}
3578
3582 DeclarationName Name) {
3584
3585 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3586 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete,
3587 DeallocLookupMode::OptionallyTyped, Name);
3588
3589 // FIXME: It's possible for this to result in ambiguity, through a
3590 // user-declared variadic operator delete or the enable_if attribute. We
3591 // should probably not consider those cases to be usual deallocation
3592 // functions. But for now we just make an arbitrary choice in that case.
3593 auto Result = resolveDeallocationOverload(*this, FoundDelete, IDP, StartLoc);
3594 if (!Result)
3595 return nullptr;
3596
3597 if (CheckDeleteOperator(*this, StartLoc, StartLoc, /*Diagnose=*/true,
3598 FoundDelete.getNamingClass(), Result.Found,
3599 Result.FD))
3600 return nullptr;
3601
3602 assert(Result.FD && "operator delete missing from global scope?");
3603 return Result.FD;
3604}
3605
3607 CXXRecordDecl *RD,
3608 bool Diagnose) {
3610
3611 FunctionDecl *OperatorDelete = nullptr;
3612 CanQualType DeallocType = Context.getCanonicalTagType(RD);
3616
3617 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, IDP, Diagnose))
3618 return nullptr;
3619
3620 if (OperatorDelete)
3621 return OperatorDelete;
3622
3623 // If there's no class-specific operator delete, look up the global
3624 // non-array delete.
3626 hasNewExtendedAlignment(*this, DeallocType));
3628 return FindUsualDeallocationFunction(Loc, IDP, Name);
3629}
3630
3632 DeclarationName Name,
3633 FunctionDecl *&Operator,
3635 bool Diagnose) {
3636 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3637 // Try to find operator delete/operator delete[] in class scope.
3639
3640 if (Found.isAmbiguous())
3641 return true;
3642
3643 Found.suppressDiagnostics();
3644
3648
3649 // C++17 [expr.delete]p10:
3650 // If the deallocation functions have class scope, the one without a
3651 // parameter of type std::size_t is selected.
3653 resolveDeallocationOverload(*this, Found, IDP, StartLoc, &Matches);
3654
3655 // If we could find an overload, use it.
3656 if (Matches.size() == 1) {
3657 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3658 return CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,
3659 Found.getNamingClass(), Matches[0].Found,
3660 Operator);
3661 }
3662
3663 // We found multiple suitable operators; complain about the ambiguity.
3664 // FIXME: The standard doesn't say to do this; it appears that the intent
3665 // is that this should never happen.
3666 if (!Matches.empty()) {
3667 if (Diagnose) {
3668 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3669 << Name << RD;
3670 for (auto &Match : Matches)
3671 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3672 }
3673 return true;
3674 }
3675
3676 // We did find operator delete/operator delete[] declarations, but
3677 // none of them were suitable.
3678 if (!Found.empty()) {
3679 if (Diagnose) {
3680 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3681 << Name << RD;
3682
3683 for (NamedDecl *D : Found)
3684 Diag(D->getUnderlyingDecl()->getLocation(),
3685 diag::note_member_declared_here) << Name;
3686 }
3687 return true;
3688 }
3689
3690 Operator = nullptr;
3691 return false;
3692}
3693
3694namespace {
3695/// Checks whether delete-expression, and new-expression used for
3696/// initializing deletee have the same array form.
3697class MismatchingNewDeleteDetector {
3698public:
3699 enum MismatchResult {
3700 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3701 NoMismatch,
3702 /// Indicates that variable is initialized with mismatching form of \a new.
3703 VarInitMismatches,
3704 /// Indicates that member is initialized with mismatching form of \a new.
3705 MemberInitMismatches,
3706 /// Indicates that 1 or more constructors' definitions could not been
3707 /// analyzed, and they will be checked again at the end of translation unit.
3708 AnalyzeLater
3709 };
3710
3711 /// \param EndOfTU True, if this is the final analysis at the end of
3712 /// translation unit. False, if this is the initial analysis at the point
3713 /// delete-expression was encountered.
3714 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3715 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3716 HasUndefinedConstructors(false) {}
3717
3718 /// Checks whether pointee of a delete-expression is initialized with
3719 /// matching form of new-expression.
3720 ///
3721 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3722 /// point where delete-expression is encountered, then a warning will be
3723 /// issued immediately. If return value is \c AnalyzeLater at the point where
3724 /// delete-expression is seen, then member will be analyzed at the end of
3725 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3726 /// couldn't be analyzed. If at least one constructor initializes the member
3727 /// with matching type of new, the return value is \c NoMismatch.
3728 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3729 /// Analyzes a class member.
3730 /// \param Field Class member to analyze.
3731 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3732 /// for deleting the \p Field.
3733 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3735 /// List of mismatching new-expressions used for initialization of the pointee
3737 /// Indicates whether delete-expression was in array form.
3738 bool IsArrayForm;
3739
3740private:
3741 const bool EndOfTU;
3742 /// Indicates that there is at least one constructor without body.
3743 bool HasUndefinedConstructors;
3744 /// Returns \c CXXNewExpr from given initialization expression.
3745 /// \param E Expression used for initializing pointee in delete-expression.
3746 /// E can be a single-element \c InitListExpr consisting of new-expression.
3747 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3748 /// Returns whether member is initialized with mismatching form of
3749 /// \c new either by the member initializer or in-class initialization.
3750 ///
3751 /// If bodies of all constructors are not visible at the end of translation
3752 /// unit or at least one constructor initializes member with the matching
3753 /// form of \c new, mismatch cannot be proven, and this function will return
3754 /// \c NoMismatch.
3755 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3756 /// Returns whether variable is initialized with mismatching form of
3757 /// \c new.
3758 ///
3759 /// If variable is initialized with matching form of \c new or variable is not
3760 /// initialized with a \c new expression, this function will return true.
3761 /// If variable is initialized with mismatching form of \c new, returns false.
3762 /// \param D Variable to analyze.
3763 bool hasMatchingVarInit(const DeclRefExpr *D);
3764 /// Checks whether the constructor initializes pointee with mismatching
3765 /// form of \c new.
3766 ///
3767 /// Returns true, if member is initialized with matching form of \c new in
3768 /// member initializer list. Returns false, if member is initialized with the
3769 /// matching form of \c new in this constructor's initializer or given
3770 /// constructor isn't defined at the point where delete-expression is seen, or
3771 /// member isn't initialized by the constructor.
3772 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3773 /// Checks whether member is initialized with matching form of
3774 /// \c new in member initializer list.
3775 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3776 /// Checks whether member is initialized with mismatching form of \c new by
3777 /// in-class initializer.
3778 MismatchResult analyzeInClassInitializer();
3779};
3780}
3781
3782MismatchingNewDeleteDetector::MismatchResult
3783MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3784 NewExprs.clear();
3785 assert(DE && "Expected delete-expression");
3786 IsArrayForm = DE->isArrayForm();
3787 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3788 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3789 return analyzeMemberExpr(ME);
3790 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3791 if (!hasMatchingVarInit(D))
3792 return VarInitMismatches;
3793 }
3794 return NoMismatch;
3795}
3796
3797const CXXNewExpr *
3798MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3799 assert(E != nullptr && "Expected a valid initializer expression");
3800 E = E->IgnoreParenImpCasts();
3801 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3802 if (ILE->getNumInits() == 1)
3803 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3804 }
3805
3806 return dyn_cast_or_null<const CXXNewExpr>(E);
3807}
3808
3809bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3810 const CXXCtorInitializer *CI) {
3811 const CXXNewExpr *NE = nullptr;
3812 if (Field == CI->getMember() &&
3813 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3814 if (NE->isArray() == IsArrayForm)
3815 return true;
3816 else
3817 NewExprs.push_back(NE);
3818 }
3819 return false;
3820}
3821
3822bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3823 const CXXConstructorDecl *CD) {
3824 if (CD->isImplicit())
3825 return false;
3826 const FunctionDecl *Definition = CD;
3828 HasUndefinedConstructors = true;
3829 return EndOfTU;
3830 }
3831 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3832 if (hasMatchingNewInCtorInit(CI))
3833 return true;
3834 }
3835 return false;
3836}
3837
3838MismatchingNewDeleteDetector::MismatchResult
3839MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3840 assert(Field != nullptr && "This should be called only for members");
3841 const Expr *InitExpr = Field->getInClassInitializer();
3842 if (!InitExpr)
3843 return EndOfTU ? NoMismatch : AnalyzeLater;
3844 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3845 if (NE->isArray() != IsArrayForm) {
3846 NewExprs.push_back(NE);
3847 return MemberInitMismatches;
3848 }
3849 }
3850 return NoMismatch;
3851}
3852
3853MismatchingNewDeleteDetector::MismatchResult
3854MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3855 bool DeleteWasArrayForm) {
3856 assert(Field != nullptr && "Analysis requires a valid class member.");
3857 this->Field = Field;
3858 IsArrayForm = DeleteWasArrayForm;
3859 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3860 for (const auto *CD : RD->ctors()) {
3861 if (hasMatchingNewInCtor(CD))
3862 return NoMismatch;
3863 }
3864 if (HasUndefinedConstructors)
3865 return EndOfTU ? NoMismatch : AnalyzeLater;
3866 if (!NewExprs.empty())
3867 return MemberInitMismatches;
3868 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3869 : NoMismatch;
3870}
3871
3872MismatchingNewDeleteDetector::MismatchResult
3873MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3874 assert(ME != nullptr && "Expected a member expression");
3875 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3876 return analyzeField(F, IsArrayForm);
3877 return NoMismatch;
3878}
3879
3880bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3881 const CXXNewExpr *NE = nullptr;
3882 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3883 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3884 NE->isArray() != IsArrayForm) {
3885 NewExprs.push_back(NE);
3886 }
3887 }
3888 return NewExprs.empty();
3889}
3890
3891static void
3893 const MismatchingNewDeleteDetector &Detector) {
3894 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3895 FixItHint H;
3896 if (!Detector.IsArrayForm)
3897 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3898 else {
3900 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3901 SemaRef.getLangOpts(), true);
3902 if (RSquare.isValid())
3903 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3904 }
3905 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3906 << Detector.IsArrayForm << H;
3907
3908 for (const auto *NE : Detector.NewExprs)
3909 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3910 << Detector.IsArrayForm;
3911}
3912
3913void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3914 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3915 return;
3916 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3917 switch (Detector.analyzeDeleteExpr(DE)) {
3918 case MismatchingNewDeleteDetector::VarInitMismatches:
3919 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3920 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3921 break;
3922 }
3923 case MismatchingNewDeleteDetector::AnalyzeLater: {
3924 DeleteExprs[Detector.Field].push_back(
3925 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3926 break;
3927 }
3928 case MismatchingNewDeleteDetector::NoMismatch:
3929 break;
3930 }
3931}
3932
3933void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3934 bool DeleteWasArrayForm) {
3935 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3936 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3937 case MismatchingNewDeleteDetector::VarInitMismatches:
3938 llvm_unreachable("This analysis should have been done for class members.");
3939 case MismatchingNewDeleteDetector::AnalyzeLater:
3940 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3941 "translation unit.");
3942 case MismatchingNewDeleteDetector::MemberInitMismatches:
3943 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3944 break;
3945 case MismatchingNewDeleteDetector::NoMismatch:
3946 break;
3947 }
3948}
3949
3951Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3952 bool ArrayForm, Expr *ExE) {
3953 // C++ [expr.delete]p1:
3954 // The operand shall have a pointer type, or a class type having a single
3955 // non-explicit conversion function to a pointer type. The result has type
3956 // void.
3957 //
3958 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3959
3960 ExprResult Ex = ExE;
3961 FunctionDecl *OperatorDelete = nullptr;
3962 bool ArrayFormAsWritten = ArrayForm;
3963 bool UsualArrayDeleteWantsSize = false;
3964
3965 if (!Ex.get()->isTypeDependent()) {
3966 // Perform lvalue-to-rvalue cast, if needed.
3967 Ex = DefaultLvalueConversion(Ex.get());
3968 if (Ex.isInvalid())
3969 return ExprError();
3970
3971 QualType Type = Ex.get()->getType();
3972
3973 class DeleteConverter : public ContextualImplicitConverter {
3974 public:
3975 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3976
3977 bool match(QualType ConvType) override {
3978 // FIXME: If we have an operator T* and an operator void*, we must pick
3979 // the operator T*.
3980 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3981 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3982 return true;
3983 return false;
3984 }
3985
3986 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3987 QualType T) override {
3988 return S.Diag(Loc, diag::err_delete_operand) << T;
3989 }
3990
3991 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3992 QualType T) override {
3993 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3994 }
3995
3996 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3997 QualType T,
3998 QualType ConvTy) override {
3999 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
4000 }
4001
4002 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4003 QualType ConvTy) override {
4004 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
4005 << ConvTy;
4006 }
4007
4008 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4009 QualType T) override {
4010 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
4011 }
4012
4013 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4014 QualType ConvTy) override {
4015 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
4016 << ConvTy;
4017 }
4018
4019 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
4020 QualType T,
4021 QualType ConvTy) override {
4022 llvm_unreachable("conversion functions are permitted");
4023 }
4024 } Converter;
4025
4026 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
4027 if (Ex.isInvalid())
4028 return ExprError();
4029 Type = Ex.get()->getType();
4030 if (!Converter.match(Type))
4031 // FIXME: PerformContextualImplicitConversion should return ExprError
4032 // itself in this case.
4033 return ExprError();
4034
4036 QualType PointeeElem = Context.getBaseElementType(Pointee);
4037
4038 if (Pointee.getAddressSpace() != LangAS::Default &&
4039 !getLangOpts().OpenCLCPlusPlus)
4040 return Diag(Ex.get()->getBeginLoc(),
4041 diag::err_address_space_qualified_delete)
4042 << Pointee.getUnqualifiedType()
4044
4045 CXXRecordDecl *PointeeRD = nullptr;
4046 if (Pointee->isVoidType() && !isSFINAEContext()) {
4047 // The C++ standard bans deleting a pointer to a non-object type, which
4048 // effectively bans deletion of "void*". However, most compilers support
4049 // this, so we treat it as a warning unless we're in a SFINAE context.
4050 // But we still prohibit this since C++26.
4051 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
4052 : diag::ext_delete_void_ptr_operand)
4053 << (LangOpts.CPlusPlus26 ? Pointee : Type)
4054 << Ex.get()->getSourceRange();
4055 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
4056 Pointee->isSizelessType()) {
4057 return ExprError(Diag(StartLoc, diag::err_delete_operand)
4058 << Type << Ex.get()->getSourceRange());
4059 } else if (!Pointee->isDependentType()) {
4060 // FIXME: This can result in errors if the definition was imported from a
4061 // module but is hidden.
4062 if (Pointee->isEnumeralType() ||
4063 !RequireCompleteType(StartLoc, Pointee,
4064 LangOpts.CPlusPlus26
4065 ? diag::err_delete_incomplete
4066 : diag::warn_delete_incomplete,
4067 Ex.get())) {
4068 PointeeRD = PointeeElem->getAsCXXRecordDecl();
4069 }
4070 }
4071
4072 if (Pointee->isArrayType() && !ArrayForm) {
4073 Diag(StartLoc, diag::warn_delete_array_type)
4074 << Type << Ex.get()->getSourceRange()
4076 ArrayForm = true;
4077 }
4078
4080 ArrayForm ? OO_Array_Delete : OO_Delete);
4081
4082 if (PointeeRD) {
4086 if (!UseGlobal &&
4087 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
4088 OperatorDelete, IDP))
4089 return ExprError();
4090
4091 // If we're allocating an array of records, check whether the
4092 // usual operator delete[] has a size_t parameter.
4093 if (ArrayForm) {
4094 // If the user specifically asked to use the global allocator,
4095 // we'll need to do the lookup into the class.
4096 if (UseGlobal)
4097 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
4098 *this, StartLoc, IDP.PassTypeIdentity, PointeeElem);
4099
4100 // Otherwise, the usual operator delete[] should be the
4101 // function we just found.
4102 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete)) {
4103 UsualDeallocFnInfo UDFI(
4104 *this, DeclAccessPair::make(OperatorDelete, AS_public), Pointee,
4105 StartLoc);
4106 UsualArrayDeleteWantsSize = isSizedDeallocation(UDFI.IDP.PassSize);
4107 }
4108 }
4109
4110 if (!PointeeRD->hasIrrelevantDestructor()) {
4111 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
4112 if (Dtor->isCalledByDelete(OperatorDelete)) {
4113 MarkFunctionReferenced(StartLoc, Dtor);
4114 if (DiagnoseUseOfDecl(Dtor, StartLoc))
4115 return ExprError();
4116 }
4117 }
4118 }
4119
4120 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
4121 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
4122 /*WarnOnNonAbstractTypes=*/!ArrayForm,
4123 SourceLocation());
4124 }
4125
4126 if (!OperatorDelete) {
4127 if (getLangOpts().OpenCLCPlusPlus) {
4128 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
4129 return ExprError();
4130 }
4131
4132 bool IsComplete = isCompleteType(StartLoc, Pointee);
4133 bool CanProvideSize =
4134 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
4135 Pointee.isDestructedType());
4136 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
4137
4138 // Look for a global declaration.
4141 alignedAllocationModeFromBool(Overaligned),
4142 sizedDeallocationModeFromBool(CanProvideSize)};
4143 OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, DeleteName);
4144 if (!OperatorDelete)
4145 return ExprError();
4146 }
4147
4148 if (OperatorDelete->isInvalidDecl())
4149 return ExprError();
4150
4151 MarkFunctionReferenced(StartLoc, OperatorDelete);
4152
4153 // Check access and ambiguity of destructor if we're going to call it.
4154 // Note that this is required even for a virtual delete.
4155 bool IsVirtualDelete = false;
4156 if (PointeeRD) {
4157 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
4158 if (Dtor->isCalledByDelete(OperatorDelete))
4159 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
4160 PDiag(diag::err_access_dtor) << PointeeElem);
4161 IsVirtualDelete = Dtor->isVirtual();
4162 }
4163 }
4164
4165 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
4166
4167 unsigned AddressParamIdx = 0;
4168 if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {
4169 QualType TypeIdentity = OperatorDelete->getParamDecl(0)->getType();
4170 if (RequireCompleteType(StartLoc, TypeIdentity,
4171 diag::err_incomplete_type))
4172 return ExprError();
4173 AddressParamIdx = 1;
4174 }
4175
4176 // Convert the operand to the type of the first parameter of operator
4177 // delete. This is only necessary if we selected a destroying operator
4178 // delete that we are going to call (non-virtually); converting to void*
4179 // is trivial and left to AST consumers to handle.
4180 QualType ParamType =
4181 OperatorDelete->getParamDecl(AddressParamIdx)->getType();
4182 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
4183 Qualifiers Qs = Pointee.getQualifiers();
4184 if (Qs.hasCVRQualifiers()) {
4185 // Qualifiers are irrelevant to this conversion; we're only looking
4186 // for access and ambiguity.
4190 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
4191 }
4192 Ex = PerformImplicitConversion(Ex.get(), ParamType,
4194 if (Ex.isInvalid())
4195 return ExprError();
4196 }
4197 }
4198
4200 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
4201 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
4202 AnalyzeDeleteExprMismatch(Result);
4203 return Result;
4204}
4205
4207 bool IsDelete,
4208 FunctionDecl *&Operator) {
4209
4211 IsDelete ? OO_Delete : OO_New);
4212
4213 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
4215 assert(!R.empty() && "implicitly declared allocation functions not found");
4216 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
4217
4218 // We do our own custom access checks below.
4220
4221 SmallVector<Expr *, 8> Args(TheCall->arguments());
4222 OverloadCandidateSet Candidates(R.getNameLoc(),
4224 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
4225 FnOvl != FnOvlEnd; ++FnOvl) {
4226 // Even member operator new/delete are implicitly treated as
4227 // static, so don't use AddMemberCandidate.
4228 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
4229
4230 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
4231 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
4232 /*ExplicitTemplateArgs=*/nullptr, Args,
4233 Candidates,
4234 /*SuppressUserConversions=*/false);
4235 continue;
4236 }
4237
4238 FunctionDecl *Fn = cast<FunctionDecl>(D);
4239 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
4240 /*SuppressUserConversions=*/false);
4241 }
4242
4243 SourceRange Range = TheCall->getSourceRange();
4244
4245 // Do the resolution.
4247 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
4248 case OR_Success: {
4249 // Got one!
4250 FunctionDecl *FnDecl = Best->Function;
4251 assert(R.getNamingClass() == nullptr &&
4252 "class members should not be considered");
4253
4255 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
4256 << (IsDelete ? 1 : 0) << Range;
4257 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
4258 << R.getLookupName() << FnDecl->getSourceRange();
4259 return true;
4260 }
4261
4262 Operator = FnDecl;
4263 return false;
4264 }
4265
4267 Candidates.NoteCandidates(
4269 S.PDiag(diag::err_ovl_no_viable_function_in_call)
4270 << R.getLookupName() << Range),
4271 S, OCD_AllCandidates, Args);
4272 return true;
4273
4274 case OR_Ambiguous:
4275 Candidates.NoteCandidates(
4277 S.PDiag(diag::err_ovl_ambiguous_call)
4278 << R.getLookupName() << Range),
4279 S, OCD_AmbiguousCandidates, Args);
4280 return true;
4281
4282 case OR_Deleted:
4284 Candidates, Best->Function, Args);
4285 return true;
4286 }
4287 llvm_unreachable("Unreachable, bad result from BestViableFunction");
4288}
4289
4290ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
4291 bool IsDelete) {
4292 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4293 if (!getLangOpts().CPlusPlus) {
4294 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
4295 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
4296 << "C++";
4297 return ExprError();
4298 }
4299 // CodeGen assumes it can find the global new and delete to call,
4300 // so ensure that they are declared.
4302
4303 FunctionDecl *OperatorNewOrDelete = nullptr;
4304 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
4305 OperatorNewOrDelete))
4306 return ExprError();
4307 assert(OperatorNewOrDelete && "should be found");
4308
4309 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
4310 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
4311
4312 TheCall->setType(OperatorNewOrDelete->getReturnType());
4313 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4314 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4315 InitializedEntity Entity =
4318 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
4319 if (Arg.isInvalid())
4320 return ExprError();
4321 TheCall->setArg(i, Arg.get());
4322 }
4323 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
4324 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4325 "Callee expected to be implicit cast to a builtin function pointer");
4326 Callee->setType(OperatorNewOrDelete->getType());
4327
4328 return TheCallResult;
4329}
4330
4332 bool IsDelete, bool CallCanBeVirtual,
4333 bool WarnOnNonAbstractTypes,
4334 SourceLocation DtorLoc) {
4335 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4336 return;
4337
4338 // C++ [expr.delete]p3:
4339 // In the first alternative (delete object), if the static type of the
4340 // object to be deleted is different from its dynamic type, the static
4341 // type shall be a base class of the dynamic type of the object to be
4342 // deleted and the static type shall have a virtual destructor or the
4343 // behavior is undefined.
4344 //
4345 const CXXRecordDecl *PointeeRD = dtor->getParent();
4346 // Note: a final class cannot be derived from, no issue there
4347 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4348 return;
4349
4350 // If the superclass is in a system header, there's nothing that can be done.
4351 // The `delete` (where we emit the warning) can be in a system header,
4352 // what matters for this warning is where the deleted type is defined.
4353 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4354 return;
4355
4356 QualType ClassType = dtor->getFunctionObjectParameterType();
4357 if (PointeeRD->isAbstract()) {
4358 // If the class is abstract, we warn by default, because we're
4359 // sure the code has undefined behavior.
4360 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4361 << ClassType;
4362 } else if (WarnOnNonAbstractTypes) {
4363 // Otherwise, if this is not an array delete, it's a bit suspect,
4364 // but not necessarily wrong.
4365 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4366 << ClassType;
4367 }
4368 if (!IsDelete) {
4369 std::string TypeStr;
4370 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4371 Diag(DtorLoc, diag::note_delete_non_virtual)
4372 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4373 }
4374}
4375
4377 SourceLocation StmtLoc,
4378 ConditionKind CK) {
4379 ExprResult E =
4380 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4381 if (E.isInvalid())
4382 return ConditionError();
4383 E = ActOnFinishFullExpr(E.get(), /*DiscardedValue*/ false);
4384 return ConditionResult(*this, ConditionVar, E,
4386}
4387
4389 SourceLocation StmtLoc,
4390 ConditionKind CK) {
4391 if (ConditionVar->isInvalidDecl())
4392 return ExprError();
4393
4394 QualType T = ConditionVar->getType();
4395
4396 // C++ [stmt.select]p2:
4397 // The declarator shall not specify a function or an array.
4398 if (T->isFunctionType())
4399 return ExprError(Diag(ConditionVar->getLocation(),
4400 diag::err_invalid_use_of_function_type)
4401 << ConditionVar->getSourceRange());
4402 else if (T->isArrayType())
4403 return ExprError(Diag(ConditionVar->getLocation(),
4404 diag::err_invalid_use_of_array_type)
4405 << ConditionVar->getSourceRange());
4406
4408 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4409 ConditionVar->getLocation());
4410
4411 switch (CK) {
4413 return CheckBooleanCondition(StmtLoc, Condition.get());
4414
4416 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4417
4419 return CheckSwitchCondition(StmtLoc, Condition.get());
4420 }
4421
4422 llvm_unreachable("unexpected condition kind");
4423}
4424
4425ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4426 // C++11 6.4p4:
4427 // The value of a condition that is an initialized declaration in a statement
4428 // other than a switch statement is the value of the declared variable
4429 // implicitly converted to type bool. If that conversion is ill-formed, the
4430 // program is ill-formed.
4431 // The value of a condition that is an expression is the value of the
4432 // expression, implicitly converted to bool.
4433 //
4434 // C++23 8.5.2p2
4435 // If the if statement is of the form if constexpr, the value of the condition
4436 // is contextually converted to bool and the converted expression shall be
4437 // a constant expression.
4438 //
4439
4441 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4442 return E;
4443
4444 E = ActOnFinishFullExpr(E.get(), E.get()->getExprLoc(),
4445 /*DiscardedValue*/ false,
4446 /*IsConstexpr*/ true);
4447 if (E.isInvalid())
4448 return E;
4449
4450 // FIXME: Return this value to the caller so they don't need to recompute it.
4451 llvm::APSInt Cond;
4453 E.get(), &Cond,
4454 diag::err_constexpr_if_condition_expression_is_not_constant);
4455 return E;
4456}
4457
4458bool
4460 // Look inside the implicit cast, if it exists.
4461 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4462 From = Cast->getSubExpr();
4463
4464 // A string literal (2.13.4) that is not a wide string literal can
4465 // be converted to an rvalue of type "pointer to char"; a wide
4466 // string literal can be converted to an rvalue of type "pointer
4467 // to wchar_t" (C++ 4.2p2).
4468 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4469 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4470 if (const BuiltinType *ToPointeeType
4471 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4472 // This conversion is considered only when there is an
4473 // explicit appropriate pointer target type (C++ 4.2p2).
4474 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4475 switch (StrLit->getKind()) {
4479 // We don't allow UTF literals to be implicitly converted
4480 break;
4483 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4484 ToPointeeType->getKind() == BuiltinType::Char_S);
4487 QualType(ToPointeeType, 0));
4489 assert(false && "Unevaluated string literal in expression");
4490 break;
4491 }
4492 }
4493 }
4494
4495 return false;
4496}
4497
4499 SourceLocation CastLoc,
4500 QualType Ty,
4501 CastKind Kind,
4503 DeclAccessPair FoundDecl,
4504 bool HadMultipleCandidates,
4505 Expr *From) {
4506 switch (Kind) {
4507 default: llvm_unreachable("Unhandled cast kind!");
4508 case CK_ConstructorConversion: {
4509 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4510 SmallVector<Expr*, 8> ConstructorArgs;
4511
4512 if (S.RequireNonAbstractType(CastLoc, Ty,
4513 diag::err_allocation_of_abstract_type))
4514 return ExprError();
4515
4516 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4517 ConstructorArgs))
4518 return ExprError();
4519
4520 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4522 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4523 return ExprError();
4524
4526 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4527 ConstructorArgs, HadMultipleCandidates,
4528 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4530 if (Result.isInvalid())
4531 return ExprError();
4532
4533 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4534 }
4535
4536 case CK_UserDefinedConversion: {
4537 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4538
4539 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4540 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4541 return ExprError();
4542
4543 // Create an implicit call expr that calls it.
4544 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4545 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4546 HadMultipleCandidates);
4547 if (Result.isInvalid())
4548 return ExprError();
4549 // Record usage of conversion in an implicit cast.
4550 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4551 CK_UserDefinedConversion, Result.get(),
4552 nullptr, Result.get()->getValueKind(),
4554
4555 return S.MaybeBindToTemporary(Result.get());
4556 }
4557 }
4558}
4559
4562 const ImplicitConversionSequence &ICS,
4563 AssignmentAction Action,
4565 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4567 !From->getType()->isRecordType())
4568 return From;
4569
4570 switch (ICS.getKind()) {
4572 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4573 Action, CCK);
4574 if (Res.isInvalid())
4575 return ExprError();
4576 From = Res.get();
4577 break;
4578 }
4579
4581
4584 QualType BeforeToType;
4585 assert(FD && "no conversion function for user-defined conversion seq");
4586 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4587 CastKind = CK_UserDefinedConversion;
4588
4589 // If the user-defined conversion is specified by a conversion function,
4590 // the initial standard conversion sequence converts the source type to
4591 // the implicit object parameter of the conversion function.
4592 BeforeToType = Context.getCanonicalTagType(Conv->getParent());
4593 } else {
4594 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4595 CastKind = CK_ConstructorConversion;
4596 // Do no conversion if dealing with ... for the first conversion.
4598 // If the user-defined conversion is specified by a constructor, the
4599 // initial standard conversion sequence converts the source type to
4600 // the type required by the argument of the constructor
4601 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4602 }
4603 }
4604 // Watch out for ellipsis conversion.
4607 From, BeforeToType, ICS.UserDefined.Before,
4609 if (Res.isInvalid())
4610 return ExprError();
4611 From = Res.get();
4612 }
4613
4615 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4616 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4618
4619 if (CastArg.isInvalid())
4620 return ExprError();
4621
4622 From = CastArg.get();
4623
4624 // C++ [over.match.oper]p7:
4625 // [...] the second standard conversion sequence of a user-defined
4626 // conversion sequence is not applied.
4628 return From;
4629
4630 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4632 }
4633
4635 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4636 PDiag(diag::err_typecheck_ambiguous_condition)
4637 << From->getSourceRange());
4638 return ExprError();
4639
4642 llvm_unreachable("bad conversion");
4643
4645 AssignConvertType ConvTy =
4646 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4647 bool Diagnosed = DiagnoseAssignmentResult(
4650 : ConvTy,
4651 From->getExprLoc(), ToType, From->getType(), From, Action);
4652 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4653 return ExprError();
4654 }
4655
4656 // Everything went well.
4657 return From;
4658}
4659
4660// adjustVectorType - Compute the intermediate cast type casting elements of the
4661// from type to the elements of the to type without resizing the vector.
4663 QualType ToType, QualType *ElTy = nullptr) {
4664 QualType ElType = ToType;
4665 if (auto *ToVec = ToType->getAs<VectorType>())
4666 ElType = ToVec->getElementType();
4667
4668 if (ElTy)
4669 *ElTy = ElType;
4670 if (!FromTy->isVectorType())
4671 return ElType;
4672 auto *FromVec = FromTy->castAs<VectorType>();
4673 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4674}
4675
4678 const StandardConversionSequence& SCS,
4679 AssignmentAction Action,
4681 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4683
4684 // Overall FIXME: we are recomputing too many types here and doing far too
4685 // much extra work. What this means is that we need to keep track of more
4686 // information that is computed when we try the implicit conversion initially,
4687 // so that we don't need to recompute anything here.
4688 QualType FromType = From->getType();
4689
4690 if (SCS.CopyConstructor) {
4691 // FIXME: When can ToType be a reference type?
4692 assert(!ToType->isReferenceType());
4693 if (SCS.Second == ICK_Derived_To_Base) {
4694 SmallVector<Expr*, 8> ConstructorArgs;
4696 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4697 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4698 return ExprError();
4699 return BuildCXXConstructExpr(
4700 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4701 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4702 /*HadMultipleCandidates*/ false,
4703 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4705 }
4706 return BuildCXXConstructExpr(
4707 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4709 /*HadMultipleCandidates*/ false,
4710 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4712 }
4713
4714 // Resolve overloaded function references.
4715 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4718 true, Found);
4719 if (!Fn)
4720 return ExprError();
4721
4722 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4723 return ExprError();
4724
4726 if (Res.isInvalid())
4727 return ExprError();
4728
4729 // We might get back another placeholder expression if we resolved to a
4730 // builtin.
4731 Res = CheckPlaceholderExpr(Res.get());
4732 if (Res.isInvalid())
4733 return ExprError();
4734
4735 From = Res.get();
4736 FromType = From->getType();
4737 }
4738
4739 // If we're converting to an atomic type, first convert to the corresponding
4740 // non-atomic type.
4741 QualType ToAtomicType;
4742 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4743 ToAtomicType = ToType;
4744 ToType = ToAtomic->getValueType();
4745 }
4746
4747 QualType InitialFromType = FromType;
4748 // Perform the first implicit conversion.
4749 switch (SCS.First) {
4750 case ICK_Identity:
4751 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4752 FromType = FromAtomic->getValueType().getUnqualifiedType();
4753 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4754 From, /*BasePath=*/nullptr, VK_PRValue,
4756 }
4757 break;
4758
4759 case ICK_Lvalue_To_Rvalue: {
4760 assert(From->getObjectKind() != OK_ObjCProperty);
4761 ExprResult FromRes = DefaultLvalueConversion(From);
4762 if (FromRes.isInvalid())
4763 return ExprError();
4764
4765 From = FromRes.get();
4766 FromType = From->getType();
4767 break;
4768 }
4769
4771 FromType = Context.getArrayDecayedType(FromType);
4772 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4773 /*BasePath=*/nullptr, CCK)
4774 .get();
4775 break;
4776
4778 if (ToType->isArrayParameterType()) {
4779 FromType = Context.getArrayParameterType(FromType);
4780 } else if (FromType->isArrayParameterType()) {
4781 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
4782 FromType = APT->getConstantArrayType(Context);
4783 }
4784 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4785 /*BasePath=*/nullptr, CCK)
4786 .get();
4787 break;
4788
4790 FromType = Context.getPointerType(FromType);
4791 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4792 VK_PRValue, /*BasePath=*/nullptr, CCK)
4793 .get();
4794 break;
4795
4796 default:
4797 llvm_unreachable("Improper first standard conversion");
4798 }
4799
4800 // Perform the second implicit conversion
4801 switch (SCS.Second) {
4802 case ICK_Identity:
4803 // C++ [except.spec]p5:
4804 // [For] assignment to and initialization of pointers to functions,
4805 // pointers to member functions, and references to functions: the
4806 // target entity shall allow at least the exceptions allowed by the
4807 // source value in the assignment or initialization.
4808 switch (Action) {
4811 // Note, function argument passing and returning are initialization.
4816 if (CheckExceptionSpecCompatibility(From, ToType))
4817 return ExprError();
4818 break;
4819
4822 // Casts and implicit conversions are not initialization, so are not
4823 // checked for exception specification mismatches.
4824 break;
4825 }
4826 // Nothing else to do.
4827 break;
4828
4831 QualType ElTy = ToType;
4832 QualType StepTy = ToType;
4833 if (FromType->isVectorType() || ToType->isVectorType())
4834 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4835 if (ElTy->isBooleanType()) {
4836 assert(FromType->castAsEnumDecl()->isFixed() &&
4838 "only enums with fixed underlying type can promote to bool");
4839 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4840 /*BasePath=*/nullptr, CCK)
4841 .get();
4842 } else {
4843 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4844 /*BasePath=*/nullptr, CCK)
4845 .get();
4846 }
4847 break;
4848 }
4849
4852 QualType StepTy = ToType;
4853 if (FromType->isVectorType() || ToType->isVectorType())
4854 StepTy = adjustVectorType(Context, FromType, ToType);
4855 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4856 /*BasePath=*/nullptr, CCK)
4857 .get();
4858 break;
4859 }
4860
4863 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4864 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4865 CastKind CK;
4866 if (FromEl->isRealFloatingType()) {
4867 if (ToEl->isRealFloatingType())
4868 CK = CK_FloatingComplexCast;
4869 else
4870 CK = CK_FloatingComplexToIntegralComplex;
4871 } else if (ToEl->isRealFloatingType()) {
4872 CK = CK_IntegralComplexToFloatingComplex;
4873 } else {
4874 CK = CK_IntegralComplexCast;
4875 }
4876 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4877 CCK)
4878 .get();
4879 break;
4880 }
4881
4882 case ICK_Floating_Integral: {
4883 QualType ElTy = ToType;
4884 QualType StepTy = ToType;
4885 if (FromType->isVectorType() || ToType->isVectorType())
4886 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4887 if (ElTy->isRealFloatingType())
4888 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4889 /*BasePath=*/nullptr, CCK)
4890 .get();
4891 else
4892 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4893 /*BasePath=*/nullptr, CCK)
4894 .get();
4895 break;
4896 }
4897
4899 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4900 "Attempting implicit fixed point conversion without a fixed "
4901 "point operand");
4902 if (FromType->isFloatingType())
4903 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4904 VK_PRValue,
4905 /*BasePath=*/nullptr, CCK).get();
4906 else if (ToType->isFloatingType())
4907 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4908 VK_PRValue,
4909 /*BasePath=*/nullptr, CCK).get();
4910 else if (FromType->isIntegralType(Context))
4911 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4912 VK_PRValue,
4913 /*BasePath=*/nullptr, CCK).get();
4914 else if (ToType->isIntegralType(Context))
4915 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4916 VK_PRValue,
4917 /*BasePath=*/nullptr, CCK).get();
4918 else if (ToType->isBooleanType())
4919 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4920 VK_PRValue,
4921 /*BasePath=*/nullptr, CCK).get();
4922 else
4923 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4924 VK_PRValue,
4925 /*BasePath=*/nullptr, CCK).get();
4926 break;
4927
4929 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4930 /*BasePath=*/nullptr, CCK).get();
4931 break;
4932
4935 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) {
4936 // Diagnose incompatible Objective-C conversions
4937 if (Action == AssignmentAction::Initializing ||
4939 Diag(From->getBeginLoc(),
4940 diag::ext_typecheck_convert_incompatible_pointer)
4941 << ToType << From->getType() << Action << From->getSourceRange()
4942 << 0;
4943 else
4944 Diag(From->getBeginLoc(),
4945 diag::ext_typecheck_convert_incompatible_pointer)
4946 << From->getType() << ToType << Action << From->getSourceRange()
4947 << 0;
4948
4949 if (From->getType()->isObjCObjectPointerType() &&
4950 ToType->isObjCObjectPointerType())
4952 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4953 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4954 From->getType())) {
4955 if (Action == AssignmentAction::Initializing)
4956 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4957 else
4958 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4959 << (Action == AssignmentAction::Casting) << From->getType()
4960 << ToType << From->getSourceRange();
4961 }
4962
4963 // Defer address space conversion to the third conversion.
4964 QualType FromPteeType = From->getType()->getPointeeType();
4965 QualType ToPteeType = ToType->getPointeeType();
4966 QualType NewToType = ToType;
4967 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4968 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4969 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4970 NewToType = Context.getAddrSpaceQualType(NewToType,
4971 FromPteeType.getAddressSpace());
4972 if (ToType->isObjCObjectPointerType())
4973 NewToType = Context.getObjCObjectPointerType(NewToType);
4974 else if (ToType->isBlockPointerType())
4975 NewToType = Context.getBlockPointerType(NewToType);
4976 else
4977 NewToType = Context.getPointerType(NewToType);
4978 }
4979
4980 CastKind Kind;
4981 CXXCastPath BasePath;
4982 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4983 return ExprError();
4984
4985 // Make sure we extend blocks if necessary.
4986 // FIXME: doing this here is really ugly.
4987 if (Kind == CK_BlockPointerToObjCPointerCast) {
4988 ExprResult E = From;
4990 From = E.get();
4991 }
4993 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4994 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4995 .get();
4996 break;
4997 }
4998
4999 case ICK_Pointer_Member: {
5000 CastKind Kind;
5001 CXXCastPath BasePath;
5003 From->getType(), ToType->castAs<MemberPointerType>(), Kind, BasePath,
5004 From->getExprLoc(), From->getSourceRange(), CStyle,
5007 assert((Kind != CK_NullToMemberPointer ||
5010 "Expr must be null pointer constant!");
5011 break;
5013 break;
5015 llvm_unreachable("unexpected result");
5017 llvm_unreachable("Should not have been called if derivation isn't OK.");
5020 return ExprError();
5021 }
5022 if (CheckExceptionSpecCompatibility(From, ToType))
5023 return ExprError();
5024
5025 From =
5026 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
5027 break;
5028 }
5029
5031 // Perform half-to-boolean conversion via float.
5032 if (From->getType()->isHalfType()) {
5033 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
5034 FromType = Context.FloatTy;
5035 }
5036 QualType ElTy = FromType;
5037 QualType StepTy = ToType;
5038 if (FromType->isVectorType())
5039 ElTy = FromType->castAs<VectorType>()->getElementType();
5040 if (getLangOpts().HLSL &&
5041 (FromType->isVectorType() || ToType->isVectorType()))
5042 StepTy = adjustVectorType(Context, FromType, ToType);
5043
5044 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
5045 VK_PRValue,
5046 /*BasePath=*/nullptr, CCK)
5047 .get();
5048 break;
5049 }
5050
5051 case ICK_Derived_To_Base: {
5052 CXXCastPath BasePath;
5054 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
5055 From->getSourceRange(), &BasePath, CStyle))
5056 return ExprError();
5057
5058 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
5059 CK_DerivedToBase, From->getValueKind(),
5060 &BasePath, CCK).get();
5061 break;
5062 }
5063
5065 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
5066 /*BasePath=*/nullptr, CCK)
5067 .get();
5068 break;
5069
5072 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
5073 /*BasePath=*/nullptr, CCK)
5074 .get();
5075 break;
5076
5077 case ICK_Vector_Splat: {
5078 // Vector splat from any arithmetic type to a vector.
5079 Expr *Elem = prepareVectorSplat(ToType, From).get();
5080 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
5081 /*BasePath=*/nullptr, CCK)
5082 .get();
5083 break;
5084 }
5085
5086 case ICK_Complex_Real:
5087 // Case 1. x -> _Complex y
5088 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
5089 QualType ElType = ToComplex->getElementType();
5090 bool isFloatingComplex = ElType->isRealFloatingType();
5091
5092 // x -> y
5093 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
5094 // do nothing
5095 } else if (From->getType()->isRealFloatingType()) {
5096 From = ImpCastExprToType(From, ElType,
5097 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
5098 } else {
5099 assert(From->getType()->isIntegerType());
5100 From = ImpCastExprToType(From, ElType,
5101 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
5102 }
5103 // y -> _Complex y
5104 From = ImpCastExprToType(From, ToType,
5105 isFloatingComplex ? CK_FloatingRealToComplex
5106 : CK_IntegralRealToComplex).get();
5107
5108 // Case 2. _Complex x -> y
5109 } else {
5110 auto *FromComplex = From->getType()->castAs<ComplexType>();
5111 QualType ElType = FromComplex->getElementType();
5112 bool isFloatingComplex = ElType->isRealFloatingType();
5113
5114 // _Complex x -> x
5115 From = ImpCastExprToType(From, ElType,
5116 isFloatingComplex ? CK_FloatingComplexToReal
5117 : CK_IntegralComplexToReal,
5118 VK_PRValue, /*BasePath=*/nullptr, CCK)
5119 .get();
5120
5121 // x -> y
5122 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
5123 // do nothing
5124 } else if (ToType->isRealFloatingType()) {
5125 From = ImpCastExprToType(From, ToType,
5126 isFloatingComplex ? CK_FloatingCast
5127 : CK_IntegralToFloating,
5128 VK_PRValue, /*BasePath=*/nullptr, CCK)
5129 .get();
5130 } else {
5131 assert(ToType->isIntegerType());
5132 From = ImpCastExprToType(From, ToType,
5133 isFloatingComplex ? CK_FloatingToIntegral
5134 : CK_IntegralCast,
5135 VK_PRValue, /*BasePath=*/nullptr, CCK)
5136 .get();
5137 }
5138 }
5139 break;
5140
5142 LangAS AddrSpaceL =
5144 LangAS AddrSpaceR =
5146 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR,
5147 getASTContext()) &&
5148 "Invalid cast");
5149 CastKind Kind =
5150 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
5151 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
5152 VK_PRValue, /*BasePath=*/nullptr, CCK)
5153 .get();
5154 break;
5155 }
5156
5158 ExprResult FromRes = From;
5159 AssignConvertType ConvTy =
5161 if (FromRes.isInvalid())
5162 return ExprError();
5163 From = FromRes.get();
5164 assert((ConvTy == AssignConvertType::Compatible) &&
5165 "Improper transparent union conversion");
5166 (void)ConvTy;
5167 break;
5168 }
5169
5172 From = ImpCastExprToType(From, ToType,
5173 CK_ZeroToOCLOpaqueType,
5174 From->getValueKind()).get();
5175 break;
5176
5181 case ICK_Qualification:
5188 llvm_unreachable("Improper second standard conversion");
5189 }
5190
5191 if (SCS.Dimension != ICK_Identity) {
5192 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
5193 // vectors or matrices.
5194
5195 // TODO: Support HLSL matrices.
5196 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
5197 "Dimension conversion for matrix types is not implemented yet.");
5198 assert((ToType->isVectorType() || ToType->isBuiltinType()) &&
5199 "Dimension conversion output must be vector or scalar type.");
5200 switch (SCS.Dimension) {
5201 case ICK_HLSL_Vector_Splat: {
5202 // Vector splat from any arithmetic type to a vector.
5203 Expr *Elem = prepareVectorSplat(ToType, From).get();
5204 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
5205 /*BasePath=*/nullptr, CCK)
5206 .get();
5207 break;
5208 }
5210 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
5211 // vector to a smaller vector or to a scalar, this can only operate on
5212 // arguments where the source type is an ExtVector and the destination
5213 // type is destination type is either an ExtVectorType or a builtin scalar
5214 // type.
5215 auto *FromVec = From->getType()->castAs<VectorType>();
5216 QualType TruncTy = FromVec->getElementType();
5217 if (auto *ToVec = ToType->getAs<VectorType>())
5218 TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements());
5219 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
5220 From->getValueKind())
5221 .get();
5222
5223 break;
5224 }
5225 case ICK_Identity:
5226 default:
5227 llvm_unreachable("Improper element standard conversion");
5228 }
5229 }
5230
5231 switch (SCS.Third) {
5232 case ICK_Identity:
5233 // Nothing to do.
5234 break;
5235
5237 // If both sides are functions (or pointers/references to them), there could
5238 // be incompatible exception declarations.
5239 if (CheckExceptionSpecCompatibility(From, ToType))
5240 return ExprError();
5241
5242 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
5243 /*BasePath=*/nullptr, CCK)
5244 .get();
5245 break;
5246
5247 case ICK_Qualification: {
5248 ExprValueKind VK = From->getValueKind();
5249 CastKind CK = CK_NoOp;
5250
5251 if (ToType->isReferenceType() &&
5252 ToType->getPointeeType().getAddressSpace() !=
5253 From->getType().getAddressSpace())
5254 CK = CK_AddressSpaceConversion;
5255
5256 if (ToType->isPointerType() &&
5257 ToType->getPointeeType().getAddressSpace() !=
5259 CK = CK_AddressSpaceConversion;
5260
5261 if (!isCast(CCK) &&
5262 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
5264 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
5265 << InitialFromType << ToType;
5266 }
5267
5268 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
5269 /*BasePath=*/nullptr, CCK)
5270 .get();
5271
5273 !getLangOpts().WritableStrings) {
5274 Diag(From->getBeginLoc(),
5276 ? diag::ext_deprecated_string_literal_conversion
5277 : diag::warn_deprecated_string_literal_conversion)
5278 << ToType.getNonReferenceType();
5279 }
5280
5281 break;
5282 }
5283
5284 default:
5285 llvm_unreachable("Improper third standard conversion");
5286 }
5287
5288 // If this conversion sequence involved a scalar -> atomic conversion, perform
5289 // that conversion now.
5290 if (!ToAtomicType.isNull()) {
5291 assert(Context.hasSameType(
5292 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
5293 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
5294 VK_PRValue, nullptr, CCK)
5295 .get();
5296 }
5297
5298 // Materialize a temporary if we're implicitly converting to a reference
5299 // type. This is not required by the C++ rules but is necessary to maintain
5300 // AST invariants.
5301 if (ToType->isReferenceType() && From->isPRValue()) {
5303 if (Res.isInvalid())
5304 return ExprError();
5305 From = Res.get();
5306 }
5307
5308 // If this conversion sequence succeeded and involved implicitly converting a
5309 // _Nullable type to a _Nonnull one, complain.
5310 if (!isCast(CCK))
5311 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
5312 From->getBeginLoc());
5313
5314 return From;
5315}
5316
5320 bool isIndirect) {
5321 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5322 "placeholders should have been weeded out by now");
5323
5324 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5325 // temporary materialization conversion otherwise.
5326 if (isIndirect)
5327 LHS = DefaultLvalueConversion(LHS.get());
5328 else if (LHS.get()->isPRValue())
5330 if (LHS.isInvalid())
5331 return QualType();
5332
5333 // The RHS always undergoes lvalue conversions.
5334 RHS = DefaultLvalueConversion(RHS.get());
5335 if (RHS.isInvalid()) return QualType();
5336
5337 const char *OpSpelling = isIndirect ? "->*" : ".*";
5338 // C++ 5.5p2
5339 // The binary operator .* [p3: ->*] binds its second operand, which shall
5340 // be of type "pointer to member of T" (where T is a completely-defined
5341 // class type) [...]
5342 QualType RHSType = RHS.get()->getType();
5343 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5344 if (!MemPtr) {
5345 Diag(Loc, diag::err_bad_memptr_rhs)
5346 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5347 return QualType();
5348 }
5349
5350 CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl();
5351
5352 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5353 // member pointer points must be completely-defined. However, there is no
5354 // reason for this semantic distinction, and the rule is not enforced by
5355 // other compilers. Therefore, we do not check this property, as it is
5356 // likely to be considered a defect.
5357
5358 // C++ 5.5p2
5359 // [...] to its first operand, which shall be of class T or of a class of
5360 // which T is an unambiguous and accessible base class. [p3: a pointer to
5361 // such a class]
5362 QualType LHSType = LHS.get()->getType();
5363 if (isIndirect) {
5364 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5365 LHSType = Ptr->getPointeeType();
5366 else {
5367 Diag(Loc, diag::err_bad_memptr_lhs)
5368 << OpSpelling << 1 << LHSType
5370 return QualType();
5371 }
5372 }
5373 CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl();
5374
5375 if (!declaresSameEntity(LHSClass, RHSClass)) {
5376 // If we want to check the hierarchy, we need a complete type.
5377 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5378 OpSpelling, (int)isIndirect)) {
5379 return QualType();
5380 }
5381
5382 if (!IsDerivedFrom(Loc, LHSClass, RHSClass)) {
5383 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5384 << (int)isIndirect << LHS.get()->getType();
5385 return QualType();
5386 }
5387
5388 // FIXME: use sugared type from member pointer.
5389 CanQualType RHSClassType = Context.getCanonicalTagType(RHSClass);
5390 CXXCastPath BasePath;
5392 LHSType, RHSClassType, Loc,
5393 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5394 &BasePath))
5395 return QualType();
5396
5397 // Cast LHS to type of use.
5398 QualType UseType =
5399 Context.getQualifiedType(RHSClassType, LHSType.getQualifiers());
5400 if (isIndirect)
5401 UseType = Context.getPointerType(UseType);
5402 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
5403 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5404 &BasePath);
5405 }
5406
5407 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5408 // Diagnose use of pointer-to-member type which when used as
5409 // the functional cast in a pointer-to-member expression.
5410 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5411 return QualType();
5412 }
5413
5414 // C++ 5.5p2
5415 // The result is an object or a function of the type specified by the
5416 // second operand.
5417 // The cv qualifiers are the union of those in the pointer and the left side,
5418 // in accordance with 5.5p5 and 5.2.5.
5419 QualType Result = MemPtr->getPointeeType();
5421
5422 // C++0x [expr.mptr.oper]p6:
5423 // In a .* expression whose object expression is an rvalue, the program is
5424 // ill-formed if the second operand is a pointer to member function with
5425 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5426 // expression is an lvalue, the program is ill-formed if the second operand
5427 // is a pointer to member function with ref-qualifier &&.
5428 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5429 switch (Proto->getRefQualifier()) {
5430 case RQ_None:
5431 // Do nothing
5432 break;
5433
5434 case RQ_LValue:
5435 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5436 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5437 // is (exactly) 'const'.
5438 if (Proto->isConst() && !Proto->isVolatile())
5440 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5441 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5442 else
5443 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5444 << RHSType << 1 << LHS.get()->getSourceRange();
5445 }
5446 break;
5447
5448 case RQ_RValue:
5449 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5450 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5451 << RHSType << 0 << LHS.get()->getSourceRange();
5452 break;
5453 }
5454 }
5455
5456 // C++ [expr.mptr.oper]p6:
5457 // The result of a .* expression whose second operand is a pointer
5458 // to a data member is of the same value category as its
5459 // first operand. The result of a .* expression whose second
5460 // operand is a pointer to a member function is a prvalue. The
5461 // result of an ->* expression is an lvalue if its second operand
5462 // is a pointer to data member and a prvalue otherwise.
5463 if (Result->isFunctionType()) {
5464 VK = VK_PRValue;
5465 return Context.BoundMemberTy;
5466 } else if (isIndirect) {
5467 VK = VK_LValue;
5468 } else {
5469 VK = LHS.get()->getValueKind();
5470 }
5471
5472 return Result;
5473}
5474
5475/// Try to convert a type to another according to C++11 5.16p3.
5476///
5477/// This is part of the parameter validation for the ? operator. If either
5478/// value operand is a class type, the two operands are attempted to be
5479/// converted to each other. This function does the conversion in one direction.
5480/// It returns true if the program is ill-formed and has already been diagnosed
5481/// as such.
5482static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5483 SourceLocation QuestionLoc,
5484 bool &HaveConversion,
5485 QualType &ToType) {
5486 HaveConversion = false;
5487 ToType = To->getType();
5488
5489 InitializationKind Kind =
5491 // C++11 5.16p3
5492 // The process for determining whether an operand expression E1 of type T1
5493 // can be converted to match an operand expression E2 of type T2 is defined
5494 // as follows:
5495 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5496 // implicitly converted to type "lvalue reference to T2", subject to the
5497 // constraint that in the conversion the reference must bind directly to
5498 // an lvalue.
5499 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5500 // implicitly converted to the type "rvalue reference to R2", subject to
5501 // the constraint that the reference must bind directly.
5502 if (To->isGLValue()) {
5503 QualType T = Self.Context.getReferenceQualifiedType(To);
5505
5506 InitializationSequence InitSeq(Self, Entity, Kind, From);
5507 if (InitSeq.isDirectReferenceBinding()) {
5508 ToType = T;
5509 HaveConversion = true;
5510 return false;
5511 }
5512
5513 if (InitSeq.isAmbiguous())
5514 return InitSeq.Diagnose(Self, Entity, Kind, From);
5515 }
5516
5517 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5518 // -- if E1 and E2 have class type, and the underlying class types are
5519 // the same or one is a base class of the other:
5520 QualType FTy = From->getType();
5521 QualType TTy = To->getType();
5522 const RecordType *FRec = FTy->getAsCanonical<RecordType>();
5523 const RecordType *TRec = TTy->getAsCanonical<RecordType>();
5524 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5525 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5526 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5527 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5528 // E1 can be converted to match E2 if the class of T2 is the
5529 // same type as, or a base class of, the class of T1, and
5530 // [cv2 > cv1].
5531 if (FRec == TRec || FDerivedFromT) {
5532 if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) {
5534 InitializationSequence InitSeq(Self, Entity, Kind, From);
5535 if (InitSeq) {
5536 HaveConversion = true;
5537 return false;
5538 }
5539
5540 if (InitSeq.isAmbiguous())
5541 return InitSeq.Diagnose(Self, Entity, Kind, From);
5542 }
5543 }
5544
5545 return false;
5546 }
5547
5548 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5549 // implicitly converted to the type that expression E2 would have
5550 // if E2 were converted to an rvalue (or the type it has, if E2 is
5551 // an rvalue).
5552 //
5553 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5554 // to the array-to-pointer or function-to-pointer conversions.
5555 TTy = TTy.getNonLValueExprType(Self.Context);
5556
5558 InitializationSequence InitSeq(Self, Entity, Kind, From);
5559 HaveConversion = !InitSeq.Failed();
5560 ToType = TTy;
5561 if (InitSeq.isAmbiguous())
5562 return InitSeq.Diagnose(Self, Entity, Kind, From);
5563
5564 return false;
5565}
5566
5567/// Try to find a common type for two according to C++0x 5.16p5.
5568///
5569/// This is part of the parameter validation for the ? operator. If either
5570/// value operand is a class type, overload resolution is used to find a
5571/// conversion to a common type.
5573 SourceLocation QuestionLoc) {
5574 Expr *Args[2] = { LHS.get(), RHS.get() };
5575 OverloadCandidateSet CandidateSet(QuestionLoc,
5577 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5578 CandidateSet);
5579
5581 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5582 case OR_Success: {
5583 // We found a match. Perform the conversions on the arguments and move on.
5584 ExprResult LHSRes = Self.PerformImplicitConversion(
5585 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5587 if (LHSRes.isInvalid())
5588 break;
5589 LHS = LHSRes;
5590
5591 ExprResult RHSRes = Self.PerformImplicitConversion(
5592 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5594 if (RHSRes.isInvalid())
5595 break;
5596 RHS = RHSRes;
5597 if (Best->Function)
5598 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5599 return false;
5600 }
5601
5603
5604 // Emit a better diagnostic if one of the expressions is a null pointer
5605 // constant and the other is a pointer type. In this case, the user most
5606 // likely forgot to take the address of the other expression.
5607 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5608 return true;
5609
5610 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5611 << LHS.get()->getType() << RHS.get()->getType()
5612 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5613 return true;
5614
5615 case OR_Ambiguous:
5616 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5617 << LHS.get()->getType() << RHS.get()->getType()
5618 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5619 // FIXME: Print the possible common types by printing the return types of
5620 // the viable candidates.
5621 break;
5622
5623 case OR_Deleted:
5624 llvm_unreachable("Conditional operator has only built-in overloads");
5625 }
5626 return true;
5627}
5628
5629/// Perform an "extended" implicit conversion as returned by
5630/// TryClassUnification.
5633 InitializationKind Kind =
5635 Expr *Arg = E.get();
5636 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5637 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5638 if (Result.isInvalid())
5639 return true;
5640
5641 E = Result;
5642 return false;
5643}
5644
5645// Check the condition operand of ?: to see if it is valid for the GCC
5646// extension.
5648 QualType CondTy) {
5649 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
5650 return false;
5651 const QualType EltTy =
5652 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5653 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
5654 return EltTy->isIntegralType(Ctx);
5655}
5656
5658 QualType CondTy) {
5659 if (!CondTy->isSveVLSBuiltinType())
5660 return false;
5661 const QualType EltTy =
5662 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
5663 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
5664 return EltTy->isIntegralType(Ctx);
5665}
5666
5668 ExprResult &RHS,
5669 SourceLocation QuestionLoc) {
5672
5673 QualType CondType = Cond.get()->getType();
5674 const auto *CondVT = CondType->castAs<VectorType>();
5675 QualType CondElementTy = CondVT->getElementType();
5676 unsigned CondElementCount = CondVT->getNumElements();
5677 QualType LHSType = LHS.get()->getType();
5678 const auto *LHSVT = LHSType->getAs<VectorType>();
5679 QualType RHSType = RHS.get()->getType();
5680 const auto *RHSVT = RHSType->getAs<VectorType>();
5681
5682 QualType ResultType;
5683
5684
5685 if (LHSVT && RHSVT) {
5686 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
5687 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
5688 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
5689 return {};
5690 }
5691
5692 // If both are vector types, they must be the same type.
5693 if (!Context.hasSameType(LHSType, RHSType)) {
5694 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
5695 << LHSType << RHSType;
5696 return {};
5697 }
5698 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
5699 } else if (LHSVT || RHSVT) {
5700 ResultType = CheckVectorOperands(
5701 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5702 /*AllowBoolConversions*/ false,
5703 /*AllowBoolOperation*/ true,
5704 /*ReportInvalid*/ true);
5705 if (ResultType.isNull())
5706 return {};
5707 } else {
5708 // Both are scalar.
5709 LHSType = LHSType.getUnqualifiedType();
5710 RHSType = RHSType.getUnqualifiedType();
5711 QualType ResultElementTy =
5712 Context.hasSameType(LHSType, RHSType)
5713 ? Context.getCommonSugaredType(LHSType, RHSType)
5714 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
5716
5717 if (ResultElementTy->isEnumeralType()) {
5718 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5719 << ResultElementTy;
5720 return {};
5721 }
5722 if (CondType->isExtVectorType())
5723 ResultType =
5724 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
5725 else
5726 ResultType = Context.getVectorType(
5727 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
5728
5729 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5730 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5731 }
5732
5733 assert(!ResultType.isNull() && ResultType->isVectorType() &&
5734 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
5735 "Result should have been a vector type");
5736 auto *ResultVectorTy = ResultType->castAs<VectorType>();
5737 QualType ResultElementTy = ResultVectorTy->getElementType();
5738 unsigned ResultElementCount = ResultVectorTy->getNumElements();
5739
5740 if (ResultElementCount != CondElementCount) {
5741 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5742 << ResultType;
5743 return {};
5744 }
5745
5746 // Boolean vectors are permitted outside of OpenCL mode.
5747 if (Context.getTypeSize(ResultElementTy) !=
5748 Context.getTypeSize(CondElementTy) &&
5749 (!CondElementTy->isBooleanType() || LangOpts.OpenCL)) {
5750 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
5751 << CondType << ResultType;
5752 return {};
5753 }
5754
5755 return ResultType;
5756}
5757
5759 ExprResult &LHS,
5760 ExprResult &RHS,
5761 SourceLocation QuestionLoc) {
5764
5765 QualType CondType = Cond.get()->getType();
5766 const auto *CondBT = CondType->castAs<BuiltinType>();
5767 QualType CondElementTy = CondBT->getSveEltType(Context);
5768 llvm::ElementCount CondElementCount =
5770
5771 QualType LHSType = LHS.get()->getType();
5772 const auto *LHSBT =
5773 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
5774 QualType RHSType = RHS.get()->getType();
5775 const auto *RHSBT =
5776 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
5777
5778 QualType ResultType;
5779
5780 if (LHSBT && RHSBT) {
5781 // If both are sizeless vector types, they must be the same type.
5782 if (!Context.hasSameType(LHSType, RHSType)) {
5783 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
5784 << LHSType << RHSType;
5785 return QualType();
5786 }
5787 ResultType = LHSType;
5788 } else if (LHSBT || RHSBT) {
5789 ResultType = CheckSizelessVectorOperands(LHS, RHS, QuestionLoc,
5790 /*IsCompAssign*/ false,
5792 if (ResultType.isNull())
5793 return QualType();
5794 } else {
5795 // Both are scalar so splat
5796 QualType ResultElementTy;
5797 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
5798 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
5799
5800 if (Context.hasSameType(LHSType, RHSType))
5801 ResultElementTy = LHSType;
5802 else
5803 ResultElementTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
5805
5806 if (ResultElementTy->isEnumeralType()) {
5807 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5808 << ResultElementTy;
5809 return QualType();
5810 }
5811
5812 ResultType = Context.getScalableVectorType(
5813 ResultElementTy, CondElementCount.getKnownMinValue());
5814
5815 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5816 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5817 }
5818
5819 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
5820 "Result should have been a vector type");
5821 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
5822 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
5823 llvm::ElementCount ResultElementCount =
5824 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
5825
5826 if (ResultElementCount != CondElementCount) {
5827 Diag(QuestionLoc, diag::err_conditional_vector_size)
5828 << CondType << ResultType;
5829 return QualType();
5830 }
5831
5832 if (Context.getTypeSize(ResultElementTy) !=
5833 Context.getTypeSize(CondElementTy)) {
5834 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
5835 << CondType << ResultType;
5836 return QualType();
5837 }
5838
5839 return ResultType;
5840}
5841
5844 ExprObjectKind &OK,
5845 SourceLocation QuestionLoc) {
5846 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5847 // pointers.
5848
5849 // Assume r-value.
5850 VK = VK_PRValue;
5851 OK = OK_Ordinary;
5852 bool IsVectorConditional =
5854
5855 bool IsSizelessVectorConditional =
5857 Cond.get()->getType());
5858
5859 // C++11 [expr.cond]p1
5860 // The first expression is contextually converted to bool.
5861 if (!Cond.get()->isTypeDependent()) {
5862 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
5864 : CheckCXXBooleanCondition(Cond.get());
5865 if (CondRes.isInvalid())
5866 return QualType();
5867 Cond = CondRes;
5868 } else {
5869 // To implement C++, the first expression typically doesn't alter the result
5870 // type of the conditional, however the GCC compatible vector extension
5871 // changes the result type to be that of the conditional. Since we cannot
5872 // know if this is a vector extension here, delay the conversion of the
5873 // LHS/RHS below until later.
5874 return Context.DependentTy;
5875 }
5876
5877
5878 // Either of the arguments dependent?
5879 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5880 return Context.DependentTy;
5881
5882 // C++11 [expr.cond]p2
5883 // If either the second or the third operand has type (cv) void, ...
5884 QualType LTy = LHS.get()->getType();
5885 QualType RTy = RHS.get()->getType();
5886 bool LVoid = LTy->isVoidType();
5887 bool RVoid = RTy->isVoidType();
5888 if (LVoid || RVoid) {
5889 // ... one of the following shall hold:
5890 // -- The second or the third operand (but not both) is a (possibly
5891 // parenthesized) throw-expression; the result is of the type
5892 // and value category of the other.
5893 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5894 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5895
5896 // Void expressions aren't legal in the vector-conditional expressions.
5897 if (IsVectorConditional) {
5898 SourceRange DiagLoc =
5899 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
5900 bool IsThrow = LVoid ? LThrow : RThrow;
5901 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
5902 << DiagLoc << IsThrow;
5903 return QualType();
5904 }
5905
5906 if (LThrow != RThrow) {
5907 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5908 VK = NonThrow->getValueKind();
5909 // DR (no number yet): the result is a bit-field if the
5910 // non-throw-expression operand is a bit-field.
5911 OK = NonThrow->getObjectKind();
5912 return NonThrow->getType();
5913 }
5914
5915 // -- Both the second and third operands have type void; the result is of
5916 // type void and is a prvalue.
5917 if (LVoid && RVoid)
5918 return Context.getCommonSugaredType(LTy, RTy);
5919
5920 // Neither holds, error.
5921 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5922 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5923 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5924 return QualType();
5925 }
5926
5927 // Neither is void.
5928 if (IsVectorConditional)
5929 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
5930
5931 if (IsSizelessVectorConditional)
5932 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
5933
5934 // WebAssembly tables are not allowed as conditional LHS or RHS.
5935 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
5936 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
5937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5938 return QualType();
5939 }
5940
5941 // C++11 [expr.cond]p3
5942 // Otherwise, if the second and third operand have different types, and
5943 // either has (cv) class type [...] an attempt is made to convert each of
5944 // those operands to the type of the other.
5945 if (!Context.hasSameType(LTy, RTy) &&
5946 (LTy->isRecordType() || RTy->isRecordType())) {
5947 // These return true if a single direction is already ambiguous.
5948 QualType L2RType, R2LType;
5949 bool HaveL2R, HaveR2L;
5950 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5951 return QualType();
5952 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5953 return QualType();
5954
5955 // If both can be converted, [...] the program is ill-formed.
5956 if (HaveL2R && HaveR2L) {
5957 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5958 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5959 return QualType();
5960 }
5961
5962 // If exactly one conversion is possible, that conversion is applied to
5963 // the chosen operand and the converted operands are used in place of the
5964 // original operands for the remainder of this section.
5965 if (HaveL2R) {
5966 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5967 return QualType();
5968 LTy = LHS.get()->getType();
5969 } else if (HaveR2L) {
5970 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5971 return QualType();
5972 RTy = RHS.get()->getType();
5973 }
5974 }
5975
5976 // C++11 [expr.cond]p3
5977 // if both are glvalues of the same value category and the same type except
5978 // for cv-qualification, an attempt is made to convert each of those
5979 // operands to the type of the other.
5980 // FIXME:
5981 // Resolving a defect in P0012R1: we extend this to cover all cases where
5982 // one of the operands is reference-compatible with the other, in order
5983 // to support conditionals between functions differing in noexcept. This
5984 // will similarly cover difference in array bounds after P0388R4.
5985 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
5986 // that instead?
5987 ExprValueKind LVK = LHS.get()->getValueKind();
5988 ExprValueKind RVK = RHS.get()->getValueKind();
5989 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
5990 // DerivedToBase was already handled by the class-specific case above.
5991 // FIXME: Should we allow ObjC conversions here?
5992 const ReferenceConversions AllowedConversions =
5993 ReferenceConversions::Qualification |
5994 ReferenceConversions::NestedQualification |
5995 ReferenceConversions::Function;
5996
5997 ReferenceConversions RefConv;
5998 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6000 !(RefConv & ~AllowedConversions) &&
6001 // [...] subject to the constraint that the reference must bind
6002 // directly [...]
6003 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6004 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6005 RTy = RHS.get()->getType();
6006 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6008 !(RefConv & ~AllowedConversions) &&
6009 !LHS.get()->refersToBitField() &&
6010 !LHS.get()->refersToVectorElement()) {
6011 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6012 LTy = LHS.get()->getType();
6013 }
6014 }
6015
6016 // C++11 [expr.cond]p4
6017 // If the second and third operands are glvalues of the same value
6018 // category and have the same type, the result is of that type and
6019 // value category and it is a bit-field if the second or the third
6020 // operand is a bit-field, or if both are bit-fields.
6021 // We only extend this to bitfields, not to the crazy other kinds of
6022 // l-values.
6023 bool Same = Context.hasSameType(LTy, RTy);
6024 if (Same && LVK == RVK && LVK != VK_PRValue &&
6027 VK = LHS.get()->getValueKind();
6028 if (LHS.get()->getObjectKind() == OK_BitField ||
6029 RHS.get()->getObjectKind() == OK_BitField)
6030 OK = OK_BitField;
6031 return Context.getCommonSugaredType(LTy, RTy);
6032 }
6033
6034 // C++11 [expr.cond]p5
6035 // Otherwise, the result is a prvalue. If the second and third operands
6036 // do not have the same type, and either has (cv) class type, ...
6037 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6038 // ... overload resolution is used to determine the conversions (if any)
6039 // to be applied to the operands. If the overload resolution fails, the
6040 // program is ill-formed.
6041 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6042 return QualType();
6043 }
6044
6045 // C++11 [expr.cond]p6
6046 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6047 // conversions are performed on the second and third operands.
6050 if (LHS.isInvalid() || RHS.isInvalid())
6051 return QualType();
6052 LTy = LHS.get()->getType();
6053 RTy = RHS.get()->getType();
6054
6055 // After those conversions, one of the following shall hold:
6056 // -- The second and third operands have the same type; the result
6057 // is of that type. If the operands have class type, the result
6058 // is a prvalue temporary of the result type, which is
6059 // copy-initialized from either the second operand or the third
6060 // operand depending on the value of the first operand.
6061 if (Context.hasSameType(LTy, RTy)) {
6062 if (LTy->isRecordType()) {
6063 // The operands have class type. Make a temporary copy.
6066 if (LHSCopy.isInvalid())
6067 return QualType();
6068
6071 if (RHSCopy.isInvalid())
6072 return QualType();
6073
6074 LHS = LHSCopy;
6075 RHS = RHSCopy;
6076 }
6077 return Context.getCommonSugaredType(LTy, RTy);
6078 }
6079
6080 // Extension: conditional operator involving vector types.
6081 if (LTy->isVectorType() || RTy->isVectorType())
6082 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6083 /*AllowBothBool*/ true,
6084 /*AllowBoolConversions*/ false,
6085 /*AllowBoolOperation*/ false,
6086 /*ReportInvalid*/ true);
6087
6088 // -- The second and third operands have arithmetic or enumeration type;
6089 // the usual arithmetic conversions are performed to bring them to a
6090 // common type, and the result is of that type.
6091 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6092 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6094 if (LHS.isInvalid() || RHS.isInvalid())
6095 return QualType();
6096 if (ResTy.isNull()) {
6097 Diag(QuestionLoc,
6098 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6099 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6100 return QualType();
6101 }
6102
6103 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6104 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6105
6106 return ResTy;
6107 }
6108
6109 // -- The second and third operands have pointer type, or one has pointer
6110 // type and the other is a null pointer constant, or both are null
6111 // pointer constants, at least one of which is non-integral; pointer
6112 // conversions and qualification conversions are performed to bring them
6113 // to their composite pointer type. The result is of the composite
6114 // pointer type.
6115 // -- The second and third operands have pointer to member type, or one has
6116 // pointer to member type and the other is a null pointer constant;
6117 // pointer to member conversions and qualification conversions are
6118 // performed to bring them to a common type, whose cv-qualification
6119 // shall match the cv-qualification of either the second or the third
6120 // operand. The result is of the common type.
6121 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6122 if (!Composite.isNull())
6123 return Composite;
6124
6125 // Similarly, attempt to find composite type of two objective-c pointers.
6126 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6127 if (LHS.isInvalid() || RHS.isInvalid())
6128 return QualType();
6129 if (!Composite.isNull())
6130 return Composite;
6131
6132 // Check if we are using a null with a non-pointer type.
6133 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6134 return QualType();
6135
6136 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6137 << LHS.get()->getType() << RHS.get()->getType()
6138 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6139 return QualType();
6140}
6141
6143 Expr *&E1, Expr *&E2,
6144 bool ConvertArgs) {
6145 assert(getLangOpts().CPlusPlus && "This function assumes C++");
6146
6147 // C++1z [expr]p14:
6148 // The composite pointer type of two operands p1 and p2 having types T1
6149 // and T2
6150 QualType T1 = E1->getType(), T2 = E2->getType();
6151
6152 // where at least one is a pointer or pointer to member type or
6153 // std::nullptr_t is:
6154 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6155 T1->isNullPtrType();
6156 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6157 T2->isNullPtrType();
6158 if (!T1IsPointerLike && !T2IsPointerLike)
6159 return QualType();
6160
6161 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6162 // This can't actually happen, following the standard, but we also use this
6163 // to implement the end of [expr.conv], which hits this case.
6164 //
6165 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6166 if (T1IsPointerLike &&
6168 if (ConvertArgs)
6169 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6170 ? CK_NullToMemberPointer
6171 : CK_NullToPointer).get();
6172 return T1;
6173 }
6174 if (T2IsPointerLike &&
6176 if (ConvertArgs)
6177 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6178 ? CK_NullToMemberPointer
6179 : CK_NullToPointer).get();
6180 return T2;
6181 }
6182
6183 // Now both have to be pointers or member pointers.
6184 if (!T1IsPointerLike || !T2IsPointerLike)
6185 return QualType();
6186 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6187 "nullptr_t should be a null pointer constant");
6188
6189 struct Step {
6190 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6191 // Qualifiers to apply under the step kind.
6192 Qualifiers Quals;
6193 /// The class for a pointer-to-member; a constant array type with a bound
6194 /// (if any) for an array.
6195 /// FIXME: Store Qualifier for pointer-to-member.
6196 const Type *ClassOrBound;
6197
6198 Step(Kind K, const Type *ClassOrBound = nullptr)
6199 : K(K), ClassOrBound(ClassOrBound) {}
6200 QualType rebuild(ASTContext &Ctx, QualType T) const {
6201 T = Ctx.getQualifiedType(T, Quals);
6202 switch (K) {
6203 case Pointer:
6204 return Ctx.getPointerType(T);
6205 case MemberPointer:
6206 return Ctx.getMemberPointerType(T, /*Qualifier=*/std::nullopt,
6207 ClassOrBound->getAsCXXRecordDecl());
6208 case ObjCPointer:
6209 return Ctx.getObjCObjectPointerType(T);
6210 case Array:
6211 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6212 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6213 ArraySizeModifier::Normal, 0);
6214 else
6215 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
6216 }
6217 llvm_unreachable("unknown step kind");
6218 }
6219 };
6220
6222
6223 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6224 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6225 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6226 // respectively;
6227 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6228 // to member of C2 of type cv2 U2" for some non-function type U, where
6229 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6230 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6231 // respectively;
6232 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6233 // T2;
6234 //
6235 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6236 // and to prepare to form the cv-combined type if so.
6237 QualType Composite1 = T1;
6238 QualType Composite2 = T2;
6239 unsigned NeedConstBefore = 0;
6240 while (true) {
6241 assert(!Composite1.isNull() && !Composite2.isNull());
6242
6243 Qualifiers Q1, Q2;
6244 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6245 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6246
6247 // Top-level qualifiers are ignored. Merge at all lower levels.
6248 if (!Steps.empty()) {
6249 // Find the qualifier union: (approximately) the unique minimal set of
6250 // qualifiers that is compatible with both types.
6252 Q2.getCVRUQualifiers());
6253
6254 // Under one level of pointer or pointer-to-member, we can change to an
6255 // unambiguous compatible address space.
6256 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6257 Quals.setAddressSpace(Q1.getAddressSpace());
6258 } else if (Steps.size() == 1) {
6259 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext());
6260 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext());
6261 if (MaybeQ1 == MaybeQ2) {
6262 // Exception for ptr size address spaces. Should be able to choose
6263 // either address space during comparison.
6266 MaybeQ1 = true;
6267 else
6268 return QualType(); // No unique best address space.
6269 }
6270 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6271 : Q2.getAddressSpace());
6272 } else {
6273 return QualType();
6274 }
6275
6276 // FIXME: In C, we merge __strong and none to __strong at the top level.
6277 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6278 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6279 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6280 assert(Steps.size() == 1);
6281 else
6282 return QualType();
6283
6284 // Mismatched lifetime qualifiers never compatibly include each other.
6285 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6286 Quals.setObjCLifetime(Q1.getObjCLifetime());
6287 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6288 assert(Steps.size() == 1);
6289 else
6290 return QualType();
6291
6293 Quals.setPointerAuth(Q1.getPointerAuth());
6294 else
6295 return QualType();
6296
6297 Steps.back().Quals = Quals;
6298 if (Q1 != Quals || Q2 != Quals)
6299 NeedConstBefore = Steps.size() - 1;
6300 }
6301
6302 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6303
6304 const ArrayType *Arr1, *Arr2;
6305 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6306 (Arr2 = Context.getAsArrayType(Composite2))) {
6307 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6308 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6309 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6310 Composite1 = Arr1->getElementType();
6311 Composite2 = Arr2->getElementType();
6312 Steps.emplace_back(Step::Array, CAT1);
6313 continue;
6314 }
6315 bool IAT1 = isa<IncompleteArrayType>(Arr1);
6316 bool IAT2 = isa<IncompleteArrayType>(Arr2);
6317 if ((IAT1 && IAT2) ||
6318 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6319 ((bool)CAT1 != (bool)CAT2) &&
6320 (Steps.empty() || Steps.back().K != Step::Array))) {
6321 // In C++20 onwards, we can unify an array of N T with an array of
6322 // a different or unknown bound. But we can't form an array whose
6323 // element type is an array of unknown bound by doing so.
6324 Composite1 = Arr1->getElementType();
6325 Composite2 = Arr2->getElementType();
6326 Steps.emplace_back(Step::Array);
6327 if (CAT1 || CAT2)
6328 NeedConstBefore = Steps.size();
6329 continue;
6330 }
6331 }
6332
6333 const PointerType *Ptr1, *Ptr2;
6334 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6335 (Ptr2 = Composite2->getAs<PointerType>())) {
6336 Composite1 = Ptr1->getPointeeType();
6337 Composite2 = Ptr2->getPointeeType();
6338 Steps.emplace_back(Step::Pointer);
6339 continue;
6340 }
6341
6342 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6343 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6344 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6345 Composite1 = ObjPtr1->getPointeeType();
6346 Composite2 = ObjPtr2->getPointeeType();
6347 Steps.emplace_back(Step::ObjCPointer);
6348 continue;
6349 }
6350
6351 const MemberPointerType *MemPtr1, *MemPtr2;
6352 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6353 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6354 Composite1 = MemPtr1->getPointeeType();
6355 Composite2 = MemPtr2->getPointeeType();
6356
6357 // At the top level, we can perform a base-to-derived pointer-to-member
6358 // conversion:
6359 //
6360 // - [...] where C1 is reference-related to C2 or C2 is
6361 // reference-related to C1
6362 //
6363 // (Note that the only kinds of reference-relatedness in scope here are
6364 // "same type or derived from".) At any other level, the class must
6365 // exactly match.
6366 CXXRecordDecl *Cls = nullptr,
6367 *Cls1 = MemPtr1->getMostRecentCXXRecordDecl(),
6368 *Cls2 = MemPtr2->getMostRecentCXXRecordDecl();
6369 if (declaresSameEntity(Cls1, Cls2))
6370 Cls = Cls1;
6371 else if (Steps.empty())
6372 Cls = IsDerivedFrom(Loc, Cls1, Cls2) ? Cls1
6373 : IsDerivedFrom(Loc, Cls2, Cls1) ? Cls2
6374 : nullptr;
6375 if (!Cls)
6376 return QualType();
6377
6378 Steps.emplace_back(Step::MemberPointer,
6380 continue;
6381 }
6382
6383 // Special case: at the top level, we can decompose an Objective-C pointer
6384 // and a 'cv void *'. Unify the qualifiers.
6385 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6386 Composite2->isObjCObjectPointerType()) ||
6387 (Composite1->isObjCObjectPointerType() &&
6388 Composite2->isVoidPointerType()))) {
6389 Composite1 = Composite1->getPointeeType();
6390 Composite2 = Composite2->getPointeeType();
6391 Steps.emplace_back(Step::Pointer);
6392 continue;
6393 }
6394
6395 // FIXME: block pointer types?
6396
6397 // Cannot unwrap any more types.
6398 break;
6399 }
6400
6401 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6402 // "pointer to function", where the function types are otherwise the same,
6403 // "pointer to function";
6404 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6405 // type is "pointer to member of C2 of type noexcept function", and C1
6406 // is reference-related to C2 or C2 is reference-related to C1, where
6407 // the function types are otherwise the same, "pointer to member of C2 of
6408 // type function" or "pointer to member of C1 of type function",
6409 // respectively;
6410 //
6411 // We also support 'noreturn' here, so as a Clang extension we generalize the
6412 // above to:
6413 //
6414 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6415 // "pointer to member function" and the pointee types can be unified
6416 // by a function pointer conversion, that conversion is applied
6417 // before checking the following rules.
6418 //
6419 // We've already unwrapped down to the function types, and we want to merge
6420 // rather than just convert, so do this ourselves rather than calling
6421 // IsFunctionConversion.
6422 //
6423 // FIXME: In order to match the standard wording as closely as possible, we
6424 // currently only do this under a single level of pointers. Ideally, we would
6425 // allow this in general, and set NeedConstBefore to the relevant depth on
6426 // the side(s) where we changed anything. If we permit that, we should also
6427 // consider this conversion when determining type similarity and model it as
6428 // a qualification conversion.
6429 if (Steps.size() == 1) {
6430 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6431 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6432 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6433 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6434
6435 // The result is noreturn if both operands are.
6436 bool Noreturn =
6437 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6438 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6439 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6440
6441 bool CFIUncheckedCallee =
6443 EPI1.CFIUncheckedCallee = CFIUncheckedCallee;
6444 EPI2.CFIUncheckedCallee = CFIUncheckedCallee;
6445
6446 // The result is nothrow if both operands are.
6447 SmallVector<QualType, 8> ExceptionTypeStorage;
6449 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
6451
6452 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6453 FPT1->getParamTypes(), EPI1);
6454 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6455 FPT2->getParamTypes(), EPI2);
6456 }
6457 }
6458 }
6459
6460 // There are some more conversions we can perform under exactly one pointer.
6461 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6462 !Context.hasSameType(Composite1, Composite2)) {
6463 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6464 // "pointer to cv2 T", where T is an object type or void,
6465 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6466 if (Composite1->isVoidType() && Composite2->isObjectType())
6467 Composite2 = Composite1;
6468 else if (Composite2->isVoidType() && Composite1->isObjectType())
6469 Composite1 = Composite2;
6470 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6471 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6472 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6473 // T1, respectively;
6474 //
6475 // The "similar type" handling covers all of this except for the "T1 is a
6476 // base class of T2" case in the definition of reference-related.
6477 else if (IsDerivedFrom(Loc, Composite1, Composite2))
6478 Composite1 = Composite2;
6479 else if (IsDerivedFrom(Loc, Composite2, Composite1))
6480 Composite2 = Composite1;
6481 }
6482
6483 // At this point, either the inner types are the same or we have failed to
6484 // find a composite pointer type.
6485 if (!Context.hasSameType(Composite1, Composite2))
6486 return QualType();
6487
6488 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6489 // differing qualifier.
6490 for (unsigned I = 0; I != NeedConstBefore; ++I)
6491 Steps[I].Quals.addConst();
6492
6493 // Rebuild the composite type.
6494 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
6495 for (auto &S : llvm::reverse(Steps))
6496 Composite = S.rebuild(Context, Composite);
6497
6498 if (ConvertArgs) {
6499 // Convert the expressions to the composite pointer type.
6500 InitializedEntity Entity =
6502 InitializationKind Kind =
6504
6505 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6506 if (!E1ToC)
6507 return QualType();
6508
6509 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6510 if (!E2ToC)
6511 return QualType();
6512
6513 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6514 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6515 if (E1Result.isInvalid())
6516 return QualType();
6517 E1 = E1Result.get();
6518
6519 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6520 if (E2Result.isInvalid())
6521 return QualType();
6522 E2 = E2Result.get();
6523 }
6524
6525 return Composite;
6526}
6527
6529 if (!E)
6530 return ExprError();
6531
6532 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6533
6534 // If the result is a glvalue, we shouldn't bind it.
6535 if (E->isGLValue())
6536 return E;
6537
6538 // In ARC, calls that return a retainable type can return retained,
6539 // in which case we have to insert a consuming cast.
6540 if (getLangOpts().ObjCAutoRefCount &&
6542
6543 bool ReturnsRetained;
6544
6545 // For actual calls, we compute this by examining the type of the
6546 // called value.
6547 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6548 Expr *Callee = Call->getCallee()->IgnoreParens();
6549 QualType T = Callee->getType();
6550
6551 if (T == Context.BoundMemberTy) {
6552 // Handle pointer-to-members.
6553 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6554 T = BinOp->getRHS()->getType();
6555 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6556 T = Mem->getMemberDecl()->getType();
6557 }
6558
6559 if (const PointerType *Ptr = T->getAs<PointerType>())
6560 T = Ptr->getPointeeType();
6561 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6562 T = Ptr->getPointeeType();
6563 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6564 T = MemPtr->getPointeeType();
6565
6566 auto *FTy = T->castAs<FunctionType>();
6567 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6568
6569 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6570 // type always produce a +1 object.
6571 } else if (isa<StmtExpr>(E)) {
6572 ReturnsRetained = true;
6573
6574 // We hit this case with the lambda conversion-to-block optimization;
6575 // we don't want any extra casts here.
6576 } else if (isa<CastExpr>(E) &&
6577 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6578 return E;
6579
6580 // For message sends and property references, we try to find an
6581 // actual method. FIXME: we should infer retention by selector in
6582 // cases where we don't have an actual method.
6583 } else {
6584 ObjCMethodDecl *D = nullptr;
6585 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6586 D = Send->getMethodDecl();
6587 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6588 D = BoxedExpr->getBoxingMethod();
6589 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6590 // Don't do reclaims if we're using the zero-element array
6591 // constant.
6592 if (ArrayLit->getNumElements() == 0 &&
6594 return E;
6595
6596 D = ArrayLit->getArrayWithObjectsMethod();
6597 } else if (ObjCDictionaryLiteral *DictLit
6598 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6599 // Don't do reclaims if we're using the zero-element dictionary
6600 // constant.
6601 if (DictLit->getNumElements() == 0 &&
6603 return E;
6604
6605 D = DictLit->getDictWithObjectsMethod();
6606 }
6607
6608 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6609
6610 // Don't do reclaims on performSelector calls; despite their
6611 // return type, the invoked method doesn't necessarily actually
6612 // return an object.
6613 if (!ReturnsRetained &&
6614 D && D->getMethodFamily() == OMF_performSelector)
6615 return E;
6616 }
6617
6618 // Don't reclaim an object of Class type.
6619 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6620 return E;
6621
6623
6624 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6625 : CK_ARCReclaimReturnedObject);
6626 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6628 }
6629
6632
6633 if (!getLangOpts().CPlusPlus)
6634 return E;
6635
6636 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6637 // a fast path for the common case that the type is directly a RecordType.
6639 const RecordType *RT = nullptr;
6640 while (!RT) {
6641 switch (T->getTypeClass()) {
6642 case Type::Record:
6643 RT = cast<RecordType>(T);
6644 break;
6645 case Type::ConstantArray:
6646 case Type::IncompleteArray:
6647 case Type::VariableArray:
6648 case Type::DependentSizedArray:
6649 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6650 break;
6651 default:
6652 return E;
6653 }
6654 }
6655
6656 // That should be enough to guarantee that this type is complete, if we're
6657 // not processing a decltype expression.
6658 CXXRecordDecl *RD =
6659 cast<CXXRecordDecl>(RT->getOriginalDecl())->getDefinitionOrSelf();
6660 if (RD->isInvalidDecl() || RD->isDependentContext())
6661 return E;
6662
6663 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6665 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6666
6667 if (Destructor) {
6670 PDiag(diag::err_access_dtor_temp)
6671 << E->getType());
6673 return ExprError();
6674
6675 // If destructor is trivial, we can avoid the extra copy.
6676 if (Destructor->isTrivial())
6677 return E;
6678
6679 // We need a cleanup, but we don't need to remember the temporary.
6681 }
6682
6685
6686 if (IsDecltype)
6687 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6688
6689 return Bind;
6690}
6691
6694 if (SubExpr.isInvalid())
6695 return ExprError();
6696
6697 return MaybeCreateExprWithCleanups(SubExpr.get());
6698}
6699
6701 assert(SubExpr && "subexpression can't be null!");
6702
6704
6705 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6706 assert(ExprCleanupObjects.size() >= FirstCleanup);
6707 assert(Cleanup.exprNeedsCleanups() ||
6708 ExprCleanupObjects.size() == FirstCleanup);
6710 return SubExpr;
6711
6712 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6713 ExprCleanupObjects.size() - FirstCleanup);
6714
6716 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6718
6719 return E;
6720}
6721
6723 assert(SubStmt && "sub-statement can't be null!");
6724
6726
6728 return SubStmt;
6729
6730 // FIXME: In order to attach the temporaries, wrap the statement into
6731 // a StmtExpr; currently this is only used for asm statements.
6732 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6733 // a new AsmStmtWithTemporaries.
6734 CompoundStmt *CompStmt =
6737 Expr *E = new (Context)
6739 /*FIXME TemplateDepth=*/0);
6741}
6742
6744 assert(ExprEvalContexts.back().ExprContext ==
6746 "not in a decltype expression");
6747
6749 if (Result.isInvalid())
6750 return ExprError();
6751 E = Result.get();
6752
6753 // C++11 [expr.call]p11:
6754 // If a function call is a prvalue of object type,
6755 // -- if the function call is either
6756 // -- the operand of a decltype-specifier, or
6757 // -- the right operand of a comma operator that is the operand of a
6758 // decltype-specifier,
6759 // a temporary object is not introduced for the prvalue.
6760
6761 // Recursively rebuild ParenExprs and comma expressions to strip out the
6762 // outermost CXXBindTemporaryExpr, if any.
6763 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6764 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6765 if (SubExpr.isInvalid())
6766 return ExprError();
6767 if (SubExpr.get() == PE->getSubExpr())
6768 return E;
6769 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6770 }
6771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6772 if (BO->getOpcode() == BO_Comma) {
6773 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6774 if (RHS.isInvalid())
6775 return ExprError();
6776 if (RHS.get() == BO->getRHS())
6777 return E;
6778 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
6779 BO->getType(), BO->getValueKind(),
6780 BO->getObjectKind(), BO->getOperatorLoc(),
6781 BO->getFPFeatures());
6782 }
6783 }
6784
6785 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6786 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6787 : nullptr;
6788 if (TopCall)
6789 E = TopCall;
6790 else
6791 TopBind = nullptr;
6792
6793 // Disable the special decltype handling now.
6794 ExprEvalContexts.back().ExprContext =
6796
6798 if (Result.isInvalid())
6799 return ExprError();
6800 E = Result.get();
6801
6802 // In MS mode, don't perform any extra checking of call return types within a
6803 // decltype expression.
6804 if (getLangOpts().MSVCCompat)
6805 return E;
6806
6807 // Perform the semantic checks we delayed until this point.
6808 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6809 I != N; ++I) {
6810 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6811 if (Call == TopCall)
6812 continue;
6813
6814 if (CheckCallReturnType(Call->getCallReturnType(Context),
6815 Call->getBeginLoc(), Call, Call->getDirectCallee()))
6816 return ExprError();
6817 }
6818
6819 // Now all relevant types are complete, check the destructors are accessible
6820 // and non-deleted, and annotate them on the temporaries.
6821 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6822 I != N; ++I) {
6824 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6825 if (Bind == TopBind)
6826 continue;
6827
6828 CXXTemporary *Temp = Bind->getTemporary();
6829
6830 CXXRecordDecl *RD =
6831 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6834
6835 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6836 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6837 PDiag(diag::err_access_dtor_temp)
6838 << Bind->getType());
6839 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6840 return ExprError();
6841
6842 // We need a cleanup, but we don't need to remember the temporary.
6844 }
6845
6846 // Possibly strip off the top CXXBindTemporaryExpr.
6847 return E;
6848}
6849
6850/// Note a set of 'operator->' functions that were used for a member access.
6852 ArrayRef<FunctionDecl *> OperatorArrows) {
6853 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6854 // FIXME: Make this configurable?
6855 unsigned Limit = 9;
6856 if (OperatorArrows.size() > Limit) {
6857 // Produce Limit-1 normal notes and one 'skipping' note.
6858 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6859 SkipCount = OperatorArrows.size() - (Limit - 1);
6860 }
6861
6862 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6863 if (I == SkipStart) {
6864 S.Diag(OperatorArrows[I]->getLocation(),
6865 diag::note_operator_arrows_suppressed)
6866 << SkipCount;
6867 I += SkipCount;
6868 } else {
6869 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6870 << OperatorArrows[I]->getCallResultType();
6871 ++I;
6872 }
6873 }
6874}
6875
6877 SourceLocation OpLoc,
6878 tok::TokenKind OpKind,
6879 ParsedType &ObjectType,
6880 bool &MayBePseudoDestructor) {
6881 // Since this might be a postfix expression, get rid of ParenListExprs.
6883 if (Result.isInvalid()) return ExprError();
6884 Base = Result.get();
6885
6887 if (Result.isInvalid()) return ExprError();
6888 Base = Result.get();
6889
6890 QualType BaseType = Base->getType();
6891 MayBePseudoDestructor = false;
6892 if (BaseType->isDependentType()) {
6893 // If we have a pointer to a dependent type and are using the -> operator,
6894 // the object type is the type that the pointer points to. We might still
6895 // have enough information about that type to do something useful.
6896 if (OpKind == tok::arrow)
6897 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6898 BaseType = Ptr->getPointeeType();
6899
6900 ObjectType = ParsedType::make(BaseType);
6901 MayBePseudoDestructor = true;
6902 return Base;
6903 }
6904
6905 // C++ [over.match.oper]p8:
6906 // [...] When operator->returns, the operator-> is applied to the value
6907 // returned, with the original second operand.
6908 if (OpKind == tok::arrow) {
6909 QualType StartingType = BaseType;
6910 bool NoArrowOperatorFound = false;
6911 bool FirstIteration = true;
6912 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6913 // The set of types we've considered so far.
6915 SmallVector<FunctionDecl*, 8> OperatorArrows;
6916 CTypes.insert(Context.getCanonicalType(BaseType));
6917
6918 while (BaseType->isRecordType()) {
6919 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6920 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6921 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6922 noteOperatorArrows(*this, OperatorArrows);
6923 Diag(OpLoc, diag::note_operator_arrow_depth)
6924 << getLangOpts().ArrowDepth;
6925 return ExprError();
6926 }
6927
6929 S, Base, OpLoc,
6930 // When in a template specialization and on the first loop iteration,
6931 // potentially give the default diagnostic (with the fixit in a
6932 // separate note) instead of having the error reported back to here
6933 // and giving a diagnostic with a fixit attached to the error itself.
6934 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6935 ? nullptr
6936 : &NoArrowOperatorFound);
6937 if (Result.isInvalid()) {
6938 if (NoArrowOperatorFound) {
6939 if (FirstIteration) {
6940 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6941 << BaseType << 1 << Base->getSourceRange()
6942 << FixItHint::CreateReplacement(OpLoc, ".");
6943 OpKind = tok::period;
6944 break;
6945 }
6946 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6947 << BaseType << Base->getSourceRange();
6948 CallExpr *CE = dyn_cast<CallExpr>(Base);
6949 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6950 Diag(CD->getBeginLoc(),
6951 diag::note_member_reference_arrow_from_operator_arrow);
6952 }
6953 }
6954 return ExprError();
6955 }
6956 Base = Result.get();
6957 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6958 OperatorArrows.push_back(OpCall->getDirectCallee());
6959 BaseType = Base->getType();
6960 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6961 if (!CTypes.insert(CBaseType).second) {
6962 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6963 noteOperatorArrows(*this, OperatorArrows);
6964 return ExprError();
6965 }
6966 FirstIteration = false;
6967 }
6968
6969 if (OpKind == tok::arrow) {
6970 if (BaseType->isPointerType())
6971 BaseType = BaseType->getPointeeType();
6972 else if (auto *AT = Context.getAsArrayType(BaseType))
6973 BaseType = AT->getElementType();
6974 }
6975 }
6976
6977 // Objective-C properties allow "." access on Objective-C pointer types,
6978 // so adjust the base type to the object type itself.
6979 if (BaseType->isObjCObjectPointerType())
6980 BaseType = BaseType->getPointeeType();
6981
6982 // C++ [basic.lookup.classref]p2:
6983 // [...] If the type of the object expression is of pointer to scalar
6984 // type, the unqualified-id is looked up in the context of the complete
6985 // postfix-expression.
6986 //
6987 // This also indicates that we could be parsing a pseudo-destructor-name.
6988 // Note that Objective-C class and object types can be pseudo-destructor
6989 // expressions or normal member (ivar or property) access expressions, and
6990 // it's legal for the type to be incomplete if this is a pseudo-destructor
6991 // call. We'll do more incomplete-type checks later in the lookup process,
6992 // so just skip this check for ObjC types.
6993 if (!BaseType->isRecordType()) {
6994 ObjectType = ParsedType::make(BaseType);
6995 MayBePseudoDestructor = true;
6996 return Base;
6997 }
6998
6999 // The object type must be complete (or dependent), or
7000 // C++11 [expr.prim.general]p3:
7001 // Unlike the object expression in other contexts, *this is not required to
7002 // be of complete type for purposes of class member access (5.2.5) outside
7003 // the member function body.
7004 if (!BaseType->isDependentType() &&
7006 RequireCompleteType(OpLoc, BaseType,
7007 diag::err_incomplete_member_access)) {
7008 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7009 }
7010
7011 // C++ [basic.lookup.classref]p2:
7012 // If the id-expression in a class member access (5.2.5) is an
7013 // unqualified-id, and the type of the object expression is of a class
7014 // type C (or of pointer to a class type C), the unqualified-id is looked
7015 // up in the scope of class C. [...]
7016 ObjectType = ParsedType::make(BaseType);
7017 return Base;
7018}
7019
7020static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7021 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7022 if (Base->hasPlaceholderType()) {
7024 if (result.isInvalid()) return true;
7025 Base = result.get();
7026 }
7027 ObjectType = Base->getType();
7028
7029 // C++ [expr.pseudo]p2:
7030 // The left-hand side of the dot operator shall be of scalar type. The
7031 // left-hand side of the arrow operator shall be of pointer to scalar type.
7032 // This scalar type is the object type.
7033 // Note that this is rather different from the normal handling for the
7034 // arrow operator.
7035 if (OpKind == tok::arrow) {
7036 // The operator requires a prvalue, so perform lvalue conversions.
7037 // Only do this if we might plausibly end with a pointer, as otherwise
7038 // this was likely to be intended to be a '.'.
7039 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7040 ObjectType->isFunctionType()) {
7042 if (BaseResult.isInvalid())
7043 return true;
7044 Base = BaseResult.get();
7045 ObjectType = Base->getType();
7046 }
7047
7048 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7049 ObjectType = Ptr->getPointeeType();
7050 } else if (!Base->isTypeDependent()) {
7051 // The user wrote "p->" when they probably meant "p."; fix it.
7052 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7053 << ObjectType << true
7054 << FixItHint::CreateReplacement(OpLoc, ".");
7055 if (S.isSFINAEContext())
7056 return true;
7057
7058 OpKind = tok::period;
7059 }
7060 }
7061
7062 return false;
7063}
7064
7065/// Check if it's ok to try and recover dot pseudo destructor calls on
7066/// pointer objects.
7067static bool
7069 QualType DestructedType) {
7070 // If this is a record type, check if its destructor is callable.
7071 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7072 if (RD->hasDefinition())
7074 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7075 return false;
7076 }
7077
7078 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7079 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7080 DestructedType->isVectorType();
7081}
7082
7084 SourceLocation OpLoc,
7085 tok::TokenKind OpKind,
7086 const CXXScopeSpec &SS,
7087 TypeSourceInfo *ScopeTypeInfo,
7088 SourceLocation CCLoc,
7089 SourceLocation TildeLoc,
7090 PseudoDestructorTypeStorage Destructed) {
7091 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7092
7093 QualType ObjectType;
7094 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7095 return ExprError();
7096
7097 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7098 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) {
7099 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7100 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7101 else {
7102 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7103 << ObjectType << Base->getSourceRange();
7104 return ExprError();
7105 }
7106 }
7107
7108 // C++ [expr.pseudo]p2:
7109 // [...] The cv-unqualified versions of the object type and of the type
7110 // designated by the pseudo-destructor-name shall be the same type.
7111 if (DestructedTypeInfo) {
7112 QualType DestructedType = DestructedTypeInfo->getType();
7113 SourceLocation DestructedTypeStart =
7114 DestructedTypeInfo->getTypeLoc().getBeginLoc();
7115 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7116 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7117 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7118 // Foo *foo;
7119 // foo.~Foo();
7120 if (OpKind == tok::period && ObjectType->isPointerType() &&
7121 Context.hasSameUnqualifiedType(DestructedType,
7122 ObjectType->getPointeeType())) {
7123 auto Diagnostic =
7124 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7125 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7126
7127 // Issue a fixit only when the destructor is valid.
7129 *this, DestructedType))
7131
7132 // Recover by setting the object type to the destructed type and the
7133 // operator to '->'.
7134 ObjectType = DestructedType;
7135 OpKind = tok::arrow;
7136 } else {
7137 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7138 << ObjectType << DestructedType << Base->getSourceRange()
7139 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7140
7141 // Recover by setting the destructed type to the object type.
7142 DestructedType = ObjectType;
7143 DestructedTypeInfo =
7144 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7145 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7146 }
7147 } else if (DestructedType.getObjCLifetime() !=
7148 ObjectType.getObjCLifetime()) {
7149
7150 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7151 // Okay: just pretend that the user provided the correctly-qualified
7152 // type.
7153 } else {
7154 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7155 << ObjectType << DestructedType << Base->getSourceRange()
7156 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7157 }
7158
7159 // Recover by setting the destructed type to the object type.
7160 DestructedType = ObjectType;
7161 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7162 DestructedTypeStart);
7163 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7164 }
7165 }
7166 }
7167
7168 // C++ [expr.pseudo]p2:
7169 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7170 // form
7171 //
7172 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7173 //
7174 // shall designate the same scalar type.
7175 if (ScopeTypeInfo) {
7176 QualType ScopeType = ScopeTypeInfo->getType();
7177 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7178 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7179
7180 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7181 diag::err_pseudo_dtor_type_mismatch)
7182 << ObjectType << ScopeType << Base->getSourceRange()
7183 << ScopeTypeInfo->getTypeLoc().getSourceRange();
7184
7185 ScopeType = QualType();
7186 ScopeTypeInfo = nullptr;
7187 }
7188 }
7189
7190 Expr *Result
7192 OpKind == tok::arrow, OpLoc,
7194 ScopeTypeInfo,
7195 CCLoc,
7196 TildeLoc,
7197 Destructed);
7198
7199 return Result;
7200}
7201
7203 SourceLocation OpLoc,
7204 tok::TokenKind OpKind,
7205 CXXScopeSpec &SS,
7206 UnqualifiedId &FirstTypeName,
7207 SourceLocation CCLoc,
7208 SourceLocation TildeLoc,
7209 UnqualifiedId &SecondTypeName) {
7210 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7211 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7212 "Invalid first type name in pseudo-destructor");
7213 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7214 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7215 "Invalid second type name in pseudo-destructor");
7216
7217 QualType ObjectType;
7218 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7219 return ExprError();
7220
7221 // Compute the object type that we should use for name lookup purposes. Only
7222 // record types and dependent types matter.
7223 ParsedType ObjectTypePtrForLookup;
7224 if (!SS.isSet()) {
7225 if (ObjectType->isRecordType())
7226 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7227 else if (ObjectType->isDependentType())
7228 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7229 }
7230
7231 // Convert the name of the type being destructed (following the ~) into a
7232 // type (with source-location information).
7233 QualType DestructedType;
7234 TypeSourceInfo *DestructedTypeInfo = nullptr;
7235 PseudoDestructorTypeStorage Destructed;
7236 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7237 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7238 SecondTypeName.StartLocation,
7239 S, &SS, true, false, ObjectTypePtrForLookup,
7240 /*IsCtorOrDtorName*/true);
7241 if (!T &&
7242 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7243 (!SS.isSet() && ObjectType->isDependentType()))) {
7244 // The name of the type being destroyed is a dependent name, and we
7245 // couldn't find anything useful in scope. Just store the identifier and
7246 // it's location, and we'll perform (qualified) name lookup again at
7247 // template instantiation time.
7248 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7249 SecondTypeName.StartLocation);
7250 } else if (!T) {
7251 Diag(SecondTypeName.StartLocation,
7252 diag::err_pseudo_dtor_destructor_non_type)
7253 << SecondTypeName.Identifier << ObjectType;
7254 if (isSFINAEContext())
7255 return ExprError();
7256
7257 // Recover by assuming we had the right type all along.
7258 DestructedType = ObjectType;
7259 } else
7260 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7261 } else {
7262 // Resolve the template-id to a type.
7263 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7264 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7265 TemplateId->NumArgs);
7268 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7269 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,
7270 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
7271 TemplateId->RAngleLoc,
7272 /*IsCtorOrDtorName*/ true);
7273 if (T.isInvalid() || !T.get()) {
7274 // Recover by assuming we had the right type all along.
7275 DestructedType = ObjectType;
7276 } else
7277 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7278 }
7279
7280 // If we've performed some kind of recovery, (re-)build the type source
7281 // information.
7282 if (!DestructedType.isNull()) {
7283 if (!DestructedTypeInfo)
7284 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7285 SecondTypeName.StartLocation);
7286 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7287 }
7288
7289 // Convert the name of the scope type (the type prior to '::') into a type.
7290 TypeSourceInfo *ScopeTypeInfo = nullptr;
7291 QualType ScopeType;
7292 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7293 FirstTypeName.Identifier) {
7294 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7295 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7296 FirstTypeName.StartLocation,
7297 S, &SS, true, false, ObjectTypePtrForLookup,
7298 /*IsCtorOrDtorName*/true);
7299 if (!T) {
7300 Diag(FirstTypeName.StartLocation,
7301 diag::err_pseudo_dtor_destructor_non_type)
7302 << FirstTypeName.Identifier << ObjectType;
7303
7304 if (isSFINAEContext())
7305 return ExprError();
7306
7307 // Just drop this type. It's unnecessary anyway.
7308 ScopeType = QualType();
7309 } else
7310 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7311 } else {
7312 // Resolve the template-id to a type.
7313 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7314 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7315 TemplateId->NumArgs);
7318 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7319 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,
7320 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
7321 TemplateId->RAngleLoc,
7322 /*IsCtorOrDtorName*/ true);
7323 if (T.isInvalid() || !T.get()) {
7324 // Recover by dropping this type.
7325 ScopeType = QualType();
7326 } else
7327 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7328 }
7329 }
7330
7331 if (!ScopeType.isNull() && !ScopeTypeInfo)
7332 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7333 FirstTypeName.StartLocation);
7334
7335
7336 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7337 ScopeTypeInfo, CCLoc, TildeLoc,
7338 Destructed);
7339}
7340
7342 SourceLocation OpLoc,
7343 tok::TokenKind OpKind,
7344 SourceLocation TildeLoc,
7345 const DeclSpec& DS) {
7346 QualType ObjectType;
7347 QualType T;
7348 TypeLocBuilder TLB;
7349 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) ||
7351 return ExprError();
7352
7353 switch (DS.getTypeSpecType()) {
7355 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7356 return true;
7357 }
7359 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7360 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7361 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7362 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7363 break;
7364 }
7367 DS.getBeginLoc(), DS.getEllipsisLoc());
7369 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
7370 DS.getBeginLoc());
7372 PITL.setEllipsisLoc(DS.getEllipsisLoc());
7373 break;
7374 }
7375 default:
7376 llvm_unreachable("Unsupported type in pseudo destructor");
7377 }
7378 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7379 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7380
7381 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7382 nullptr, SourceLocation(), TildeLoc,
7383 Destructed);
7384}
7385
7387 SourceLocation RParen) {
7388 // If the operand is an unresolved lookup expression, the expression is ill-
7389 // formed per [over.over]p1, because overloaded function names cannot be used
7390 // without arguments except in explicit contexts.
7391 ExprResult R = CheckPlaceholderExpr(Operand);
7392 if (R.isInvalid())
7393 return R;
7394
7396 if (R.isInvalid())
7397 return ExprError();
7398
7399 Operand = R.get();
7400
7401 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
7402 Operand->HasSideEffects(Context, false)) {
7403 // The expression operand for noexcept is in an unevaluated expression
7404 // context, so side effects could result in unintended consequences.
7405 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7406 }
7407
7408 CanThrowResult CanThrow = canThrow(Operand);
7409 return new (Context)
7410 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7411}
7412
7414 Expr *Operand, SourceLocation RParen) {
7415 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7416}
7417
7419 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
7420 DeclRefExpr *LHS = nullptr;
7421 bool IsCompoundAssign = false;
7422 bool isIncrementDecrementUnaryOp = false;
7423 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7424 if (BO->getLHS()->getType()->isDependentType() ||
7425 BO->getRHS()->getType()->isDependentType()) {
7426 if (BO->getOpcode() != BO_Assign)
7427 return;
7428 } else if (!BO->isAssignmentOp())
7429 return;
7430 else
7431 IsCompoundAssign = BO->isCompoundAssignmentOp();
7432 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
7433 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7434 if (COCE->getOperator() != OO_Equal)
7435 return;
7436 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
7437 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7438 if (!UO->isIncrementDecrementOp())
7439 return;
7440 isIncrementDecrementUnaryOp = true;
7441 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
7442 }
7443 if (!LHS)
7444 return;
7445 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
7446 if (!VD)
7447 return;
7448 // Don't decrement RefsMinusAssignments if volatile variable with compound
7449 // assignment (+=, ...) or increment/decrement unary operator to avoid
7450 // potential unused-but-set-variable warning.
7451 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
7453 return;
7454 auto iter = RefsMinusAssignments.find(VD);
7455 if (iter == RefsMinusAssignments.end())
7456 return;
7457 iter->getSecond()--;
7458}
7459
7460/// Perform the conversions required for an expression used in a
7461/// context that ignores the result.
7464
7465 if (E->hasPlaceholderType()) {
7467 if (result.isInvalid()) return E;
7468 E = result.get();
7469 }
7470
7471 if (getLangOpts().CPlusPlus) {
7472 // The C++11 standard defines the notion of a discarded-value expression;
7473 // normally, we don't need to do anything to handle it, but if it is a
7474 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7475 // conversion.
7478 if (Res.isInvalid())
7479 return E;
7480 E = Res.get();
7481 } else {
7482 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7483 // it occurs as a discarded-value expression.
7485 }
7486
7487 // C++1z:
7488 // If the expression is a prvalue after this optional conversion, the
7489 // temporary materialization conversion is applied.
7490 //
7491 // We do not materialize temporaries by default in order to avoid creating
7492 // unnecessary temporary objects. If we skip this step, IR generation is
7493 // able to synthesize the storage for itself in the aggregate case, and
7494 // adding the extra node to the AST is just clutter.
7496 E->isPRValue() && !E->getType()->isVoidType()) {
7498 if (Res.isInvalid())
7499 return E;
7500 E = Res.get();
7501 }
7502 return E;
7503 }
7504
7505 // C99 6.3.2.1:
7506 // [Except in specific positions,] an lvalue that does not have
7507 // array type is converted to the value stored in the
7508 // designated object (and is no longer an lvalue).
7509 if (E->isPRValue()) {
7510 // In C, function designators (i.e. expressions of function type)
7511 // are r-values, but we still want to do function-to-pointer decay
7512 // on them. This is both technically correct and convenient for
7513 // some clients.
7516
7517 return E;
7518 }
7519
7520 // GCC seems to also exclude expressions of incomplete enum type.
7521 if (const auto *ED = E->getType()->getAsEnumDecl(); ED && !ED->isComplete()) {
7522 // FIXME: stupid workaround for a codegen bug!
7523 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7524 return E;
7525 }
7526
7528 if (Res.isInvalid())
7529 return E;
7530 E = Res.get();
7531
7532 if (!E->getType()->isVoidType())
7534 diag::err_incomplete_type);
7535 return E;
7536}
7537
7539 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7540 // it occurs as an unevaluated operand.
7542
7543 return E;
7544}
7545
7546// If we can unambiguously determine whether Var can never be used
7547// in a constant expression, return true.
7548// - if the variable and its initializer are non-dependent, then
7549// we can unambiguously check if the variable is a constant expression.
7550// - if the initializer is not value dependent - we can determine whether
7551// it can be used to initialize a constant expression. If Init can not
7552// be used to initialize a constant expression we conclude that Var can
7553// never be a constant expression.
7554// - FXIME: if the initializer is dependent, we can still do some analysis and
7555// identify certain cases unambiguously as non-const by using a Visitor:
7556// - such as those that involve odr-use of a ParmVarDecl, involve a new
7557// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7560 if (isa<ParmVarDecl>(Var)) return true;
7561 const VarDecl *DefVD = nullptr;
7562
7563 // If there is no initializer - this can not be a constant expression.
7564 const Expr *Init = Var->getAnyInitializer(DefVD);
7565 if (!Init)
7566 return true;
7567 assert(DefVD);
7568 if (DefVD->isWeak())
7569 return false;
7570
7571 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7572 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7573 // of value-dependent expressions, and use it here to determine whether the
7574 // initializer is a potential constant expression.
7575 return false;
7576 }
7577
7579}
7580
7581/// Check if the current lambda has any potential captures
7582/// that must be captured by any of its enclosing lambdas that are ready to
7583/// capture. If there is a lambda that can capture a nested
7584/// potential-capture, go ahead and do so. Also, check to see if any
7585/// variables are uncaptureable or do not involve an odr-use so do not
7586/// need to be captured.
7587
7589 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7590
7591 assert(!S.isUnevaluatedContext());
7592 assert(S.CurContext->isDependentContext());
7593#ifndef NDEBUG
7594 DeclContext *DC = S.CurContext;
7595 while (isa_and_nonnull<CapturedDecl>(DC))
7596 DC = DC->getParent();
7597 assert(
7598 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) &&
7599 "The current call operator must be synchronized with Sema's CurContext");
7600#endif // NDEBUG
7601
7602 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7603
7604 // All the potentially captureable variables in the current nested
7605 // lambda (within a generic outer lambda), must be captured by an
7606 // outer lambda that is enclosed within a non-dependent context.
7607 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
7608 // If the variable is clearly identified as non-odr-used and the full
7609 // expression is not instantiation dependent, only then do we not
7610 // need to check enclosing lambda's for speculative captures.
7611 // For e.g.:
7612 // Even though 'x' is not odr-used, it should be captured.
7613 // int test() {
7614 // const int x = 10;
7615 // auto L = [=](auto a) {
7616 // (void) +x + a;
7617 // };
7618 // }
7619 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7620 !IsFullExprInstantiationDependent)
7621 return;
7622
7623 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
7624 if (!UnderlyingVar)
7625 return;
7626
7627 // If we have a capture-capable lambda for the variable, go ahead and
7628 // capture the variable in that lambda (and all its enclosing lambdas).
7629 if (const UnsignedOrNone Index =
7631 S.FunctionScopes, Var, S))
7632 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
7633 const bool IsVarNeverAConstantExpression =
7635 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7636 // This full expression is not instantiation dependent or the variable
7637 // can not be used in a constant expression - which means
7638 // this variable must be odr-used here, so diagnose a
7639 // capture violation early, if the variable is un-captureable.
7640 // This is purely for diagnosing errors early. Otherwise, this
7641 // error would get diagnosed when the lambda becomes capture ready.
7642 QualType CaptureType, DeclRefType;
7643 SourceLocation ExprLoc = VarExpr->getExprLoc();
7644 if (S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit,
7645 /*EllipsisLoc*/ SourceLocation(),
7646 /*BuildAndDiagnose*/ false, CaptureType,
7647 DeclRefType, nullptr)) {
7648 // We will never be able to capture this variable, and we need
7649 // to be able to in any and all instantiations, so diagnose it.
7651 /*EllipsisLoc*/ SourceLocation(),
7652 /*BuildAndDiagnose*/ true, CaptureType,
7653 DeclRefType, nullptr);
7654 }
7655 }
7656 });
7657
7658 // Check if 'this' needs to be captured.
7659 if (CurrentLSI->hasPotentialThisCapture()) {
7660 // If we have a capture-capable lambda for 'this', go ahead and capture
7661 // 'this' in that lambda (and all its enclosing lambdas).
7662 if (const UnsignedOrNone Index =
7664 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7665 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
7667 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7668 &FunctionScopeIndexOfCapturableLambda);
7669 }
7670 }
7671
7672 // Reset all the potential captures at the end of each full-expression.
7673 CurrentLSI->clearPotentialCaptures();
7674}
7675
7677 bool DiscardedValue, bool IsConstexpr,
7678 bool IsTemplateArgument) {
7679 ExprResult FullExpr = FE;
7680
7681 if (!FullExpr.get())
7682 return ExprError();
7683
7684 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
7685 return ExprError();
7686
7687 if (DiscardedValue) {
7688 // Top-level expressions default to 'id' when we're in a debugger.
7689 if (getLangOpts().DebuggerCastResultToId &&
7690 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7692 if (FullExpr.isInvalid())
7693 return ExprError();
7694 }
7695
7697 if (FullExpr.isInvalid())
7698 return ExprError();
7699
7701 if (FullExpr.isInvalid())
7702 return ExprError();
7703
7704 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
7705 }
7706
7707 if (FullExpr.isInvalid())
7708 return ExprError();
7709
7710 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7711
7712 // At the end of this full expression (which could be a deeply nested
7713 // lambda), if there is a potential capture within the nested lambda,
7714 // have the outer capture-able lambda try and capture it.
7715 // Consider the following code:
7716 // void f(int, int);
7717 // void f(const int&, double);
7718 // void foo() {
7719 // const int x = 10, y = 20;
7720 // auto L = [=](auto a) {
7721 // auto M = [=](auto b) {
7722 // f(x, b); <-- requires x to be captured by L and M
7723 // f(y, a); <-- requires y to be captured by L, but not all Ms
7724 // };
7725 // };
7726 // }
7727
7728 // FIXME: Also consider what happens for something like this that involves
7729 // the gnu-extension statement-expressions or even lambda-init-captures:
7730 // void f() {
7731 // const int n = 0;
7732 // auto L = [&](auto a) {
7733 // +n + ({ 0; a; });
7734 // };
7735 // }
7736 //
7737 // Here, we see +n, and then the full-expression 0; ends, so we don't
7738 // capture n (and instead remove it from our list of potential captures),
7739 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7740 // for us to see that we need to capture n after all.
7741
7742 LambdaScopeInfo *const CurrentLSI =
7743 getCurLambda(/*IgnoreCapturedRegions=*/true);
7744 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7745 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7746 // for an example of the code that might cause this asynchrony.
7747 // By ensuring we are in the context of a lambda's call operator
7748 // we can fix the bug (we only need to check whether we need to capture
7749 // if we are within a lambda's body); but per the comments in that
7750 // PR, a proper fix would entail :
7751 // "Alternative suggestion:
7752 // - Add to Sema an integer holding the smallest (outermost) scope
7753 // index that we are *lexically* within, and save/restore/set to
7754 // FunctionScopes.size() in InstantiatingTemplate's
7755 // constructor/destructor.
7756 // - Teach the handful of places that iterate over FunctionScopes to
7757 // stop at the outermost enclosing lexical scope."
7758 DeclContext *DC = CurContext;
7759 while (isa_and_nonnull<CapturedDecl>(DC))
7760 DC = DC->getParent();
7761 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7762 if (IsInLambdaDeclContext && CurrentLSI &&
7763 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7765 *this);
7767}
7768
7770 if (!FullStmt) return StmtError();
7771
7772 return MaybeCreateStmtWithCleanups(FullStmt);
7773}
7774
7777 const DeclarationNameInfo &TargetNameInfo) {
7778 DeclarationName TargetName = TargetNameInfo.getName();
7779 if (!TargetName)
7781
7782 // If the name itself is dependent, then the result is dependent.
7783 if (TargetName.isDependentName())
7785
7786 // Do the redeclaration lookup in the current scope.
7787 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7788 RedeclarationKind::NotForRedeclaration);
7789 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
7791
7792 switch (R.getResultKind()) {
7798
7801
7804 }
7805
7806 llvm_unreachable("Invalid LookupResult Kind!");
7807}
7808
7810 SourceLocation KeywordLoc,
7811 bool IsIfExists,
7812 CXXScopeSpec &SS,
7813 UnqualifiedId &Name) {
7814 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7815
7816 // Check for an unexpanded parameter pack.
7817 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7818 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7819 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7820 return IfExistsResult::Error;
7821
7822 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7823}
7824
7826 return BuildExprRequirement(E, /*IsSimple=*/true,
7827 /*NoexceptLoc=*/SourceLocation(),
7828 /*ReturnTypeRequirement=*/{});
7829}
7830
7832 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7833 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
7834 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
7835 "Exactly one of TypeName and TemplateId must be specified.");
7836 TypeSourceInfo *TSI = nullptr;
7837 if (TypeName) {
7838 QualType T =
7840 SS.getWithLocInContext(Context), *TypeName, NameLoc,
7841 &TSI, /*DeducedTSTContext=*/false);
7842 if (T.isNull())
7843 return nullptr;
7844 } else {
7845 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
7846 TemplateId->NumArgs);
7847 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
7848 TemplateId->TemplateKWLoc,
7849 TemplateId->Template, TemplateId->Name,
7850 TemplateId->TemplateNameLoc,
7851 TemplateId->LAngleLoc, ArgsPtr,
7852 TemplateId->RAngleLoc);
7853 if (T.isInvalid())
7854 return nullptr;
7855 if (GetTypeFromParser(T.get(), &TSI).isNull())
7856 return nullptr;
7857 }
7858 return BuildTypeRequirement(TSI);
7859}
7860
7863 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
7864 /*ReturnTypeRequirement=*/{});
7865}
7866
7869 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7870 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
7871 // C++2a [expr.prim.req.compound] p1.3.3
7872 // [..] the expression is deduced against an invented function template
7873 // F [...] F is a void function template with a single type template
7874 // parameter T declared with the constrained-parameter. Form a new
7875 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
7876 // around the constrained-parameter. F has a single parameter whose
7877 // type-specifier is cv T followed by the abstract-declarator. [...]
7878 //
7879 // The cv part is done in the calling function - we get the concept with
7880 // arguments and the abstract declarator with the correct CV qualification and
7881 // have to synthesize T and the single parameter of F.
7882 auto &II = Context.Idents.get("expr-type");
7885 SourceLocation(), Depth,
7886 /*Index=*/0, &II,
7887 /*Typename=*/true,
7888 /*ParameterPack=*/false,
7889 /*HasTypeConstraint=*/true);
7890
7891 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
7892 /*EllipsisLoc=*/SourceLocation(),
7893 /*AllowUnexpandedPack=*/true))
7894 // Just produce a requirement with no type requirements.
7895 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
7896
7899 ArrayRef<NamedDecl *>(TParam),
7901 /*RequiresClause=*/nullptr);
7902 return BuildExprRequirement(
7903 E, /*IsSimple=*/false, NoexceptLoc,
7905}
7906
7909 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
7912 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
7914 ReturnTypeRequirement.isDependent())
7916 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
7918 else if (ReturnTypeRequirement.isSubstitutionFailure())
7920 else if (ReturnTypeRequirement.isTypeConstraint()) {
7921 // C++2a [expr.prim.req]p1.3.3
7922 // The immediately-declared constraint ([temp]) of decltype((E)) shall
7923 // be satisfied.
7925 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
7926 QualType MatchedType =
7929 Args.push_back(TemplateArgument(MatchedType));
7930
7931 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
7932
7933 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
7934 MLTAL.addOuterRetainedLevels(TPL->getDepth());
7935 const TypeConstraint *TC = Param->getTypeConstraint();
7936 assert(TC && "Type Constraint cannot be null here");
7937 auto *IDC = TC->getImmediatelyDeclaredConstraint();
7938 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
7939 ExprResult Constraint = SubstExpr(IDC, MLTAL);
7940 if (Constraint.isInvalid()) {
7942 createSubstDiagAt(IDC->getExprLoc(),
7943 [&](llvm::raw_ostream &OS) {
7944 IDC->printPretty(OS, /*Helper=*/nullptr,
7945 getPrintingPolicy());
7946 }),
7947 IsSimple, NoexceptLoc, ReturnTypeRequirement);
7948 }
7949 SubstitutedConstraintExpr =
7950 cast<ConceptSpecializationExpr>(Constraint.get());
7951 if (!SubstitutedConstraintExpr->isSatisfied())
7953 }
7954 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
7955 ReturnTypeRequirement, Status,
7956 SubstitutedConstraintExpr);
7957}
7958
7961 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
7962 bool IsSimple, SourceLocation NoexceptLoc,
7964 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
7965 IsSimple, NoexceptLoc,
7966 ReturnTypeRequirement);
7967}
7968
7972}
7973
7977 return new (Context) concepts::TypeRequirement(SubstDiag);
7978}
7979
7981 return BuildNestedRequirement(Constraint);
7982}
7983
7986 ConstraintSatisfaction Satisfaction;
7987 if (!Constraint->isInstantiationDependent() &&
7989 /*TemplateArgs=*/{},
7990 Constraint->getSourceRange(), Satisfaction))
7991 return nullptr;
7992 return new (Context) concepts::NestedRequirement(Context, Constraint,
7993 Satisfaction);
7994}
7995
7997Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
7998 const ASTConstraintSatisfaction &Satisfaction) {
8000 InvalidConstraintEntity,
8002}
8003
8006 ArrayRef<ParmVarDecl *> LocalParameters,
8007 Scope *BodyScope) {
8008 assert(BodyScope);
8009
8011 RequiresKWLoc);
8012
8013 PushDeclContext(BodyScope, Body);
8014
8015 for (ParmVarDecl *Param : LocalParameters) {
8016 if (Param->getType()->isVoidType()) {
8017 if (LocalParameters.size() > 1) {
8018 Diag(Param->getBeginLoc(), diag::err_void_only_param);
8019 Param->setType(Context.IntTy);
8020 } else if (Param->getIdentifier()) {
8021 Diag(Param->getBeginLoc(), diag::err_param_with_void_type);
8022 Param->setType(Context.IntTy);
8023 } else if (Param->getType().hasQualifiers()) {
8024 Diag(Param->getBeginLoc(), diag::err_void_param_qualified);
8025 }
8026 } else if (Param->hasDefaultArg()) {
8027 // C++2a [expr.prim.req] p4
8028 // [...] A local parameter of a requires-expression shall not have a
8029 // default argument. [...]
8030 Diag(Param->getDefaultArgRange().getBegin(),
8031 diag::err_requires_expr_local_parameter_default_argument);
8032 // Ignore default argument and move on
8033 } else if (Param->isExplicitObjectParameter()) {
8034 // C++23 [dcl.fct]p6:
8035 // An explicit-object-parameter-declaration is a parameter-declaration
8036 // with a this specifier. An explicit-object-parameter-declaration
8037 // shall appear only as the first parameter-declaration of a
8038 // parameter-declaration-list of either:
8039 // - a member-declarator that declares a member function, or
8040 // - a lambda-declarator.
8041 //
8042 // The parameter-declaration-list of a requires-expression is not such
8043 // a context.
8044 Diag(Param->getExplicitObjectParamThisLoc(),
8045 diag::err_requires_expr_explicit_object_parameter);
8046 Param->setExplicitObjectParameterLoc(SourceLocation());
8047 }
8048
8049 Param->setDeclContext(Body);
8050 // If this has an identifier, add it to the scope stack.
8051 if (Param->getIdentifier()) {
8052 CheckShadow(BodyScope, Param);
8053 PushOnScopeChains(Param, BodyScope);
8054 }
8055 }
8056 return Body;
8057}
8058
8060 assert(CurContext && "DeclContext imbalance!");
8062 assert(CurContext && "Popped translation unit!");
8063}
8064
8066 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
8067 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
8068 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
8069 SourceLocation ClosingBraceLoc) {
8070 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
8071 LocalParameters, RParenLoc, Requirements,
8072 ClosingBraceLoc);
8074 return ExprError();
8075 return RE;
8076}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines a function that returns the minimum OS versions supporting C++17's aligned allocation functio...
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2777
const Decl * D
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:3531
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, TypeAwareAllocationMode PassType, QualType allocType)
Determine whether a given type is a class for which 'delete[]' would call a member 'operator delete[]...
static void collectPublicBases(CXXRecordDecl *RD, llvm::DenseMap< CXXRecordDecl *, unsigned > &SubobjectsSeen, llvm::SmallPtrSetImpl< CXXRecordDecl * > &VBases, llvm::SetVector< CXXRecordDecl * > &PublicSubobjectsSeen, bool ParentIsPublic)
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T)
Perform an "extended" implicit conversion as returned by TryClassUnification.
static void MaybeDecrementCount(Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc, SourceRange Range, bool Diagnose, CXXRecordDecl *NamingClass, DeclAccessPair Decl, FunctionDecl *Operator)
static void DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, const MismatchingNewDeleteDetector &Detector)
static void getUnambiguousPublicSubobjects(CXXRecordDecl *RD, llvm::SmallVectorImpl< CXXRecordDecl * > &Objects)
static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, Expr *Init, bool IsCPlusPlus20)
static QualType adjustVectorType(ASTContext &Context, QualType FromTy, QualType ToType, QualType *ElTy=nullptr)
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S)
Check if the current lambda has any potential captures that must be captured by any of its enclosing ...
static void getUuidAttrOfType(Sema &SemaRef, QualType QT, llvm::SmallSetVector< const UuidAttr *, 1 > &UuidAttrs)
Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to a single GUID.
DeallocLookupMode
static QualType adjustCVQualifiersForCXXThisWithinLambda(ArrayRef< FunctionScopeInfo * > FunctionScopes, QualType ThisTy, DeclContext *CurSemaContext, ASTContext &ASTCtx)
static bool resolveAllocationOverloadInterior(Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode, SmallVectorImpl< Expr * > &Args, AlignedAllocationMode &PassAlignment, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Try to find a common type for two according to C++0x 5.16p5.
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, SourceLocation QuestionLoc, bool &HaveConversion, QualType &ToType)
Try to convert a type to another according to C++11 5.16p3.
static bool resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl< Expr * > &Args, ImplicitAllocationParameters &IAP, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
static UsualDeallocFnInfo resolveDeallocationOverload(Sema &S, LookupResult &R, const ImplicitDeallocationParameters &IDP, SourceLocation Loc, llvm::SmallVectorImpl< UsualDeallocFnInfo > *BestFns=nullptr)
Select the correct "usual" deallocation function to use from a selection of deallocation functions (e...
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType)
Determine whether a type has new-extended alignment.
static ExprResult BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, DeclAccessPair FoundDecl, bool HadMultipleCandidates, Expr *From)
ResolveMode
static bool VariableCanNeverBeAConstantExpression(VarDecl *Var, ASTContext &Context)
static bool canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, QualType DestructedType)
Check if it's ok to try and recover dot pseudo destructor calls on pointer objects.
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, tok::TokenKind &OpKind, SourceLocation OpLoc)
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, bool IsDelete, FunctionDecl *&Operator)
static bool isValidVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static void LookupGlobalDeallocationFunctions(Sema &S, SourceLocation Loc, LookupResult &FoundDelete, DeallocLookupMode Mode, DeclarationName Name)
static void noteOperatorArrows(Sema &S, ArrayRef< FunctionDecl * > OperatorArrows)
Note a set of 'operator->' functions that were used for a member access.
static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI)
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
This file declares semantic analysis for HLSL constructs.
This file provides some common utility functions for processing Lambdas.
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
This file declares semantic analysis for Objective-C.
This file declares semantic analysis functions specific to PowerPC.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
a trap message and trap category.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:744
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
CanQualType FloatTy
Definition: ASTContext.h:1234
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1249
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType DependentTy
Definition: ASTContext.h:1250
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
CanQualType NullPtrTy
Definition: ASTContext.h:1249
IdentifierTable & Idents
Definition: ASTContext.h:740
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1223
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:860
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType BoundMemberTy
Definition: ASTContext.h:1250
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1231
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1250
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2333
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2625
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
Definition: ASTContext.h:1222
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1251
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1750
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2418
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2437
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2465
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:2060
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2656
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2629
PtrTy get() const
Definition: Ownership.h:171
bool isInvalid() const
Definition: Ownership.h:167
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: TypeBase.h:3908
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition: Type.cpp:279
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
QualType getElementType() const
Definition: TypeBase.h:3750
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: TypeBase.h:8142
Attr - This represents one attribute.
Definition: Attr.h:44
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4938
Pointer to a block type.
Definition: TypeBase.h:3558
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1494
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1118
const Expr * getSubExpr() const
Definition: ExprCXX.h:1516
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:723
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1549
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2604
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2937
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2369
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2509
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2571
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2620
bool isArrayForm() const
Definition: ExprCXX.h:2646
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2670
Expr * getArgument()
Definition: ExprCXX.h:2661
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
static CXXFunctionalCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, TypeSourceInfo *Written, CastKind Kind, Expr *Op, const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc, SourceLocation RPLoc)
Definition: ExprCXX.cpp:918
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
bool isVirtual() const
Definition: DeclCXX.h:2184
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2255
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2279
bool isConst() const
Definition: DeclCXX.h:2181
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2349
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, const ImplicitAllocationParameters &IAP, bool UsualArrayDeleteWantsSize, ArrayRef< Expr * > PlacementArgs, SourceRange TypeIdParens, std::optional< Expr * > ArraySize, CXXNewInitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange)
Create a c++ new expression.
Definition: ExprCXX.cpp:293
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4303
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:768
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:84
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2739
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition: DeclCXX.cpp:132
base_class_range bases()
Definition: DeclCXX.h:608
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1214
capture_const_range captures() const
Definition: DeclCXX.h:1097
ctor_range ctors() const
Definition: DeclCXX.h:670
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1221
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1402
bool hasDefinition() const
Definition: DeclCXX.h:561
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2121
CXXRecordDecl * getDefinitionOrSelf() const
Definition: DeclCXX.h:555
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1736
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2198
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:180
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition: DeclSpec.cpp:116
SourceLocation getEndLoc() const
Definition: DeclSpec.h:84
SourceRange getRange() const
Definition: DeclSpec.h:79
bool isSet() const
Deprecated.
Definition: DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:183
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:103
Represents a C++ temporary.
Definition: ExprCXX.h:1460
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1473
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1113
Represents the this expression in C++.
Definition: ExprCXX.h:1155
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition: ExprCXX.cpp:1585
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1209
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:848
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool IsListInit)
Definition: ExprCXX.cpp:1488
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1069
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3083
SourceLocation getBeginLoc() const
Definition: Expr.h:3213
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3096
Expr * getCallee()
Definition: Expr.h:3026
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3070
arg_range arguments()
Definition: Expr.h:3131
Decl * getCalleeDecl()
Definition: Expr.h:3056
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: TypeBase.h:3293
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1720
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:390
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Definition: ExprConcepts.h:126
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:214
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:254
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:37
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1382
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1879
bool isRecord() const
Definition: DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1793
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
ValueDecl * getDecl()
Definition: Expr.h:1340
Captures information about "declaration specifiers".
Definition: DeclSpec.h:217
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:530
TST getTypeSpecType() const
Definition: DeclSpec.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:545
static const TST TST_typename_pack_indexing
Definition: DeclSpec.h:283
ParsedType getRepAsType() const
Definition: DeclSpec.h:517
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:593
Expr * getRepAsExpr() const
Definition: DeclSpec.h:525
static const TST TST_decltype
Definition: DeclSpec.h:281
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:552
static const TST TST_decltype_auto
Definition: DeclSpec.h:282
static const TST TST_error
Definition: DeclSpec.h:298
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:562
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:435
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:593
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:156
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:251
bool isInvalidDecl() const
Definition: DeclBase.h:588
SourceLocation getLocation() const
Definition: DeclBase.h:439
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:829
void setImplicit(bool I=true)
Definition: DeclBase.h:594
DeclContext * getDeclContext()
Definition: DeclBase.h:448
bool hasAttr() const
Definition: DeclBase.h:577
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:881
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:427
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:830
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1874
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2271
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2268
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: TypeBase.h:7146
bool isDeduced() const
Definition: TypeBase.h:7168
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1548
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:596
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:950
Represents an enum.
Definition: Decl.h:4004
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4227
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4953
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4222
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1464
bool isLValue() const
Definition: Expr.h:387
bool isRValue() const
Definition: Expr.h:391
This represents one expression.
Definition: Expr.h:112
bool isReadIfDiscardedInCPlusPlus11() const
Determine whether an lvalue-to-rvalue conversion should implicitly be applied to this expression if i...
Definition: Expr.cpp:2548
bool isGLValue() const
Definition: Expr.h:287
void setType(QualType t)
Definition: Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:444
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:4218
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3073
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
bool isPRValue() const
Definition: Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3293
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:833
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:451
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3624
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:223
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:4001
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:412
QualType getType() const
Definition: Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:455
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:434
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
Represents a member of a struct/union/class.
Definition: Decl.h:3157
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:128
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:102
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1051
Represents a function declaration or definition.
Definition: Decl.h:1999
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition: Decl.h:2641
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition: Decl.h:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4146
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2313
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2755
QualType getReturnType() const
Definition: Decl.h:2842
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2376
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.h:2593
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2539
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition: Decl.cpp:3547
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4490
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3767
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3238
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
Declaration of a template function.
Definition: DeclTemplate.h:952
ExtInfo withCallingConv(CallingConv cc) const
Definition: TypeBase.h:4701
ExtInfo withNoReturn(bool noReturn) const
Definition: TypeBase.h:4660
bool getProducesResult() const
Definition: TypeBase.h:4635
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
ExtInfo getExtInfo() const
Definition: TypeBase.h:4834
One of these records is kept for each identifier that is lexed.
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine whether this is a name reserved for the implementation (C99 7.1.3, C++ [lib....
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
StringRef getName() const
Return the actual identifier string.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn't alre...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3789
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:615
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:666
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:670
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5235
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7739
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3881
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8821
bool Failed() const
Determine whether the initialization sequence is invalid.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
Definition: SemaInit.cpp:3870
Describes an entity that is being initialized.
static InitializedEntity InitializeException(SourceLocation ThrowLoc, QualType Type)
Create the initialization entity for an exception object.
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type)
Create the initialization entity for an object allocated via new.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:971
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:469
bool hasGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:719
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:640
bool hasHiddenGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:734
bool hasProtectedGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:729
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1377
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:723
bool hasNext() const
Definition: Lookup.h:708
NamedDecl * next()
Definition: Lookup.h:712
Represents the results of name lookup.
Definition: Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:607
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:751
bool isAmbiguous() const
Definition: Lookup.h:324
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
bool isClassLookup() const
Returns whether these results arose from performing a lookup into a class.
Definition: Lookup.h:432
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
A global _GUID constant.
Definition: DeclCXX.h:4392
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3383
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition: Type.cpp:5502
QualType getPointeeType() const
Definition: TypeBase.h:3687
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:316
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Type
A type, stored as a Type*.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:192
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:128
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:308
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: TypeBase.h:7961
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: TypeBase.h:7973
bool hasEmptyCollections() const
Are the empty collection symbols available?
Definition: ObjCRuntime.h:436
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
PtrTy get() const
Definition: Ownership.h:81
static OpaquePtr make(QualType P)
Definition: Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1157
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2296
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
Represents a parameter to a function.
Definition: Decl.h:1789
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2946
bool isEquivalent(PointerAuthQualifier Other) const
Definition: TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2688
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2704
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: TypeBase.h:8427
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3591
@ DK_nontrivial_c_struct
Definition: TypeBase.h:1538
QualType withConst() const
Definition: TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition: TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: TypeBase.h:1438
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: TypeBase.h:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2944
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: TypeBase.h:1545
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: TypeBase.h:1332
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: TypeBase.h:8508
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition: TypeBase.h:495
GC getObjCGCAttr() const
Definition: TypeBase.h:519
@ OCL_None
There is no lifetime qualification on this type.
Definition: TypeBase.h:350
bool hasCVRQualifiers() const
Definition: TypeBase.h:487
bool hasUnaligned() const
Definition: TypeBase.h:511
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: TypeBase.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition: TypeBase.h:708
void setAddressSpace(LangAS space)
Definition: TypeBase.h:591
unsigned getCVRUQualifiers() const
Definition: TypeBase.h:489
PointerAuthQualifier getPointerAuth() const
Definition: TypeBase.h:603
void setObjCGCAttr(GC type)
Definition: TypeBase.h:520
ObjCLifetime getObjCLifetime() const
Definition: TypeBase.h:545
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: TypeBase.h:441
LangAS getAddressSpace() const
Definition: TypeBase.h:571
void setPointerAuth(PointerAuthQualifier Q)
Definition: TypeBase.h:606
void setObjCLifetime(ObjCLifetime type)
Definition: TypeBase.h:548
Represents a struct/union/class.
Definition: Decl.h:4309
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
Represents the body of a requires-expression.
Definition: DeclCXX.h:2098
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2389
static RequiresExpr * Create(ASTContext &C, SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation RBraceLoc)
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:75
@ ClassScope
The scope of a struct/union/class definition.
Definition: Scope.h:69
@ TryScope
This is the scope of a C++ try statement.
Definition: Scope.h:105
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:51
@ ObjCMethodScope
This scope corresponds to an Objective-C method body.
Definition: Scope.h:99
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:111
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
Sema & SemaRef
Definition: SemaBase.h:40
CUDAFunctionTarget CurrentTarget()
Gets the CUDA target for the current context.
Definition: SemaCUDA.h:152
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition: SemaCUDA.cpp:836
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:318
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:225
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition: SemaPPC.cpp:262
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled=true)
Introduce a new scope where 'this' may be allowed (when enabled), using the given declaration (which ...
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:10258
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6383
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:1113
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2033
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:8189
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:9296
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9284
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9326
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:405
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1642
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
SemaCUDA & CUDA()
Definition: Sema.h:1438
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20730
ConditionKind
Definition: Sema.h:7788
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6030
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:1216
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10350
AccessResult
Definition: Sema.h:1650
@ AR_inaccessible
Definition: Sema.h:1652
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:3469
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:18752
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10312
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:2042
concepts::Requirement * ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc)
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1647
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry)
Definition: SemaStmt.cpp:4461
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1108
ASTContext & Context
Definition: Sema.h:1276
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition: Sema.cpp:680
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:8014
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition: Sema.h:1483
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1555
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19998
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:748
ASTContext & getASTContext() const
Definition: Sema.h:918
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef< QualType > Params)
DeclareGlobalAllocationFunction - Declares a single implicit global allocation function if it doesn't...
bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE)
If the given requirees-expression contains an unexpanded reference to one of its own parameter packs,...
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:19252
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:756
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6276
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose=true)
Checks access to an overloaded operator new or delete.
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
void ActOnFinishRequiresExpr()
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, std::optional< Expr * > ArraySize, SourceRange DirectInitRange, Expr *Initializer)
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:1184
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2298
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:8307
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
Definition: SemaStmt.cpp:3392
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix)
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:405
FPOptions & getCurFPFeatures()
Definition: Sema.h:913
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_IfExists
Microsoft __if_exists.
Definition: Sema.h:14271
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:14274
const LangOptions & getLangOpts() const
Definition: Sema.h:911
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14709
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7382
SemaOpenACC & OpenACC()
Definition: Sema.h:1488
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:1275
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization)
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9286
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition: Sema.h:1274
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2557
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
Check the use of the given variable as a C++ condition in an if, while, do-while, or switch statement...
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7699
SemaHLSL & HLSL()
Definition: Sema.h:1448
CXXRecordDecl * getStdBadAlloc() const
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17784
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:75
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20409
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R)
Checks that a type is suitable as the allocated type in a new-expression.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6915
ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation ClosingBraceLoc)
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:849
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a Microsoft __uuidof expression with a type operand.
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10580
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6912
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9944
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:633
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:8130
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9807
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9710
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:2517
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7759
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5948
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:8045
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:8122
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1627
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
Parsed a C++ 'new' expression (C++ 5.3.4).
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen)
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
Definition: Sema.h:8318
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4154
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21316
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17644
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13791
SourceManager & getSourceManager() const
Definition: Sema.h:916
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose=true)
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:8389
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
Definition: SemaStmt.cpp:3527
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
CanThrowResult canThrow(const Stmt *E)
bool isThisOutsideMemberFunctionBody(QualType BaseType)
Determine whether the given type is the type of *this that is used outside of the body of a member fu...
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
concepts::ExprRequirement * BuildExprRequirement(Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:218
concepts::Requirement * ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8440
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
Definition: SemaExprCXX.cpp:57
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:15279
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition: Sema.h:8314
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17422
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:270
RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef< ParmVarDecl * > LocalParameters, Scope *BodyScope)
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6919
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:123
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16943
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9813
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5693
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20602
SemaPPC & PPC()
Definition: Sema.h:1503
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9241
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21246
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition: Sema.h:8325
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18228
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:8262
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1366
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
DiagnosticsEngine & Diags
Definition: Sema.h:1278
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
NamespaceDecl * getStdNamespace() const
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope)
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:509
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9874
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:1785
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
Definition: SemaType.cpp:9827
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:17081
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18401
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:2096
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21528
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:71
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:8311
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2773
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
static ConditionResult ConditionError()
Definition: Sema.h:7775
IdentifierResolver IdResolver
Definition: Sema.h:3461
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, ImplicitDeallocationParameters, DeclarationName Name)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
ExprResult ActOnCXXThis(SourceLocation Loc)
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5409
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8599
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:386
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:385
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4531
Stmt - This represents one statement.
Definition: Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
StringRef getString() const
Definition: Expr.h:1869
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with '::operator new(size_t)' is g...
Definition: TargetInfo.h:761
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target.
Definition: TargetInfo.h:1719
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:527
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Represents a template argument.
Definition: TemplateBase.h:61
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:146
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:223
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:240
Represents a declaration of a type.
Definition: Decl.h:3510
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:154
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:193
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2572
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: TypeBase.h:8912
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
bool isVoidPointerType() const
Definition: Type.cpp:712
bool isArrayType() const
Definition: TypeBase.h:8679
CXXRecordDecl * castAsCXXRecordDecl() const
Definition: Type.h:36
bool isArithmeticType() const
Definition: Type.cpp:2341
bool isPointerType() const
Definition: TypeBase.h:8580
bool isArrayParameterType() const
Definition: TypeBase.h:8695
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isScalarType() const
Definition: TypeBase.h:9038
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2612
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isExtVectorType() const
Definition: TypeBase.h:8723
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.h:65
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2651
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: TypeBase.h:8703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
bool isHalfType() const
Definition: TypeBase.h:8940
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2060
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2562
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isMatrixType() const
Definition: TypeBase.h:8737
EnumDecl * castAsEnumDecl() const
Definition: Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: TypeBase.h:2818
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5355
bool isObjectType() const
Determine whether this type is an object type.
Definition: TypeBase.h:2528
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool isPointerOrReferenceType() const
Definition: TypeBase.h:8584
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:5299
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
bool isVectorType() const
Definition: TypeBase.h:8719
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
bool isFloatingType() const
Definition: Type.cpp:2308
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:5305
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
bool isObjCRetainableType() const
Definition: Type.cpp:5336
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:998
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1056
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition: DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1050
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5449
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3566
Represents a variable declaration or definition.
Definition: Decl.h:925
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2190
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2528
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1357
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
TemplateParameterList * getTypeConstraintTemplateParameterList() const
Definition: ExprConcepts.h:350
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:282
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:432
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:170
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:227
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:758
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1096
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:950
bool hasPotentialThisCapture() const
Definition: ScopeInfo.h:1002
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:251
bool hasPotentialCaptures() const
Definition: ScopeInfo.h:1068
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition: ScopeInfo.h:1051
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
void visitPotentialCaptures(llvm::function_ref< void(ValueDecl *, Expr *)> Callback) const
Definition: ScopeInfo.cpp:235
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition: gpuintrin.h:32
Defines the clang::TargetInfo interface.
Definition: SPIR.cpp:47
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1260
ComparisonCategoryResult Compare(const T &X, const T &Y)
Helper to compare two comparable types.
Definition: Primitives.h:25
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
bool isLambdaCallWithImplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:50
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ Match
This is not an overload because the signature exactly matches an existing declaration.
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
VariadicCallType
Definition: Sema.h:511
CanThrowResult
Possible results from evaluation of a noexcept expression.
AllocationFunctionScope
The scope in which to find allocation functions.
Definition: Sema.h:777
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
@ Global
Only look for allocation functions in the global scope.
@ Class
Only look for allocation functions in the scope of the allocated class.
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:102
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
@ NotFound
No entity found met the criteria.
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
@ Found
Name lookup found a single declaration that met the criteria.
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
AlignedAllocationMode alignedAllocationModeFromBool(bool IsAligned)
Definition: ExprCXX.h:2271
@ Conditional
A conditional (?:) operator.
@ RQ_None
No ref-qualifier was provided.
Definition: TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: TypeBase.h:1788
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
UnsignedOrNone getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:180
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ Bind
'bind' clause, allowed on routine constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ AS_public
Definition: Specifiers.h:124
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:45
@ SC_None
Definition: Specifiers.h:250
bool isAlignedAllocation(AlignedAllocationMode Mode)
Definition: ExprCXX.h:2267
@ OMF_performSelector
AlignedAllocationMode
Definition: ExprCXX.h:2265
StmtResult StmtError()
Definition: Ownership.h:266
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ Result
The result type of a method or function.
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition: Overload.h:205
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:208
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition: Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition: Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition: Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition: Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition: Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition: Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
@ Template
We are parsing a template declaration.
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:687
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
@ Compatible
Compatible - the types are compatible according to the standard.
@ Class
The "class" keyword.
ExprResult ExprError()
Definition: Ownership.h:265
bool isTypeAwareAllocation(TypeAwareAllocationMode Mode)
Definition: ExprCXX.h:2255
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
SizedDeallocationMode sizedDeallocationModeFromBool(bool IsSized)
Definition: ExprCXX.h:2281
AssignmentAction
Definition: Sema.h:213
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:95
SizedDeallocationMode
Definition: ExprCXX.h:2275
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:230
const FunctionProtoType * T
bool isSizedDeallocation(SizedDeallocationMode Mode)
Definition: ExprCXX.h:2277
TypeAwareAllocationMode
Definition: ExprCXX.h:2253
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition: Sema.h:789
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
@ Exists
The symbol exists.
@ Error
An error occurred.
@ DoesNotExist
The symbol does not exist.
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1288
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:366
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ CC_C
Definition: Specifiers.h:279
@ Generic
not a target-specific vector type
@ ArrayBound
Array bound in array declarator or new-expression.
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ReservedIdentifierStatus
@ Other
Other implicit parameter.
CXXNewInitializationStyle
Definition: ExprCXX.h:2242
@ Parens
New-expression has a C++98 paren-delimited initializer.
@ None
New-expression has no initializer as written.
@ Braces
New-expression has a C++11 list-initializer.
@ EST_DynamicNone
throw()
@ EST_BasicNoexcept
noexcept
@ EST_Dynamic
throw(T1, T2)
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:435
@ CStyleCast
A C-style cast.
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ FunctionalCast
A functional-style cast.
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:60
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:259
#define false
Definition: stdbool.h:26
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:91
static ASTConstraintSatisfaction * Rebuild(const ASTContext &C, const ASTConstraintSatisfaction &Satisfaction)
Definition: ASTConcept.cpp:69
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition: DeclSpec.h:1282
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1291
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1221
ArrayTypeInfo Arr
Definition: DeclSpec.h:1611
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1229
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: TypeBase.h:5341
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: TypeBase.h:5344
Extra information about a function prototype.
Definition: TypeBase.h:5367
AlignedAllocationMode PassAlignment
Definition: ExprCXX.h:2309
TypeAwareAllocationMode PassTypeIdentity
Definition: ExprCXX.h:2308
unsigned getNumImplicitArgs() const
Definition: ExprCXX.h:2298
TypeAwareAllocationMode PassTypeIdentity
Definition: ExprCXX.h:2340
SizedDeallocationMode PassSize
Definition: ExprCXX.h:2342
AlignedAllocationMode PassAlignment
Definition: ExprCXX.h:2341
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4367
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:926
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10358
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:482
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:504
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:495
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:499
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:490
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:509