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