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