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