clang 17.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/DeclObjC.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
33#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/Lookup.h"
38#include "clang/Sema/Scope.h"
42#include "clang/Sema/Template.h"
44#include "llvm/ADT/APInt.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/TypeSize.h"
48#include <optional>
49using namespace clang;
50using namespace sema;
51
52/// Handle the result of the special case name lookup for inheriting
53/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
54/// constructor names in member using declarations, even if 'X' is not the
55/// name of the corresponding type.
57 SourceLocation NameLoc,
58 IdentifierInfo &Name) {
60
61 // Convert the nested-name-specifier into a type.
63 switch (NNS->getKind()) {
66 Type = QualType(NNS->getAsType(), 0);
67 break;
68
70 // Strip off the last layer of the nested-name-specifier and build a
71 // typename type for it.
72 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
74 NNS->getAsIdentifier());
75 break;
76
81 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
82 }
83
84 // This reference to the type is located entirely at the location of the
85 // final identifier in the qualified-id.
88}
89
91 SourceLocation NameLoc,
92 Scope *S, CXXScopeSpec &SS,
93 bool EnteringContext) {
94 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
95 assert(CurClass && &II == CurClass->getIdentifier() &&
96 "not a constructor name");
97
98 // When naming a constructor as a member of a dependent context (eg, in a
99 // friend declaration or an inherited constructor declaration), form an
100 // unresolved "typename" type.
101 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
103 return ParsedType::make(T);
104 }
105
106 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
107 return ParsedType();
108
109 // Find the injected-class-name declaration. Note that we make no attempt to
110 // diagnose cases where the injected-class-name is shadowed: the only
111 // declaration that can validly shadow the injected-class-name is a
112 // non-static data member, and if the class contains both a non-static data
113 // member and a constructor then it is ill-formed (we check that in
114 // CheckCompletedCXXClass).
115 CXXRecordDecl *InjectedClassName = nullptr;
116 for (NamedDecl *ND : CurClass->lookup(&II)) {
117 auto *RD = dyn_cast<CXXRecordDecl>(ND);
118 if (RD && RD->isInjectedClassName()) {
119 InjectedClassName = RD;
120 break;
121 }
122 }
123 if (!InjectedClassName) {
124 if (!CurClass->isInvalidDecl()) {
125 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
126 // properly. Work around it here for now.
128 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
129 }
130 return ParsedType();
131 }
132
133 QualType T = Context.getTypeDeclType(InjectedClassName);
134 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
135 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
136
137 return ParsedType::make(T);
138}
139
141 IdentifierInfo &II,
142 SourceLocation NameLoc,
143 Scope *S, CXXScopeSpec &SS,
144 ParsedType ObjectTypePtr,
145 bool EnteringContext) {
146 // Determine where to perform name lookup.
147
148 // FIXME: This area of the standard is very messy, and the current
149 // wording is rather unclear about which scopes we search for the
150 // destructor name; see core issues 399 and 555. Issue 399 in
151 // particular shows where the current description of destructor name
152 // lookup is completely out of line with existing practice, e.g.,
153 // this appears to be ill-formed:
154 //
155 // namespace N {
156 // template <typename T> struct S {
157 // ~S();
158 // };
159 // }
160 //
161 // void f(N::S<int>* s) {
162 // s->N::S<int>::~S();
163 // }
164 //
165 // See also PR6358 and PR6359.
166 //
167 // For now, we accept all the cases in which the name given could plausibly
168 // be interpreted as a correct destructor name, issuing off-by-default
169 // extension diagnostics on the cases that don't strictly conform to the
170 // C++20 rules. This basically means we always consider looking in the
171 // nested-name-specifier prefix, the complete nested-name-specifier, and
172 // the scope, and accept if we find the expected type in any of the three
173 // places.
174
175 if (SS.isInvalid())
176 return nullptr;
177
178 // Whether we've failed with a diagnostic already.
179 bool Failed = false;
180
183
184 // If we have an object type, it's because we are in a
185 // pseudo-destructor-expression or a member access expression, and
186 // we know what type we're looking for.
187 QualType SearchType =
188 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
189
190 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
191 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
192 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
193 if (!Type)
194 return false;
195
196 if (SearchType.isNull() || SearchType->isDependentType())
197 return true;
198
200 return Context.hasSameUnqualifiedType(T, SearchType);
201 };
202
203 unsigned NumAcceptableResults = 0;
204 for (NamedDecl *D : Found) {
205 if (IsAcceptableResult(D))
206 ++NumAcceptableResults;
207
208 // Don't list a class twice in the lookup failure diagnostic if it's
209 // found by both its injected-class-name and by the name in the enclosing
210 // scope.
211 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
212 if (RD->isInjectedClassName())
213 D = cast<NamedDecl>(RD->getParent());
214
215 if (FoundDeclSet.insert(D).second)
216 FoundDecls.push_back(D);
217 }
218
219 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
220 // results, and all non-matching results if we have a search type. It's not
221 // clear what the right behavior is if destructor lookup hits an ambiguity,
222 // but other compilers do generally accept at least some kinds of
223 // ambiguity.
224 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
225 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
226 LookupResult::Filter F = Found.makeFilter();
227 while (F.hasNext()) {
228 NamedDecl *D = F.next();
229 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
230 Diag(D->getLocation(), diag::note_destructor_type_here)
232 else
233 Diag(D->getLocation(), diag::note_destructor_nontype_here);
234
235 if (!IsAcceptableResult(D))
236 F.erase();
237 }
238 F.done();
239 }
240
241 if (Found.isAmbiguous())
242 Failed = true;
243
244 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
245 if (IsAcceptableResult(Type)) {
247 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
250 }
251 }
252
253 return nullptr;
254 };
255
256 bool IsDependent = false;
257
258 auto LookupInObjectType = [&]() -> ParsedType {
259 if (Failed || SearchType.isNull())
260 return nullptr;
261
262 IsDependent |= SearchType->isDependentType();
263
264 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
265 DeclContext *LookupCtx = computeDeclContext(SearchType);
266 if (!LookupCtx)
267 return nullptr;
268 LookupQualifiedName(Found, LookupCtx);
269 return CheckLookupResult(Found);
270 };
271
272 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
273 if (Failed)
274 return nullptr;
275
276 IsDependent |= isDependentScopeSpecifier(LookupSS);
277 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
278 if (!LookupCtx)
279 return nullptr;
280
281 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
282 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
283 Failed = true;
284 return nullptr;
285 }
286 LookupQualifiedName(Found, LookupCtx);
287 return CheckLookupResult(Found);
288 };
289
290 auto LookupInScope = [&]() -> ParsedType {
291 if (Failed || !S)
292 return nullptr;
293
294 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
295 LookupName(Found, S);
296 return CheckLookupResult(Found);
297 };
298
299 // C++2a [basic.lookup.qual]p6:
300 // In a qualified-id of the form
301 //
302 // nested-name-specifier[opt] type-name :: ~ type-name
303 //
304 // the second type-name is looked up in the same scope as the first.
305 //
306 // We interpret this as meaning that if you do a dual-scope lookup for the
307 // first name, you also do a dual-scope lookup for the second name, per
308 // C++ [basic.lookup.classref]p4:
309 //
310 // If the id-expression in a class member access is a qualified-id of the
311 // form
312 //
313 // class-name-or-namespace-name :: ...
314 //
315 // the class-name-or-namespace-name following the . or -> is first looked
316 // up in the class of the object expression and the name, if found, is used.
317 // Otherwise, it is looked up in the context of the entire
318 // postfix-expression.
319 //
320 // This looks in the same scopes as for an unqualified destructor name:
321 //
322 // C++ [basic.lookup.classref]p3:
323 // If the unqualified-id is ~ type-name, the type-name is looked up
324 // in the context of the entire postfix-expression. If the type T
325 // of the object expression is of a class type C, the type-name is
326 // also looked up in the scope of class C. At least one of the
327 // lookups shall find a name that refers to cv T.
328 //
329 // FIXME: The intent is unclear here. Should type-name::~type-name look in
330 // the scope anyway if it finds a non-matching name declared in the class?
331 // If both lookups succeed and find a dependent result, which result should
332 // we retain? (Same question for p->~type-name().)
333
334 if (NestedNameSpecifier *Prefix =
335 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
336 // This is
337 //
338 // nested-name-specifier type-name :: ~ type-name
339 //
340 // Look for the second type-name in the nested-name-specifier.
341 CXXScopeSpec PrefixSS;
342 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
343 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
344 return T;
345 } else {
346 // This is one of
347 //
348 // type-name :: ~ type-name
349 // ~ type-name
350 //
351 // Look in the scope and (if any) the object type.
352 if (ParsedType T = LookupInScope())
353 return T;
354 if (ParsedType T = LookupInObjectType())
355 return T;
356 }
357
358 if (Failed)
359 return nullptr;
360
361 if (IsDependent) {
362 // We didn't find our type, but that's OK: it's dependent anyway.
363
364 // FIXME: What if we have no nested-name-specifier?
367 II, NameLoc);
368 return ParsedType::make(T);
369 }
370
371 // The remaining cases are all non-standard extensions imitating the behavior
372 // of various other compilers.
373 unsigned NumNonExtensionDecls = FoundDecls.size();
374
375 if (SS.isSet()) {
376 // For compatibility with older broken C++ rules and existing code,
377 //
378 // nested-name-specifier :: ~ type-name
379 //
380 // also looks for type-name within the nested-name-specifier.
381 if (ParsedType T = LookupInNestedNameSpec(SS)) {
382 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
383 << SS.getRange()
385 ("::" + II.getName()).str());
386 return T;
387 }
388
389 // For compatibility with other compilers and older versions of Clang,
390 //
391 // nested-name-specifier type-name :: ~ type-name
392 //
393 // also looks for type-name in the scope. Unfortunately, we can't
394 // reasonably apply this fallback for dependent nested-name-specifiers.
395 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
396 if (ParsedType T = LookupInScope()) {
397 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
399 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
400 << GetTypeFromParser(T);
401 return T;
402 }
403 }
404 }
405
406 // We didn't find anything matching; tell the user what we did find (if
407 // anything).
408
409 // Don't tell the user about declarations we shouldn't have found.
410 FoundDecls.resize(NumNonExtensionDecls);
411
412 // List types before non-types.
413 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
414 [](NamedDecl *A, NamedDecl *B) {
415 return isa<TypeDecl>(A->getUnderlyingDecl()) >
416 isa<TypeDecl>(B->getUnderlyingDecl());
417 });
418
419 // Suggest a fixit to properly name the destroyed type.
420 auto MakeFixItHint = [&]{
421 const CXXRecordDecl *Destroyed = nullptr;
422 // FIXME: If we have a scope specifier, suggest its last component?
423 if (!SearchType.isNull())
424 Destroyed = SearchType->getAsCXXRecordDecl();
425 else if (S)
426 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
427 if (Destroyed)
429 Destroyed->getNameAsString());
430 return FixItHint();
431 };
432
433 if (FoundDecls.empty()) {
434 // FIXME: Attempt typo-correction?
435 Diag(NameLoc, diag::err_undeclared_destructor_name)
436 << &II << MakeFixItHint();
437 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
438 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
439 assert(!SearchType.isNull() &&
440 "should only reject a type result if we have a search type");
442 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
443 << T << SearchType << MakeFixItHint();
444 } else {
445 Diag(NameLoc, diag::err_destructor_expr_nontype)
446 << &II << MakeFixItHint();
447 }
448 } else {
449 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
450 : diag::err_destructor_expr_mismatch)
451 << &II << SearchType << MakeFixItHint();
452 }
453
454 for (NamedDecl *FoundD : FoundDecls) {
455 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
456 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
458 else
459 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
460 << FoundD;
461 }
462
463 return nullptr;
464}
465
467 ParsedType ObjectType) {
469 return nullptr;
470
472 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
473 return nullptr;
474 }
475
477 "unexpected type in getDestructorType");
479
480 // If we know the type of the object, check that the correct destructor
481 // type was named now; we can give better diagnostics this way.
482 QualType SearchType = GetTypeFromParser(ObjectType);
483 if (!SearchType.isNull() && !SearchType->isDependentType() &&
484 !Context.hasSameUnqualifiedType(T, SearchType)) {
485 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
486 << T << SearchType;
487 return nullptr;
488 }
489
490 return ParsedType::make(T);
491}
492
494 const UnqualifiedId &Name, bool IsUDSuffix) {
495 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
496 if (!IsUDSuffix) {
497 // [over.literal] p8
498 //
499 // double operator""_Bq(long double); // OK: not a reserved identifier
500 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
501 IdentifierInfo *II = Name.Identifier;
503 SourceLocation Loc = Name.getEndLoc();
504 if (isReservedInAllContexts(Status) &&
506 Diag(Loc, diag::warn_reserved_extern_symbol)
507 << II << static_cast<int>(Status)
509 Name.getSourceRange(),
510 (StringRef("operator\"\"") + II->getName()).str());
511 }
512 }
513
514 if (!SS.isValid())
515 return false;
516
517 switch (SS.getScopeRep()->getKind()) {
521 // Per C++11 [over.literal]p2, literal operators can only be declared at
522 // namespace scope. Therefore, this unqualified-id cannot name anything.
523 // Reject it early, because we have no AST representation for this in the
524 // case where the scope is dependent.
525 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
526 << SS.getScopeRep();
527 return true;
528
533 return false;
534 }
535
536 llvm_unreachable("unknown nested name specifier kind");
537}
538
539/// Build a C++ typeid expression with a type operand.
541 SourceLocation TypeidLoc,
542 TypeSourceInfo *Operand,
543 SourceLocation RParenLoc) {
544 // C++ [expr.typeid]p4:
545 // The top-level cv-qualifiers of the lvalue expression or the type-id
546 // that is the operand of typeid are always ignored.
547 // If the type of the type-id is a class type or a reference to a class
548 // type, the class shall be completely-defined.
549 Qualifiers Quals;
550 QualType T
551 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
552 Quals);
553 if (T->getAs<RecordType>() &&
554 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
555 return ExprError();
556
557 if (T->isVariablyModifiedType())
558 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
559
560 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
561 return ExprError();
562
563 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
564 SourceRange(TypeidLoc, RParenLoc));
565}
566
567/// Build a C++ typeid expression with an expression operand.
569 SourceLocation TypeidLoc,
570 Expr *E,
571 SourceLocation RParenLoc) {
572 bool WasEvaluated = false;
573 if (E && !E->isTypeDependent()) {
574 if (E->hasPlaceholderType()) {
576 if (result.isInvalid()) return ExprError();
577 E = result.get();
578 }
579
580 QualType T = E->getType();
581 if (const RecordType *RecordT = T->getAs<RecordType>()) {
582 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
583 // C++ [expr.typeid]p3:
584 // [...] If the type of the expression is a class type, the class
585 // shall be completely-defined.
586 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
587 return ExprError();
588
589 // C++ [expr.typeid]p3:
590 // When typeid is applied to an expression other than an glvalue of a
591 // polymorphic class type [...] [the] expression is an unevaluated
592 // operand. [...]
593 if (RecordD->isPolymorphic() && E->isGLValue()) {
594 if (isUnevaluatedContext()) {
595 // The operand was processed in unevaluated context, switch the
596 // context and recheck the subexpression.
598 if (Result.isInvalid())
599 return ExprError();
600 E = Result.get();
601 }
602
603 // We require a vtable to query the type at run time.
604 MarkVTableUsed(TypeidLoc, RecordD);
605 WasEvaluated = true;
606 }
607 }
608
610 if (Result.isInvalid())
611 return ExprError();
612 E = Result.get();
613
614 // C++ [expr.typeid]p4:
615 // [...] If the type of the type-id is a reference to a possibly
616 // cv-qualified type, the result of the typeid expression refers to a
617 // std::type_info object representing the cv-unqualified referenced
618 // type.
619 Qualifiers Quals;
620 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
621 if (!Context.hasSameType(T, UnqualT)) {
622 T = UnqualT;
623 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
624 }
625 }
626
628 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
629 << E->getType());
630 else if (!inTemplateInstantiation() &&
631 E->HasSideEffects(Context, WasEvaluated)) {
632 // The expression operand for typeid is in an unevaluated expression
633 // context, so side effects could result in unintended consequences.
634 Diag(E->getExprLoc(), WasEvaluated
635 ? diag::warn_side_effects_typeid
636 : diag::warn_side_effects_unevaluated_context);
637 }
638
639 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
640 SourceRange(TypeidLoc, RParenLoc));
641}
642
643/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
646 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
647 // typeid is not supported in OpenCL.
648 if (getLangOpts().OpenCLCPlusPlus) {
649 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
650 << "typeid");
651 }
652
653 // Find the std::type_info type.
654 if (!getStdNamespace())
655 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
656
657 if (!CXXTypeInfoDecl) {
658 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
659 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
662 // Microsoft's typeinfo doesn't have type_info in std but in the global
663 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
664 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
667 }
668 if (!CXXTypeInfoDecl)
669 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
670 }
671
672 if (!getLangOpts().RTTI) {
673 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
674 }
675
677
678 if (isType) {
679 // The operand is a type; handle it as such.
680 TypeSourceInfo *TInfo = nullptr;
682 &TInfo);
683 if (T.isNull())
684 return ExprError();
685
686 if (!TInfo)
687 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
688
689 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
690 }
691
692 // The operand is an expression.
694 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
695
696 if (!getLangOpts().RTTIData && !Result.isInvalid())
697 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
698 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
699 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
700 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
702 return Result;
703}
704
705/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
706/// a single GUID.
707static void
710 // Optionally remove one level of pointer, reference or array indirection.
711 const Type *Ty = QT.getTypePtr();
712 if (QT->isPointerType() || QT->isReferenceType())
713 Ty = QT->getPointeeType().getTypePtr();
714 else if (QT->isArrayType())
715 Ty = Ty->getBaseElementTypeUnsafe();
716
717 const auto *TD = Ty->getAsTagDecl();
718 if (!TD)
719 return;
720
721 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
722 UuidAttrs.insert(Uuid);
723 return;
724 }
725
726 // __uuidof can grab UUIDs from template arguments.
727 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
728 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
729 for (const TemplateArgument &TA : TAL.asArray()) {
730 const UuidAttr *UuidForTA = nullptr;
731 if (TA.getKind() == TemplateArgument::Type)
732 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
733 else if (TA.getKind() == TemplateArgument::Declaration)
734 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
735
736 if (UuidForTA)
737 UuidAttrs.insert(UuidForTA);
738 }
739 }
740}
741
742/// Build a Microsoft __uuidof expression with a type operand.
744 SourceLocation TypeidLoc,
745 TypeSourceInfo *Operand,
746 SourceLocation RParenLoc) {
747 MSGuidDecl *Guid = nullptr;
748 if (!Operand->getType()->isDependentType()) {
750 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
751 if (UuidAttrs.empty())
752 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
753 if (UuidAttrs.size() > 1)
754 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
755 Guid = UuidAttrs.back()->getGuidDecl();
756 }
757
758 return new (Context)
759 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
760}
761
762/// Build a Microsoft __uuidof expression with an expression operand.
764 Expr *E, SourceLocation RParenLoc) {
765 MSGuidDecl *Guid = nullptr;
766 if (!E->getType()->isDependentType()) {
768 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
770 } else {
772 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
773 if (UuidAttrs.empty())
774 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
775 if (UuidAttrs.size() > 1)
776 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
777 Guid = UuidAttrs.back()->getGuidDecl();
778 }
779 }
780
781 return new (Context)
782 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
783}
784
785/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
788 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
789 QualType GuidType = Context.getMSGuidType();
790 GuidType.addConst();
791
792 if (isType) {
793 // The operand is a type; handle it as such.
794 TypeSourceInfo *TInfo = nullptr;
796 &TInfo);
797 if (T.isNull())
798 return ExprError();
799
800 if (!TInfo)
801 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
802
803 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
804 }
805
806 // The operand is an expression.
807 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
808}
809
810/// ActOnCXXBoolLiteral - Parse {true,false} literals.
813 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
814 "Unknown C++ Boolean value!");
815 return new (Context)
816 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
817}
818
819/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
823}
824
825/// ActOnCXXThrow - Parse throw expressions.
828 bool IsThrownVarInScope = false;
829 if (Ex) {
830 // C++0x [class.copymove]p31:
831 // When certain criteria are met, an implementation is allowed to omit the
832 // copy/move construction of a class object [...]
833 //
834 // - in a throw-expression, when the operand is the name of a
835 // non-volatile automatic object (other than a function or catch-
836 // clause parameter) whose scope does not extend beyond the end of the
837 // innermost enclosing try-block (if there is one), the copy/move
838 // operation from the operand to the exception object (15.1) can be
839 // omitted by constructing the automatic object directly into the
840 // exception object
841 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
842 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
843 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
844 for( ; S; S = S->getParent()) {
845 if (S->isDeclScope(Var)) {
846 IsThrownVarInScope = true;
847 break;
848 }
849
850 // FIXME: Many of the scope checks here seem incorrect.
851 if (S->getFlags() &
854 break;
855 }
856 }
857 }
858 }
859
860 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
861}
862
864 bool IsThrownVarInScope) {
865 // Don't report an error if 'throw' is used in system headers.
866 if (!getLangOpts().CXXExceptions &&
867 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
868 // Delay error emission for the OpenMP device code.
869 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
870 }
871
872 // Exceptions aren't allowed in CUDA device code.
873 if (getLangOpts().CUDA)
874 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
875 << "throw" << CurrentCUDATarget();
876
877 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
878 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
879
880 if (Ex && !Ex->isTypeDependent()) {
881 // Initialize the exception result. This implicitly weeds out
882 // abstract types or types with inaccessible copy constructors.
883
884 // C++0x [class.copymove]p31:
885 // When certain criteria are met, an implementation is allowed to omit the
886 // copy/move construction of a class object [...]
887 //
888 // - in a throw-expression, when the operand is the name of a
889 // non-volatile automatic object (other than a function or
890 // catch-clause
891 // parameter) whose scope does not extend beyond the end of the
892 // innermost enclosing try-block (if there is one), the copy/move
893 // operation from the operand to the exception object (15.1) can be
894 // omitted by constructing the automatic object directly into the
895 // exception object
896 NamedReturnInfo NRInfo =
897 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
898
899 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
900 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
901 return ExprError();
902
903 InitializedEntity Entity =
904 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
905 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
906 if (Res.isInvalid())
907 return ExprError();
908 Ex = Res.get();
909 }
910
911 // PPC MMA non-pointer types are not allowed as throw expr types.
912 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
913 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
914
915 return new (Context)
916 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
917}
918
919static void
921 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
922 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
923 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
924 bool ParentIsPublic) {
925 for (const CXXBaseSpecifier &BS : RD->bases()) {
926 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
927 bool NewSubobject;
928 // Virtual bases constitute the same subobject. Non-virtual bases are
929 // always distinct subobjects.
930 if (BS.isVirtual())
931 NewSubobject = VBases.insert(BaseDecl).second;
932 else
933 NewSubobject = true;
934
935 if (NewSubobject)
936 ++SubobjectsSeen[BaseDecl];
937
938 // Only add subobjects which have public access throughout the entire chain.
939 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
940 if (PublicPath)
941 PublicSubobjectsSeen.insert(BaseDecl);
942
943 // Recurse on to each base subobject.
944 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
945 PublicPath);
946 }
947}
948
951 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
952 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
953 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
954 SubobjectsSeen[RD] = 1;
955 PublicSubobjectsSeen.insert(RD);
956 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
957 /*ParentIsPublic=*/true);
958
959 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
960 // Skip ambiguous objects.
961 if (SubobjectsSeen[PublicSubobject] > 1)
962 continue;
963
964 Objects.push_back(PublicSubobject);
965 }
966}
967
968/// CheckCXXThrowOperand - Validate the operand of a throw.
970 QualType ExceptionObjectTy, Expr *E) {
971 // If the type of the exception would be an incomplete type or a pointer
972 // to an incomplete type other than (cv) void the program is ill-formed.
973 QualType Ty = ExceptionObjectTy;
974 bool isPointer = false;
975 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
976 Ty = Ptr->getPointeeType();
977 isPointer = true;
978 }
979 if (!isPointer || !Ty->isVoidType()) {
980 if (RequireCompleteType(ThrowLoc, Ty,
981 isPointer ? diag::err_throw_incomplete_ptr
982 : diag::err_throw_incomplete,
983 E->getSourceRange()))
984 return true;
985
986 if (!isPointer && Ty->isSizelessType()) {
987 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
988 return true;
989 }
990
991 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
992 diag::err_throw_abstract_type, E))
993 return true;
994 }
995
996 // If the exception has class type, we need additional handling.
998 if (!RD)
999 return false;
1000
1001 // If we are throwing a polymorphic class type or pointer thereof,
1002 // exception handling will make use of the vtable.
1003 MarkVTableUsed(ThrowLoc, RD);
1004
1005 // If a pointer is thrown, the referenced object will not be destroyed.
1006 if (isPointer)
1007 return false;
1008
1009 // If the class has a destructor, we must be able to call it.
1010 if (!RD->hasIrrelevantDestructor()) {
1011 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1012 MarkFunctionReferenced(E->getExprLoc(), Destructor);
1013 CheckDestructorAccess(E->getExprLoc(), Destructor,
1014 PDiag(diag::err_access_dtor_exception) << Ty);
1015 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1016 return true;
1017 }
1018 }
1019
1020 // The MSVC ABI creates a list of all types which can catch the exception
1021 // object. This list also references the appropriate copy constructor to call
1022 // if the object is caught by value and has a non-trivial copy constructor.
1024 // We are only interested in the public, unambiguous bases contained within
1025 // the exception object. Bases which are ambiguous or otherwise
1026 // inaccessible are not catchable types.
1027 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1028 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1029
1030 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1031 // Attempt to lookup the copy constructor. Various pieces of machinery
1032 // will spring into action, like template instantiation, which means this
1033 // cannot be a simple walk of the class's decls. Instead, we must perform
1034 // lookup and overload resolution.
1035 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1036 if (!CD || CD->isDeleted())
1037 continue;
1038
1039 // Mark the constructor referenced as it is used by this throw expression.
1041
1042 // Skip this copy constructor if it is trivial, we don't need to record it
1043 // in the catchable type data.
1044 if (CD->isTrivial())
1045 continue;
1046
1047 // The copy constructor is non-trivial, create a mapping from this class
1048 // type to this constructor.
1049 // N.B. The selection of copy constructor is not sensitive to this
1050 // particular throw-site. Lookup will be performed at the catch-site to
1051 // ensure that the copy constructor is, in fact, accessible (via
1052 // friendship or any other means).
1054
1055 // We don't keep the instantiated default argument expressions around so
1056 // we must rebuild them here.
1057 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1058 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1059 return true;
1060 }
1061 }
1062 }
1063
1064 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1065 // the runtime with no ability for the compiler to request additional
1066 // alignment. Warn if the exception type requires alignment beyond the minimum
1067 // guaranteed by the target C++ runtime.
1069 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1070 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1071 if (ExnObjAlign < TypeAlign) {
1072 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1073 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1074 << Ty << (unsigned)TypeAlign.getQuantity()
1075 << (unsigned)ExnObjAlign.getQuantity();
1076 }
1077 }
1078
1079 return false;
1080}
1081
1083 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1084 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1085
1086 QualType ClassType = ThisTy->getPointeeType();
1087 LambdaScopeInfo *CurLSI = nullptr;
1088 DeclContext *CurDC = CurSemaContext;
1089
1090 // Iterate through the stack of lambdas starting from the innermost lambda to
1091 // the outermost lambda, checking if '*this' is ever captured by copy - since
1092 // that could change the cv-qualifiers of the '*this' object.
1093 // The object referred to by '*this' starts out with the cv-qualifiers of its
1094 // member function. We then start with the innermost lambda and iterate
1095 // outward checking to see if any lambda performs a by-copy capture of '*this'
1096 // - and if so, any nested lambda must respect the 'constness' of that
1097 // capturing lamdbda's call operator.
1098 //
1099
1100 // Since the FunctionScopeInfo stack is representative of the lexical
1101 // nesting of the lambda expressions during initial parsing (and is the best
1102 // place for querying information about captures about lambdas that are
1103 // partially processed) and perhaps during instantiation of function templates
1104 // that contain lambda expressions that need to be transformed BUT not
1105 // necessarily during instantiation of a nested generic lambda's function call
1106 // operator (which might even be instantiated at the end of the TU) - at which
1107 // time the DeclContext tree is mature enough to query capture information
1108 // reliably - we use a two pronged approach to walk through all the lexically
1109 // enclosing lambda expressions:
1110 //
1111 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1112 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1113 // enclosed by the call-operator of the LSI below it on the stack (while
1114 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1115 // the stack represents the innermost lambda.
1116 //
1117 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1118 // represents a lambda's call operator. If it does, we must be instantiating
1119 // a generic lambda's call operator (represented by the Current LSI, and
1120 // should be the only scenario where an inconsistency between the LSI and the
1121 // DeclContext should occur), so climb out the DeclContexts if they
1122 // represent lambdas, while querying the corresponding closure types
1123 // regarding capture information.
1124
1125 // 1) Climb down the function scope info stack.
1126 for (int I = FunctionScopes.size();
1127 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1128 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1129 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1130 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1131 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1132
1133 if (!CurLSI->isCXXThisCaptured())
1134 continue;
1135
1136 auto C = CurLSI->getCXXThisCapture();
1137
1138 if (C.isCopyCapture()) {
1139 if (!CurLSI->Mutable)
1140 ClassType.addConst();
1141 return ASTCtx.getPointerType(ClassType);
1142 }
1143 }
1144
1145 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1146 // can happen during instantiation of its nested generic lambda call
1147 // operator); 2. if we're in a lambda scope (lambda body).
1148 if (CurLSI && isLambdaCallOperator(CurDC)) {
1150 "While computing 'this' capture-type for a generic lambda, when we "
1151 "run out of enclosing LSI's, yet the enclosing DC is a "
1152 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1153 "lambda call oeprator");
1154 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1155
1156 auto IsThisCaptured =
1157 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1158 IsConst = false;
1159 IsByCopy = false;
1160 for (auto &&C : Closure->captures()) {
1161 if (C.capturesThis()) {
1162 if (C.getCaptureKind() == LCK_StarThis)
1163 IsByCopy = true;
1164 if (Closure->getLambdaCallOperator()->isConst())
1165 IsConst = true;
1166 return true;
1167 }
1168 }
1169 return false;
1170 };
1171
1172 bool IsByCopyCapture = false;
1173 bool IsConstCapture = false;
1174 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1175 while (Closure &&
1176 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1177 if (IsByCopyCapture) {
1178 if (IsConstCapture)
1179 ClassType.addConst();
1180 return ASTCtx.getPointerType(ClassType);
1181 }
1182 Closure = isLambdaCallOperator(Closure->getParent())
1183 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1184 : nullptr;
1185 }
1186 }
1187 return ASTCtx.getPointerType(ClassType);
1188}
1189
1193
1194 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1195 if (method && method->isInstance())
1196 ThisTy = method->getThisType();
1197 }
1198
1199 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1200 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1201
1202 // This is a lambda call operator that is being instantiated as a default
1203 // initializer. DC must point to the enclosing class type, so we can recover
1204 // the 'this' type from it.
1205 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1206 // There are no cv-qualifiers for 'this' within default initializers,
1207 // per [expr.prim.general]p4.
1208 ThisTy = Context.getPointerType(ClassTy);
1209 }
1210
1211 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1212 // might need to be adjusted if the lambda or any of its enclosing lambda's
1213 // captures '*this' by copy.
1214 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1217 return ThisTy;
1218}
1219
1221 Decl *ContextDecl,
1222 Qualifiers CXXThisTypeQuals,
1223 bool Enabled)
1224 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1225{
1226 if (!Enabled || !ContextDecl)
1227 return;
1228
1229 CXXRecordDecl *Record = nullptr;
1230 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1231 Record = Template->getTemplatedDecl();
1232 else
1233 Record = cast<CXXRecordDecl>(ContextDecl);
1234
1235 QualType T = S.Context.getRecordType(Record);
1236 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1237
1239
1240 this->Enabled = true;
1241}
1242
1243
1245 if (Enabled) {
1246 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1247 }
1248}
1249
1251 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1252 assert(!LSI->isCXXThisCaptured());
1253 // [=, this] {}; // until C++20: Error: this when = is the default
1255 !Sema.getLangOpts().CPlusPlus20)
1256 return;
1257 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1259 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1260}
1261
1262bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1263 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1264 const bool ByCopy) {
1265 // We don't need to capture this in an unevaluated context.
1266 if (isUnevaluatedContext() && !Explicit)
1267 return true;
1268
1269 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1270
1271 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1272 ? *FunctionScopeIndexToStopAt
1273 : FunctionScopes.size() - 1;
1274
1275 // Check that we can capture the *enclosing object* (referred to by '*this')
1276 // by the capturing-entity/closure (lambda/block/etc) at
1277 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1278
1279 // Note: The *enclosing object* can only be captured by-value by a
1280 // closure that is a lambda, using the explicit notation:
1281 // [*this] { ... }.
1282 // Every other capture of the *enclosing object* results in its by-reference
1283 // capture.
1284
1285 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1286 // stack), we can capture the *enclosing object* only if:
1287 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1288 // - or, 'L' has an implicit capture.
1289 // AND
1290 // -- there is no enclosing closure
1291 // -- or, there is some enclosing closure 'E' that has already captured the
1292 // *enclosing object*, and every intervening closure (if any) between 'E'
1293 // and 'L' can implicitly capture the *enclosing object*.
1294 // -- or, every enclosing closure can implicitly capture the
1295 // *enclosing object*
1296
1297
1298 unsigned NumCapturingClosures = 0;
1299 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1300 if (CapturingScopeInfo *CSI =
1301 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1302 if (CSI->CXXThisCaptureIndex != 0) {
1303 // 'this' is already being captured; there isn't anything more to do.
1304 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1305 break;
1306 }
1307 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1309 // This context can't implicitly capture 'this'; fail out.
1310 if (BuildAndDiagnose) {
1311 Diag(Loc, diag::err_this_capture)
1312 << (Explicit && idx == MaxFunctionScopesIndex);
1313 if (!Explicit)
1314 buildLambdaThisCaptureFixit(*this, LSI);
1315 }
1316 return true;
1317 }
1318 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1319 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1320 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1321 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1322 (Explicit && idx == MaxFunctionScopesIndex)) {
1323 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1324 // iteration through can be an explicit capture, all enclosing closures,
1325 // if any, must perform implicit captures.
1326
1327 // This closure can capture 'this'; continue looking upwards.
1328 NumCapturingClosures++;
1329 continue;
1330 }
1331 // This context can't implicitly capture 'this'; fail out.
1332 if (BuildAndDiagnose)
1333 Diag(Loc, diag::err_this_capture)
1334 << (Explicit && idx == MaxFunctionScopesIndex);
1335
1336 if (!Explicit)
1337 buildLambdaThisCaptureFixit(*this, LSI);
1338 return true;
1339 }
1340 break;
1341 }
1342 if (!BuildAndDiagnose) return false;
1343
1344 // If we got here, then the closure at MaxFunctionScopesIndex on the
1345 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1346 // (including implicit by-reference captures in any enclosing closures).
1347
1348 // In the loop below, respect the ByCopy flag only for the closure requesting
1349 // the capture (i.e. first iteration through the loop below). Ignore it for
1350 // all enclosing closure's up to NumCapturingClosures (since they must be
1351 // implicitly capturing the *enclosing object* by reference (see loop
1352 // above)).
1353 assert((!ByCopy ||
1354 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1355 "Only a lambda can capture the enclosing object (referred to by "
1356 "*this) by copy");
1357 QualType ThisTy = getCurrentThisType();
1358 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1359 --idx, --NumCapturingClosures) {
1360 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1361
1362 // The type of the corresponding data member (not a 'this' pointer if 'by
1363 // copy').
1364 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1365
1366 bool isNested = NumCapturingClosures > 1;
1367 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1368 }
1369 return false;
1370}
1371
1373 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1374 /// is a non-lvalue expression whose value is the address of the object for
1375 /// which the function is called.
1376
1377 QualType ThisTy = getCurrentThisType();
1378 if (ThisTy.isNull())
1379 return Diag(Loc, diag::err_invalid_this_use);
1380 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1381}
1382
1384 bool IsImplicit) {
1385 if (getLangOpts().HLSL && Type.getTypePtr()->isPointerType()) {
1386 auto *This = new (Context)
1387 CXXThisExpr(Loc, Type.getTypePtr()->getPointeeType(), IsImplicit);
1388 This->setValueKind(ExprValueKind::VK_LValue);
1389 MarkThisReferenced(This);
1390 return This;
1391 }
1392 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1393 MarkThisReferenced(This);
1394 return This;
1395}
1396
1398 CheckCXXThisCapture(This->getExprLoc());
1399}
1400
1402 // If we're outside the body of a member function, then we'll have a specified
1403 // type for 'this'.
1405 return false;
1406
1407 // Determine whether we're looking into a class that's currently being
1408 // defined.
1409 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1410 return Class && Class->isBeingDefined();
1411}
1412
1413/// Parse construction of a specified type.
1414/// Can be interpreted either as function-style casting ("int(x)")
1415/// or class type construction ("ClassType(x,y,z)")
1416/// or creation of a value-initialized type ("int()").
1419 SourceLocation LParenOrBraceLoc,
1420 MultiExprArg exprs,
1421 SourceLocation RParenOrBraceLoc,
1422 bool ListInitialization) {
1423 if (!TypeRep)
1424 return ExprError();
1425
1426 TypeSourceInfo *TInfo;
1427 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1428 if (!TInfo)
1430
1431 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1432 RParenOrBraceLoc, ListInitialization);
1433 // Avoid creating a non-type-dependent expression that contains typos.
1434 // Non-type-dependent expressions are liable to be discarded without
1435 // checking for embedded typos.
1436 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1437 !Result.get()->isTypeDependent())
1439 else if (Result.isInvalid())
1441 RParenOrBraceLoc, exprs, Ty);
1442 return Result;
1443}
1444
1447 SourceLocation LParenOrBraceLoc,
1448 MultiExprArg Exprs,
1449 SourceLocation RParenOrBraceLoc,
1450 bool ListInitialization) {
1451 QualType Ty = TInfo->getType();
1452 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1453
1454 assert((!ListInitialization || Exprs.size() == 1) &&
1455 "List initialization must have exactly one expression.");
1456 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1457
1458 InitializedEntity Entity =
1460 InitializationKind Kind =
1461 Exprs.size()
1462 ? ListInitialization
1464 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1465 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1466 RParenOrBraceLoc)
1467 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1468 RParenOrBraceLoc);
1469
1470 // C++17 [expr.type.conv]p1:
1471 // If the type is a placeholder for a deduced class type, [...perform class
1472 // template argument deduction...]
1473 // C++23:
1474 // Otherwise, if the type contains a placeholder type, it is replaced by the
1475 // type determined by placeholder type deduction.
1476 DeducedType *Deduced = Ty->getContainedDeducedType();
1477 if (Deduced && !Deduced->isDeduced() &&
1478 isa<DeducedTemplateSpecializationType>(Deduced)) {
1480 Kind, Exprs);
1481 if (Ty.isNull())
1482 return ExprError();
1483 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1484 } else if (Deduced && !Deduced->isDeduced()) {
1485 MultiExprArg Inits = Exprs;
1486 if (ListInitialization) {
1487 auto *ILE = cast<InitListExpr>(Exprs[0]);
1488 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1489 }
1490
1491 if (Inits.empty())
1492 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1493 << Ty << FullRange);
1494 if (Inits.size() > 1) {
1495 Expr *FirstBad = Inits[1];
1496 return ExprError(Diag(FirstBad->getBeginLoc(),
1497 diag::err_auto_expr_init_multiple_expressions)
1498 << Ty << FullRange);
1499 }
1500 if (getLangOpts().CPlusPlus23) {
1501 if (Ty->getAs<AutoType>())
1502 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1503 }
1504 Expr *Deduce = Inits[0];
1505 if (isa<InitListExpr>(Deduce))
1506 return ExprError(
1507 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1508 << ListInitialization << Ty << FullRange);
1510 TemplateDeductionInfo Info(Deduce->getExprLoc());
1512 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1514 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1515 << Ty << Deduce->getType() << FullRange
1516 << Deduce->getSourceRange());
1517 if (DeducedType.isNull()) {
1518 assert(Result == TDK_AlreadyDiagnosed);
1519 return ExprError();
1520 }
1521
1522 Ty = DeducedType;
1523 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1524 }
1525
1528 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1529 RParenOrBraceLoc, ListInitialization);
1530
1531 // C++ [expr.type.conv]p1:
1532 // If the expression list is a parenthesized single expression, the type
1533 // conversion expression is equivalent (in definedness, and if defined in
1534 // meaning) to the corresponding cast expression.
1535 if (Exprs.size() == 1 && !ListInitialization &&
1536 !isa<InitListExpr>(Exprs[0])) {
1537 Expr *Arg = Exprs[0];
1538 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1539 RParenOrBraceLoc);
1540 }
1541
1542 // For an expression of the form T(), T shall not be an array type.
1543 QualType ElemTy = Ty;
1544 if (Ty->isArrayType()) {
1545 if (!ListInitialization)
1546 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1547 << FullRange);
1548 ElemTy = Context.getBaseElementType(Ty);
1549 }
1550
1551 // Only construct objects with object types.
1552 // The standard doesn't explicitly forbid function types here, but that's an
1553 // obvious oversight, as there's no way to dynamically construct a function
1554 // in general.
1555 if (Ty->isFunctionType())
1556 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1557 << Ty << FullRange);
1558
1559 // C++17 [expr.type.conv]p2:
1560 // If the type is cv void and the initializer is (), the expression is a
1561 // prvalue of the specified type that performs no initialization.
1562 if (!Ty->isVoidType() &&
1563 RequireCompleteType(TyBeginLoc, ElemTy,
1564 diag::err_invalid_incomplete_type_use, FullRange))
1565 return ExprError();
1566
1567 // Otherwise, the expression is a prvalue of the specified type whose
1568 // result object is direct-initialized (11.6) with the initializer.
1569 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1571
1572 if (Result.isInvalid())
1573 return Result;
1574
1575 Expr *Inner = Result.get();
1576 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1577 Inner = BTE->getSubExpr();
1578 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1579 CE && CE->isImmediateInvocation())
1580 Inner = CE->getSubExpr();
1581 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1582 !isa<CXXScalarValueInitExpr>(Inner)) {
1583 // If we created a CXXTemporaryObjectExpr, that node also represents the
1584 // functional cast. Otherwise, create an explicit cast to represent
1585 // the syntactic form of a functional-style cast that was used here.
1586 //
1587 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1588 // would give a more consistent AST representation than using a
1589 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1590 // is sometimes handled by initialization and sometimes not.
1591 QualType ResultType = Result.get()->getType();
1592 SourceRange Locs = ListInitialization
1593 ? SourceRange()
1594 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1596 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1597 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1598 Locs.getBegin(), Locs.getEnd());
1599 }
1600
1601 return Result;
1602}
1603
1605 // [CUDA] Ignore this function, if we can't call it.
1606 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1607 if (getLangOpts().CUDA) {
1608 auto CallPreference = IdentifyCUDAPreference(Caller, Method);
1609 // If it's not callable at all, it's not the right function.
1610 if (CallPreference < CFP_WrongSide)
1611 return false;
1612 if (CallPreference == CFP_WrongSide) {
1613 // Maybe. We have to check if there are better alternatives.
1615 Method->getDeclContext()->lookup(Method->getDeclName());
1616 for (const auto *D : R) {
1617 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1618 if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
1619 return false;
1620 }
1621 }
1622 // We've found no better variants.
1623 }
1624 }
1625
1627 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1628
1629 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1630 return Result;
1631
1632 // In case of CUDA, return true if none of the 1-argument deallocator
1633 // functions are actually callable.
1634 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1635 assert(FD->getNumParams() == 1 &&
1636 "Only single-operand functions should be in PreventedBy");
1637 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1638 });
1639}
1640
1641/// Determine whether the given function is a non-placement
1642/// deallocation function.
1644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1645 return S.isUsualDeallocationFunction(Method);
1646
1647 if (FD->getOverloadedOperator() != OO_Delete &&
1648 FD->getOverloadedOperator() != OO_Array_Delete)
1649 return false;
1650
1651 unsigned UsualParams = 1;
1652
1653 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1655 FD->getParamDecl(UsualParams)->getType(),
1656 S.Context.getSizeType()))
1657 ++UsualParams;
1658
1659 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1661 FD->getParamDecl(UsualParams)->getType(),
1663 ++UsualParams;
1664
1665 return UsualParams == FD->getNumParams();
1666}
1667
1668namespace {
1669 struct UsualDeallocFnInfo {
1670 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1671 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1672 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1673 Destroying(false), HasSizeT(false), HasAlignValT(false),
1674 CUDAPref(Sema::CFP_Native) {
1675 // A function template declaration is never a usual deallocation function.
1676 if (!FD)
1677 return;
1678 unsigned NumBaseParams = 1;
1679 if (FD->isDestroyingOperatorDelete()) {
1680 Destroying = true;
1681 ++NumBaseParams;
1682 }
1683
1684 if (NumBaseParams < FD->getNumParams() &&
1686 FD->getParamDecl(NumBaseParams)->getType(),
1687 S.Context.getSizeType())) {
1688 ++NumBaseParams;
1689 HasSizeT = true;
1690 }
1691
1692 if (NumBaseParams < FD->getNumParams() &&
1693 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1694 ++NumBaseParams;
1695 HasAlignValT = true;
1696 }
1697
1698 // In CUDA, determine how much we'd like / dislike to call this.
1699 if (S.getLangOpts().CUDA)
1700 if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
1701 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1702 }
1703
1704 explicit operator bool() const { return FD; }
1705
1706 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1707 bool WantAlign) const {
1708 // C++ P0722:
1709 // A destroying operator delete is preferred over a non-destroying
1710 // operator delete.
1711 if (Destroying != Other.Destroying)
1712 return Destroying;
1713
1714 // C++17 [expr.delete]p10:
1715 // If the type has new-extended alignment, a function with a parameter
1716 // of type std::align_val_t is preferred; otherwise a function without
1717 // such a parameter is preferred
1718 if (HasAlignValT != Other.HasAlignValT)
1719 return HasAlignValT == WantAlign;
1720
1721 if (HasSizeT != Other.HasSizeT)
1722 return HasSizeT == WantSize;
1723
1724 // Use CUDA call preference as a tiebreaker.
1725 return CUDAPref > Other.CUDAPref;
1726 }
1727
1728 DeclAccessPair Found;
1729 FunctionDecl *FD;
1730 bool Destroying, HasSizeT, HasAlignValT;
1732 };
1733}
1734
1735/// Determine whether a type has new-extended alignment. This may be called when
1736/// the type is incomplete (for a delete-expression with an incomplete pointee
1737/// type), in which case it will conservatively return false if the alignment is
1738/// not known.
1739static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1740 return S.getLangOpts().AlignedAllocation &&
1741 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1743}
1744
1745/// Select the correct "usual" deallocation function to use from a selection of
1746/// deallocation functions (either global or class-scope).
1747static UsualDeallocFnInfo resolveDeallocationOverload(
1748 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1749 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1750 UsualDeallocFnInfo Best;
1751
1752 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1753 UsualDeallocFnInfo Info(S, I.getPair());
1754 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1755 Info.CUDAPref == Sema::CFP_Never)
1756 continue;
1757
1758 if (!Best) {
1759 Best = Info;
1760 if (BestFns)
1761 BestFns->push_back(Info);
1762 continue;
1763 }
1764
1765 if (Best.isBetterThan(Info, WantSize, WantAlign))
1766 continue;
1767
1768 // If more than one preferred function is found, all non-preferred
1769 // functions are eliminated from further consideration.
1770 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1771 BestFns->clear();
1772
1773 Best = Info;
1774 if (BestFns)
1775 BestFns->push_back(Info);
1776 }
1777
1778 return Best;
1779}
1780
1781/// Determine whether a given type is a class for which 'delete[]' would call
1782/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1783/// we need to store the array size (even if the type is
1784/// trivially-destructible).
1786 QualType allocType) {
1787 const RecordType *record =
1788 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1789 if (!record) return false;
1790
1791 // Try to find an operator delete[] in class scope.
1792
1793 DeclarationName deleteName =
1794 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1795 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1796 S.LookupQualifiedName(ops, record->getDecl());
1797
1798 // We're just doing this for information.
1799 ops.suppressDiagnostics();
1800
1801 // Very likely: there's no operator delete[].
1802 if (ops.empty()) return false;
1803
1804 // If it's ambiguous, it should be illegal to call operator delete[]
1805 // on this thing, so it doesn't matter if we allocate extra space or not.
1806 if (ops.isAmbiguous()) return false;
1807
1808 // C++17 [expr.delete]p10:
1809 // If the deallocation functions have class scope, the one without a
1810 // parameter of type std::size_t is selected.
1811 auto Best = resolveDeallocationOverload(
1812 S, ops, /*WantSize*/false,
1813 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1814 return Best && Best.HasSizeT;
1815}
1816
1817/// Parsed a C++ 'new' expression (C++ 5.3.4).
1818///
1819/// E.g.:
1820/// @code new (memory) int[size][4] @endcode
1821/// or
1822/// @code ::new Foo(23, "hello") @endcode
1823///
1824/// \param StartLoc The first location of the expression.
1825/// \param UseGlobal True if 'new' was prefixed with '::'.
1826/// \param PlacementLParen Opening paren of the placement arguments.
1827/// \param PlacementArgs Placement new arguments.
1828/// \param PlacementRParen Closing paren of the placement arguments.
1829/// \param TypeIdParens If the type is in parens, the source range.
1830/// \param D The type to be allocated, as well as array dimensions.
1831/// \param Initializer The initializing expression or initializer-list, or null
1832/// if there is none.
1834Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1835 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1836 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1838 std::optional<Expr *> ArraySize;
1839 // If the specified type is an array, unwrap it and save the expression.
1840 if (D.getNumTypeObjects() > 0 &&
1842 DeclaratorChunk &Chunk = D.getTypeObject(0);
1843 if (D.getDeclSpec().hasAutoTypeSpec())
1844 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1845 << D.getSourceRange());
1846 if (Chunk.Arr.hasStatic)
1847 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1848 << D.getSourceRange());
1849 if (!Chunk.Arr.NumElts && !Initializer)
1850 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1851 << D.getSourceRange());
1852
1853 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1855 }
1856
1857 // Every dimension shall be of constant size.
1858 if (ArraySize) {
1859 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1861 break;
1862
1864 if (Expr *NumElts = (Expr *)Array.NumElts) {
1865 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1866 // FIXME: GCC permits constant folding here. We should either do so consistently
1867 // or not do so at all, rather than changing behavior in C++14 onwards.
1868 if (getLangOpts().CPlusPlus14) {
1869 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1870 // shall be a converted constant expression (5.19) of type std::size_t
1871 // and shall evaluate to a strictly positive value.
1872 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1873 Array.NumElts
1876 .get();
1877 } else {
1878 Array.NumElts =
1880 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1881 .get();
1882 }
1883 if (!Array.NumElts)
1884 return ExprError();
1885 }
1886 }
1887 }
1888 }
1889
1890 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1891 QualType AllocType = TInfo->getType();
1892 if (D.isInvalidType())
1893 return ExprError();
1894
1895 SourceRange DirectInitRange;
1896 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1897 DirectInitRange = List->getSourceRange();
1898
1899 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1900 PlacementLParen, PlacementArgs, PlacementRParen,
1901 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1902 Initializer);
1903}
1904
1906 Expr *Init) {
1907 if (!Init)
1908 return true;
1909 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1910 return PLE->getNumExprs() == 0;
1911 if (isa<ImplicitValueInitExpr>(Init))
1912 return true;
1913 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1914 return !CCE->isListInitialization() &&
1915 CCE->getConstructor()->isDefaultConstructor();
1916 else if (Style == CXXNewExpr::ListInit) {
1917 assert(isa<InitListExpr>(Init) &&
1918 "Shouldn't create list CXXConstructExprs for arrays.");
1919 return true;
1920 }
1921 return false;
1922}
1923
1924bool
1926 if (!getLangOpts().AlignedAllocationUnavailable)
1927 return false;
1928 if (FD.isDefined())
1929 return false;
1930 std::optional<unsigned> AlignmentParam;
1931 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1932 AlignmentParam)
1933 return true;
1934 return false;
1935}
1936
1937// Emit a diagnostic if an aligned allocation/deallocation function that is not
1938// implemented in the standard library is selected.
1940 SourceLocation Loc) {
1942 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1943 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1944 getASTContext().getTargetInfo().getPlatformName());
1945 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1946
1948 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1949 Diag(Loc, diag::err_aligned_allocation_unavailable)
1950 << IsDelete << FD.getType().getAsString() << OSName
1951 << OSVersion.getAsString() << OSVersion.empty();
1952 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1953 }
1954}
1955
1957 SourceLocation PlacementLParen,
1958 MultiExprArg PlacementArgs,
1959 SourceLocation PlacementRParen,
1960 SourceRange TypeIdParens, QualType AllocType,
1961 TypeSourceInfo *AllocTypeInfo,
1962 std::optional<Expr *> ArraySize,
1963 SourceRange DirectInitRange, Expr *Initializer) {
1964 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1965 SourceLocation StartLoc = Range.getBegin();
1966
1968 if (DirectInitRange.isValid()) {
1969 assert(Initializer && "Have parens but no initializer.");
1970 initStyle = CXXNewExpr::CallInit;
1971 } else if (Initializer && isa<InitListExpr>(Initializer))
1972 initStyle = CXXNewExpr::ListInit;
1973 else {
1974 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1975 isa<CXXConstructExpr>(Initializer)) &&
1976 "Initializer expression that cannot have been implicitly created.");
1977 initStyle = CXXNewExpr::NoInit;
1978 }
1979
1980 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
1981 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1982 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1983 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
1984 }
1985
1986 // C++11 [expr.new]p15:
1987 // A new-expression that creates an object of type T initializes that
1988 // object as follows:
1990 // - If the new-initializer is omitted, the object is default-
1991 // initialized (8.5); if no initialization is performed,
1992 // the object has indeterminate value
1993 = initStyle == CXXNewExpr::NoInit
1995 // - Otherwise, the new-initializer is interpreted according to
1996 // the
1997 // initialization rules of 8.5 for direct-initialization.
1998 : initStyle == CXXNewExpr::ListInit
2000 TypeRange.getBegin(), Initializer->getBeginLoc(),
2001 Initializer->getEndLoc())
2003 DirectInitRange.getBegin(),
2004 DirectInitRange.getEnd());
2005
2006 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2007 auto *Deduced = AllocType->getContainedDeducedType();
2008 if (Deduced && !Deduced->isDeduced() &&
2009 isa<DeducedTemplateSpecializationType>(Deduced)) {
2010 if (ArraySize)
2011 return ExprError(
2012 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2013 diag::err_deduced_class_template_compound_type)
2014 << /*array*/ 2
2015 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2016
2017 InitializedEntity Entity
2018 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2020 AllocTypeInfo, Entity, Kind, Exprs);
2021 if (AllocType.isNull())
2022 return ExprError();
2023 } else if (Deduced && !Deduced->isDeduced()) {
2024 MultiExprArg Inits = Exprs;
2025 bool Braced = (initStyle == CXXNewExpr::ListInit);
2026 if (Braced) {
2027 auto *ILE = cast<InitListExpr>(Exprs[0]);
2028 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2029 }
2030
2031 if (initStyle == CXXNewExpr::NoInit || Inits.empty())
2032 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2033 << AllocType << TypeRange);
2034 if (Inits.size() > 1) {
2035 Expr *FirstBad = Inits[1];
2036 return ExprError(Diag(FirstBad->getBeginLoc(),
2037 diag::err_auto_new_ctor_multiple_expressions)
2038 << AllocType << TypeRange);
2039 }
2040 if (Braced && !getLangOpts().CPlusPlus17)
2041 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2042 << AllocType << TypeRange;
2043 Expr *Deduce = Inits[0];
2044 if (isa<InitListExpr>(Deduce))
2045 return ExprError(
2046 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2047 << Braced << AllocType << TypeRange);
2049 TemplateDeductionInfo Info(Deduce->getExprLoc());
2051 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2053 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2054 << AllocType << Deduce->getType() << TypeRange
2055 << Deduce->getSourceRange());
2056 if (DeducedType.isNull()) {
2057 assert(Result == TDK_AlreadyDiagnosed);
2058 return ExprError();
2059 }
2060 AllocType = DeducedType;
2061 }
2062
2063 // Per C++0x [expr.new]p5, the type being constructed may be a
2064 // typedef of an array type.
2065 if (!ArraySize) {
2066 if (const ConstantArrayType *Array
2067 = Context.getAsConstantArrayType(AllocType)) {
2068 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2070 TypeRange.getEnd());
2071 AllocType = Array->getElementType();
2072 }
2073 }
2074
2075 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2076 return ExprError();
2077
2078 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2079 return ExprError();
2080
2081 // In ARC, infer 'retaining' for the allocated
2082 if (getLangOpts().ObjCAutoRefCount &&
2083 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2084 AllocType->isObjCLifetimeType()) {
2085 AllocType = Context.getLifetimeQualifiedType(AllocType,
2086 AllocType->getObjCARCImplicitLifetime());
2087 }
2088
2089 QualType ResultType = Context.getPointerType(AllocType);
2090
2091 if (ArraySize && *ArraySize &&
2092 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2093 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2094 if (result.isInvalid()) return ExprError();
2095 ArraySize = result.get();
2096 }
2097 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2098 // integral or enumeration type with a non-negative value."
2099 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2100 // enumeration type, or a class type for which a single non-explicit
2101 // conversion function to integral or unscoped enumeration type exists.
2102 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2103 // std::size_t.
2104 std::optional<uint64_t> KnownArraySize;
2105 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2106 ExprResult ConvertedSize;
2107 if (getLangOpts().CPlusPlus14) {
2108 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2109
2110 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2112
2113 if (!ConvertedSize.isInvalid() &&
2114 (*ArraySize)->getType()->getAs<RecordType>())
2115 // Diagnose the compatibility of this conversion.
2116 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2117 << (*ArraySize)->getType() << 0 << "'size_t'";
2118 } else {
2119 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2120 protected:
2121 Expr *ArraySize;
2122
2123 public:
2124 SizeConvertDiagnoser(Expr *ArraySize)
2125 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2126 ArraySize(ArraySize) {}
2127
2128 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2129 QualType T) override {
2130 return S.Diag(Loc, diag::err_array_size_not_integral)
2131 << S.getLangOpts().CPlusPlus11 << T;
2132 }
2133
2134 SemaDiagnosticBuilder diagnoseIncomplete(
2135 Sema &S, SourceLocation Loc, QualType T) override {
2136 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2137 << T << ArraySize->getSourceRange();
2138 }
2139
2140 SemaDiagnosticBuilder diagnoseExplicitConv(
2141 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2142 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2143 }
2144
2145 SemaDiagnosticBuilder noteExplicitConv(
2146 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2147 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2148 << ConvTy->isEnumeralType() << ConvTy;
2149 }
2150
2151 SemaDiagnosticBuilder diagnoseAmbiguous(
2152 Sema &S, SourceLocation Loc, QualType T) override {
2153 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2154 }
2155
2156 SemaDiagnosticBuilder noteAmbiguous(
2157 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2158 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2159 << ConvTy->isEnumeralType() << ConvTy;
2160 }
2161
2162 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2163 QualType T,
2164 QualType ConvTy) override {
2165 return S.Diag(Loc,
2166 S.getLangOpts().CPlusPlus11
2167 ? diag::warn_cxx98_compat_array_size_conversion
2168 : diag::ext_array_size_conversion)
2169 << T << ConvTy->isEnumeralType() << ConvTy;
2170 }
2171 } SizeDiagnoser(*ArraySize);
2172
2173 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2174 SizeDiagnoser);
2175 }
2176 if (ConvertedSize.isInvalid())
2177 return ExprError();
2178
2179 ArraySize = ConvertedSize.get();
2180 QualType SizeType = (*ArraySize)->getType();
2181
2182 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2183 return ExprError();
2184
2185 // C++98 [expr.new]p7:
2186 // The expression in a direct-new-declarator shall have integral type
2187 // with a non-negative value.
2188 //
2189 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2190 // per CWG1464. Otherwise, if it's not a constant, we must have an
2191 // unparenthesized array type.
2192
2193 // We've already performed any required implicit conversion to integer or
2194 // unscoped enumeration type.
2195 // FIXME: Per CWG1464, we are required to check the value prior to
2196 // converting to size_t. This will never find a negative array size in
2197 // C++14 onwards, because Value is always unsigned here!
2198 if (std::optional<llvm::APSInt> Value =
2199 (*ArraySize)->getIntegerConstantExpr(Context)) {
2200 if (Value->isSigned() && Value->isNegative()) {
2201 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2202 diag::err_typecheck_negative_array_size)
2203 << (*ArraySize)->getSourceRange());
2204 }
2205
2206 if (!AllocType->isDependentType()) {
2207 unsigned ActiveSizeBits =
2209 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2210 return ExprError(
2211 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2212 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2213 }
2214
2215 KnownArraySize = Value->getZExtValue();
2216 } else if (TypeIdParens.isValid()) {
2217 // Can't have dynamic array size when the type-id is in parentheses.
2218 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2219 << (*ArraySize)->getSourceRange()
2220 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2221 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2222
2223 TypeIdParens = SourceRange();
2224 }
2225
2226 // Note that we do *not* convert the argument in any way. It can
2227 // be signed, larger than size_t, whatever.
2228 }
2229
2230 FunctionDecl *OperatorNew = nullptr;
2231 FunctionDecl *OperatorDelete = nullptr;
2232 unsigned Alignment =
2233 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2234 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2235 bool PassAlignment = getLangOpts().AlignedAllocation &&
2236 Alignment > NewAlignment;
2237
2239 if (!AllocType->isDependentType() &&
2240 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2242 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2243 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2244 OperatorNew, OperatorDelete))
2245 return ExprError();
2246
2247 // If this is an array allocation, compute whether the usual array
2248 // deallocation function for the type has a size_t parameter.
2249 bool UsualArrayDeleteWantsSize = false;
2250 if (ArraySize && !AllocType->isDependentType())
2251 UsualArrayDeleteWantsSize =
2252 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2253
2254 SmallVector<Expr *, 8> AllPlaceArgs;
2255 if (OperatorNew) {
2256 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2257 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2259
2260 // We've already converted the placement args, just fill in any default
2261 // arguments. Skip the first parameter because we don't have a corresponding
2262 // argument. Skip the second parameter too if we're passing in the
2263 // alignment; we've already filled it in.
2264 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2265 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2266 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2267 CallType))
2268 return ExprError();
2269
2270 if (!AllPlaceArgs.empty())
2271 PlacementArgs = AllPlaceArgs;
2272
2273 // We would like to perform some checking on the given `operator new` call,
2274 // but the PlacementArgs does not contain the implicit arguments,
2275 // namely allocation size and maybe allocation alignment,
2276 // so we need to conjure them.
2277
2278 QualType SizeTy = Context.getSizeType();
2279 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2280
2281 llvm::APInt SingleEltSize(
2282 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2283
2284 // How many bytes do we want to allocate here?
2285 std::optional<llvm::APInt> AllocationSize;
2286 if (!ArraySize && !AllocType->isDependentType()) {
2287 // For non-array operator new, we only want to allocate one element.
2288 AllocationSize = SingleEltSize;
2289 } else if (KnownArraySize && !AllocType->isDependentType()) {
2290 // For array operator new, only deal with static array size case.
2291 bool Overflow;
2292 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2293 .umul_ov(SingleEltSize, Overflow);
2294 (void)Overflow;
2295 assert(
2296 !Overflow &&
2297 "Expected that all the overflows would have been handled already.");
2298 }
2299
2300 IntegerLiteral AllocationSizeLiteral(
2301 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2302 SizeTy, SourceLocation());
2303 // Otherwise, if we failed to constant-fold the allocation size, we'll
2304 // just give up and pass-in something opaque, that isn't a null pointer.
2305 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2306 OK_Ordinary, /*SourceExpr=*/nullptr);
2307
2308 // Let's synthesize the alignment argument in case we will need it.
2309 // Since we *really* want to allocate these on stack, this is slightly ugly
2310 // because there might not be a `std::align_val_t` type.
2312 QualType AlignValT =
2314 IntegerLiteral AlignmentLiteral(
2315 Context,
2316 llvm::APInt(Context.getTypeSize(SizeTy),
2317 Alignment / Context.getCharWidth()),
2318 SizeTy, SourceLocation());
2319 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2320 CK_IntegralCast, &AlignmentLiteral,
2322
2323 // Adjust placement args by prepending conjured size and alignment exprs.
2325 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2326 CallArgs.emplace_back(AllocationSize
2327 ? static_cast<Expr *>(&AllocationSizeLiteral)
2328 : &OpaqueAllocationSize);
2329 if (PassAlignment)
2330 CallArgs.emplace_back(&DesiredAlignment);
2331 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2332
2333 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2334
2335 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2336 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2337
2338 // Warn if the type is over-aligned and is being allocated by (unaligned)
2339 // global operator new.
2340 if (PlacementArgs.empty() && !PassAlignment &&
2341 (OperatorNew->isImplicit() ||
2342 (OperatorNew->getBeginLoc().isValid() &&
2343 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2344 if (Alignment > NewAlignment)
2345 Diag(StartLoc, diag::warn_overaligned_type)
2346 << AllocType
2347 << unsigned(Alignment / Context.getCharWidth())
2348 << unsigned(NewAlignment / Context.getCharWidth());
2349 }
2350 }
2351
2352 // Array 'new' can't have any initializers except empty parentheses.
2353 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2354 // dialect distinction.
2355 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2356 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2357 Exprs.back()->getEndLoc());
2358 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2359 return ExprError();
2360 }
2361
2362 // If we can perform the initialization, and we've not already done so,
2363 // do it now.
2364 if (!AllocType->isDependentType() &&
2366 // The type we initialize is the complete type, including the array bound.
2367 QualType InitType;
2368 if (KnownArraySize)
2369 InitType = Context.getConstantArrayType(
2370 AllocType,
2371 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2372 *KnownArraySize),
2373 *ArraySize, ArrayType::Normal, 0);
2374 else if (ArraySize)
2375 InitType =
2377 else
2378 InitType = AllocType;
2379
2380 InitializedEntity Entity
2381 = InitializedEntity::InitializeNew(StartLoc, InitType);
2382 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2383 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2384 if (FullInit.isInvalid())
2385 return ExprError();
2386
2387 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2388 // we don't want the initialized object to be destructed.
2389 // FIXME: We should not create these in the first place.
2390 if (CXXBindTemporaryExpr *Binder =
2391 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2392 FullInit = Binder->getSubExpr();
2393
2394 Initializer = FullInit.get();
2395
2396 // FIXME: If we have a KnownArraySize, check that the array bound of the
2397 // initializer is no greater than that constant value.
2398
2399 if (ArraySize && !*ArraySize) {
2400 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2401 if (CAT) {
2402 // FIXME: Track that the array size was inferred rather than explicitly
2403 // specified.
2404 ArraySize = IntegerLiteral::Create(
2405 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2406 } else {
2407 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2408 << Initializer->getSourceRange();
2409 }
2410 }
2411 }
2412
2413 // Mark the new and delete operators as referenced.
2414 if (OperatorNew) {
2415 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2416 return ExprError();
2417 MarkFunctionReferenced(StartLoc, OperatorNew);
2418 }
2419 if (OperatorDelete) {
2420 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2421 return ExprError();
2422 MarkFunctionReferenced(StartLoc, OperatorDelete);
2423 }
2424
2425 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2426 PassAlignment, UsualArrayDeleteWantsSize,
2427 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2428 Initializer, ResultType, AllocTypeInfo, Range,
2429 DirectInitRange);
2430}
2431
2432/// Checks that a type is suitable as the allocated type
2433/// in a new-expression.
2435 SourceRange R) {
2436 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2437 // abstract class type or array thereof.
2438 if (AllocType->isFunctionType())
2439 return Diag(Loc, diag::err_bad_new_type)
2440 << AllocType << 0 << R;
2441 else if (AllocType->isReferenceType())
2442 return Diag(Loc, diag::err_bad_new_type)
2443 << AllocType << 1 << R;
2444 else if (!AllocType->isDependentType() &&
2446 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2447 return true;
2448 else if (RequireNonAbstractType(Loc, AllocType,
2449 diag::err_allocation_of_abstract_type))
2450 return true;
2451 else if (AllocType->isVariablyModifiedType())
2452 return Diag(Loc, diag::err_variably_modified_new_type)
2453 << AllocType;
2454 else if (AllocType.getAddressSpace() != LangAS::Default &&
2455 !getLangOpts().OpenCLCPlusPlus)
2456 return Diag(Loc, diag::err_address_space_qualified_new)
2457 << AllocType.getUnqualifiedType()
2459 else if (getLangOpts().ObjCAutoRefCount) {
2460 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2461 QualType BaseAllocType = Context.getBaseElementType(AT);
2462 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2463 BaseAllocType->isObjCLifetimeType())
2464 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2465 << BaseAllocType;
2466 }
2467 }
2468
2469 return false;
2470}
2471
2474 bool &PassAlignment, FunctionDecl *&Operator,
2475 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2476 OverloadCandidateSet Candidates(R.getNameLoc(),
2478 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2479 Alloc != AllocEnd; ++Alloc) {
2480 // Even member operator new/delete are implicitly treated as
2481 // static, so don't use AddMemberCandidate.
2482 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2483
2484 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2485 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2486 /*ExplicitTemplateArgs=*/nullptr, Args,
2487 Candidates,
2488 /*SuppressUserConversions=*/false);
2489 continue;
2490 }
2491
2492 FunctionDecl *Fn = cast<FunctionDecl>(D);
2493 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2494 /*SuppressUserConversions=*/false);
2495 }
2496
2497 // Do the resolution.
2499 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2500 case OR_Success: {
2501 // Got one!
2502 FunctionDecl *FnDecl = Best->Function;
2503 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2504 Best->FoundDecl) == Sema::AR_inaccessible)
2505 return true;
2506
2507 Operator = FnDecl;
2508 return false;
2509 }
2510
2512 // C++17 [expr.new]p13:
2513 // If no matching function is found and the allocated object type has
2514 // new-extended alignment, the alignment argument is removed from the
2515 // argument list, and overload resolution is performed again.
2516 if (PassAlignment) {
2517 PassAlignment = false;
2518 AlignArg = Args[1];
2519 Args.erase(Args.begin() + 1);
2520 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2521 Operator, &Candidates, AlignArg,
2522 Diagnose);
2523 }
2524
2525 // MSVC will fall back on trying to find a matching global operator new
2526 // if operator new[] cannot be found. Also, MSVC will leak by not
2527 // generating a call to operator delete or operator delete[], but we
2528 // will not replicate that bug.
2529 // FIXME: Find out how this interacts with the std::align_val_t fallback
2530 // once MSVC implements it.
2531 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2532 S.Context.getLangOpts().MSVCCompat) {
2533 R.clear();
2536 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2537 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2538 Operator, /*Candidates=*/nullptr,
2539 /*AlignArg=*/nullptr, Diagnose);
2540 }
2541
2542 if (Diagnose) {
2543 // If this is an allocation of the form 'new (p) X' for some object
2544 // pointer p (or an expression that will decay to such a pointer),
2545 // diagnose the missing inclusion of <new>.
2546 if (!R.isClassLookup() && Args.size() == 2 &&
2547 (Args[1]->getType()->isObjectPointerType() ||
2548 Args[1]->getType()->isArrayType())) {
2549 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2550 << R.getLookupName() << Range;
2551 // Listing the candidates is unlikely to be useful; skip it.
2552 return true;
2553 }
2554
2555 // Finish checking all candidates before we note any. This checking can
2556 // produce additional diagnostics so can't be interleaved with our
2557 // emission of notes.
2558 //
2559 // For an aligned allocation, separately check the aligned and unaligned
2560 // candidates with their respective argument lists.
2563 llvm::SmallVector<Expr*, 4> AlignedArgs;
2564 if (AlignedCandidates) {
2565 auto IsAligned = [](OverloadCandidate &C) {
2566 return C.Function->getNumParams() > 1 &&
2567 C.Function->getParamDecl(1)->getType()->isAlignValT();
2568 };
2569 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2570
2571 AlignedArgs.reserve(Args.size() + 1);
2572 AlignedArgs.push_back(Args[0]);
2573 AlignedArgs.push_back(AlignArg);
2574 AlignedArgs.append(Args.begin() + 1, Args.end());
2575 AlignedCands = AlignedCandidates->CompleteCandidates(
2576 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2577
2578 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2579 R.getNameLoc(), IsUnaligned);
2580 } else {
2581 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2582 R.getNameLoc());
2583 }
2584
2585 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2586 << R.getLookupName() << Range;
2587 if (AlignedCandidates)
2588 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2589 R.getNameLoc());
2590 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2591 }
2592 return true;
2593
2594 case OR_Ambiguous:
2595 if (Diagnose) {
2596 Candidates.NoteCandidates(
2598 S.PDiag(diag::err_ovl_ambiguous_call)
2599 << R.getLookupName() << Range),
2600 S, OCD_AmbiguousCandidates, Args);
2601 }
2602 return true;
2603
2604 case OR_Deleted: {
2605 if (Diagnose) {
2606 Candidates.NoteCandidates(
2608 S.PDiag(diag::err_ovl_deleted_call)
2609 << R.getLookupName() << Range),
2610 S, OCD_AllCandidates, Args);
2611 }
2612 return true;
2613 }
2614 }
2615 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2616}
2617
2619 AllocationFunctionScope NewScope,
2620 AllocationFunctionScope DeleteScope,
2621 QualType AllocType, bool IsArray,
2622 bool &PassAlignment, MultiExprArg PlaceArgs,
2623 FunctionDecl *&OperatorNew,
2624 FunctionDecl *&OperatorDelete,
2625 bool Diagnose) {
2626 // --- Choosing an allocation function ---
2627 // C++ 5.3.4p8 - 14 & 18
2628 // 1) If looking in AFS_Global scope for allocation functions, only look in
2629 // the global scope. Else, if AFS_Class, only look in the scope of the
2630 // allocated class. If AFS_Both, look in both.
2631 // 2) If an array size is given, look for operator new[], else look for
2632 // operator new.
2633 // 3) The first argument is always size_t. Append the arguments from the
2634 // placement form.
2635
2636 SmallVector<Expr*, 8> AllocArgs;
2637 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2638
2639 // We don't care about the actual value of these arguments.
2640 // FIXME: Should the Sema create the expression and embed it in the syntax
2641 // tree? Or should the consumer just recalculate the value?
2642 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2643 IntegerLiteral Size(
2644 Context,
2645 llvm::APInt::getZero(
2648 AllocArgs.push_back(&Size);
2649
2650 QualType AlignValT = Context.VoidTy;
2651 if (PassAlignment) {
2654 }
2655 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2656 if (PassAlignment)
2657 AllocArgs.push_back(&Align);
2658
2659 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2660
2661 // C++ [expr.new]p8:
2662 // If the allocated type is a non-array type, the allocation
2663 // function's name is operator new and the deallocation function's
2664 // name is operator delete. If the allocated type is an array
2665 // type, the allocation function's name is operator new[] and the
2666 // deallocation function's name is operator delete[].
2668 IsArray ? OO_Array_New : OO_New);
2669
2670 QualType AllocElemType = Context.getBaseElementType(AllocType);
2671
2672 // Find the allocation function.
2673 {
2674 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2675
2676 // C++1z [expr.new]p9:
2677 // If the new-expression begins with a unary :: operator, the allocation
2678 // function's name is looked up in the global scope. Otherwise, if the
2679 // allocated type is a class type T or array thereof, the allocation
2680 // function's name is looked up in the scope of T.
2681 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2682 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2683
2684 // We can see ambiguity here if the allocation function is found in
2685 // multiple base classes.
2686 if (R.isAmbiguous())
2687 return true;
2688
2689 // If this lookup fails to find the name, or if the allocated type is not
2690 // a class type, the allocation function's name is looked up in the
2691 // global scope.
2692 if (R.empty()) {
2693 if (NewScope == AFS_Class)
2694 return true;
2695
2697 }
2698
2699 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2700 if (PlaceArgs.empty()) {
2701 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2702 } else {
2703 Diag(StartLoc, diag::err_openclcxx_placement_new);
2704 }
2705 return true;
2706 }
2707
2708 assert(!R.empty() && "implicitly declared allocation functions not found");
2709 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2710
2711 // We do our own custom access checks below.
2713
2714 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2715 OperatorNew, /*Candidates=*/nullptr,
2716 /*AlignArg=*/nullptr, Diagnose))
2717 return true;
2718 }
2719
2720 // We don't need an operator delete if we're running under -fno-exceptions.
2721 if (!getLangOpts().Exceptions) {
2722 OperatorDelete = nullptr;
2723 return false;
2724 }
2725
2726 // Note, the name of OperatorNew might have been changed from array to
2727 // non-array by resolveAllocationOverload.
2729 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2730 ? OO_Array_Delete
2731 : OO_Delete);
2732
2733 // C++ [expr.new]p19:
2734 //
2735 // If the new-expression begins with a unary :: operator, the
2736 // deallocation function's name is looked up in the global
2737 // scope. Otherwise, if the allocated type is a class type T or an
2738 // array thereof, the deallocation function's name is looked up in
2739 // the scope of T. If this lookup fails to find the name, or if
2740 // the allocated type is not a class type or array thereof, the
2741 // deallocation function's name is looked up in the global scope.
2742 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2743 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2744 auto *RD =
2745 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2746 LookupQualifiedName(FoundDelete, RD);
2747 }
2748 if (FoundDelete.isAmbiguous())
2749 return true; // FIXME: clean up expressions?
2750
2751 // Filter out any destroying operator deletes. We can't possibly call such a
2752 // function in this context, because we're handling the case where the object
2753 // was not successfully constructed.
2754 // FIXME: This is not covered by the language rules yet.
2755 {
2756 LookupResult::Filter Filter = FoundDelete.makeFilter();
2757 while (Filter.hasNext()) {
2758 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2759 if (FD && FD->isDestroyingOperatorDelete())
2760 Filter.erase();
2761 }
2762 Filter.done();
2763 }
2764
2765 bool FoundGlobalDelete = FoundDelete.empty();
2766 if (FoundDelete.empty()) {
2767 FoundDelete.clear(LookupOrdinaryName);
2768
2769 if (DeleteScope == AFS_Class)
2770 return true;
2771
2774 }
2775
2776 FoundDelete.suppressDiagnostics();
2777
2779
2780 // Whether we're looking for a placement operator delete is dictated
2781 // by whether we selected a placement operator new, not by whether
2782 // we had explicit placement arguments. This matters for things like
2783 // struct A { void *operator new(size_t, int = 0); ... };
2784 // A *a = new A()
2785 //
2786 // We don't have any definition for what a "placement allocation function"
2787 // is, but we assume it's any allocation function whose
2788 // parameter-declaration-clause is anything other than (size_t).
2789 //
2790 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2791 // This affects whether an exception from the constructor of an overaligned
2792 // type uses the sized or non-sized form of aligned operator delete.
2793 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2794 OperatorNew->isVariadic();
2795
2796 if (isPlacementNew) {
2797 // C++ [expr.new]p20:
2798 // A declaration of a placement deallocation function matches the
2799 // declaration of a placement allocation function if it has the
2800 // same number of parameters and, after parameter transformations
2801 // (8.3.5), all parameter types except the first are
2802 // identical. [...]
2803 //
2804 // To perform this comparison, we compute the function type that
2805 // the deallocation function should have, and use that type both
2806 // for template argument deduction and for comparison purposes.
2807 QualType ExpectedFunctionType;
2808 {
2809 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2810
2811 SmallVector<QualType, 4> ArgTypes;
2812 ArgTypes.push_back(Context.VoidPtrTy);
2813 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2814 ArgTypes.push_back(Proto->getParamType(I));
2815
2817 // FIXME: This is not part of the standard's rule.
2818 EPI.Variadic = Proto->isVariadic();
2819
2820 ExpectedFunctionType
2821 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2822 }
2823
2824 for (LookupResult::iterator D = FoundDelete.begin(),
2825 DEnd = FoundDelete.end();
2826 D != DEnd; ++D) {
2827 FunctionDecl *Fn = nullptr;
2828 if (FunctionTemplateDecl *FnTmpl =
2829 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2830 // Perform template argument deduction to try to match the
2831 // expected function type.
2832 TemplateDeductionInfo Info(StartLoc);
2833 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2834 Info))
2835 continue;
2836 } else
2837 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2838
2840 ExpectedFunctionType,
2841 /*AdjustExcpetionSpec*/true),
2842 ExpectedFunctionType))
2843 Matches.push_back(std::make_pair(D.getPair(), Fn));
2844 }
2845
2846 if (getLangOpts().CUDA)
2847 EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2848 Matches);
2849 } else {
2850 // C++1y [expr.new]p22:
2851 // For a non-placement allocation function, the normal deallocation
2852 // function lookup is used
2853 //
2854 // Per [expr.delete]p10, this lookup prefers a member operator delete
2855 // without a size_t argument, but prefers a non-member operator delete
2856 // with a size_t where possible (which it always is in this case).
2858 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2859 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2860 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2861 &BestDeallocFns);
2862 if (Selected)
2863 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2864 else {
2865 // If we failed to select an operator, all remaining functions are viable
2866 // but ambiguous.
2867 for (auto Fn : BestDeallocFns)
2868 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2869 }
2870 }
2871
2872 // C++ [expr.new]p20:
2873 // [...] If the lookup finds a single matching deallocation
2874 // function, that function will be called; otherwise, no
2875 // deallocation function will be called.
2876 if (Matches.size() == 1) {
2877 OperatorDelete = Matches[0].second;
2878
2879 // C++1z [expr.new]p23:
2880 // If the lookup finds a usual deallocation function (3.7.4.2)
2881 // with a parameter of type std::size_t and that function, considered
2882 // as a placement deallocation function, would have been
2883 // selected as a match for the allocation function, the program
2884 // is ill-formed.
2885 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2886 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2887 UsualDeallocFnInfo Info(*this,
2888 DeclAccessPair::make(OperatorDelete, AS_public));
2889 // Core issue, per mail to core reflector, 2016-10-09:
2890 // If this is a member operator delete, and there is a corresponding
2891 // non-sized member operator delete, this isn't /really/ a sized
2892 // deallocation function, it just happens to have a size_t parameter.
2893 bool IsSizedDelete = Info.HasSizeT;
2894 if (IsSizedDelete && !FoundGlobalDelete) {
2895 auto NonSizedDelete =
2896 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2897 /*WantAlign*/Info.HasAlignValT);
2898 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2899 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2900 IsSizedDelete = false;
2901 }
2902
2903 if (IsSizedDelete) {
2904 SourceRange R = PlaceArgs.empty()
2905 ? SourceRange()
2906 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2907 PlaceArgs.back()->getEndLoc());
2908 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2909 if (!OperatorDelete->isImplicit())
2910 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2911 << DeleteName;
2912 }
2913 }
2914
2915 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2916 Matches[0].first);
2917 } else if (!Matches.empty()) {
2918 // We found multiple suitable operators. Per [expr.new]p20, that means we
2919 // call no 'operator delete' function, but we should at least warn the user.
2920 // FIXME: Suppress this warning if the construction cannot throw.
2921 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2922 << DeleteName << AllocElemType;
2923
2924 for (auto &Match : Matches)
2925 Diag(Match.second->getLocation(),
2926 diag::note_member_declared_here) << DeleteName;
2927 }
2928
2929 return false;
2930}
2931
2932/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2933/// delete. These are:
2934/// @code
2935/// // C++03:
2936/// void* operator new(std::size_t) throw(std::bad_alloc);
2937/// void* operator new[](std::size_t) throw(std::bad_alloc);
2938/// void operator delete(void *) throw();
2939/// void operator delete[](void *) throw();
2940/// // C++11:
2941/// void* operator new(std::size_t);
2942/// void* operator new[](std::size_t);
2943/// void operator delete(void *) noexcept;
2944/// void operator delete[](void *) noexcept;
2945/// // C++1y:
2946/// void* operator new(std::size_t);
2947/// void* operator new[](std::size_t);
2948/// void operator delete(void *) noexcept;
2949/// void operator delete[](void *) noexcept;
2950/// void operator delete(void *, std::size_t) noexcept;
2951/// void operator delete[](void *, std::size_t) noexcept;
2952/// @endcode
2953/// Note that the placement and nothrow forms of new are *not* implicitly
2954/// declared. Their use requires including <new>.
2957 return;
2958
2959 // The implicitly declared new and delete operators
2960 // are not supported in OpenCL.
2961 if (getLangOpts().OpenCLCPlusPlus)
2962 return;
2963
2964 // C++ [basic.stc.dynamic.general]p2:
2965 // The library provides default definitions for the global allocation
2966 // and deallocation functions. Some global allocation and deallocation
2967 // functions are replaceable ([new.delete]); these are attached to the
2968 // global module ([module.unit]).
2969 if (getLangOpts().CPlusPlusModules && getCurrentModule())
2970 PushGlobalModuleFragment(SourceLocation());
2971
2972 // C++ [basic.std.dynamic]p2:
2973 // [...] The following allocation and deallocation functions (18.4) are
2974 // implicitly declared in global scope in each translation unit of a
2975 // program
2976 //
2977 // C++03:
2978 // void* operator new(std::size_t) throw(std::bad_alloc);
2979 // void* operator new[](std::size_t) throw(std::bad_alloc);
2980 // void operator delete(void*) throw();
2981 // void operator delete[](void*) throw();
2982 // C++11:
2983 // void* operator new(std::size_t);
2984 // void* operator new[](std::size_t);
2985 // void operator delete(void*) noexcept;
2986 // void operator delete[](void*) noexcept;
2987 // C++1y:
2988 // void* operator new(std::size_t);
2989 // void* operator new[](std::size_t);
2990 // void operator delete(void*) noexcept;
2991 // void operator delete[](void*) noexcept;
2992 // void operator delete(void*, std::size_t) noexcept;
2993 // void operator delete[](void*, std::size_t) noexcept;
2994 //
2995 // These implicit declarations introduce only the function names operator
2996 // new, operator new[], operator delete, operator delete[].
2997 //
2998 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2999 // "std" or "bad_alloc" as necessary to form the exception specification.
3000 // However, we do not make these implicit declarations visible to name
3001 // lookup.
3002 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3003 // The "std::bad_alloc" class has not yet been declared, so build it
3004 // implicitly.
3008 &PP.getIdentifierTable().get("bad_alloc"),
3009 nullptr);
3010 getStdBadAlloc()->setImplicit(true);
3011
3012 // The implicitly declared "std::bad_alloc" should live in global module
3013 // fragment.
3014 if (TheGlobalModuleFragment) {
3017 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3018 }
3019 }
3020 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3021 // The "std::align_val_t" enum class has not yet been declared, so build it
3022 // implicitly.
3023 auto *AlignValT = EnumDecl::Create(
3025 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3026
3027 // The implicitly declared "std::align_val_t" should live in global module
3028 // fragment.
3029 if (TheGlobalModuleFragment) {
3030 AlignValT->setModuleOwnershipKind(
3032 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3033 }
3034
3035 AlignValT->setIntegerType(Context.getSizeType());
3036 AlignValT->setPromotionType(Context.getSizeType());
3037 AlignValT->setImplicit(true);
3038
3039 StdAlignValT = AlignValT;
3040 }
3041
3043
3045 QualType SizeT = Context.getSizeType();
3046
3047 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3048 QualType Return, QualType Param) {
3050 Params.push_back(Param);
3051
3052 // Create up to four variants of the function (sized/aligned).
3053 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3054 (Kind == OO_Delete || Kind == OO_Array_Delete);
3055 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3056
3057 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3058 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3059 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3060 if (Sized)
3061 Params.push_back(SizeT);
3062
3063 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3064 if (Aligned)
3065 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3066
3068 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3069
3070 if (Aligned)
3071 Params.pop_back();
3072 }
3073 }
3074 };
3075
3076 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3077 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3078 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3079 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3080
3081 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3082 PopGlobalModuleFragment();
3083}
3084
3085/// DeclareGlobalAllocationFunction - Declares a single implicit global
3086/// allocation function if it doesn't already exist.
3088 QualType Return,
3089 ArrayRef<QualType> Params) {
3091
3092 // Check if this function is already declared.
3093 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3094 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3095 Alloc != AllocEnd; ++Alloc) {
3096 // Only look at non-template functions, as it is the predefined,
3097 // non-templated allocation function we are trying to declare here.
3098 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3099 if (Func->getNumParams() == Params.size()) {
3101 for (auto *P : Func->parameters())
3102 FuncParams.push_back(
3103 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3104 if (llvm::ArrayRef(FuncParams) == Params) {
3105 // Make the function visible to name lookup, even if we found it in
3106 // an unimported module. It either is an implicitly-declared global
3107 // allocation function, or is suppressing that function.
3108 Func->setVisibleDespiteOwningModule();
3109 return;
3110 }
3111 }
3112 }
3113 }
3114
3116 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3117
3118 QualType BadAllocType;
3119 bool HasBadAllocExceptionSpec
3120 = (Name.getCXXOverloadedOperator() == OO_New ||
3121 Name.getCXXOverloadedOperator() == OO_Array_New);
3122 if (HasBadAllocExceptionSpec) {
3123 if (!getLangOpts().CPlusPlus11) {
3124 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3125 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3127 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3128 }
3129 if (getLangOpts().NewInfallible) {
3131 }
3132 } else {
3133 EPI.ExceptionSpec =
3135 }
3136
3137 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3138 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3140 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3141 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3142 true);
3143 Alloc->setImplicit();
3144 // Global allocation functions should always be visible.
3146
3147 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible)
3148 Alloc->addAttr(
3149 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3150
3151 // C++ [basic.stc.dynamic.general]p2:
3152 // The library provides default definitions for the global allocation
3153 // and deallocation functions. Some global allocation and deallocation
3154 // functions are replaceable ([new.delete]); these are attached to the
3155 // global module ([module.unit]).
3156 //
3157 // In the language wording, these functions are attched to the global
3158 // module all the time. But in the implementation, the global module
3159 // is only meaningful when we're in a module unit. So here we attach
3160 // these allocation functions to global module conditionally.
3161 if (TheGlobalModuleFragment) {
3164 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3165 }
3166
3167 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3168 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3169 ? VisibilityAttr::Hidden
3170 : VisibilityAttr::Default));
3171
3173 for (QualType T : Params) {
3174 ParamDecls.push_back(ParmVarDecl::Create(
3175 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3176 /*TInfo=*/nullptr, SC_None, nullptr));
3177 ParamDecls.back()->setImplicit();
3178 }
3179 Alloc->setParams(ParamDecls);
3180 if (ExtraAttr)
3181 Alloc->addAttr(ExtraAttr);
3184 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3185 };
3186
3187 if (!LangOpts.CUDA)
3188 CreateAllocationFunctionDecl(nullptr);
3189 else {
3190 // Host and device get their own declaration so each can be
3191 // defined or re-declared independently.
3192 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3193 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3194 }
3195}
3196
3198 bool CanProvideSize,
3199 bool Overaligned,
3200 DeclarationName Name) {
3202
3203 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3205
3206 // FIXME: It's possible for this to result in ambiguity, through a
3207 // user-declared variadic operator delete or the enable_if attribute. We
3208 // should probably not consider those cases to be usual deallocation
3209 // functions. But for now we just make an arbitrary choice in that case.
3210 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3211 Overaligned);
3212 assert(Result.FD && "operator delete missing from global scope?");
3213 return Result.FD;
3214}
3215
3217 CXXRecordDecl *RD) {
3219
3220 FunctionDecl *OperatorDelete = nullptr;
3221 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3222 return nullptr;
3223 if (OperatorDelete)
3224 return OperatorDelete;
3225
3226 // If there's no class-specific operator delete, look up the global
3227 // non-array delete.
3229 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3230 Name);
3231}
3232
3234 DeclarationName Name,
3235 FunctionDecl *&Operator, bool Diagnose,
3236 bool WantSize, bool WantAligned) {
3237 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3238 // Try to find operator delete/operator delete[] in class scope.
3239 LookupQualifiedName(Found, RD);
3240
3241 if (Found.isAmbiguous())
3242 return true;
3243
3244 Found.suppressDiagnostics();
3245
3246 bool Overaligned =
3247 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3248
3249 // C++17 [expr.delete]p10:
3250 // If the deallocation functions have class scope, the one without a
3251 // parameter of type std::size_t is selected.
3253 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3254 /*WantAlign*/ Overaligned, &Matches);
3255
3256 // If we could find an overload, use it.
3257 if (Matches.size() == 1) {
3258 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3259
3260 // FIXME: DiagnoseUseOfDecl?
3261 if (Operator->isDeleted()) {
3262 if (Diagnose) {
3263 Diag(StartLoc, diag::err_deleted_function_use);
3264 NoteDeletedFunction(Operator);
3265 }
3266 return true;
3267 }
3268
3269 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3270 Matches[0].Found, Diagnose) == AR_inaccessible)
3271 return true;
3272
3273 return false;
3274 }
3275
3276 // We found multiple suitable operators; complain about the ambiguity.
3277 // FIXME: The standard doesn't say to do this; it appears that the intent
3278 // is that this should never happen.
3279 if (!Matches.empty()) {
3280 if (Diagnose) {
3281 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3282 << Name << RD;
3283 for (auto &Match : Matches)
3284 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3285 }
3286 return true;
3287 }
3288
3289 // We did find operator delete/operator delete[] declarations, but
3290 // none of them were suitable.
3291 if (!Found.empty()) {
3292 if (Diagnose) {
3293 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3294 << Name << RD;
3295
3296 for (NamedDecl *D : Found)
3297 Diag(D->getUnderlyingDecl()->getLocation(),
3298 diag::note_member_declared_here) << Name;
3299 }
3300 return true;
3301 }
3302
3303 Operator = nullptr;
3304 return false;
3305}
3306
3307namespace {
3308/// Checks whether delete-expression, and new-expression used for
3309/// initializing deletee have the same array form.
3310class MismatchingNewDeleteDetector {
3311public:
3312 enum MismatchResult {
3313 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3314 NoMismatch,
3315 /// Indicates that variable is initialized with mismatching form of \a new.
3316 VarInitMismatches,
3317 /// Indicates that member is initialized with mismatching form of \a new.
3318 MemberInitMismatches,
3319 /// Indicates that 1 or more constructors' definitions could not been
3320 /// analyzed, and they will be checked again at the end of translation unit.
3321 AnalyzeLater
3322 };
3323
3324 /// \param EndOfTU True, if this is the final analysis at the end of
3325 /// translation unit. False, if this is the initial analysis at the point
3326 /// delete-expression was encountered.
3327 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3328 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3329 HasUndefinedConstructors(false) {}
3330
3331 /// Checks whether pointee of a delete-expression is initialized with
3332 /// matching form of new-expression.
3333 ///
3334 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3335 /// point where delete-expression is encountered, then a warning will be
3336 /// issued immediately. If return value is \c AnalyzeLater at the point where
3337 /// delete-expression is seen, then member will be analyzed at the end of
3338 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3339 /// couldn't be analyzed. If at least one constructor initializes the member
3340 /// with matching type of new, the return value is \c NoMismatch.
3341 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3342 /// Analyzes a class member.
3343 /// \param Field Class member to analyze.
3344 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3345 /// for deleting the \p Field.
3346 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3348 /// List of mismatching new-expressions used for initialization of the pointee
3350 /// Indicates whether delete-expression was in array form.
3351 bool IsArrayForm;
3352
3353private:
3354 const bool EndOfTU;
3355 /// Indicates that there is at least one constructor without body.
3356 bool HasUndefinedConstructors;
3357 /// Returns \c CXXNewExpr from given initialization expression.
3358 /// \param E Expression used for initializing pointee in delete-expression.
3359 /// E can be a single-element \c InitListExpr consisting of new-expression.
3360 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3361 /// Returns whether member is initialized with mismatching form of
3362 /// \c new either by the member initializer or in-class initialization.
3363 ///
3364 /// If bodies of all constructors are not visible at the end of translation
3365 /// unit or at least one constructor initializes member with the matching
3366 /// form of \c new, mismatch cannot be proven, and this function will return
3367 /// \c NoMismatch.
3368 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3369 /// Returns whether variable is initialized with mismatching form of
3370 /// \c new.
3371 ///
3372 /// If variable is initialized with matching form of \c new or variable is not
3373 /// initialized with a \c new expression, this function will return true.
3374 /// If variable is initialized with mismatching form of \c new, returns false.
3375 /// \param D Variable to analyze.
3376 bool hasMatchingVarInit(const DeclRefExpr *D);
3377 /// Checks whether the constructor initializes pointee with mismatching
3378 /// form of \c new.
3379 ///
3380 /// Returns true, if member is initialized with matching form of \c new in
3381 /// member initializer list. Returns false, if member is initialized with the
3382 /// matching form of \c new in this constructor's initializer or given
3383 /// constructor isn't defined at the point where delete-expression is seen, or
3384 /// member isn't initialized by the constructor.
3385 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3386 /// Checks whether member is initialized with matching form of
3387 /// \c new in member initializer list.
3388 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3389 /// Checks whether member is initialized with mismatching form of \c new by
3390 /// in-class initializer.
3391 MismatchResult analyzeInClassInitializer();
3392};
3393}
3394
3395MismatchingNewDeleteDetector::MismatchResult
3396MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3397 NewExprs.clear();
3398 assert(DE && "Expected delete-expression");
3399 IsArrayForm = DE->isArrayForm();
3400 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3401 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3402 return analyzeMemberExpr(ME);
3403 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3404 if (!hasMatchingVarInit(D))
3405 return VarInitMismatches;
3406 }
3407 return NoMismatch;
3408}
3409
3410const CXXNewExpr *
3411MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3412 assert(E != nullptr && "Expected a valid initializer expression");
3413 E = E->IgnoreParenImpCasts();
3414 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3415 if (ILE->getNumInits() == 1)
3416 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3417 }
3418
3419 return dyn_cast_or_null<const CXXNewExpr>(E);
3420}
3421
3422bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3423 const CXXCtorInitializer *CI) {
3424 const CXXNewExpr *NE = nullptr;
3425 if (Field == CI->getMember() &&
3426 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3427 if (NE->isArray() == IsArrayForm)
3428 return true;
3429 else
3430 NewExprs.push_back(NE);
3431 }
3432 return false;
3433}
3434
3435bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3436 const CXXConstructorDecl *CD) {
3437 if (CD->isImplicit())
3438 return false;
3439 const FunctionDecl *Definition = CD;
3441 HasUndefinedConstructors = true;
3442 return EndOfTU;
3443 }
3444 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3445 if (hasMatchingNewInCtorInit(CI))
3446 return true;
3447 }
3448 return false;
3449}
3450
3451MismatchingNewDeleteDetector::MismatchResult
3452MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3453 assert(Field != nullptr && "This should be called only for members");
3454 const Expr *InitExpr = Field->getInClassInitializer();
3455 if (!InitExpr)
3456 return EndOfTU ? NoMismatch : AnalyzeLater;
3457 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3458 if (NE->isArray() != IsArrayForm) {
3459 NewExprs.push_back(NE);
3460 return MemberInitMismatches;
3461 }
3462 }
3463 return NoMismatch;
3464}
3465
3466MismatchingNewDeleteDetector::MismatchResult
3467MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3468 bool DeleteWasArrayForm) {
3469 assert(Field != nullptr && "Analysis requires a valid class member.");
3470 this->Field = Field;
3471 IsArrayForm = DeleteWasArrayForm;
3472 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3473 for (const auto *CD : RD->ctors()) {
3474 if (hasMatchingNewInCtor(CD))
3475 return NoMismatch;
3476 }
3477 if (HasUndefinedConstructors)
3478 return EndOfTU ? NoMismatch : AnalyzeLater;
3479 if (!NewExprs.empty())
3480 return MemberInitMismatches;
3481 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3482 : NoMismatch;
3483}
3484
3485MismatchingNewDeleteDetector::MismatchResult
3486MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3487 assert(ME != nullptr && "Expected a member expression");
3488 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3489 return analyzeField(F, IsArrayForm);
3490 return NoMismatch;
3491}
3492
3493bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3494 const CXXNewExpr *NE = nullptr;
3495 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3496 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3497 NE->isArray() != IsArrayForm) {
3498 NewExprs.push_back(NE);
3499 }
3500 }
3501 return NewExprs.empty();
3502}
3503
3504static void
3506 const MismatchingNewDeleteDetector &Detector) {
3507 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3508 FixItHint H;
3509 if (!Detector.IsArrayForm)
3510 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3511 else {
3513 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3514 SemaRef.getLangOpts(), true);
3515 if (RSquare.isValid())
3516 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3517 }
3518 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3519 << Detector.IsArrayForm << H;
3520
3521 for (const auto *NE : Detector.NewExprs)
3522 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3523 << Detector.IsArrayForm;
3524}
3525
3526void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3527 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3528 return;
3529 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3530 switch (Detector.analyzeDeleteExpr(DE)) {
3531 case MismatchingNewDeleteDetector::VarInitMismatches:
3532 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3533 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3534 break;
3535 }
3536 case MismatchingNewDeleteDetector::AnalyzeLater: {
3537 DeleteExprs[Detector.Field].push_back(
3538 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3539 break;
3540 }
3541 case MismatchingNewDeleteDetector::NoMismatch:
3542 break;
3543 }
3544}
3545
3546void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3547 bool DeleteWasArrayForm) {
3548 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3549 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3550 case MismatchingNewDeleteDetector::VarInitMismatches:
3551 llvm_unreachable("This analysis should have been done for class members.");
3552 case MismatchingNewDeleteDetector::AnalyzeLater:
3553 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3554 "translation unit.");
3555 case MismatchingNewDeleteDetector::MemberInitMismatches:
3556 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3557 break;
3558 case MismatchingNewDeleteDetector::NoMismatch:
3559 break;
3560 }
3561}
3562
3563/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3564/// @code ::delete ptr; @endcode
3565/// or
3566/// @code delete [] ptr; @endcode
3568Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3569 bool ArrayForm, Expr *ExE) {
3570 // C++ [expr.delete]p1:
3571 // The operand shall have a pointer type, or a class type having a single
3572 // non-explicit conversion function to a pointer type. The result has type
3573 // void.
3574 //
3575 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3576
3577 ExprResult Ex = ExE;
3578 FunctionDecl *OperatorDelete = nullptr;
3579 bool ArrayFormAsWritten = ArrayForm;
3580 bool UsualArrayDeleteWantsSize = false;
3581
3582 if (!Ex.get()->isTypeDependent()) {
3583 // Perform lvalue-to-rvalue cast, if needed.
3584 Ex = DefaultLvalueConversion(Ex.get());
3585 if (Ex.isInvalid())
3586 return ExprError();
3587
3588 QualType Type = Ex.get()->getType();
3589
3590 class DeleteConverter : public ContextualImplicitConverter {
3591 public:
3592 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3593
3594 bool match(QualType ConvType) override {
3595 // FIXME: If we have an operator T* and an operator void*, we must pick
3596 // the operator T*.
3597 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3598 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3599 return true;
3600 return false;
3601 }
3602
3603 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3604 QualType T) override {
3605 return S.Diag(Loc, diag::err_delete_operand) << T;
3606 }
3607
3608 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3609 QualType T) override {
3610 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3611 }
3612
3613 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3614 QualType T,
3615 QualType ConvTy) override {
3616 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3617 }
3618
3619 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3620 QualType ConvTy) override {
3621 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3622 << ConvTy;
3623 }
3624
3625 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3626 QualType T) override {
3627 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3628 }
3629
3630 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3631 QualType ConvTy) override {
3632 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3633 << ConvTy;
3634 }
3635
3636 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3637 QualType T,
3638 QualType ConvTy) override {
3639 llvm_unreachable("conversion functions are permitted");
3640 }
3641 } Converter;
3642
3643 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3644 if (Ex.isInvalid())
3645 return ExprError();
3646 Type = Ex.get()->getType();
3647 if (!Converter.match(Type))
3648 // FIXME: PerformContextualImplicitConversion should return ExprError
3649 // itself in this case.
3650 return ExprError();
3651
3652 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3653 QualType PointeeElem = Context.getBaseElementType(Pointee);
3654
3655 if (Pointee.getAddressSpace() != LangAS::Default &&
3656 !getLangOpts().OpenCLCPlusPlus)
3657 return Diag(Ex.get()->getBeginLoc(),
3658 diag::err_address_space_qualified_delete)
3659 << Pointee.getUnqualifiedType()
3661
3662 CXXRecordDecl *PointeeRD = nullptr;
3663 if (Pointee->isVoidType() && !isSFINAEContext()) {
3664 // The C++ standard bans deleting a pointer to a non-object type, which
3665 // effectively bans deletion of "void*". However, most compilers support
3666 // this, so we treat it as a warning unless we're in a SFINAE context.
3667 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3668 << Type << Ex.get()->getSourceRange();
3669 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3670 Pointee->isSizelessType()) {
3671 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3672 << Type << Ex.get()->getSourceRange());
3673 } else if (!Pointee->isDependentType()) {
3674 // FIXME: This can result in errors if the definition was imported from a
3675 // module but is hidden.
3676 if (!RequireCompleteType(StartLoc, Pointee,
3677 diag::warn_delete_incomplete, Ex.get())) {
3678 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3679 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3680 }
3681 }
3682
3683 if (Pointee->isArrayType() && !ArrayForm) {
3684 Diag(StartLoc, diag::warn_delete_array_type)
3685 << Type << Ex.get()->getSourceRange()
3687 ArrayForm = true;
3688 }
3689
3691 ArrayForm ? OO_Array_Delete : OO_Delete);
3692
3693 if (PointeeRD) {
3694 if (!UseGlobal &&
3695 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3696 OperatorDelete))
3697 return ExprError();
3698
3699 // If we're allocating an array of records, check whether the
3700 // usual operator delete[] has a size_t parameter.
3701 if (ArrayForm) {
3702 // If the user specifically asked to use the global allocator,
3703 // we'll need to do the lookup into the class.
3704 if (UseGlobal)
3705 UsualArrayDeleteWantsSize =
3706 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3707
3708 // Otherwise, the usual operator delete[] should be the
3709 // function we just found.
3710 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3711 UsualArrayDeleteWantsSize =
3712 UsualDeallocFnInfo(*this,
3713 DeclAccessPair::make(OperatorDelete, AS_public))
3714 .HasSizeT;
3715 }
3716
3717 if (!PointeeRD->hasIrrelevantDestructor())
3718 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3719 MarkFunctionReferenced(StartLoc,
3720 const_cast<CXXDestructorDecl*>(Dtor));
3721 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3722 return ExprError();
3723 }
3724
3725 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3726 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3727 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3728 SourceLocation());
3729 }
3730
3731 if (!OperatorDelete) {
3732 if (getLangOpts().OpenCLCPlusPlus) {
3733 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3734 return ExprError();
3735 }
3736
3737 bool IsComplete = isCompleteType(StartLoc, Pointee);
3738 bool CanProvideSize =
3739 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3740 Pointee.isDestructedType());
3741 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3742
3743 // Look for a global declaration.
3744 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3745 Overaligned, DeleteName);
3746 }
3747
3748 MarkFunctionReferenced(StartLoc, OperatorDelete);
3749
3750 // Check access and ambiguity of destructor if we're going to call it.
3751 // Note that this is required even for a virtual delete.
3752 bool IsVirtualDelete = false;
3753 if (PointeeRD) {
3754 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3755 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3756 PDiag(diag::err_access_dtor) << PointeeElem);
3757 IsVirtualDelete = Dtor->isVirtual();
3758 }
3759 }
3760
3761 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3762
3763 // Convert the operand to the type of the first parameter of operator
3764 // delete. This is only necessary if we selected a destroying operator
3765 // delete that we are going to call (non-virtually); converting to void*
3766 // is trivial and left to AST consumers to handle.
3767 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3768 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3769 Qualifiers Qs = Pointee.getQualifiers();
3770 if (Qs.hasCVRQualifiers()) {
3771 // Qualifiers are irrelevant to this conversion; we're only looking
3772 // for access and ambiguity.
3776 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3777 }
3778 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3779 if (Ex.isInvalid())
3780 return ExprError();
3781 }
3782 }
3783
3785 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3786 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3787 AnalyzeDeleteExprMismatch(Result);
3788 return Result;
3789}
3790
3792 bool IsDelete,
3793 FunctionDecl *&Operator) {
3794
3796 IsDelete ? OO_Delete : OO_New);
3797
3798 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3800 assert(!R.empty() && "implicitly declared allocation functions not found");
3801 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3802
3803 // We do our own custom access checks below.
3805
3806 SmallVector<Expr *, 8> Args(TheCall->arguments());
3807 OverloadCandidateSet Candidates(R.getNameLoc(),
3809 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3810 FnOvl != FnOvlEnd; ++FnOvl) {
3811 // Even member operator new/delete are implicitly treated as
3812 // static, so don't use AddMemberCandidate.
3813 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3814
3815 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3816 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3817 /*ExplicitTemplateArgs=*/nullptr, Args,
3818 Candidates,
3819 /*SuppressUserConversions=*/false);
3820 continue;
3821 }
3822
3823 FunctionDecl *Fn = cast<FunctionDecl>(D);
3824 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3825 /*SuppressUserConversions=*/false);
3826 }
3827
3828 SourceRange Range = TheCall->getSourceRange();
3829
3830 // Do the resolution.
3832 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3833 case OR_Success: {
3834 // Got one!
3835 FunctionDecl *FnDecl = Best->Function;
3836 assert(R.getNamingClass() == nullptr &&
3837 "class members should not be considered");
3838
3840 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3841 << (IsDelete ? 1 : 0) << Range;
3842 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3843 << R.getLookupName() << FnDecl->getSourceRange();
3844 return true;
3845 }
3846
3847 Operator = FnDecl;
3848 return false;
3849 }
3850
3852 Candidates.NoteCandidates(
3854 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3855 << R.getLookupName() << Range),
3856 S, OCD_AllCandidates, Args);
3857 return true;
3858
3859 case OR_Ambiguous:
3860 Candidates.NoteCandidates(
3862 S.PDiag(diag::err_ovl_ambiguous_call)
3863 << R.getLookupName() << Range),
3864 S, OCD_AmbiguousCandidates, Args);
3865 return true;
3866
3867 case OR_Deleted: {
3868 Candidates.NoteCandidates(
3869 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3870 << R.getLookupName() << Range),
3871 S, OCD_AllCandidates, Args);
3872 return true;
3873 }
3874 }
3875 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3876}
3877
3879Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3880 bool IsDelete) {
3881 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3882 if (!getLangOpts().CPlusPlus) {
3883 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3884 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3885 << "C++";
3886 return ExprError();
3887 }
3888 // CodeGen assumes it can find the global new and delete to call,
3889 // so ensure that they are declared.
3891
3892 FunctionDecl *OperatorNewOrDelete = nullptr;
3893 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3894 OperatorNewOrDelete))
3895 return ExprError();
3896 assert(OperatorNewOrDelete && "should be found");
3897
3898 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3899 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3900
3901 TheCall->setType(OperatorNewOrDelete->getReturnType());
3902 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3903 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3904 InitializedEntity Entity =
3907 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3908 if (Arg.isInvalid())
3909 return ExprError();
3910 TheCall->setArg(i, Arg.get());
3911 }
3912 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3913 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3914 "Callee expected to be implicit cast to a builtin function pointer");
3915 Callee->setType(OperatorNewOrDelete->getType());
3916
3917 return TheCallResult;
3918}
3919
3921 bool IsDelete, bool CallCanBeVirtual,
3922 bool WarnOnNonAbstractTypes,
3923 SourceLocation DtorLoc) {
3924 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3925 return;
3926
3927 // C++ [expr.delete]p3:
3928 // In the first alternative (delete object), if the static type of the
3929 // object to be deleted is different from its dynamic type, the static
3930 // type shall be a base class of the dynamic type of the object to be
3931 // deleted and the static type shall have a virtual destructor or the
3932 // behavior is undefined.
3933 //
3934 const CXXRecordDecl *PointeeRD = dtor->getParent();
3935 // Note: a final class cannot be derived from, no issue there
3936 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3937 return;
3938
3939 // If the superclass is in a system header, there's nothing that can be done.
3940 // The `delete` (where we emit the warning) can be in a system header,
3941 // what matters for this warning is where the deleted type is defined.
3942 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3943 return;
3944
3945 QualType ClassType = dtor->getThisType()->getPointeeType();
3946 if (PointeeRD->isAbstract()) {
3947 // If the class is abstract, we warn by default, because we're
3948 // sure the code has undefined behavior.
3949 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3950 << ClassType;
3951 } else if (WarnOnNonAbstractTypes) {
3952 // Otherwise, if this is not an array delete, it's a bit suspect,
3953 // but not necessarily wrong.
3954 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3955 << ClassType;
3956 }
3957 if (!IsDelete) {
3958 std::string TypeStr;
3959 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3960 Diag(DtorLoc, diag::note_delete_non_virtual)
3961 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3962 }
3963}
3964
3966 SourceLocation StmtLoc,
3967 ConditionKind CK) {
3968 ExprResult E =
3969 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3970 if (E.isInvalid())
3971 return ConditionError();
3972 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3974}
3975
3976/// Check the use of the given variable as a C++ condition in an if,
3977/// while, do-while, or switch statement.
3979 SourceLocation StmtLoc,
3980 ConditionKind CK) {
3981 if (ConditionVar->isInvalidDecl())
3982 return ExprError();
3983
3984 QualType T = ConditionVar->getType();
3985
3986 // C++ [stmt.select]p2:
3987 // The declarator shall not specify a function or an array.
3988 if (T->isFunctionType())
3989 return ExprError(Diag(ConditionVar->getLocation(),
3990 diag::err_invalid_use_of_function_type)
3991 << ConditionVar->getSourceRange());
3992 else if (T->isArrayType())
3993 return ExprError(Diag(ConditionVar->getLocation(),
3994 diag::err_invalid_use_of_array_type)
3995 << ConditionVar->getSourceRange());
3996
3998 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3999 ConditionVar->getLocation());
4000
4001 switch (CK) {
4003 return CheckBooleanCondition(StmtLoc, Condition.get());
4004
4006 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4007
4009 return CheckSwitchCondition(StmtLoc, Condition.get());
4010 }
4011
4012 llvm_unreachable("unexpected condition kind");
4013}
4014
4015/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4016ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4017 // C++11 6.4p4:
4018 // The value of a condition that is an initialized declaration in a statement
4019 // other than a switch statement is the value of the declared variable
4020 // implicitly converted to type bool. If that conversion is ill-formed, the
4021 // program is ill-formed.
4022 // The value of a condition that is an expression is the value of the
4023 // expression, implicitly converted to bool.
4024 //
4025 // C++23 8.5.2p2
4026 // If the if statement is of the form if constexpr, the value of the condition
4027 // is contextually converted to bool and the converted expression shall be
4028 // a constant expression.
4029 //
4030
4032 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4033 return E;
4034
4035 // FIXME: Return this value to the caller so they don't need to recompute it.
4036 llvm::APSInt Cond;
4038 E.get(), &Cond,
4039 diag::err_constexpr_if_condition_expression_is_not_constant);
4040 return E;
4041}
4042
4043/// Helper function to determine whether this is the (deprecated) C++
4044/// conversion from a string literal to a pointer to non-const char or
4045/// non-const wchar_t (for narrow and wide string literals,
4046/// respectively).
4047bool
4049 // Look inside the implicit cast, if it exists.
4050 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4051 From = Cast->getSubExpr();
4052
4053 // A string literal (2.13.4) that is not a wide string literal can
4054 // be converted to an rvalue of type "pointer to char"; a wide
4055 // string literal can be converted to an rvalue of type "pointer
4056 // to wchar_t" (C++ 4.2p2).
4057 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4058 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4059 if (const BuiltinType *ToPointeeType
4060 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4061 // This conversion is considered only when there is an
4062 // explicit appropriate pointer target type (C++ 4.2p2).
4063 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4064 switch (StrLit->getKind()) {
4068 // We don't allow UTF literals to be implicitly converted
4069 break;
4071 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4072 ToPointeeType->getKind() == BuiltinType::Char_S);
4075 QualType(ToPointeeType, 0));
4076 }
4077 }
4078 }
4079
4080 return false;
4081}
4082
4084 SourceLocation CastLoc,
4085 QualType Ty,
4086 CastKind Kind,
4087 CXXMethodDecl *Method,
4088 DeclAccessPair FoundDecl,
4089 bool HadMultipleCandidates,
4090 Expr *From) {
4091 switch (Kind) {
4092 default: llvm_unreachable("Unhandled cast kind!");
4093 case CK_ConstructorConversion: {
4094 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4095 SmallVector<Expr*, 8> ConstructorArgs;
4096
4097 if (S.RequireNonAbstractType(CastLoc, Ty,
4098 diag::err_allocation_of_abstract_type))
4099 return ExprError();
4100
4101 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4102 ConstructorArgs))
4103 return ExprError();
4104
4105 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4107 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4108 return ExprError();
4109
4111 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4112 ConstructorArgs, HadMultipleCandidates,
4113 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4115 if (Result.isInvalid())
4116 return ExprError();
4117
4118 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4119 }
4120
4121 case CK_UserDefinedConversion: {
4122 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4123
4124 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4125 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4126 return ExprError();
4127
4128 // Create an implicit call expr that calls it.
4129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4130 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4131 HadMultipleCandidates);
4132 if (Result.isInvalid())
4133 return ExprError();
4134 // Record usage of conversion in an implicit cast.
4135 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4136 CK_UserDefinedConversion, Result.get(),
4137 nullptr, Result.get()->getValueKind(),
4139
4140 return S.MaybeBindToTemporary(Result.get());
4141 }
4142 }
4143}
4144
4145/// PerformImplicitConversion - Perform an implicit conversion of the
4146/// expression From to the type ToType using the pre-computed implicit
4147/// conversion sequence ICS. Returns the converted
4148/// expression. Action is the kind of conversion we're performing,
4149/// used in the error message.
4152 const ImplicitConversionSequence &ICS,
4153 AssignmentAction Action,
4155 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4156 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
4157 return From;
4158
4159 switch (ICS.getKind()) {
4161 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4162 Action, CCK);
4163 if (Res.isInvalid())
4164 return ExprError();
4165 From = Res.get();
4166 break;
4167 }
4168
4170
4173 QualType BeforeToType;
4174 assert(FD && "no conversion function for user-defined conversion seq");
4175 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4176 CastKind = CK_UserDefinedConversion;
4177
4178 // If the user-defined conversion is specified by a conversion function,
4179 // the initial standard conversion sequence converts the source type to
4180 // the implicit object parameter of the conversion function.
4181 BeforeToType = Context.getTagDeclType(Conv->getParent());
4182 } else {
4183 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4184 CastKind = CK_ConstructorConversion;
4185 // Do no conversion if dealing with ... for the first conversion.
4187 // If the user-defined conversion is specified by a constructor, the
4188 // initial standard conversion sequence converts the source type to
4189 // the type required by the argument of the constructor
4190 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4191 }
4192 }
4193 // Watch out for ellipsis conversion.
4195 ExprResult Res =
4196 PerformImplicitConversion(From, BeforeToType,
4198 CCK);
4199 if (Res.isInvalid())
4200 return ExprError();
4201 From = Res.get();
4202 }
4203
4205 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4206 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4208
4209 if (CastArg.isInvalid())
4210 return ExprError();
4211
4212 From = CastArg.get();
4213
4214 // C++ [over.match.oper]p7:
4215 // [...] the second standard conversion sequence of a user-defined
4216 // conversion sequence is not applied.
4217 if (CCK == CCK_ForBuiltinOverloadedOp)
4218 return From;
4219
4220 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4221 AA_Converting, CCK);
4222 }
4223
4225 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4226 PDiag(diag::err_typecheck_ambiguous_condition)
4227 << From->getSourceRange());
4228 return ExprError();
4229
4232 llvm_unreachable("bad conversion");
4233
4236 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4237 bool Diagnosed = DiagnoseAssignmentResult(
4238 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4239 ToType, From->getType(), From, Action);
4240 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4241 return ExprError();
4242 }
4243
4244 // Everything went well.
4245 return From;
4246}
4247
4248/// PerformImplicitConversion - Perform an implicit conversion of the
4249/// expression From to the type ToType by following the standard
4250/// conversion sequence SCS. Returns the converted
4251/// expression. Flavor is the context in which we're performing this
4252/// conversion, for use in error messages.
4255 const StandardConversionSequence& SCS,
4256 AssignmentAction Action,
4258 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
4259
4260 // Overall FIXME: we are recomputing too many types here and doing far too
4261 // much extra work. What this means is that we need to keep track of more
4262 // information that is computed when we try the implicit conversion initially,
4263 // so that we don't need to recompute anything here.
4264 QualType FromType = From->getType();
4265
4266 if (SCS.CopyConstructor) {
4267 // FIXME: When can ToType be a reference type?
4268 assert(!ToType->isReferenceType());
4269 if (SCS.Second == ICK_Derived_To_Base) {
4270 SmallVector<Expr*, 8> ConstructorArgs;
4272 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4273 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4274 return ExprError();
4275 return BuildCXXConstructExpr(
4276 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4278 ConstructorArgs, /*HadMultipleCandidates*/ false,
4279 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4281 }
4282 return BuildCXXConstructExpr(
4283 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4285 From, /*HadMultipleCandidates*/ false,
4286 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4288 }
4289
4290 // Resolve overloaded function references.
4291 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4292 DeclAccessPair Found;
4294 true, Found);
4295 if (!Fn)
4296 return ExprError();
4297
4298 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4299 return ExprError();
4300
4301 From = FixOverloadedFunctionReference(From, Found, Fn);
4302
4303 // We might get back another placeholder expression if we resolved to a
4304 // builtin.
4305 ExprResult Checked = CheckPlaceholderExpr(From);
4306 if (Checked.isInvalid())
4307 return ExprError();
4308
4309 From = Checked.get();
4310 FromType = From->getType();
4311 }
4312
4313 // If we're converting to an atomic type, first convert to the corresponding
4314 // non-atomic type.
4315 QualType ToAtomicType;
4316 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4317 ToAtomicType = ToType;
4318 ToType = ToAtomic->getValueType();
4319 }
4320
4321 QualType InitialFromType = FromType;
4322 // Perform the first implicit conversion.
4323 switch (SCS.First) {
4324 case ICK_Identity:
4325 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4326 FromType = FromAtomic->getValueType().getUnqualifiedType();
4327 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4328 From, /*BasePath=*/nullptr, VK_PRValue,
4330 }
4331 break;
4332
4333 case ICK_Lvalue_To_Rvalue: {
4334 assert(From->getObjectKind() != OK_ObjCProperty);
4335 ExprResult FromRes = DefaultLvalueConversion(From);
4336 if (FromRes.isInvalid())
4337 return ExprError();
4338
4339 From = FromRes.get();
4340 FromType = From->getType();
4341 break;
4342 }
4343
4345 FromType = Context.getArrayDecayedType(FromType);
4346 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4347 /*BasePath=*/nullptr, CCK)
4348 .get();
4349 break;
4350
4352 FromType = Context.getPointerType(FromType);
4353 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4354 VK_PRValue, /*BasePath=*/nullptr, CCK)
4355 .get();
4356 break;
4357
4358 default:
4359 llvm_unreachable("Improper first standard conversion");
4360 }
4361
4362 // Perform the second implicit conversion
4363 switch (SCS.Second) {
4364 case ICK_Identity:
4365 // C++ [except.spec]p5:
4366 // [For] assignment to and initialization of pointers to functions,
4367 // pointers to member functions, and references to functions: the
4368 // target entity shall allow at least the exceptions allowed by the
4369 // source value in the assignment or initialization.
4370 switch (Action) {
4371 case AA_Assigning:
4372 case AA_Initializing:
4373 // Note, function argument passing and returning are initialization.
4374 case AA_Passing:
4375 case AA_Returning:
4376 case AA_Sending:
4378 if (CheckExceptionSpecCompatibility(From, ToType))
4379 return ExprError();
4380 break;
4381
4382 case AA_Casting:
4383 case AA_Converting:
4384 // Casts and implicit conversions are not initialization, so are not
4385 // checked for exception specification mismatches.
4386 break;
4387 }
4388 // Nothing else to do.
4389 break;
4390
4393 if (ToType->isBooleanType()) {
4394 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4396 "only enums with fixed underlying type can promote to bool");
4397 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4398 /*BasePath=*/nullptr, CCK)
4399 .get();
4400 } else {
4401 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4402 /*BasePath=*/nullptr, CCK)
4403 .get();
4404 }
4405 break;
4406
4409 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4410 /*BasePath=*/nullptr, CCK)
4411 .get();
4412 break;
4413
4416 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4417 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4418 CastKind CK;
4419 if (FromEl->isRealFloatingType()) {
4420 if (ToEl->isRealFloatingType())
4421 CK = CK_FloatingComplexCast;
4422 else
4423 CK = CK_FloatingComplexToIntegralComplex;
4424 } else if (ToEl->isRealFloatingType()) {
4425 CK = CK_IntegralComplexToFloatingComplex;
4426 } else {
4427 CK = CK_IntegralComplexCast;
4428 }
4429 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4430 CCK)
4431 .get();
4432 break;
4433 }
4434
4436 if (ToType->isRealFloatingType())
4437 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4438 /*BasePath=*/nullptr, CCK)
4439 .get();
4440 else
4441 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4442 /*BasePath=*/nullptr, CCK)
4443 .get();
4444 break;
4445
4447 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4448 /*BasePath=*/nullptr, CCK).get();
4449 break;
4450
4453 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4454 // Diagnose incompatible Objective-C conversions
4455 if (Action == AA_Initializing || Action == AA_Assigning)
4456 Diag(From->getBeginLoc(),
4457 diag::ext_typecheck_convert_incompatible_pointer)
4458 << ToType << From->getType() << Action << From->getSourceRange()
4459 << 0;
4460 else
4461 Diag(From->getBeginLoc(),
4462 diag::ext_typecheck_convert_incompatible_pointer)
4463 << From->getType() << ToType << Action << From->getSourceRange()
4464 << 0;
4465
4466 if (From->getType()->isObjCObjectPointerType() &&
4467 ToType->isObjCObjectPointerType())
4469 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4471 From->getType())) {
4472 if (Action == AA_Initializing)
4473 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4474 else
4475 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4476 << (Action == AA_Casting) << From->getType() << ToType
4477 << From->getSourceRange();
4478 }
4479
4480 // Defer address space conversion to the third conversion.
4481 QualType FromPteeType = From->getType()->getPointeeType();
4482 QualType ToPteeType = ToType->getPointeeType();
4483 QualType NewToType = ToType;
4484 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4485 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4486 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4487 NewToType = Context.getAddrSpaceQualType(NewToType,
4488 FromPteeType.getAddressSpace());
4489 if (ToType->isObjCObjectPointerType())
4490 NewToType = Context.getObjCObjectPointerType(NewToType);
4491 else if (ToType->isBlockPointerType())
4492 NewToType = Context.getBlockPointerType(NewToType);
4493 else
4494 NewToType = Context.getPointerType(NewToType);
4495 }
4496
4497 CastKind Kind;
4498 CXXCastPath BasePath;
4499 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4500 return ExprError();
4501
4502 // Make sure we extend blocks if necessary.
4503 // FIXME: doing this here is really ugly.
4504 if (Kind == CK_BlockPointerToObjCPointerCast) {
4505 ExprResult E = From;
4507 From = E.get();
4508 }
4510 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4511 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4512 .get();
4513 break;
4514 }
4515
4516 case ICK_Pointer_Member: {
4517 CastKind Kind;
4518 CXXCastPath BasePath;
4519 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4520 return ExprError();
4521 if (CheckExceptionSpecCompatibility(From, ToType))
4522 return ExprError();
4523
4524 // We may not have been able to figure out what this member pointer resolved
4525 // to up until this exact point. Attempt to lock-in it's inheritance model.
4527 (void)isCompleteType(From->getExprLoc(), From->getType());
4528 (void)isCompleteType(From->getExprLoc(), ToType);
4529 }
4530
4531 From =
4532 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4533 break;
4534 }
4535
4537 // Perform half-to-boolean conversion via float.
4538 if (From->getType()->isHalfType()) {
4539 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4540 FromType = Context.FloatTy;
4541 }
4542
4543 From = ImpCastExprToType(From, Context.BoolTy,
4545 /*BasePath=*/nullptr, CCK)
4546 .get();
4547 break;
4548
4549 case ICK_Derived_To_Base: {
4550 CXXCastPath BasePath;
4552 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4553 From->getSourceRange(), &BasePath, CStyle))
4554 return ExprError();
4555
4556 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4557 CK_DerivedToBase, From->getValueKind(),
4558 &BasePath, CCK).get();
4559 break;
4560 }
4561
4563 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4564 /*BasePath=*/nullptr, CCK)
4565 .get();
4566 break;
4567
4570 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4571 /*BasePath=*/nullptr, CCK)
4572 .get();
4573 break;
4574
4575 case ICK_Vector_Splat: {
4576 // Vector splat from any arithmetic type to a vector.
4577 Expr *Elem = prepareVectorSplat(ToType, From).get();
4578 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4579 /*BasePath=*/nullptr, CCK)
4580 .get();
4581 break;
4582 }
4583
4584 case ICK_Complex_Real:
4585 // Case 1. x -> _Complex y
4586 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4587 QualType ElType = ToComplex->getElementType();
4588 bool isFloatingComplex = ElType->isRealFloatingType();
4589
4590 // x -> y
4591 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4592 // do nothing
4593 } else if (From->getType()->isRealFloatingType()) {
4594 From = ImpCastExprToType(From, ElType,
4595 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4596 } else {
4597 assert(From->getType()->isIntegerType());
4598 From = ImpCastExprToType(From, ElType,
4599 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4600 }
4601 // y -> _Complex y
4602 From = ImpCastExprToType(From, ToType,
4603 isFloatingComplex ? CK_FloatingRealToComplex
4604 : CK_IntegralRealToComplex).get();
4605
4606 // Case 2. _Complex x -> y
4607 } else {
4608 auto *FromComplex = From->getType()->castAs<ComplexType>();
4609 QualType ElType = FromComplex->getElementType();
4610 bool isFloatingComplex = ElType->isRealFloatingType();
4611
4612 // _Complex x -> x
4613 From = ImpCastExprToType(From, ElType,
4614 isFloatingComplex ? CK_FloatingComplexToReal
4615 : CK_IntegralComplexToReal,
4616 VK_PRValue, /*BasePath=*/nullptr, CCK)
4617 .get();
4618
4619 // x -> y
4620 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4621 // do nothing
4622 } else if (ToType->isRealFloatingType()) {
4623 From = ImpCastExprToType(From, ToType,
4624 isFloatingComplex ? CK_FloatingCast
4625 : CK_IntegralToFloating,
4626 VK_PRValue, /*BasePath=*/nullptr, CCK)
4627 .get();
4628 } else {
4629 assert(ToType->isIntegerType());
4630 From = ImpCastExprToType(From, ToType,
4631 isFloatingComplex ? CK_FloatingToIntegral
4632 : CK_IntegralCast,
4633 VK_PRValue, /*BasePath=*/nullptr, CCK)
4634 .get();
4635 }
4636 }
4637 break;
4638
4640 LangAS AddrSpaceL =
4641 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4642 LangAS AddrSpaceR =
4643 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4644 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4645 "Invalid cast");
4646 CastKind Kind =
4647 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4648 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4649 VK_PRValue, /*BasePath=*/nullptr, CCK)
4650 .get();
4651 break;
4652 }
4653
4655 ExprResult FromRes = From;
4658 if (FromRes.isInvalid())
4659 return ExprError();
4660 From = FromRes.get();
4661 assert ((ConvTy == Sema::Compatible) &&
4662 "Improper transparent union conversion");
4663 (void)ConvTy;
4664 break;
4665 }
4666
4669 From = ImpCastExprToType(From, ToType,
4670 CK_ZeroToOCLOpaqueType,
4671 From->getValueKind()).get();
4672 break;
4673
4678 case ICK_Qualification:
4682 llvm_unreachable("Improper second standard conversion");
4683 }
4684
4685 switch (SCS.Third) {
4686 case ICK_Identity:
4687 // Nothing to do.
4688 break;
4689
4691 // If both sides are functions (or pointers/references to them), there could
4692 // be incompatible exception declarations.
4693 if (CheckExceptionSpecCompatibility(From, ToType))
4694 return ExprError();
4695
4696 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4697 /*BasePath=*/nullptr, CCK)
4698 .get();
4699 break;
4700
4701 case ICK_Qualification: {
4702 ExprValueKind VK = From->getValueKind();
4703 CastKind CK = CK_NoOp;
4704
4705 if (ToType->isReferenceType() &&
4706 ToType->getPointeeType().getAddressSpace() !=
4707 From->getType().getAddressSpace())
4708 CK = CK_AddressSpaceConversion;
4709
4710 if (ToType->isPointerType() &&
4711 ToType->getPointeeType().getAddressSpace() !=
4713 CK = CK_AddressSpaceConversion;
4714
4715 if (!isCast(CCK) &&
4716 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4718 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4719 << InitialFromType << ToType;
4720 }
4721
4722 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4723 /*BasePath=*/nullptr, CCK)
4724 .get();
4725
4727 !getLangOpts().WritableStrings) {
4728 Diag(From->getBeginLoc(),
4730 ? diag::ext_deprecated_string_literal_conversion
4731 : diag::warn_deprecated_string_literal_conversion)
4732 << ToType.getNonReferenceType();
4733 }
4734
4735 break;
4736 }
4737
4738 default:
4739 llvm_unreachable("Improper third standard conversion");
4740 }
4741
4742 // If this conversion sequence involved a scalar -> atomic conversion, perform
4743 // that conversion now.
4744 if (!ToAtomicType.isNull()) {
4745 assert(Context.hasSameType(
4746 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4747 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4748 VK_PRValue, nullptr, CCK)
4749 .get();
4750 }
4751
4752 // Materialize a temporary if we're implicitly converting to a reference
4753 // type. This is not required by the C++ rules but is necessary to maintain
4754 // AST invariants.
4755 if (ToType->isReferenceType() && From->isPRValue()) {
4757 if (Res.isInvalid())
4758 return ExprError();
4759 From = Res.get();
4760 }
4761
4762 // If this conversion sequence succeeded and involved implicitly converting a
4763 // _Nullable type to a _Nonnull one, complain.
4764 if (!isCast(CCK))
4765 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4766 From->getBeginLoc());
4767
4768 return From;
4769}
4770
4771/// Check the completeness of a type in a unary type trait.
4772///
4773/// If the particular type trait requires a complete type, tries to complete
4774/// it. If completing the type fails, a diagnostic is emitted and false
4775/// returned. If completing the type succeeds or no completion was required,
4776/// returns true.
4778 SourceLocation Loc,
4779 QualType ArgTy) {
4780 // C++0x [meta.unary.prop]p3:
4781 // For all of the class templates X declared in this Clause, instantiating
4782 // that template with a template argument that is a class template
4783 // specialization may result in the implicit instantiation of the template
4784 // argument if and only if the semantics of X require that the argument
4785 // must be a complete type.
4786 // We apply this rule to all the type trait expressions used to implement
4787 // these class templates. We also try to follow any GCC documented behavior
4788 // in these expressions to ensure portability of standard libraries.
4789 switch (UTT) {
4790 default: llvm_unreachable("not a UTT");
4791 // is_complete_type somewhat obviously cannot require a complete type.
4792 case UTT_IsCompleteType:
4793 // Fall-through
4794
4795 // These traits are modeled on the type predicates in C++0x
4796 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4797 // requiring a complete type, as whether or not they return true cannot be
4798 // impacted by the completeness of the type.
4799 case UTT_IsVoid:
4800 case UTT_IsIntegral:
4801 case UTT_IsFloatingPoint:
4802 case UTT_IsArray:
4803 case UTT_IsBoundedArray:
4804 case UTT_IsPointer:
4805 case UTT_IsNullPointer:
4806 case UTT_IsReferenceable:
4807 case UTT_IsLvalueReference:
4808 case UTT_IsRvalueReference:
4809 case UTT_IsMemberFunctionPointer:
4810 case UTT_IsMemberObjectPointer:
4811 case UTT_IsEnum:
4812 case UTT_IsScopedEnum:
4813 case UTT_IsUnion:
4814 case UTT_IsClass:
4815 case UTT_IsFunction:
4816 case UTT_IsReference:
4817 case UTT_IsArithmetic:
4818 case UTT_IsFundamental:
4819 case UTT_IsObject:
4820 case UTT_IsScalar:
4821 case UTT_IsCompound:
4822 case UTT_IsMemberPointer:
4823 // Fall-through
4824
4825 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4826 // which requires some of its traits to have the complete type. However,
4827 // the completeness of the type cannot impact these traits' semantics, and
4828 // so they don't require it. This matches the comments on these traits in
4829 // Table 49.
4830 case UTT_IsConst:
4831 case UTT_IsVolatile:
4832 case UTT_IsSigned:
4833 case UTT_IsUnboundedArray:
4834 case UTT_IsUnsigned:
4835
4836 // This type trait always returns false, checking the type is moot.
4837 case UTT_IsInterfaceClass:
4838 return true;
4839
4840 // C++14 [meta.unary.prop]:
4841 // If T is a non-union class type, T shall be a complete type.
4842 case UTT_IsEmpty:
4843 case UTT_IsPolymorphic:
4844 case UTT_IsAbstract:
4845 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4846 if (!RD->isUnion())
4847 return !S.RequireCompleteType(
4848 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4849 return true;
4850
4851 // C++14 [meta.unary.prop]:
4852 // If T is a class type, T shall be a complete type.
4853 case UTT_IsFinal:
4854 case UTT_IsSealed:
4855 if (ArgTy->getAsCXXRecordDecl())
4856 return !S.RequireCompleteType(
4857 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4858 return true;
4859
4860 // LWG3823: T shall be an array type, a complete type, or cv void.
4861 case UTT_IsAggregate:
4862 if (ArgTy->isArrayType() || ArgTy->isVoidType())
4863 return true;
4864
4865 return !S.RequireCompleteType(
4866 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4867
4868 // C++1z [meta.unary.prop]:
4869 // remove_all_extents_t<T> shall be a complete type or cv void.
4870 case UTT_IsTrivial:
4871 case UTT_IsTriviallyCopyable:
4872 case UTT_IsStandardLayout:
4873 case UTT_IsPOD:
4874 case UTT_IsLiteral:
4875 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
4876 // impose the same constraints.
4877 case UTT_IsTriviallyRelocatable:
4878 case UTT_IsTriviallyEqualityComparable:
4879 case UTT_CanPassInRegs:
4880 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4881 // or an array of unknown bound. But GCC actually imposes the same constraints
4882 // as above.
4883 case UTT_HasNothrowAssign:
4884 case UTT_HasNothrowMoveAssign:
4885 case UTT_HasNothrowConstructor:
4886 case UTT_HasNothrowCopy:
4887 case UTT_HasTrivialAssign:
4888 case UTT_HasTrivialMoveAssign:
4889 case UTT_HasTrivialDefaultConstructor:
4890 case UTT_HasTrivialMoveConstructor:
4891 case UTT_HasTrivialCopy:
4892 case UTT_HasTrivialDestructor:
4893 case UTT_HasVirtualDestructor:
4894 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4895 [[fallthrough]];
4896
4897 // C++1z [meta.unary.prop]:
4898 // T shall be a complete type, cv void, or an array of unknown bound.
4899 case UTT_IsDestructible:
4900 case UTT_IsNothrowDestructible:
4901 case UTT_IsTriviallyDestructible:
4902 case UTT_HasUniqueObjectRepresentations:
4903 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4904 return true;
4905
4906 return !S.RequireCompleteType(
4907 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4908 }
4909}
4910
4912 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4913 bool (CXXRecordDecl::*HasTrivial)() const,
4914 bool (CXXRecordDecl::*HasNonTrivial)() const,
4915 bool (CXXMethodDecl::*IsDesiredOp)() const)
4916{
4917 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4918 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4919 return true;
4920
4921 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4922 DeclarationNameInfo NameInfo(Name, KeyLoc);
4923 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4924 if (Self.LookupQualifiedName(Res, RD)) {
4925 bool FoundOperator = false;
4926 Res.suppressDiagnostics();
4927 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4928 Op != OpEnd; ++Op) {
4929 if (isa<FunctionTemplateDecl>(*Op))
4930 continue;
4931
4932 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4933 if((Operator->*IsDesiredOp)()) {
4934 FoundOperator = true;
4935 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4936 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4937 if (!CPT || !CPT->isNothrow())
4938 return false;
4939 }
4940 }
4941 return FoundOperator;
4942 }
4943 return false;
4944}
4945
4947 SourceLocation KeyLoc, QualType T) {
4948 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4949
4950 ASTContext &C = Self.Context;
4951 switch(UTT) {
4952 default: llvm_unreachable("not a UTT");
4953 // Type trait expressions corresponding to the primary type category
4954 // predicates in C++0x [meta.unary.cat].