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