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